<commit_before>/*************************************************************************
 *
 *  $RCSfile: labelexp.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 15:25:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _COM_SUN_STAR_TEXT_XTEXTFIELDSSUPPLIER_HPP_
#include <com/sun/star/text/XTextFieldsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _LABFMT_HXX
#include <labfmt.hxx>
#endif
#ifndef _UNOTOOLS_HXX
#include <unotools.hxx>
#endif
#ifndef _UNOATXT_HXX //autogen wg. SwXAutoTextEntry
#include <unoatxt.hxx>
#endif
#ifndef _UNOOBJ_HXX //
#include <unoobj.hxx>
#endif
#ifndef _UNOPRNMS_HXX //
#include <unoprnms.hxx>
#endif

using namespace ::com::sun::star;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::uno;
using namespace ::comphelper;
using namespace ::rtl;

#define C2U(char) rtl::OUString::createFromAscii(char)

/* -----------------08.07.99 15:15-------------------

 --------------------------------------------------*/
void SwVisitingCardPage::InitFrameControl()
{
    Link aLink(LINK(this, SwVisitingCardPage, FrameControlInitializedHdl));
    pExampleFrame = new SwOneExampleFrame( aExampleWIN,
                                    EX_SHOW_BUSINESS_CARDS, &aLink );

    uno::Reference< lang::XMultiServiceFactory >  xMgr =
                                            getProcessServiceFactory();
    //now the AutoText ListBoxes have to be filled

    uno::Reference< uno::XInterface >  xAText =
        xMgr->createInstance( C2U("com.sun.star.text.AutoTextContainer") );
    _xAutoText = uno::Reference< container::XNameAccess >(xAText, uno::UNO_QUERY);

    uno::Sequence<OUString> aNames = _xAutoText->getElementNames();
    const OUString* pGroups = aNames.getConstArray();
    OUString uTitleName( C2U(SW_PROP_NAME_STR(UNO_NAME_TITLE)) );

    for(sal_uInt16 i = 0; i < aNames.getLength(); i++)
    {
        uno::Any aGroup = _xAutoText->getByName(pGroups[i]);
        uno::Reference< text::XAutoTextGroup >  xGroup;
        aGroup >>= xGroup;
        uno::Reference< container::XIndexAccess >  xIdxAcc(xGroup, uno::UNO_QUERY);
        try
        {
            if(!xIdxAcc.is() || xIdxAcc->getCount())
            {
                uno::Reference< beans::XPropertySet >  xPrSet(xGroup, uno::UNO_QUERY);
                uno::Any aTitle = xPrSet->getPropertyValue( uTitleName );
                OUString uTitle;
                aTitle >>= uTitle;
                String sGroup(pGroups[i]);
                sal_uInt16 nEntry = aAutoTextGroupLB.InsertEntry(uTitle);
                aAutoTextGroupLB.SetEntryData(nEntry, new String(sGroup));
            }
        }
        catch(Exception&)
        {
        }
    }
    if(aAutoTextGroupLB.GetEntryCount())
    {
        if(LISTBOX_ENTRY_NOTFOUND == aAutoTextGroupLB.GetSelectEntryPos())
            aAutoTextGroupLB.SelectEntryPos(0);
        String sCurGroupName(
            *(String*)aAutoTextGroupLB.GetEntryData(aAutoTextGroupLB.GetSelectEntryPos()));
        if(_xAutoText->hasByName(sCurGroupName))
        {
            uno::Any aGroup = _xAutoText->getByName(sCurGroupName);
            try
            {
                uno::Reference< text::XAutoTextGroup >  xGroup;
                aGroup >>= xGroup;
                uno::Sequence< OUString > aBlockNames = xGroup->getElementNames();
                uno::Sequence< OUString > aTitles = xGroup->getTitles() ;

                SetUserData( aBlockNames.getLength(), aTitles.getConstArray(),
                            aBlockNames.getConstArray() );
            }
            catch( uno::RuntimeException& )
            {
                // we'll be her if path settings were wrong
            }
        }
    }
}
/* -----------------01.10.99 13:19-------------------

 --------------------------------------------------*/
IMPL_LINK( SwVisitingCardPage, FrameControlInitializedHdl, void*, EMPTYARG )
{
    SvLBoxEntry* pSel = aAutoTextLB.FirstSelected();
    String sEntry;
    if( pSel )
        sEntry = *(String*)pSel->GetUserData();
    uno::Reference< text::XTextCursor > & xCrsr = pExampleFrame->GetTextCursor();
    OUString uEntry(sEntry);

    if(LISTBOX_ENTRY_NOTFOUND != aAutoTextGroupLB.GetSelectEntryPos())
    {
        String sGroup( *(String*)aAutoTextGroupLB.GetEntryData(
                                    aAutoTextGroupLB.GetSelectEntryPos() ) );
        uno::Any aGroup = _xAutoText->getByName(sGroup);
        uno::Reference< text::XAutoTextGroup >  xGroup;
        aGroup >>= xGroup;

        if( sEntry.Len() && xGroup->hasByName( uEntry ) )
        {
            uno::Any aEntry(xGroup->getByName(uEntry));
            uno::Reference< text::XAutoTextEntry >  xEntry;
            aEntry >>= xEntry;
            if(xEntry.is())
            {
                uno::Reference< text::XTextRange >  xRange(xCrsr, uno::UNO_QUERY);
                xEntry->applyTo(xRange);
            }
            UpdateFields();
        }
    }
    return 0;
}
/* -----------------22.07.99 11:06-------------------

 --------------------------------------------------*/
IMPL_LINK( SwVisitingCardPage, AutoTextSelectHdl, void*, pBox )
{
    if(_xAutoText.is())
    {
        if( &aAutoTextGroupLB == pBox )
        {
            String sGroup( *(String*)aAutoTextGroupLB.GetEntryData(
                                    aAutoTextGroupLB.GetSelectEntryPos()));
            uno::Any aGroup = _xAutoText->getByName(sGroup);
            uno::Reference< text::XAutoTextGroup >  xGroup;
            aGroup >>= xGroup;

            ClearUserData();
            aAutoTextLB.Clear();

            uno::Sequence<OUString> aBlockNames = xGroup->getElementNames();
            uno::Sequence< OUString > aTitles = xGroup->getTitles() ;
            SetUserData( aBlockNames.getLength(), aTitles.getConstArray(),
                        aBlockNames.getConstArray() );
        }
        if(pExampleFrame->IsInitialized())
            pExampleFrame->ClearDocument( TRUE );
    }
    return 0;
}

/* -----------------01.10.99 11:59-------------------

 --------------------------------------------------*/
void SwVisitingCardPage::UpdateFields()
{
    uno::Reference< frame::XModel >  xModel;
    if( pExampleFrame && (xModel = pExampleFrame->GetModel()).is())
    {
        SwLabDlg::UpdateFieldInformation(xModel, aLabItem);
    }
}
/* -----------------01.10.99 15:16-------------------

 --------------------------------------------------*/
void SwLabDlg::UpdateFieldInformation(uno::Reference< frame::XModel > & xModel, const SwLabItem& rItem)
{
    uno::Reference< text::XTextFieldsSupplier >  xFlds(xModel, uno::UNO_QUERY);
    uno::Reference< container::XNameAccess >  xFldMasters = xFlds->getTextFieldMasters();

    static const struct _SwLabItemMap {
        const char* pName;
        rtl::OUString SwLabItem:: *pValue;
    }  aArr[] = {
        { "BC_PRIV_FIRSTNAME"  , &SwLabItem::aPrivFirstName },
        { "BC_PRIV_NAME"       , &SwLabItem::aPrivName },
        { "BC_PRIV_INITIALS"   , &SwLabItem::aPrivShortCut },
        { "BC_PRIV_FIRSTNAME_2", &SwLabItem::aPrivFirstName2 },
        { "BC_PRIV_NAME_2"     , &SwLabItem::aPrivName2 },
        { "BC_PRIV_INITIALS_2" , &SwLabItem::aPrivShortCut2 },
        { "BC_PRIV_STREET"     , &SwLabItem::aPrivStreet },
        { "BC_PRIV_ZIP"        , &SwLabItem::aPrivZip },
        { "BC_PRIV_CITY"       , &SwLabItem::aPrivCity },
        { "BC_PRIV_COUNTRY"    , &SwLabItem::aPrivCountry },
        { "BC_PRIV_STATE"      , &SwLabItem::aPrivState },
        { "BC_PRIV_TITLE"      , &SwLabItem::aPrivTitle },
        { "BC_PRIV_PROFESSION" , &SwLabItem::aPrivProfession },
        { "BC_PRIV_PHONE"      , &SwLabItem::aPrivPhone },
        { "BC_PRIV_MOBILE"     , &SwLabItem::aPrivMobile },
        { "BC_PRIV_FAX"        , &SwLabItem::aPrivFax },
        { "BC_PRIV_WWW"        , &SwLabItem::aPrivWWW },
        { "BC_PRIV_MAIL"       , &SwLabItem::aPrivMail },
        { "BC_COMP_COMPANY"    , &SwLabItem::aCompCompany },
        { "BC_COMP_COMPANYEXT" , &SwLabItem::aCompCompanyExt },
        { "BC_COMP_SLOGAN"     , &SwLabItem::aCompSlogan },
        { "BC_COMP_STREET"     , &SwLabItem::aCompStreet },
        { "BC_COMP_ZIP"        , &SwLabItem::aCompZip },
        { "BC_COMP_CITY"       , &SwLabItem::aCompCity },
        { "BC_COMP_COUNTRY"    , &SwLabItem::aCompCountry },
        { "BC_COMP_STATE"      , &SwLabItem::aCompState },
        { "BC_COMP_POSITION"   , &SwLabItem::aCompPosition },
        { "BC_COMP_PHONE"      , &SwLabItem::aCompPhone },
        { "BC_COMP_MOBILE"     , &SwLabItem::aCompMobile },
        { "BC_COMP_FAX"        , &SwLabItem::aCompFax },
        { "BC_COMP_WWW"        , &SwLabItem::aCompWWW },
        { "BC_COMP_MAIL"       , &SwLabItem::aCompMail },
        { 0, 0 }
    };

    try
    {
        String sFldName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM(
                            "com.sun.star.text.FieldMaster.User." )));
        OUString uCntName( C2U( SW_PROP_NAME_STR(UNO_NAME_CONTENT )));
        for( const _SwLabItemMap* p = aArr; p->pName; ++p )
        {
            String sCurFldName( sFldName );
            sCurFldName.AppendAscii( p->pName );
            OUString uFldName( sCurFldName );
            if( xFldMasters->hasByName( uFldName ))
            {
                uno::Any aFirstName = xFldMasters->getByName( uFldName );
                uno::Reference< beans::XPropertySet >  xFld;
                aFirstName >>= xFld;
                uno::Any aContent;
                aContent <<= rItem.*p->pValue;
                xFld->setPropertyValue( uCntName, aContent );
            }
        }
    }
    catch( uno::RuntimeException&)
    {
        //
    }

    uno::Reference< container::XEnumerationAccess >  xFldAcc = xFlds->getTextFields();
    uno::Reference< util::XRefreshable >  xRefresh(xFldAcc, uno::UNO_QUERY);
    xRefresh->refresh();
}

<commit_msg>INTEGRATION: CWS tune03 (1.4.580); FILE MERGED 2004/07/19 19:11:11 mhu 1.4.580.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
 *
 *  $RCSfile: labelexp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 08:51:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#pragma hdrstop

#ifndef _COM_SUN_STAR_TEXT_XTEXTFIELDSSUPPLIER_HPP_
#include <com/sun/star/text/XTextFieldsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _LABFMT_HXX
#include <labfmt.hxx>
#endif
#ifndef _UNOTOOLS_HXX
#include <unotools.hxx>
#endif
#ifndef _UNOATXT_HXX //autogen wg. SwXAutoTextEntry
#include <unoatxt.hxx>
#endif
#ifndef _UNOOBJ_HXX //
#include <unoobj.hxx>
#endif
#ifndef _UNOPRNMS_HXX //
#include <unoprnms.hxx>
#endif

using namespace ::com::sun::star;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::uno;
using namespace ::comphelper;
using namespace ::rtl;

#define C2U(char) rtl::OUString::createFromAscii(char)

#ifdef SW_PROP_NAME_STR
#undef SW_PROP_NAME_STR
#endif
#define SW_PROP_NAME_STR(nId) SwGetPropName((nId)).pName

/* -----------------08.07.99 15:15-------------------

 --------------------------------------------------*/
void SwVisitingCardPage::InitFrameControl()
{
    Link aLink(LINK(this, SwVisitingCardPage, FrameControlInitializedHdl));
    pExampleFrame = new SwOneExampleFrame( aExampleWIN,
                                    EX_SHOW_BUSINESS_CARDS, &aLink );

    uno::Reference< lang::XMultiServiceFactory >  xMgr =
                                            getProcessServiceFactory();
    //now the AutoText ListBoxes have to be filled

    uno::Reference< uno::XInterface >  xAText =
        xMgr->createInstance( C2U("com.sun.star.text.AutoTextContainer") );
    _xAutoText = uno::Reference< container::XNameAccess >(xAText, uno::UNO_QUERY);

    uno::Sequence<OUString> aNames = _xAutoText->getElementNames();
    const OUString* pGroups = aNames.getConstArray();
    OUString uTitleName( C2U(SW_PROP_NAME_STR(UNO_NAME_TITLE)) );

    for(sal_uInt16 i = 0; i < aNames.getLength(); i++)
    {
        uno::Any aGroup = _xAutoText->getByName(pGroups[i]);
        uno::Reference< text::XAutoTextGroup >  xGroup;
        aGroup >>= xGroup;
        uno::Reference< container::XIndexAccess >  xIdxAcc(xGroup, uno::UNO_QUERY);
        try
        {
            if(!xIdxAcc.is() || xIdxAcc->getCount())
            {
                uno::Reference< beans::XPropertySet >  xPrSet(xGroup, uno::UNO_QUERY);
                uno::Any aTitle = xPrSet->getPropertyValue( uTitleName );
                OUString uTitle;
                aTitle >>= uTitle;
                String sGroup(pGroups[i]);
                sal_uInt16 nEntry = aAutoTextGroupLB.InsertEntry(uTitle);
                aAutoTextGroupLB.SetEntryData(nEntry, new String(sGroup));
            }
        }
        catch(Exception&)
        {
        }
    }
    if(aAutoTextGroupLB.GetEntryCount())
    {
        if(LISTBOX_ENTRY_NOTFOUND == aAutoTextGroupLB.GetSelectEntryPos())
            aAutoTextGroupLB.SelectEntryPos(0);
        String sCurGroupName(
            *(String*)aAutoTextGroupLB.GetEntryData(aAutoTextGroupLB.GetSelectEntryPos()));
        if(_xAutoText->hasByName(sCurGroupName))
        {
            uno::Any aGroup = _xAutoText->getByName(sCurGroupName);
            try
            {
                uno::Reference< text::XAutoTextGroup >  xGroup;
                aGroup >>= xGroup;
                uno::Sequence< OUString > aBlockNames = xGroup->getElementNames();
                uno::Sequence< OUString > aTitles = xGroup->getTitles() ;

                SetUserData( aBlockNames.getLength(), aTitles.getConstArray(),
                            aBlockNames.getConstArray() );
            }
            catch( uno::RuntimeException& )
            {
                // we'll be her if path settings were wrong
            }
        }
    }
}
/* -----------------01.10.99 13:19-------------------

 --------------------------------------------------*/
IMPL_LINK( SwVisitingCardPage, FrameControlInitializedHdl, void*, EMPTYARG )
{
    SvLBoxEntry* pSel = aAutoTextLB.FirstSelected();
    String sEntry;
    if( pSel )
        sEntry = *(String*)pSel->GetUserData();
    uno::Reference< text::XTextCursor > & xCrsr = pExampleFrame->GetTextCursor();
    OUString uEntry(sEntry);

    if(LISTBOX_ENTRY_NOTFOUND != aAutoTextGroupLB.GetSelectEntryPos())
    {
        String sGroup( *(String*)aAutoTextGroupLB.GetEntryData(
                                    aAutoTextGroupLB.GetSelectEntryPos() ) );
        uno::Any aGroup = _xAutoText->getByName(sGroup);
        uno::Reference< text::XAutoTextGroup >  xGroup;
        aGroup >>= xGroup;

        if( sEntry.Len() && xGroup->hasByName( uEntry ) )
        {
            uno::Any aEntry(xGroup->getByName(uEntry));
            uno::Reference< text::XAutoTextEntry >  xEntry;
            aEntry >>= xEntry;
            if(xEntry.is())
            {
                uno::Reference< text::XTextRange >  xRange(xCrsr, uno::UNO_QUERY);
                xEntry->applyTo(xRange);
            }
            UpdateFields();
        }
    }
    return 0;
}
/* -----------------22.07.99 11:06-------------------

 --------------------------------------------------*/
IMPL_LINK( SwVisitingCardPage, AutoTextSelectHdl, void*, pBox )
{
    if(_xAutoText.is())
    {
        if( &aAutoTextGroupLB == pBox )
        {
            String sGroup( *(String*)aAutoTextGroupLB.GetEntryData(
                                    aAutoTextGroupLB.GetSelectEntryPos()));
            uno::Any aGroup = _xAutoText->getByName(sGroup);
            uno::Reference< text::XAutoTextGroup >  xGroup;
            aGroup >>= xGroup;

            ClearUserData();
            aAutoTextLB.Clear();

            uno::Sequence<OUString> aBlockNames = xGroup->getElementNames();
            uno::Sequence< OUString > aTitles = xGroup->getTitles() ;
            SetUserData( aBlockNames.getLength(), aTitles.getConstArray(),
                        aBlockNames.getConstArray() );
        }
        if(pExampleFrame->IsInitialized())
            pExampleFrame->ClearDocument( TRUE );
    }
    return 0;
}

/* -----------------01.10.99 11:59-------------------

 --------------------------------------------------*/
void SwVisitingCardPage::UpdateFields()
{
    uno::Reference< frame::XModel >  xModel;
    if( pExampleFrame && (xModel = pExampleFrame->GetModel()).is())
    {
        SwLabDlg::UpdateFieldInformation(xModel, aLabItem);
    }
}
/* -----------------01.10.99 15:16-------------------

 --------------------------------------------------*/
void SwLabDlg::UpdateFieldInformation(uno::Reference< frame::XModel > & xModel, const SwLabItem& rItem)
{
    uno::Reference< text::XTextFieldsSupplier >  xFlds(xModel, uno::UNO_QUERY);
    uno::Reference< container::XNameAccess >  xFldMasters = xFlds->getTextFieldMasters();

    static const struct _SwLabItemMap {
        const char* pName;
        rtl::OUString SwLabItem:: *pValue;
    }  aArr[] = {
        { "BC_PRIV_FIRSTNAME"  , &SwLabItem::aPrivFirstName },
        { "BC_PRIV_NAME"       , &SwLabItem::aPrivName },
        { "BC_PRIV_INITIALS"   , &SwLabItem::aPrivShortCut },
        { "BC_PRIV_FIRSTNAME_2", &SwLabItem::aPrivFirstName2 },
        { "BC_PRIV_NAME_2"     , &SwLabItem::aPrivName2 },
        { "BC_PRIV_INITIALS_2" , &SwLabItem::aPrivShortCut2 },
        { "BC_PRIV_STREET"     , &SwLabItem::aPrivStreet },
        { "BC_PRIV_ZIP"        , &SwLabItem::aPrivZip },
        { "BC_PRIV_CITY"       , &SwLabItem::aPrivCity },
        { "BC_PRIV_COUNTRY"    , &SwLabItem::aPrivCountry },
        { "BC_PRIV_STATE"      , &SwLabItem::aPrivState },
        { "BC_PRIV_TITLE"      , &SwLabItem::aPrivTitle },
        { "BC_PRIV_PROFESSION" , &SwLabItem::aPrivProfession },
        { "BC_PRIV_PHONE"      , &SwLabItem::aPrivPhone },
        { "BC_PRIV_MOBILE"     , &SwLabItem::aPrivMobile },
        { "BC_PRIV_FAX"        , &SwLabItem::aPrivFax },
        { "BC_PRIV_WWW"        , &SwLabItem::aPrivWWW },
        { "BC_PRIV_MAIL"       , &SwLabItem::aPrivMail },
        { "BC_COMP_COMPANY"    , &SwLabItem::aCompCompany },
        { "BC_COMP_COMPANYEXT" , &SwLabItem::aCompCompanyExt },
        { "BC_COMP_SLOGAN"     , &SwLabItem::aCompSlogan },
        { "BC_COMP_STREET"     , &SwLabItem::aCompStreet },
        { "BC_COMP_ZIP"        , &SwLabItem::aCompZip },
        { "BC_COMP_CITY"       , &SwLabItem::aCompCity },
        { "BC_COMP_COUNTRY"    , &SwLabItem::aCompCountry },
        { "BC_COMP_STATE"      , &SwLabItem::aCompState },
        { "BC_COMP_POSITION"   , &SwLabItem::aCompPosition },
        { "BC_COMP_PHONE"      , &SwLabItem::aCompPhone },
        { "BC_COMP_MOBILE"     , &SwLabItem::aCompMobile },
        { "BC_COMP_FAX"        , &SwLabItem::aCompFax },
        { "BC_COMP_WWW"        , &SwLabItem::aCompWWW },
        { "BC_COMP_MAIL"       , &SwLabItem::aCompMail },
        { 0, 0 }
    };

    try
    {
        String sFldName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM(
                            "com.sun.star.text.FieldMaster.User." )));
        OUString uCntName( C2U( SW_PROP_NAME_STR(UNO_NAME_CONTENT )));
        for( const _SwLabItemMap* p = aArr; p->pName; ++p )
        {
            String sCurFldName( sFldName );
            sCurFldName.AppendAscii( p->pName );
            OUString uFldName( sCurFldName );
            if( xFldMasters->hasByName( uFldName ))
            {
                uno::Any aFirstName = xFldMasters->getByName( uFldName );
                uno::Reference< beans::XPropertySet >  xFld;
                aFirstName >>= xFld;
                uno::Any aContent;
                aContent <<= rItem.*p->pValue;
                xFld->setPropertyValue( uCntName, aContent );
            }
        }
    }
    catch( uno::RuntimeException&)
    {
        //
    }

    uno::Reference< container::XEnumerationAccess >  xFldAcc = xFlds->getTextFields();
    uno::Reference< util::XRefreshable >  xRefresh(xFldAcc, uno::UNO_QUERY);
    xRefresh->refresh();
}

<|endoftext|>


<commit_before>void loadlibs ()
{
  gSystem->Load("libPhysics");
  gSystem->Load("libMinuit");
  gSystem->Load("libmicrocern");
  gSystem->Load("libpdf");
  gSystem->Load("libpythia6");
  gSystem->Load("libEG");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libEGPythia6");

  gSystem->Load("libRAWData");
  gSystem->Load("libESD");
  gSystem->Load("libSTEER");
  gSystem->Load("libEVGEN");
  gSystem->Load("libFASTSIM");
  gSystem->Load("libAliPythia6");
  gSystem->Load("libSTRUCT");
  gSystem->Load("libMUONmapping");
  gSystem->Load("libMUONgeometry");
  gSystem->Load("libMUONbase");

  gSystem->Load("libMUONsim");
  new AliRun("gAlice","The ALICE Off-line Simulation Framework");

  gSystem->Load("libMUONrec");

}
<commit_msg>Adding libMUONraw.so in loading (Christian)<commit_after>void loadlibs ()
{
  gSystem->Load("libPhysics");
  gSystem->Load("libmicrocern");
  gSystem->Load("libpdf");
  gSystem->Load("libpythia6");
  gSystem->Load("libEG");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libEGPythia6");

  gSystem->Load("libRAWData");
  gSystem->Load("libESD");
  gSystem->Load("libSTEER");
  gSystem->Load("libEVGEN");
  gSystem->Load("libFASTSIM");
  gSystem->Load("libAliPythia6");
  gSystem->Load("libSTRUCT");
  gSystem->Load("libMUONmapping");
  gSystem->Load("libMUONgeometry");
  gSystem->Load("libMUONbase");
  gSystem->Load("libMUONraw");

  gSystem->Load("libMUONsim");
  new AliRun("gAlice","The ALICE Off-line Simulation Framework");

  gSystem->Load("libMUONrec");

}
<|endoftext|>


<commit_before>/*
	This file is part of the E_Rendering library.
	Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_Mesh.h"
#include "E_VertexDescription.h"
#include "../E_RenderingContext.h"
#include "../E_BufferObject.h"

#include <Rendering/Mesh/MeshVertexData.h>
#include <Rendering/Mesh/MeshIndexData.h>

#include <E_Geometry/E_Box.h>
#include <E_Util/E_FileName.h>
#include <E_Util/E_Utils.h>
#include <EScript/EScript.h>

using namespace EScript;

namespace E_Rendering {

//! (static)
EScript::Type * E_Mesh::getTypeObject() {
	// E_Mesh ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! initMembers
void E_Mesh::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = getTypeObject();
	initPrintableName(typeObject,getClassName());
	declareConstant(&lib,getClassName(),typeObject);

	using namespace Rendering;

	//!	[ESMF] new Rendering.Mesh( Mesh )
	ES_CONSTRUCTOR(typeObject,1,1, {
		Mesh* source = parameter[0].to<Mesh*>(rt);
		MeshIndexData indexData(source->openIndexData());
		MeshVertexData vertexData(source->openVertexData());
		Mesh* mesh = new Mesh(indexData, vertexData);
		mesh->setDataStrategy(source->getDataStrategy());
		mesh->setDrawMode(source->getDrawMode());
		mesh->setFileName(source->getFileName());
		mesh->setUseIndexData(mesh->isUsingIndexData());
		return EScript::create(mesh);
	})

	//! [ESMF] VertexDescription Mesh.getVertexDescription()
	ES_MFUN(typeObject,const Mesh,"getVertexDescription",0,0,thisObj->getVertexDescription())

	//! [ESMF] Number Mesh.getVertexCount()
	ES_MFUN(typeObject,const Mesh,"getVertexCount",0,0,thisObj->getVertexCount())

	//! [ESMF] Array Mesh._getIndices()
	ES_MFUNCTION(typeObject,Mesh,"_getIndices",0,0,{
		MeshIndexData & indexData = thisObj->openIndexData();
		auto arr = EScript::Array::create();
		arr->reserve(indexData.getIndexCount());
		for(size_t idx = 0; idx<indexData.getIndexCount(); ++idx)
			arr->pushBack(EScript::create(indexData[idx]));
		return arr;
	})

	//! [ESMF] Number Mesh.getIndexCount()
	ES_MFUN(typeObject,const Mesh,"getIndexCount",0,0,thisObj->getIndexCount())

	//! [ESMF] Box Mesh.getBoundingBox()
	ES_MFUN(typeObject,const Mesh,"getBoundingBox",0,0,thisObj->getBoundingBox())

	//! [ESMF] FileName Mesh.getFileName()
	ES_MFUN(typeObject,const Mesh,"getFileName",0,0,	new E_Util::E_FileName(thisObj->getFileName()))

	//! [ESMF] FileName Mesh.getMainMemoryUsage()
	ES_MFUN(typeObject,const Mesh,"getMainMemoryUsage",0,0,	static_cast<double>(thisObj->getMainMemoryUsage()))

	//! [ESMF] FileName Mesh.getGraphicsMemoryUsage()
	ES_MFUN(typeObject,const Mesh,"getGraphicsMemoryUsage",0,0,	static_cast<double>(thisObj->getGraphicsMemoryUsage()))

	//! [ESMF] Number Mesh.getPrimitiveCount()
	ES_MFUN(typeObject,const Mesh,"getPrimitiveCount",0,0,	static_cast<double>(thisObj->getPrimitiveCount()))

	//! [ESMF] Bool Mesh.isUsingIndexData()
	ES_MFUN(typeObject,const Mesh,"isUsingIndexData",0,0,thisObj->isUsingIndexData())

	//! [ESMF] thisEObj Mesh.releaseLocalData()
	ES_MFUNCTION(typeObject, Mesh, "releaseLocalData", 0, 0, {
		thisObj->openVertexData().releaseLocalData();
		thisObj->openIndexData().releaseLocalData();
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh.releaseLocalData()
	ES_MFUNCTION(typeObject, Mesh, "assureLocalData", 0, 0, {
		thisObj->openVertexData();
		thisObj->openIndexData();
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh.setDrawMode(Number)
	ES_MFUN(typeObject,Mesh,"setDrawMode",1,1,(thisObj->setDrawMode(static_cast<Rendering::Mesh::draw_mode_t>(parameter[0].toUInt())),thisEObj))

	//! [ESMF] Number Mesh.getDrawMode()
	ES_MFUN(typeObject,const Mesh,"getDrawMode",0,0, static_cast<uint32_t>(thisObj->getDrawMode()))

	//! [ESMF] thisEObj Mesh.setDrawLines()
	ES_MFUN(typeObject,Mesh,"setDrawLines",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_LINES),thisEObj))

	//! [ESMF] thisEObj Mesh.setDrawLineStrip()
	ES_MFUN(typeObject,Mesh,"setDrawLineStrip",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_LINE_STRIP),thisEObj))

	//! [ESMF] thisEObj Mesh.setDrawPoints()
	ES_MFUN(typeObject,Mesh,"setDrawPoints",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_POINTS),thisEObj))

	//! [ESMF] thisEObj Mesh.setDrawTriangles()
	ES_MFUN(typeObject,Mesh,"setDrawTriangles",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_TRIANGLES),thisEObj))

	//! [ESMF] thisEObj Mesh._setIndices(Array)
	ES_MFUNCTION(typeObject,Mesh,"_setIndices",1,1,{
		auto arr = parameter[0].to<EScript::Array*>(rt);
		MeshIndexData & indices = thisObj->_getIndexData();
		indices.allocate(arr->size());
		for(size_t i=0;i<arr->size();++i)
			indices[i] = arr->at(i).to<uint32_t>(rt);
		indices.updateIndexRange();
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh.setFileName([[FileName, String] name])
	ES_MFUNCTION(typeObject,Mesh,"setFileName",0,1,{
		if(parameter.count() == 0){
			thisObj->setFileName(Util::FileName());
		}else{
			E_Util::E_FileName * t = dynamic_cast<E_Util::E_FileName *>(parameter[0].get());
			if(t){
				thisObj->setFileName(t->ref());
			}else{
				thisObj->setFileName(Util::FileName(parameter[0].toString()));
			}
		}
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh.setUseIndexData(Bool)
	ES_MFUN(typeObject,Mesh,"setUseIndexData",1,1,(thisObj->setUseIndexData(parameter[0].toBool()),thisEObj))

	//! [ESMF] thisEObj Mesh.swap(Mesh)
	ES_MFUN(typeObject,Mesh,"swap",1,1,(thisObj->swap(*parameter[0].to<Mesh*>(rt)),thisEObj))

	//! [ESMF] thisEObj Mesh._markAsChanged() (wrapper for VertexData and IndexData.markAsChanged(), updateBB, and updateIndexRange , as these have no wrapper objects)
	ES_MFUNCTION(typeObject,Mesh,"_markAsChanged",0,0,{
		thisObj->openVertexData().markAsChanged();
		thisObj->openVertexData().updateBoundingBox();
		thisObj->openIndexData().markAsChanged();
		thisObj->openIndexData().updateIndexRange();
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh._swapVertexBuffer(BufferObject)
	ES_MFUN(typeObject,Mesh,"_swapVertexBuffer",1,1,(thisObj->_getVertexData()._swapBufferObject(parameter[0].to<CountedBufferObject*>(rt)->get()),thisEObj))

	//! [ESMF] thisEObj Mesh._swapIndexBuffer(BufferObject)
	ES_MFUN(typeObject,Mesh,"_swapIndexBuffer",1,1,(thisObj->_getIndexData()._swapBufferObject(parameter[0].to<CountedBufferObject*>(rt)->get()),thisEObj))

	//! [ESMF] thisEObj Mesh._upload([usageHint])
	ES_MFUN(typeObject,Mesh,"_upload",0,1,(parameter.size() > 0 ? thisObj->_getVertexData().upload(parameter[0].toUInt()) : thisObj->_getVertexData().upload(),thisEObj))

	E_Util::E_Utils::registerConverter(new E_Util::E_Utils::CountedRefAttrConverter<Rendering::Mesh,E_Mesh>);
}

//---

std::string E_Mesh::toString() const{
	std::stringstream ss;
	ss << "#Mesh:" << (**this).get();
	return ss.str();
}

}
<commit_msg>Mesh._upload didn't upload index data<commit_after>/*
	This file is part of the E_Rendering library.
	Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_Mesh.h"
#include "E_VertexDescription.h"
#include "../E_RenderingContext.h"
#include "../E_BufferObject.h"

#include <Rendering/Mesh/MeshVertexData.h>
#include <Rendering/Mesh/MeshIndexData.h>

#include <E_Geometry/E_Box.h>
#include <E_Util/E_FileName.h>
#include <E_Util/E_Utils.h>
#include <EScript/EScript.h>

using namespace EScript;

namespace E_Rendering {

//! (static)
EScript::Type * E_Mesh::getTypeObject() {
	// E_Mesh ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! initMembers
void E_Mesh::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = getTypeObject();
	initPrintableName(typeObject,getClassName());
	declareConstant(&lib,getClassName(),typeObject);

	using namespace Rendering;

	//!	[ESMF] new Rendering.Mesh( Mesh )
	ES_CONSTRUCTOR(typeObject,1,1, {
		Mesh* source = parameter[0].to<Mesh*>(rt);
		MeshIndexData indexData(source->openIndexData());
		MeshVertexData vertexData(source->openVertexData());
		Mesh* mesh = new Mesh(indexData, vertexData);
		mesh->setDataStrategy(source->getDataStrategy());
		mesh->setDrawMode(source->getDrawMode());
		mesh->setFileName(source->getFileName());
		mesh->setUseIndexData(mesh->isUsingIndexData());
		return EScript::create(mesh);
	})

	//! [ESMF] VertexDescription Mesh.getVertexDescription()
	ES_MFUN(typeObject,const Mesh,"getVertexDescription",0,0,thisObj->getVertexDescription())

	//! [ESMF] Number Mesh.getVertexCount()
	ES_MFUN(typeObject,const Mesh,"getVertexCount",0,0,thisObj->getVertexCount())

	//! [ESMF] Array Mesh._getIndices()
	ES_MFUNCTION(typeObject,Mesh,"_getIndices",0,0,{
		MeshIndexData & indexData = thisObj->openIndexData();
		auto arr = EScript::Array::create();
		arr->reserve(indexData.getIndexCount());
		for(size_t idx = 0; idx<indexData.getIndexCount(); ++idx)
			arr->pushBack(EScript::create(indexData[idx]));
		return arr;
	})

	//! [ESMF] Number Mesh.getIndexCount()
	ES_MFUN(typeObject,const Mesh,"getIndexCount",0,0,thisObj->getIndexCount())

	//! [ESMF] Box Mesh.getBoundingBox()
	ES_MFUN(typeObject,const Mesh,"getBoundingBox",0,0,thisObj->getBoundingBox())

	//! [ESMF] FileName Mesh.getFileName()
	ES_MFUN(typeObject,const Mesh,"getFileName",0,0,	new E_Util::E_FileName(thisObj->getFileName()))

	//! [ESMF] FileName Mesh.getMainMemoryUsage()
	ES_MFUN(typeObject,const Mesh,"getMainMemoryUsage",0,0,	static_cast<double>(thisObj->getMainMemoryUsage()))

	//! [ESMF] FileName Mesh.getGraphicsMemoryUsage()
	ES_MFUN(typeObject,const Mesh,"getGraphicsMemoryUsage",0,0,	static_cast<double>(thisObj->getGraphicsMemoryUsage()))

	//! [ESMF] Number Mesh.getPrimitiveCount()
	ES_MFUN(typeObject,const Mesh,"getPrimitiveCount",0,0,	static_cast<double>(thisObj->getPrimitiveCount()))

	//! [ESMF] Bool Mesh.isUsingIndexData()
	ES_MFUN(typeObject,const Mesh,"isUsingIndexData",0,0,thisObj->isUsingIndexData())

	//! [ESMF] thisEObj Mesh.releaseLocalData()
	ES_MFUNCTION(typeObject, Mesh, "releaseLocalData", 0, 0, {
		thisObj->openVertexData().releaseLocalData();
		thisObj->openIndexData().releaseLocalData();
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh.releaseLocalData()
	ES_MFUNCTION(typeObject, Mesh, "assureLocalData", 0, 0, {
		thisObj->openVertexData();
		thisObj->openIndexData();
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh.setDrawMode(Number)
	ES_MFUN(typeObject,Mesh,"setDrawMode",1,1,(thisObj->setDrawMode(static_cast<Rendering::Mesh::draw_mode_t>(parameter[0].toUInt())),thisEObj))

	//! [ESMF] Number Mesh.getDrawMode()
	ES_MFUN(typeObject,const Mesh,"getDrawMode",0,0, static_cast<uint32_t>(thisObj->getDrawMode()))

	//! [ESMF] thisEObj Mesh.setDrawLines()
	ES_MFUN(typeObject,Mesh,"setDrawLines",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_LINES),thisEObj))

	//! [ESMF] thisEObj Mesh.setDrawLineStrip()
	ES_MFUN(typeObject,Mesh,"setDrawLineStrip",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_LINE_STRIP),thisEObj))

	//! [ESMF] thisEObj Mesh.setDrawPoints()
	ES_MFUN(typeObject,Mesh,"setDrawPoints",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_POINTS),thisEObj))

	//! [ESMF] thisEObj Mesh.setDrawTriangles()
	ES_MFUN(typeObject,Mesh,"setDrawTriangles",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_TRIANGLES),thisEObj))

	//! [ESMF] thisEObj Mesh._setIndices(Array)
	ES_MFUNCTION(typeObject,Mesh,"_setIndices",1,1,{
		auto arr = parameter[0].to<EScript::Array*>(rt);
		MeshIndexData & indices = thisObj->_getIndexData();
		indices.allocate(arr->size());
		for(size_t i=0;i<arr->size();++i)
			indices[i] = arr->at(i).to<uint32_t>(rt);
		indices.updateIndexRange();
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh.setFileName([[FileName, String] name])
	ES_MFUNCTION(typeObject,Mesh,"setFileName",0,1,{
		if(parameter.count() == 0){
			thisObj->setFileName(Util::FileName());
		}else{
			E_Util::E_FileName * t = dynamic_cast<E_Util::E_FileName *>(parameter[0].get());
			if(t){
				thisObj->setFileName(t->ref());
			}else{
				thisObj->setFileName(Util::FileName(parameter[0].toString()));
			}
		}
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh.setUseIndexData(Bool)
	ES_MFUN(typeObject,Mesh,"setUseIndexData",1,1,(thisObj->setUseIndexData(parameter[0].toBool()),thisEObj))

	//! [ESMF] thisEObj Mesh.swap(Mesh)
	ES_MFUN(typeObject,Mesh,"swap",1,1,(thisObj->swap(*parameter[0].to<Mesh*>(rt)),thisEObj))

	//! [ESMF] thisEObj Mesh._markAsChanged() (wrapper for VertexData and IndexData.markAsChanged(), updateBB, and updateIndexRange , as these have no wrapper objects)
	ES_MFUNCTION(typeObject,Mesh,"_markAsChanged",0,0,{
		thisObj->openVertexData().markAsChanged();
		thisObj->openVertexData().updateBoundingBox();
		thisObj->openIndexData().markAsChanged();
		thisObj->openIndexData().updateIndexRange();
		return thisEObj;
	})

	//! [ESMF] thisEObj Mesh._swapVertexBuffer(BufferObject)
	ES_MFUN(typeObject,Mesh,"_swapVertexBuffer",1,1,(thisObj->_getVertexData()._swapBufferObject(parameter[0].to<CountedBufferObject*>(rt)->get()),thisEObj))

	//! [ESMF] thisEObj Mesh._swapIndexBuffer(BufferObject)
	ES_MFUN(typeObject,Mesh,"_swapIndexBuffer",1,1,(thisObj->_getIndexData()._swapBufferObject(parameter[0].to<CountedBufferObject*>(rt)->get()),thisEObj))

	//! [ESMF] thisEObj Mesh._upload([usageHint])
	ES_MFUNCTION(typeObject,Mesh,"_upload",0,1,{
		if(parameter.size() > 0) {
			thisObj->_getVertexData().upload(parameter[0].toUInt());
			if(thisObj->isUsingIndexData()) thisObj->_getIndexData().upload(parameter[0].toUInt());
		} else {
			thisObj->_getVertexData().upload();
			if(thisObj->isUsingIndexData()) thisObj->_getIndexData().upload();
		}
		return thisEObj;
	})

	E_Util::E_Utils::registerConverter(new E_Util::E_Utils::CountedRefAttrConverter<Rendering::Mesh,E_Mesh>);
}

//---

std::string E_Mesh::toString() const{
	std::stringstream ss;
	ss << "#Mesh:" << (**this).get();
	return ss.str();
}

}
<|endoftext|>


<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#include <boost/test/unit_test.hpp>
#include "Grappa.hpp"
#include "ParallelLoop.hpp"
#include "GlobalAllocator.hpp"
#include "Delegate.hpp"
#include "GlobalHashTable.hpp"
#include "GlobalHashSet.hpp"
#include "Statistics.hpp"

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>

using namespace Grappa;

BOOST_AUTO_TEST_SUITE( GlobalHashTable_tests );

DEFINE_int64(nelems, 100, "number of elements in (large) test arrays");
DEFINE_int64(global_hash_size, 1024, "number of elements in (large) test arrays");
DEFINE_int64(max_key, 1<<10, "maximum random key");

DEFINE_int64(ntrials, 1, "number of independent trials to average over");

DEFINE_bool(table_perf, false, "do performance test of GlobalHashTable");
DEFINE_bool(set_perf, false, "do performance test of GlobalHashSet");

GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, ght_insert_time, 0);
GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, hashset_insert_time, 0);

template< typename T >
inline T next_random() {
  using engine_t = boost::mt19937_64;
  using dist_t = boost::uniform_int<T>;
  using gen_t = boost::variate_generator<engine_t&,dist_t>;

  // continue using same generator with multiple calls (to not repeat numbers)
  // but start at different seed on each node so we don't get overlap
  static engine_t engine(12345L*mycore());
  static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max()));
  return gen();
}

uint64_t kahan_hash(long k) { return k * 1299227; } // "Kahan's Hash"
uint64_t identity_hash(long k) { return k; }

enum class Exp { INSERT_UNIQUE };

template< Exp EXP,
          typename K, typename V, uint64_t (*H)(K),
          CompletionEvent* CE = &impl::local_ce,
          int64_t          TH = impl::USE_LOOP_THRESHOLD_FLAG >
double test_insert_throughput(GlobalAddress<GlobalHashTable<K,V,H>> ha) {
  double t = Grappa_walltime();

  forall_global_private<CE,TH>(0, FLAGS_nelems, [ha](int64_t i){
    if (EXP == Exp::INSERT_UNIQUE) {
      ha->insert_unique(next_random<long>());
    }
  });

  t = Grappa_walltime() - t;
  return t;
}

void test_correctness() {
  LOG(INFO) << "Testing correctness...";
  auto ha = GlobalHashTable<long,long,&identity_hash>::create(FLAGS_global_hash_size);
  for (int i=0; i<10; i++) {
    ha->insert(i, 42);
  }
  ha->global_set_RO();
  for (int i=0; i<10; i++) {
    GlobalAddress<long> res;
    BOOST_CHECK_EQUAL(ha->lookup(i, &res), 1);
    BOOST_CHECK_EQUAL(delegate::read(res), 42);
  }

  ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); });

  forall_global_private(10, FLAGS_nelems-10, [ha](int64_t i){
    ha->insert(i, 42);
  });
  ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); });

  ha->forall_entries([](long key, BufferVector<long>& vals){
    BOOST_CHECK_EQUAL(vals.size(), 1);
    auto a = vals.getReadBuffer();
    BOOST_CHECK_EQUAL(a.core(), mycore());
    BOOST_CHECK_EQUAL(delegate::read(a), 42);
  });

  ha->destroy();
}

void test_set_correctness() {
  LOG(INFO) << "Testing correctness of GlobalHashSet...";
  auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size);

  for (int i=0; i<10; i++) {
    // BOOST_CHECK_EQUAL(sa->insert(i), false);
    sa->insert(42+i);
  }
  for (int i=0; i<10; i++) {
    // BOOST_CHECK_EQUAL(sa->insert(i), true);
    BOOST_CHECK_EQUAL(sa->lookup(42+i), true);
  }

  on_all_cores([sa]{
    for (int i=10; i<20; i++) {
      sa->insert(42+i);
    }
  });

  sa->forall_keys([](long& k) { BOOST_CHECK(k < 42+20 && k >= 42); });

  BOOST_CHECK_EQUAL(sa->size(), 20);
  sa->destroy();
}

double test_set_insert_throughput() {
  auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size);

  double t = walltime();

  forall_global_private(0, FLAGS_nelems, [sa](int64_t i){
    sa->insert(next_random<long>() % FLAGS_max_key);
  });

  t = walltime() - t;

  VLOG(1) << "set_size: " << sa->size();
  sa->destroy();
  return t;
}

void user_main( void * ignore ) {
  if (FLAGS_table_perf) {
    auto ha = GlobalHashTable<long,long,&kahan_hash>::create(FLAGS_global_hash_size);

    for (int i=0; i<FLAGS_ntrials; i++) {
      ght_insert_time += test_insert_throughput<Exp::INSERT_UNIQUE>(ha);
    }

    ha->destroy();

  } else if (FLAGS_set_perf) {
    for (int i=0; i<FLAGS_ntrials; i++) {
      hashset_insert_time += test_set_insert_throughput();
    }
  } else {
    test_correctness();
    test_set_correctness();
  }

  Statistics::merge_and_print();
}

BOOST_AUTO_TEST_CASE( test1 ) {
  Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
                &(boost::unit_test::framework::master_test_suite().argv) );
  Grappa_activate();
  Grappa_run_user_main( &user_main, (void*)NULL );
  Grappa_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();

<commit_msg>Add option to test GHS insert_async<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#include <boost/test/unit_test.hpp>
#include "Grappa.hpp"
#include "ParallelLoop.hpp"
#include "GlobalAllocator.hpp"
#include "Delegate.hpp"
#include "GlobalHashTable.hpp"
#include "GlobalHashSet.hpp"
#include "Statistics.hpp"

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>

using namespace Grappa;

BOOST_AUTO_TEST_SUITE( GlobalHashTable_tests );

DEFINE_int64(nelems, 100, "number of elements in (large) test arrays");
DEFINE_int64(global_hash_size, 1024, "number of elements in (large) test arrays");
DEFINE_int64(max_key, 1<<10, "maximum random key");

DEFINE_int64(ntrials, 1, "number of independent trials to average over");

DEFINE_bool(table_perf, false, "do performance test of GlobalHashTable");
DEFINE_bool(set_perf, false, "do performance test of GlobalHashSet");

DEFINE_bool(insert_async, false, "do async inserts");

GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, ght_insert_time, 0);
GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, hashset_insert_time, 0);

template< typename T >
inline T next_random() {
  using engine_t = boost::mt19937_64;
  using dist_t = boost::uniform_int<T>;
  using gen_t = boost::variate_generator<engine_t&,dist_t>;

  // continue using same generator with multiple calls (to not repeat numbers)
  // but start at different seed on each node so we don't get overlap
  static engine_t engine(12345L*mycore());
  static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max()));
  return gen();
}

uint64_t kahan_hash(long k) { return k * 1299227; } // "Kahan's Hash"
uint64_t identity_hash(long k) { return k; }

enum class Exp { INSERT_UNIQUE };

template< Exp EXP,
          typename K, typename V, uint64_t (*H)(K),
          CompletionEvent* CE = &impl::local_ce,
          int64_t          TH = impl::USE_LOOP_THRESHOLD_FLAG >
double test_insert_throughput(GlobalAddress<GlobalHashTable<K,V,H>> ha) {
  double t = Grappa_walltime();

  forall_global_private<CE,TH>(0, FLAGS_nelems, [ha](int64_t i){
    if (EXP == Exp::INSERT_UNIQUE) {
      ha->insert_unique(next_random<long>());
    }
  });

  t = Grappa_walltime() - t;
  return t;
}

void test_correctness() {
  LOG(INFO) << "Testing correctness...";
  auto ha = GlobalHashTable<long,long,&identity_hash>::create(FLAGS_global_hash_size);
  for (int i=0; i<10; i++) {
    ha->insert(i, 42);
  }
  ha->global_set_RO();
  for (int i=0; i<10; i++) {
    GlobalAddress<long> res;
    BOOST_CHECK_EQUAL(ha->lookup(i, &res), 1);
    BOOST_CHECK_EQUAL(delegate::read(res), 42);
  }

  ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); });

  forall_global_private(10, FLAGS_nelems-10, [ha](int64_t i){
    ha->insert(i, 42);
  });
  ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); });

  ha->forall_entries([](long key, BufferVector<long>& vals){
    BOOST_CHECK_EQUAL(vals.size(), 1);
    auto a = vals.getReadBuffer();
    BOOST_CHECK_EQUAL(a.core(), mycore());
    BOOST_CHECK_EQUAL(delegate::read(a), 42);
  });

  ha->destroy();
}

void test_set_correctness() {
  LOG(INFO) << "Testing correctness of GlobalHashSet...";
  auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size);

  for (int i=0; i<10; i++) {
    // BOOST_CHECK_EQUAL(sa->insert(i), false);
    sa->insert(42+i);
  }
  for (int i=0; i<10; i++) {
    // BOOST_CHECK_EQUAL(sa->insert(i), true);
    BOOST_CHECK_EQUAL(sa->lookup(42+i), true);
  }

  on_all_cores([sa]{
    for (int i=10; i<20; i++) {
      sa->insert(42+i);
    }
  });

  sa->forall_keys([](long& k) { BOOST_CHECK(k < 42+20 && k >= 42); });

  BOOST_CHECK_EQUAL(sa->size(), 20);
  sa->destroy();
}

CompletionEvent lce;

double test_set_insert_throughput() {
  auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size);

  double t = walltime();

  if (FLAGS_insert_async) {
    forall_global_private<&lce>(0, FLAGS_nelems, [sa](int64_t i){
      auto k = next_random<long>() % FLAGS_max_key;
      lce.enroll();
      sa->insert_async(k, []{ lce.complete(); });
    });
    sa->sync_all_cores();
  } else {
    forall_global_private(0, FLAGS_nelems, [sa](int64_t i){
      auto k = next_random<long>() % FLAGS_max_key;
      sa->insert(k);
    });
  }

  t = walltime() - t;

  VLOG(1) << "set_size: " << sa->size();
  sa->destroy();
  return t;
}

void user_main( void * ignore ) {
  if (FLAGS_table_perf) {
    auto ha = GlobalHashTable<long,long,&kahan_hash>::create(FLAGS_global_hash_size);

    for (int i=0; i<FLAGS_ntrials; i++) {
      ght_insert_time += test_insert_throughput<Exp::INSERT_UNIQUE>(ha);
    }

    ha->destroy();

  } else if (FLAGS_set_perf) {
    for (int i=0; i<FLAGS_ntrials; i++) {
      hashset_insert_time += test_set_insert_throughput();
    }
  } else {
    test_correctness();
    test_set_correctness();
  }

  Statistics::merge_and_print();
}

BOOST_AUTO_TEST_CASE( test1 ) {
  Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
                &(boost::unit_test::framework::master_test_suite().argv) );
  Grappa_activate();
  Grappa_run_user_main( &user_main, (void*)NULL );
  Grappa_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();

<|endoftext|>


<commit_before>#ifndef __SNOWMAN_HPP__
#define __SNOWMAN_HPP__

#include <stdexcept>
#include <vector>
#include <string>
#include <map>

struct Variable;

typedef bool tUndefined;
typedef double tNum;
typedef std::vector<Variable> tArray;
typedef std::string tBlock;

typedef tArray::size_type vvs;
typedef tBlock::size_type ss;

class SnowmanException: public std::runtime_error {
    public:
        SnowmanException(std::string msg = "Snowman error occurred",
                bool fatal = false): std::runtime_error(msg), fatal(fatal) {}
        bool fatal;
};

struct Variable {
    // constructors
    Variable(): undefinedVal(true) { type = UNDEFINED; }
    Variable(tUndefined x): undefinedVal(x) { type = UNDEFINED; }
    Variable(tNum x): numVal(x) { type = NUM; }
    Variable(tArray* x): arrayVal(x) { type = ARRAY; }
    Variable(tBlock* x): blockVal(x) { type = BLOCK; }

    // destructor
    ~Variable() {}

    // copy constructor
    Variable(const Variable& v) {
        switch (v.type) {
        case UNDEFINED: type = UNDEFINED; undefinedVal = false; break;
        case NUM: type = NUM; numVal = v.numVal; break;
        case ARRAY: type = ARRAY; arrayVal = new tArray(*v.arrayVal); break;
        case BLOCK: type = BLOCK; blockVal = new tBlock(*v.blockVal); break;
        }
    }

    // assignment operator
    Variable& operator=(const Variable& v) {
        switch (v.type) {
        case UNDEFINED: type = UNDEFINED; undefinedVal = false; break;
        case NUM: type = NUM; numVal = v.numVal; break;
        case ARRAY: type = ARRAY; arrayVal = new tArray(*v.arrayVal); break;
        case BLOCK: type = BLOCK; blockVal = new tBlock(*v.blockVal); break;
        }
        return *this;
    }

    // operators
    bool operator==(const Variable& v) const {
        if (type != v.type) return false;
        switch (v.type) {
        case UNDEFINED: return true;
        case NUM: return numVal == v.numVal;
        case ARRAY: return arrayVal == v.arrayVal;
        case BLOCK: return blockVal == v.blockVal;
        default: throw SnowmanException("at Variable::operator==: impossible"
                    "type?", true);
        }
    }
    bool operator<(const Variable& v) const {
        if (type != v.type) return type < v.type;
        switch (v.type) {
        case UNDEFINED: return false;
        case NUM: return numVal < v.numVal;
        case ARRAY: return arrayVal < v.arrayVal;
        case BLOCK: return blockVal < v.blockVal;
        default: throw SnowmanException("at Variable::operator<: impossible"
                     "type?", true);
        }
    }

    // manage memory (use when modifying value)
    // BE VERY CAREFUL when calling this function
    void mm() {
        switch (type) {
        case ARRAY: delete arrayVal; break;
        case BLOCK: delete blockVal; break;
        default: break;
        }
    }

    // the actual data
    enum { UNDEFINED, NUM, ARRAY, BLOCK } type;
    union {
        tUndefined undefinedVal;
        tNum numVal;
        tArray* arrayVal;
        tBlock* blockVal;
    };
};

// used for subroutines
struct VarState {
    Variable vars[8];
    bool activeVars[8];
};

class Snowman {
    private:
        // internal evaluation methods
        void evalToken(std::string token);
        void store(Variable v);
        Variable retrieve(int type, bool consume = true, int skip = 0);

        template<typename T = tUndefined, typename U = tUndefined,
            typename V = tUndefined, typename W = tUndefined> class Retrieval{};

        // utility methods having to do with the language itself
        static std::string arrToString(tArray arr);
        static Variable stringToArr(std::string str);
        static std::string inspect(Variable str);
        static bool toBool(Variable v);

        // command line args
        tArray args;

        // variables and permavars
        Variable vars[8];
        bool activeVars[8];
        std::vector<VarState> subroutines;
        std::map<int, Variable> permavars;
        int activePermavar;
        bool savedActiveState[8];

    public:
        // constructor / destructor
        Snowman();
        ~Snowman();

        // for manipulating a string of code
        static std::vector<std::string> tokenize(std::string code);
        void run(std::string code);

        // command line args
        void addArg(std::string arg);

        // debugging (also used for REPL)
        std::string debug();
        bool debugOutput;

        // version
        const static int MAJOR_VERSION = 1;
        const static int MINOR_VERSION = 0;
        const static int PATCH_VERSION = 1;
};

#endif
<commit_msg>release 1.0.2<commit_after>#ifndef __SNOWMAN_HPP__
#define __SNOWMAN_HPP__

#include <stdexcept>
#include <vector>
#include <string>
#include <map>

struct Variable;

typedef bool tUndefined;
typedef double tNum;
typedef std::vector<Variable> tArray;
typedef std::string tBlock;

typedef tArray::size_type vvs;
typedef tBlock::size_type ss;

class SnowmanException: public std::runtime_error {
    public:
        SnowmanException(std::string msg = "Snowman error occurred",
                bool fatal = false): std::runtime_error(msg), fatal(fatal) {}
        bool fatal;
};

struct Variable {
    // constructors
    Variable(): undefinedVal(true) { type = UNDEFINED; }
    Variable(tUndefined x): undefinedVal(x) { type = UNDEFINED; }
    Variable(tNum x): numVal(x) { type = NUM; }
    Variable(tArray* x): arrayVal(x) { type = ARRAY; }
    Variable(tBlock* x): blockVal(x) { type = BLOCK; }

    // destructor
    ~Variable() {}

    // copy constructor
    Variable(const Variable& v) {
        switch (v.type) {
        case UNDEFINED: type = UNDEFINED; undefinedVal = false; break;
        case NUM: type = NUM; numVal = v.numVal; break;
        case ARRAY: type = ARRAY; arrayVal = new tArray(*v.arrayVal); break;
        case BLOCK: type = BLOCK; blockVal = new tBlock(*v.blockVal); break;
        }
    }

    // assignment operator
    Variable& operator=(const Variable& v) {
        switch (v.type) {
        case UNDEFINED: type = UNDEFINED; undefinedVal = false; break;
        case NUM: type = NUM; numVal = v.numVal; break;
        case ARRAY: type = ARRAY; arrayVal = new tArray(*v.arrayVal); break;
        case BLOCK: type = BLOCK; blockVal = new tBlock(*v.blockVal); break;
        }
        return *this;
    }

    // operators
    bool operator==(const Variable& v) const {
        if (type != v.type) return false;
        switch (v.type) {
        case UNDEFINED: return true;
        case NUM: return numVal == v.numVal;
        case ARRAY: return arrayVal == v.arrayVal;
        case BLOCK: return blockVal == v.blockVal;
        default: throw SnowmanException("at Variable::operator==: impossible"
                    "type?", true);
        }
    }
    bool operator<(const Variable& v) const {
        if (type != v.type) return type < v.type;
        switch (v.type) {
        case UNDEFINED: return false;
        case NUM: return numVal < v.numVal;
        case ARRAY: return arrayVal < v.arrayVal;
        case BLOCK: return blockVal < v.blockVal;
        default: throw SnowmanException("at Variable::operator<: impossible"
                     "type?", true);
        }
    }

    // manage memory (use when modifying value)
    // BE VERY CAREFUL when calling this function
    void mm() {
        switch (type) {
        case ARRAY: delete arrayVal; break;
        case BLOCK: delete blockVal; break;
        default: break;
        }
    }

    // the actual data
    enum { UNDEFINED, NUM, ARRAY, BLOCK } type;
    union {
        tUndefined undefinedVal;
        tNum numVal;
        tArray* arrayVal;
        tBlock* blockVal;
    };
};

// used for subroutines
struct VarState {
    Variable vars[8];
    bool activeVars[8];
};

class Snowman {
    private:
        // internal evaluation methods
        void evalToken(std::string token);
        void store(Variable v);
        Variable retrieve(int type, bool consume = true, int skip = 0);

        template<typename T = tUndefined, typename U = tUndefined,
            typename V = tUndefined, typename W = tUndefined> class Retrieval{};

        // utility methods having to do with the language itself
        static std::string arrToString(tArray arr);
        static Variable stringToArr(std::string str);
        static std::string inspect(Variable str);
        static bool toBool(Variable v);

        // command line args
        tArray args;

        // variables and permavars
        Variable vars[8];
        bool activeVars[8];
        std::vector<VarState> subroutines;
        std::map<int, Variable> permavars;
        int activePermavar;
        bool savedActiveState[8];

    public:
        // constructor / destructor
        Snowman();
        ~Snowman();

        // for manipulating a string of code
        static std::vector<std::string> tokenize(std::string code);
        void run(std::string code);

        // command line args
        void addArg(std::string arg);

        // debugging (also used for REPL)
        std::string debug();
        bool debugOutput;

        // version
        const static int MAJOR_VERSION = 1;
        const static int MINOR_VERSION = 0;
        const static int PATCH_VERSION = 2;
};

#endif
<|endoftext|>


<commit_before>#ifndef __SNOWMAN_HPP__
#define __SNOWMAN_HPP__

#include <stdexcept>
#include <vector>
#include <string>
#include <map>

struct Variable;

typedef std::vector<Variable>::size_type vvs;
typedef std::string::size_type ss;

class SnowmanException: public std::runtime_error {
    public:
        SnowmanException(std::string msg = "Snowman error occurred",
                bool fatal = false): std::runtime_error(msg), fatal(fatal) {}
        bool fatal;
};

struct Variable {
    // constructors
    Variable(): undefinedVal(true) { type = UNDEFINED; }
    Variable(bool x): undefinedVal(x) { type = UNDEFINED; }
    Variable(double x): numVal(x) { type = NUM; }
    Variable(std::vector<Variable>* x): arrayVal(x) { type = ARRAY; }
    Variable(std::string* x): blockVal(x) { type = BLOCK; }

    // destructor
    ~Variable() {}

    // copy constructor
    Variable(const Variable& v) {
        switch (v.type) {
        case UNDEFINED: type = UNDEFINED; undefinedVal = false; break;
        case NUM: type = NUM; numVal = v.numVal; break;
        case ARRAY: type = ARRAY; arrayVal = new std::vector<Variable>(*v.arrayVal); break;
        case BLOCK: type = BLOCK; blockVal = new std::string(*v.blockVal); break;
        }
    }

    // operators
    bool operator==(const Variable& v) const {
        if (type != v.type) return false;
        switch (v.type) {
        case UNDEFINED: return true;
        case NUM: return numVal == v.numVal;
        case ARRAY: return arrayVal == v.arrayVal;
        case BLOCK: return blockVal == v.blockVal;
        default: throw SnowmanException("at Variable::operator==: impossible"
                    "type?", true);
        }
    }
    bool operator<(const Variable& v) const {
        if (type != v.type) return type < v.type;
        switch (v.type) {
        case UNDEFINED: return false;
        case NUM: return numVal < v.numVal;
        case ARRAY: return arrayVal < v.arrayVal;
        case BLOCK: return blockVal < v.blockVal;
        default: throw SnowmanException("at Variable::operator<: impossible"
                     "type?", true);
        }
    }

    // manage memory (use when modifying value)
    // BE VERY CAREFUL when calling this function
    void mm() {
        switch (type) {
        case ARRAY: delete arrayVal; break;
        case BLOCK: delete blockVal; break;
        default: break;
        }
    }

    // the actual data
    enum { UNDEFINED, NUM, ARRAY, BLOCK } type;
    union {
        bool undefinedVal;
        double numVal;
        std::vector<Variable>* arrayVal;
        std::string* blockVal;
    };
};

// used for subroutines
struct VarState {
    Variable vars[8];
    bool activeVars[8];
};

class Snowman {
    private:
        // internal evaluation methods
        void evalToken(std::string token);
        void store(Variable v);
        std::vector<Variable> retrieve(int type, vvs count = 1, bool consume =
            true, int skip = 0, bool doNotDelete = false);

        // utility methods having to do with the language itself
        static std::string arrToString(Variable arr);
        static Variable stringToArr(std::string str);
        static std::string inspect(Variable str);
        static bool toBool(Variable v);

        // command line args
        std::vector<Variable> args;

        // variables and permavars
        Variable vars[8];
        bool activeVars[8];
        std::vector<VarState> subroutines;
        std::map<int, Variable> permavars;
        int activePermavar;
        bool savedActiveState[8];

        // ugly, ugly "garbage collector"
        std::vector<Variable> gc;

    public:
        // constructor / destructor
        Snowman();
        ~Snowman();

        // for manipulating a string of code
        static std::vector<std::string> tokenize(std::string code);
        void run(std::string code);

        // command line args
        void addArg(std::string arg);

        // debugging (also used for REPL)
        std::string debug();
        bool debugOutput;

        // version
        const static int MAJOR_VERSION = 1;
        const static int MINOR_VERSION = 0;
        const static int PATCH_VERSION = 0;
};

#endif
<commit_msg>release 1.0.1<commit_after>#ifndef __SNOWMAN_HPP__
#define __SNOWMAN_HPP__

#include <stdexcept>
#include <vector>
#include <string>
#include <map>

struct Variable;

typedef std::vector<Variable>::size_type vvs;
typedef std::string::size_type ss;

class SnowmanException: public std::runtime_error {
    public:
        SnowmanException(std::string msg = "Snowman error occurred",
                bool fatal = false): std::runtime_error(msg), fatal(fatal) {}
        bool fatal;
};

struct Variable {
    // constructors
    Variable(): undefinedVal(true) { type = UNDEFINED; }
    Variable(bool x): undefinedVal(x) { type = UNDEFINED; }
    Variable(double x): numVal(x) { type = NUM; }
    Variable(std::vector<Variable>* x): arrayVal(x) { type = ARRAY; }
    Variable(std::string* x): blockVal(x) { type = BLOCK; }

    // destructor
    ~Variable() {}

    // copy constructor
    Variable(const Variable& v) {
        switch (v.type) {
        case UNDEFINED: type = UNDEFINED; undefinedVal = false; break;
        case NUM: type = NUM; numVal = v.numVal; break;
        case ARRAY: type = ARRAY; arrayVal = new std::vector<Variable>(*v.arrayVal); break;
        case BLOCK: type = BLOCK; blockVal = new std::string(*v.blockVal); break;
        }
    }

    // operators
    bool operator==(const Variable& v) const {
        if (type != v.type) return false;
        switch (v.type) {
        case UNDEFINED: return true;
        case NUM: return numVal == v.numVal;
        case ARRAY: return arrayVal == v.arrayVal;
        case BLOCK: return blockVal == v.blockVal;
        default: throw SnowmanException("at Variable::operator==: impossible"
                    "type?", true);
        }
    }
    bool operator<(const Variable& v) const {
        if (type != v.type) return type < v.type;
        switch (v.type) {
        case UNDEFINED: return false;
        case NUM: return numVal < v.numVal;
        case ARRAY: return arrayVal < v.arrayVal;
        case BLOCK: return blockVal < v.blockVal;
        default: throw SnowmanException("at Variable::operator<: impossible"
                     "type?", true);
        }
    }

    // manage memory (use when modifying value)
    // BE VERY CAREFUL when calling this function
    void mm() {
        switch (type) {
        case ARRAY: delete arrayVal; break;
        case BLOCK: delete blockVal; break;
        default: break;
        }
    }

    // the actual data
    enum { UNDEFINED, NUM, ARRAY, BLOCK } type;
    union {
        bool undefinedVal;
        double numVal;
        std::vector<Variable>* arrayVal;
        std::string* blockVal;
    };
};

// used for subroutines
struct VarState {
    Variable vars[8];
    bool activeVars[8];
};

class Snowman {
    private:
        // internal evaluation methods
        void evalToken(std::string token);
        void store(Variable v);
        std::vector<Variable> retrieve(int type, vvs count = 1, bool consume =
            true, int skip = 0, bool doNotDelete = false);

        // utility methods having to do with the language itself
        static std::string arrToString(Variable arr);
        static Variable stringToArr(std::string str);
        static std::string inspect(Variable str);
        static bool toBool(Variable v);

        // command line args
        std::vector<Variable> args;

        // variables and permavars
        Variable vars[8];
        bool activeVars[8];
        std::vector<VarState> subroutines;
        std::map<int, Variable> permavars;
        int activePermavar;
        bool savedActiveState[8];

        // ugly, ugly "garbage collector"
        std::vector<Variable> gc;

    public:
        // constructor / destructor
        Snowman();
        ~Snowman();

        // for manipulating a string of code
        static std::vector<std::string> tokenize(std::string code);
        void run(std::string code);

        // command line args
        void addArg(std::string arg);

        // debugging (also used for REPL)
        std::string debug();
        bool debugOutput;

        // version
        const static int MAJOR_VERSION = 1;
        const static int MINOR_VERSION = 0;
        const static int PATCH_VERSION = 1;
};

#endif
<|endoftext|>


<commit_before>#include "CPU.h"
#if defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
#endif
#include "Log.h"
namespace i2p
{
namespace cpu
{
	bool aesni = false;
	bool avx = false;

	void Detect()
	{
#if defined(__x86_64__) || defined(__i386__)
		int info[4];
		__cpuid(0, info[0], info[1], info[2], info[3]);
		if (info[0] >= 0x00000001) {
			__cpuid(0x00000001, info[0], info[1], info[2], info[3]);
			aesni = info[2] & bit_AES;  // AESNI
			avx = info[2] & bit_AVX;  // AVX
		}
#endif
		if(aesni)
		{
			LogPrint(eLogInfo, "AESNI enabled");
		}
		if(avx)
		{
			LogPrint(eLogInfo, "AVX enabled");
		}
	}
}
}
<commit_msg>define cpu_* if not set<commit_after>#include "CPU.h"
#if defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
#endif
#include "Log.h"

#ifndef bit_AES
#define bit_AES (1 << 25)
#endif
#ifndef bit_AVX
#define bit_AVX (1 << 28)
#endif

namespace i2p
{
namespace cpu
{
	bool aesni = false;
	bool avx = false;

	void Detect()
	{
#if defined(__x86_64__) || defined(__i386__)
		int info[4];
		__cpuid(0, info[0], info[1], info[2], info[3]);
		if (info[0] >= 0x00000001) {
			__cpuid(0x00000001, info[0], info[1], info[2], info[3]);
			aesni = info[2] & bit_AES;  // AESNI
			avx = info[2] & bit_AVX;  // AVX
		}
#endif
		if(aesni)
		{
			LogPrint(eLogInfo, "AESNI enabled");
		}
		if(avx)
		{
			LogPrint(eLogInfo, "AVX enabled");
		}
	}
}
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////
// OBJ.cpp
//
// Copyright 2007 cDc@seacave
// Distributed under the Boost Software License, Version 1.0
// (See http://www.boost.org/LICENSE_1_0.txt)

#include "Common.h"
#include "OBJ.h"

using namespace SEACAVE;

// D E F I N E S ///////////////////////////////////////////////////

// uncomment to enable multi-threading based on OpenMP
#ifdef _USE_OPENMP
#define OBJ_USE_OPENMP
#endif

#define OBJ_INDEX_OFFSET 1

// S T R U C T S ///////////////////////////////////////////////////

ObjModel::MaterialLib::Material::Material(const Image8U3& _diffuse_map, const Color& _Kd)
	:
	diffuse_map(_diffuse_map),
	Kd(_Kd)
{
}

bool ObjModel::MaterialLib::Material::LoadDiffuseMap()
{
	if (diffuse_map.empty())
		return diffuse_map.Load(diffuse_name);
	return true;
}
/*----------------------------------------------------------------*/

// S T R U C T S ///////////////////////////////////////////////////

ObjModel::MaterialLib::MaterialLib()
{
}

bool ObjModel::MaterialLib::Save(const String& prefix, bool texLossless) const
{
	std::ofstream out((prefix+".mtl").c_str());
	if (!out.good())
		return false;

	const String pathName(Util::getFilePath(prefix));
	const String name(Util::getFileNameExt(prefix));
	#ifdef OBJ_USE_OPENMP
	bool bSuccess(true);
	#pragma omp parallel for
	#endif
	for (int_t i = 0; i < (int_t)materials.size(); ++i) {
		const Material& mat = materials[i];
		// save material description
		out << "newmtl " << mat.name << "\n"
			<< "Ka 1.000000 1.000000 1.000000" << "\n"
			<< "Kd " << mat.Kd.r << " " << mat.Kd.g << " " << mat.Kd.b << "\n"
			<< "Ks 0.000000 0.000000 0.000000" << "\n"
			<< "Tr 1.000000" << "\n"
			<< "illum 1" << "\n"
			<< "Ns 1.000000" << "\n";
		// save material maps
		if (mat.diffuse_map.empty())
			continue;
		if (mat.diffuse_name.IsEmpty())
			const_cast<String&>(mat.diffuse_name) = name+"_"+mat.name+"_map_Kd."+(texLossless?"png":"jpg");
		out << "map_Kd " << mat.diffuse_name << "\n";
		const bool bRet(mat.diffuse_map.Save(pathName+mat.diffuse_name));
		#ifdef OBJ_USE_OPENMP
		#pragma omp critical
		if (!bRet)
			bSuccess = false;
		#else
		if (!bRet)
			return false;
		#endif
	}
	#ifdef OBJ_USE_OPENMP
	return bSuccess;
	#else
	return true;
	#endif
}

bool ObjModel::MaterialLib::Load(const String& fileName)
{
	const size_t numMaterials(materials.size());
	std::ifstream in(fileName.c_str());
	String keyword;
	while (in.good() && in >> keyword) {
		if (keyword == "newmtl") {
			in >> keyword;
			materials.push_back(Material(keyword));
		} else if (keyword == "Kd") {
			ASSERT(numMaterials < materials.size());
			Color c;
			in >> c.r >> c.g >> c.b;
			materials.back().Kd = c;
		} else if (keyword == "map_Kd") {
			ASSERT(numMaterials < materials.size());
			String& diffuse_name = materials.back().diffuse_name;
			in >> diffuse_name;
			diffuse_name = Util::getFilePath(fileName) + diffuse_name;
		}
	}
	return numMaterials < materials.size();
}
/*----------------------------------------------------------------*/

// S T R U C T S ///////////////////////////////////////////////////

bool ObjModel::Save(const String& fileName, unsigned precision, bool texLossless) const
{
	if (vertices.empty())
		return false;
	const String prefix(Util::getFileFullName(fileName));
	const String name(Util::getFileNameExt(prefix));

	if (!material_lib.Save(prefix, texLossless))
		return false;

	std::ofstream out((prefix + ".obj").c_str());
	if (!out.good())
		return false;

	out << "mtllib " << name << ".mtl" << "\n";

	out << std::fixed << std::setprecision(precision);
	for (size_t i = 0; i < vertices.size(); ++i) {
		out << "v "
			<< vertices[i][0] << " "
			<< vertices[i][1] << " "
			<< vertices[i][2] << "\n";
	}

	for (size_t i = 0; i < texcoords.size(); ++i) {
		out << "vt "
			<< texcoords[i][0] << " "
			<< texcoords[i][1] << "\n";
	}

	for (size_t i = 0; i < normals.size(); ++i) {
		out << "vn "
			<< normals[i][0] << " "
			<< normals[i][1] << " "
			<< normals[i][2] << "\n";
	}

	for (size_t i = 0; i < groups.size(); ++i) {
		out << "usemtl " << groups[i].material_name << "\n";
		for (size_t j = 0; j < groups[i].faces.size(); ++j) {
			const Face& face =  groups[i].faces[j];
			out << "f";
			for (size_t k = 0; k < 3; ++k) {
				out << " " << face.vertices[k]  + OBJ_INDEX_OFFSET;
				if (!texcoords.empty()) {
					out << "/" << face.texcoords[k]  + OBJ_INDEX_OFFSET;
					if (!normals.empty())
						out << "/" << face.normals[k]  + OBJ_INDEX_OFFSET;
				} else
				if (!normals.empty())
					out << "//" << face.normals[k]  + OBJ_INDEX_OFFSET;
			}
			out << "\n";
		}
	}
	return true;
}

bool ObjModel::Load(const String& fileName)
{
	ASSERT(vertices.empty() && groups.empty() && material_lib.materials.empty());
	std::ifstream fin(fileName.c_str());
	String line, keyword;
	std::istringstream in;
	while (fin.good()) {
		std::getline(fin, line);
		if (line.empty() || line[0u] == '#')
			continue;
		in.str(line);
		in >> keyword;
		if (keyword == "v") {
			Vertex v;
			in >> v[0] >> v[1] >> v[2];
			if (in.fail())
				return false;
			vertices.push_back(v);
		} else
		if (keyword == "vt") {
			TexCoord vt;
			in >> vt[0] >> vt[1];
			if (in.fail())
				return false;
			texcoords.push_back(vt);
		} else
		if (keyword == "vn") {
			Normal vn;
			in >> vn[0] >> vn[1] >> vn[2];
			if (in.fail())
				return false;
			normals.push_back(vn);
		} else
		if (keyword == "f") {
			Face f;
			memset(&f, 0xFF, sizeof(Face));
			for (size_t k = 0; k < 3; ++k) {
				in >> keyword;
				switch (sscanf(keyword, "%u/%u/%u", f.vertices+k, f.texcoords+k, f.normals+k)) {
				case 1:
					f.vertices[k] -= OBJ_INDEX_OFFSET;
					break;
				case 2:
					f.vertices[k] -= OBJ_INDEX_OFFSET;
					if (f.texcoords[k] != NO_ID)
						f.texcoords[k] -= OBJ_INDEX_OFFSET;
					if (f.normals[k] != NO_ID)
						f.normals[k] -= OBJ_INDEX_OFFSET;
					break;
				case 3:
					f.vertices[k] -= OBJ_INDEX_OFFSET;
					f.texcoords[k] -= OBJ_INDEX_OFFSET;
					f.normals[k] -= OBJ_INDEX_OFFSET;
					break;
				default:
					return false;
				}
			}
			if (in.fail())
				return false;
			groups.back().faces.push_back(f);
		} else
		if (keyword == "mtllib") {
			in >> keyword;
			if (!material_lib.Load(keyword))
				return false;
		} else
		if (keyword == "usemtl") {
			Group group;
			in >> group.material_name;
			if (in.fail())
				return false;
			groups.push_back(group);
		}
		in.clear();
	}
	return !vertices.empty();
}

ObjModel::Group& ObjModel::AddGroup(const String& material_name)
{
	groups.push_back(Group());
	Group& group = groups.back();
	group.material_name = material_name;
	if (!GetMaterial(material_name))
		material_lib.materials.push_back(MaterialLib::Material(material_name));
	return group;
}

ObjModel::MaterialLib::Material* ObjModel::GetMaterial(const String& name)
{
	MaterialLib::Materials::iterator it(std::find_if(material_lib.materials.begin(), material_lib.materials.end(), [&name](const MaterialLib::Material& mat) { return mat.name == name; }));
	if (it == material_lib.materials.end())
		return NULL;
	return &(*it);
}
/*----------------------------------------------------------------*/
<commit_msg>io: fix read obj without material<commit_after>////////////////////////////////////////////////////////////////////
// OBJ.cpp
//
// Copyright 2007 cDc@seacave
// Distributed under the Boost Software License, Version 1.0
// (See http://www.boost.org/LICENSE_1_0.txt)

#include "Common.h"
#include "OBJ.h"

using namespace SEACAVE;

// D E F I N E S ///////////////////////////////////////////////////

// uncomment to enable multi-threading based on OpenMP
#ifdef _USE_OPENMP
#define OBJ_USE_OPENMP
#endif

#define OBJ_INDEX_OFFSET 1

// S T R U C T S ///////////////////////////////////////////////////

ObjModel::MaterialLib::Material::Material(const Image8U3& _diffuse_map, const Color& _Kd)
	:
	diffuse_map(_diffuse_map),
	Kd(_Kd)
{
}

bool ObjModel::MaterialLib::Material::LoadDiffuseMap()
{
	if (diffuse_map.empty())
		return diffuse_map.Load(diffuse_name);
	return true;
}
/*----------------------------------------------------------------*/

// S T R U C T S ///////////////////////////////////////////////////

ObjModel::MaterialLib::MaterialLib()
{
}

bool ObjModel::MaterialLib::Save(const String& prefix, bool texLossless) const
{
	std::ofstream out((prefix+".mtl").c_str());
	if (!out.good())
		return false;

	const String pathName(Util::getFilePath(prefix));
	const String name(Util::getFileNameExt(prefix));
	#ifdef OBJ_USE_OPENMP
	bool bSuccess(true);
	#pragma omp parallel for
	#endif
	for (int_t i = 0; i < (int_t)materials.size(); ++i) {
		const Material& mat = materials[i];
		// save material description
		out << "newmtl " << mat.name << "\n"
			<< "Ka 1.000000 1.000000 1.000000" << "\n"
			<< "Kd " << mat.Kd.r << " " << mat.Kd.g << " " << mat.Kd.b << "\n"
			<< "Ks 0.000000 0.000000 0.000000" << "\n"
			<< "Tr 1.000000" << "\n"
			<< "illum 1" << "\n"
			<< "Ns 1.000000" << "\n";
		// save material maps
		if (mat.diffuse_map.empty())
			continue;
		if (mat.diffuse_name.IsEmpty())
			const_cast<String&>(mat.diffuse_name) = name+"_"+mat.name+"_map_Kd."+(texLossless?"png":"jpg");
		out << "map_Kd " << mat.diffuse_name << "\n";
		const bool bRet(mat.diffuse_map.Save(pathName+mat.diffuse_name));
		#ifdef OBJ_USE_OPENMP
		#pragma omp critical
		if (!bRet)
			bSuccess = false;
		#else
		if (!bRet)
			return false;
		#endif
	}
	#ifdef OBJ_USE_OPENMP
	return bSuccess;
	#else
	return true;
	#endif
}

bool ObjModel::MaterialLib::Load(const String& fileName)
{
	const size_t numMaterials(materials.size());
	std::ifstream in(fileName.c_str());
	String keyword;
	while (in.good() && in >> keyword) {
		if (keyword == "newmtl") {
			in >> keyword;
			materials.push_back(Material(keyword));
		} else if (keyword == "Kd") {
			ASSERT(numMaterials < materials.size());
			Color c;
			in >> c.r >> c.g >> c.b;
			materials.back().Kd = c;
		} else if (keyword == "map_Kd") {
			ASSERT(numMaterials < materials.size());
			String& diffuse_name = materials.back().diffuse_name;
			in >> diffuse_name;
			diffuse_name = Util::getFilePath(fileName) + diffuse_name;
		}
	}
	return numMaterials < materials.size();
}
/*----------------------------------------------------------------*/

// S T R U C T S ///////////////////////////////////////////////////

bool ObjModel::Save(const String& fileName, unsigned precision, bool texLossless) const
{
	if (vertices.empty())
		return false;
	const String prefix(Util::getFileFullName(fileName));
	const String name(Util::getFileNameExt(prefix));

	if (!material_lib.Save(prefix, texLossless))
		return false;

	std::ofstream out((prefix + ".obj").c_str());
	if (!out.good())
		return false;

	out << "mtllib " << name << ".mtl" << "\n";

	out << std::fixed << std::setprecision(precision);
	for (size_t i = 0; i < vertices.size(); ++i) {
		out << "v "
			<< vertices[i][0] << " "
			<< vertices[i][1] << " "
			<< vertices[i][2] << "\n";
	}

	for (size_t i = 0; i < texcoords.size(); ++i) {
		out << "vt "
			<< texcoords[i][0] << " "
			<< texcoords[i][1] << "\n";
	}

	for (size_t i = 0; i < normals.size(); ++i) {
		out << "vn "
			<< normals[i][0] << " "
			<< normals[i][1] << " "
			<< normals[i][2] << "\n";
	}

	for (size_t i = 0; i < groups.size(); ++i) {
		out << "usemtl " << groups[i].material_name << "\n";
		for (size_t j = 0; j < groups[i].faces.size(); ++j) {
			const Face& face =  groups[i].faces[j];
			out << "f";
			for (size_t k = 0; k < 3; ++k) {
				out << " " << face.vertices[k]  + OBJ_INDEX_OFFSET;
				if (!texcoords.empty()) {
					out << "/" << face.texcoords[k]  + OBJ_INDEX_OFFSET;
					if (!normals.empty())
						out << "/" << face.normals[k]  + OBJ_INDEX_OFFSET;
				} else
				if (!normals.empty())
					out << "//" << face.normals[k]  + OBJ_INDEX_OFFSET;
			}
			out << "\n";
		}
	}
	return true;
}

bool ObjModel::Load(const String& fileName)
{
	ASSERT(vertices.empty() && groups.empty() && material_lib.materials.empty());
	std::ifstream fin(fileName.c_str());
	String line, keyword;
	std::istringstream in;
	while (fin.good()) {
		std::getline(fin, line);
		if (line.empty() || line[0u] == '#')
			continue;
		in.str(line);
		in >> keyword;
		if (keyword == "v") {
			Vertex v;
			in >> v[0] >> v[1] >> v[2];
			if (in.fail())
				return false;
			vertices.push_back(v);
		} else
		if (keyword == "vt") {
			TexCoord vt;
			in >> vt[0] >> vt[1];
			if (in.fail())
				return false;
			texcoords.push_back(vt);
		} else
		if (keyword == "vn") {
			Normal vn;
			in >> vn[0] >> vn[1] >> vn[2];
			if (in.fail())
				return false;
			normals.push_back(vn);
		} else
		if (keyword == "f") {
			Face f;
			memset(&f, 0xFF, sizeof(Face));
			for (size_t k = 0; k < 3; ++k) {
				in >> keyword;
				switch (sscanf(keyword, "%u/%u/%u", f.vertices+k, f.texcoords+k, f.normals+k)) {
				case 1:
					f.vertices[k] -= OBJ_INDEX_OFFSET;
					break;
				case 2:
					f.vertices[k] -= OBJ_INDEX_OFFSET;
					if (f.texcoords[k] != NO_ID)
						f.texcoords[k] -= OBJ_INDEX_OFFSET;
					if (f.normals[k] != NO_ID)
						f.normals[k] -= OBJ_INDEX_OFFSET;
					break;
				case 3:
					f.vertices[k] -= OBJ_INDEX_OFFSET;
					f.texcoords[k] -= OBJ_INDEX_OFFSET;
					f.normals[k] -= OBJ_INDEX_OFFSET;
					break;
				default:
					return false;
				}
			}
			if (in.fail())
				return false;
			if (groups.empty())
				AddGroup("");
			groups.back().faces.push_back(f);
		} else
		if (keyword == "mtllib") {
			in >> keyword;
			if (!material_lib.Load(keyword))
				return false;
		} else
		if (keyword == "usemtl") {
			Group group;
			in >> group.material_name;
			if (in.fail())
				return false;
			groups.push_back(group);
		}
		in.clear();
	}
	return !vertices.empty();
}

ObjModel::Group& ObjModel::AddGroup(const String& material_name)
{
	groups.push_back(Group());
	Group& group = groups.back();
	group.material_name = material_name;
	if (!GetMaterial(material_name))
		material_lib.materials.push_back(MaterialLib::Material(material_name));
	return group;
}

ObjModel::MaterialLib::Material* ObjModel::GetMaterial(const String& name)
{
	MaterialLib::Materials::iterator it(std::find_if(material_lib.materials.begin(), material_lib.materials.end(), [&name](const MaterialLib::Material& mat) { return mat.name == name; }));
	if (it == material_lib.materials.end())
		return NULL;
	return &(*it);
}
/*----------------------------------------------------------------*/
<|endoftext|>


<commit_before>#include "SM_Polyline.h"

#include <cavc/polylineoffset.hpp>

namespace sm
{

std::vector<std::vector<vec2>>
polyline_offset(const std::vector<vec2>& polyline, float distance, bool is_closed)
{
	cavc::Polyline<float> input;
	input.isClosed() = is_closed;

	const size_t n = is_closed ? polyline.size() - 1 : polyline.size();
	for (int i = 0; i < n; ++i) {
		input.addVertex(polyline[i].x, polyline[i].y, 0.0f);
	}

	auto results = cavc::parallelOffset(input, distance);

	std::vector<std::vector<vec2>> polylines;
	for (auto& src : results)
	{
		std::vector<vec2> dst;
		for (auto& pos : src.vertexes()) {
			dst.push_back(sm::vec2(pos.x(), pos.y()));
		}
		polylines.push_back(dst);
	}

	return polylines;
}

std::vector<std::vector<vec2>>
polyline_expand(const std::vector<vec2>& polyline, float offste, bool is_closed)
{
	std::vector<std::vector<sm::vec2>> ret;

	auto off0 = polyline_offset(polyline, offste, is_closed);
	auto off1 = polyline_offset(polyline, -offste, is_closed);

	if (off0.size() != off1.size() || off0.empty()) {
		return ret;
	}

	for (int i = 0, n = off0.size(); i < n; ++i)
	{
		auto off(off0[i]);
		std::copy(off1[i].rbegin(), off1[i].rend(), std::back_inserter(off));
		ret.push_back(off);
	}

	return ret;
}

}<commit_msg>fix poly_offset<commit_after>#include "SM_Polyline.h"

#include <cavc/polylineoffset.hpp>

namespace sm
{

std::vector<std::vector<vec2>>
polyline_offset(const std::vector<vec2>& polyline, float distance, bool is_closed)
{
	cavc::Polyline<float> input;
	input.isClosed() = is_closed;

	const size_t n = (is_closed && polyline.front() == polyline.back()) ?
		polyline.size() - 1 : polyline.size();
	for (int i = 0; i < n; ++i) {
		input.addVertex(polyline[i].x, polyline[i].y, 0.0f);
	}

	auto results = cavc::parallelOffset(input, distance);

	std::vector<std::vector<vec2>> polylines;
	for (auto& src : results)
	{
		std::vector<vec2> dst;
		for (auto& pos : src.vertexes()) {
			dst.push_back(sm::vec2(pos.x(), pos.y()));
		}
		polylines.push_back(dst);
	}

	return polylines;
}

std::vector<std::vector<vec2>>
polyline_expand(const std::vector<vec2>& polyline, float offste, bool is_closed)
{
	std::vector<std::vector<sm::vec2>> ret;

	auto off0 = polyline_offset(polyline, offste, is_closed);
	auto off1 = polyline_offset(polyline, -offste, is_closed);

	if (off0.size() != off1.size() || off0.empty()) {
		return ret;
	}

	for (int i = 0, n = off0.size(); i < n; ++i)
	{
		auto off(off0[i]);
		std::copy(off1[i].rbegin(), off1[i].rend(), std::back_inserter(off));
		ret.push_back(off);
	}

	return ret;
}

}<|endoftext|>