<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextMasterPageContext.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 18:46:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSTATES_HPP_
#include <com/sun/star/beans/XMultiPropertyStates.hpp>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_TEXTMASTERPAGECONTEXT_HXX_
#include "XMLTextMasterPageContext.hxx"
#endif
#ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_
#include "XMLTextHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX
#include "PageMasterImportContext.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//using namespace ::com::sun::star::text;
using namespace ::xmloff::token;

Reference < XStyle > XMLTextMasterPageContext::Create()
{
    Reference < XStyle > xNewStyle;

    Reference< XMultiServiceFactory > xFactory( GetImport().GetModel(),
                                                    UNO_QUERY );
    if( xFactory.is() )
    {
        Reference < XInterface > xIfc =
            xFactory->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM(
                                    "com.sun.star.style.PageStyle")) );
        if( xIfc.is() )
            xNewStyle = Reference < XStyle >( xIfc, UNO_QUERY );
    }

    return xNewStyle;
}
TYPEINIT1( XMLTextMasterPageContext, SvXMLStyleContext );

XMLTextMasterPageContext::XMLTextMasterPageContext( SvXMLImport& rImport,
        sal_uInt16 nPrfx, const OUString& rLName,
        const Reference< XAttributeList > & xAttrList,
        sal_Bool bOverwrite )
:   SvXMLStyleContext( rImport, nPrfx, rLName, xAttrList, XML_STYLE_FAMILY_MASTER_PAGE )
,   sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) )
,   sPageStyleLayout( RTL_CONSTASCII_USTRINGPARAM( "PageStyleLayout" ) )
,   sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) )
,   bInsertHeader( sal_False )
,   bInsertFooter( sal_False )
,   bInsertHeaderLeft( sal_False )
,   bInsertFooterLeft( sal_False )
,   bHeaderInserted( sal_False )
,   bFooterInserted( sal_False )
,   bHeaderLeftInserted( sal_False )
,   bFooterLeftInserted( sal_False )
{
    OUString sName, sDisplayName;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
        if( XML_NAMESPACE_STYLE == nPrefix )
        {
            if( IsXMLToken( aLocalName, XML_NAME ) )
            {
                sName = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_DISPLAY_NAME ) )
            {
                sDisplayName = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_NEXT_STYLE_NAME ) )
            {
                sFollow = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_PAGE_LAYOUT_NAME ) )
            {
                sPageMasterName = xAttrList->getValueByIndex( i );
            }
        }
    }

    if( sDisplayName.getLength() )
    {
        rImport.AddStyleDisplayName( XML_STYLE_FAMILY_MASTER_PAGE, sName,
                                     sDisplayName );
    }
    else
    {
        sDisplayName = sName;
    }

    if( 0 == sDisplayName.getLength() )
        return;

    Reference < XNameContainer > xPageStyles =
            GetImport().GetTextImport()->GetPageStyles();
    if( !xPageStyles.is() )
        return;

    Any aAny;
    sal_Bool bNew = sal_False;
    if( xPageStyles->hasByName( sDisplayName ) )
    {
        aAny = xPageStyles->getByName( sDisplayName );
        aAny >>= xStyle;
    }
    else
    {
        xStyle = Create();
        if( !xStyle.is() )
            return;

        aAny <<= xStyle;
        xPageStyles->insertByName( sDisplayName, aAny );
        bNew = sal_True;
    }

    Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo =
                xPropSet->getPropertySetInfo();
    if( !bNew && xPropSetInfo->hasPropertyByName( sIsPhysical ) )
    {
        aAny = xPropSet->getPropertyValue( sIsPhysical );
        bNew = !*(sal_Bool *)aAny.getValue();
    }
    SetNew( bNew );

    if( bOverwrite || bNew )
    {
        Reference < XMultiPropertyStates > xMultiStates( xPropSet,
                                                         UNO_QUERY );
        OSL_ENSURE( xMultiStates.is(),
                    "text page style does not support multi property set" );
        if( xMultiStates.is() )
            xMultiStates->setAllPropertiesToDefault();

        bInsertHeader = bInsertFooter = sal_True;
        bInsertHeaderLeft = bInsertFooterLeft = sal_True;
    }
}

XMLTextMasterPageContext::~XMLTextMasterPageContext()
{
}

SvXMLImportContext *XMLTextMasterPageContext::CreateChildContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    const SvXMLTokenMap& rTokenMap =
        GetImport().GetTextImport()->GetTextMasterPageElemTokenMap();

    sal_Bool bInsert = sal_False, bFooter = sal_False, bLeft = sal_False;
    switch( rTokenMap.Get( nPrefix, rLocalName ) )
    {
    case XML_TOK_TEXT_MP_HEADER:
        if( bInsertHeader && !bHeaderInserted )
        {
            bInsert = sal_True;
            bHeaderInserted = sal_True;
        }
        break;
    case XML_TOK_TEXT_MP_FOOTER:
        if( bInsertFooter && !bFooterInserted )
        {
            bInsert = bFooter = sal_True;
            bFooterInserted = sal_True;
        }
        break;
    case XML_TOK_TEXT_MP_HEADER_LEFT:
        if( bInsertHeaderLeft && bHeaderInserted && !bHeaderLeftInserted )
            bInsert = bLeft = sal_True;
        break;
    case XML_TOK_TEXT_MP_FOOTER_LEFT:
        if( bInsertFooterLeft && bFooterInserted && !bFooterLeftInserted )
            bInsert = bFooter = bLeft = sal_True;
        break;
    }

    if( bInsert && xStyle.is() )
    {
        pContext = CreateHeaderFooterContext( nPrefix, rLocalName,
                                                    xAttrList,
                                                    bFooter, bLeft );
    }
    else
    {
        pContext = SvXMLStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                          xAttrList );
    }

    return pContext;
}

SvXMLImportContext *XMLTextMasterPageContext::CreateHeaderFooterContext(
            sal_uInt16 nPrefix,
            const ::rtl::OUString& rLocalName,
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            const sal_Bool bFooter,
            const sal_Bool bLeft )
{
    Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
    return new XMLTextHeaderFooterContext( GetImport(),
                                                nPrefix, rLocalName,
                                                xAttrList,
                                                xPropSet,
                                                bFooter, bLeft );
}

void XMLTextMasterPageContext::Finish( sal_Bool bOverwrite )
{
    if( xStyle.is() && (IsNew() || bOverwrite) )
    {
        Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
        if( sPageMasterName.getLength() )
        {
            XMLPropStyleContext* pStyle =
                GetImport().GetTextImport()->FindPageMaster( sPageMasterName );
            if (pStyle)
            {
                pStyle->FillPropertySet(xPropSet);
            }
        }

        Reference < XNameContainer > xPageStyles =
            GetImport().GetTextImport()->GetPageStyles();
        if( !xPageStyles.is() )
            return;

        Reference< XPropertySetInfo > xPropSetInfo =
            xPropSet->getPropertySetInfo();
        if( xPropSetInfo->hasPropertyByName( sFollowStyle ) )
        {
            OUString sDisplayFollow(
                GetImport().GetStyleDisplayName(
                        XML_STYLE_FAMILY_MASTER_PAGE, sFollow ) );
            if( !sDisplayFollow.getLength() ||
                !xPageStyles->hasByName( sDisplayFollow ) )
                sDisplayFollow = xStyle->getName();

            Any aAny = xPropSet->getPropertyValue( sFollowStyle );
            OUString sCurrFollow;
            aAny >>= sCurrFollow;
            if( sCurrFollow != sDisplayFollow )
            {
                aAny <<= sDisplayFollow;
                xPropSet->setPropertyValue( sFollowStyle, aAny );
            }
        }
    }
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.11.34); FILE MERGED 2006/09/01 18:00:08 kaib 1.11.34.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextMasterPageContext.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 11:14:35 $
 *
 *  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 _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSTATES_HPP_
#include <com/sun/star/beans/XMultiPropertyStates.hpp>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_TEXTMASTERPAGECONTEXT_HXX_
#include "XMLTextMasterPageContext.hxx"
#endif
#ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_
#include "XMLTextHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX
#include "PageMasterImportContext.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//using namespace ::com::sun::star::text;
using namespace ::xmloff::token;

Reference < XStyle > XMLTextMasterPageContext::Create()
{
    Reference < XStyle > xNewStyle;

    Reference< XMultiServiceFactory > xFactory( GetImport().GetModel(),
                                                    UNO_QUERY );
    if( xFactory.is() )
    {
        Reference < XInterface > xIfc =
            xFactory->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM(
                                    "com.sun.star.style.PageStyle")) );
        if( xIfc.is() )
            xNewStyle = Reference < XStyle >( xIfc, UNO_QUERY );
    }

    return xNewStyle;
}
TYPEINIT1( XMLTextMasterPageContext, SvXMLStyleContext );

XMLTextMasterPageContext::XMLTextMasterPageContext( SvXMLImport& rImport,
        sal_uInt16 nPrfx, const OUString& rLName,
        const Reference< XAttributeList > & xAttrList,
        sal_Bool bOverwrite )
:   SvXMLStyleContext( rImport, nPrfx, rLName, xAttrList, XML_STYLE_FAMILY_MASTER_PAGE )
,   sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) )
,   sPageStyleLayout( RTL_CONSTASCII_USTRINGPARAM( "PageStyleLayout" ) )
,   sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) )
,   bInsertHeader( sal_False )
,   bInsertFooter( sal_False )
,   bInsertHeaderLeft( sal_False )
,   bInsertFooterLeft( sal_False )
,   bHeaderInserted( sal_False )
,   bFooterInserted( sal_False )
,   bHeaderLeftInserted( sal_False )
,   bFooterLeftInserted( sal_False )
{
    OUString sName, sDisplayName;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
        if( XML_NAMESPACE_STYLE == nPrefix )
        {
            if( IsXMLToken( aLocalName, XML_NAME ) )
            {
                sName = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_DISPLAY_NAME ) )
            {
                sDisplayName = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_NEXT_STYLE_NAME ) )
            {
                sFollow = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_PAGE_LAYOUT_NAME ) )
            {
                sPageMasterName = xAttrList->getValueByIndex( i );
            }
        }
    }

    if( sDisplayName.getLength() )
    {
        rImport.AddStyleDisplayName( XML_STYLE_FAMILY_MASTER_PAGE, sName,
                                     sDisplayName );
    }
    else
    {
        sDisplayName = sName;
    }

    if( 0 == sDisplayName.getLength() )
        return;

    Reference < XNameContainer > xPageStyles =
            GetImport().GetTextImport()->GetPageStyles();
    if( !xPageStyles.is() )
        return;

    Any aAny;
    sal_Bool bNew = sal_False;
    if( xPageStyles->hasByName( sDisplayName ) )
    {
        aAny = xPageStyles->getByName( sDisplayName );
        aAny >>= xStyle;
    }
    else
    {
        xStyle = Create();
        if( !xStyle.is() )
            return;

        aAny <<= xStyle;
        xPageStyles->insertByName( sDisplayName, aAny );
        bNew = sal_True;
    }

    Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo =
                xPropSet->getPropertySetInfo();
    if( !bNew && xPropSetInfo->hasPropertyByName( sIsPhysical ) )
    {
        aAny = xPropSet->getPropertyValue( sIsPhysical );
        bNew = !*(sal_Bool *)aAny.getValue();
    }
    SetNew( bNew );

    if( bOverwrite || bNew )
    {
        Reference < XMultiPropertyStates > xMultiStates( xPropSet,
                                                         UNO_QUERY );
        OSL_ENSURE( xMultiStates.is(),
                    "text page style does not support multi property set" );
        if( xMultiStates.is() )
            xMultiStates->setAllPropertiesToDefault();

        bInsertHeader = bInsertFooter = sal_True;
        bInsertHeaderLeft = bInsertFooterLeft = sal_True;
    }
}

XMLTextMasterPageContext::~XMLTextMasterPageContext()
{
}

SvXMLImportContext *XMLTextMasterPageContext::CreateChildContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    const SvXMLTokenMap& rTokenMap =
        GetImport().GetTextImport()->GetTextMasterPageElemTokenMap();

    sal_Bool bInsert = sal_False, bFooter = sal_False, bLeft = sal_False;
    switch( rTokenMap.Get( nPrefix, rLocalName ) )
    {
    case XML_TOK_TEXT_MP_HEADER:
        if( bInsertHeader && !bHeaderInserted )
        {
            bInsert = sal_True;
            bHeaderInserted = sal_True;
        }
        break;
    case XML_TOK_TEXT_MP_FOOTER:
        if( bInsertFooter && !bFooterInserted )
        {
            bInsert = bFooter = sal_True;
            bFooterInserted = sal_True;
        }
        break;
    case XML_TOK_TEXT_MP_HEADER_LEFT:
        if( bInsertHeaderLeft && bHeaderInserted && !bHeaderLeftInserted )
            bInsert = bLeft = sal_True;
        break;
    case XML_TOK_TEXT_MP_FOOTER_LEFT:
        if( bInsertFooterLeft && bFooterInserted && !bFooterLeftInserted )
            bInsert = bFooter = bLeft = sal_True;
        break;
    }

    if( bInsert && xStyle.is() )
    {
        pContext = CreateHeaderFooterContext( nPrefix, rLocalName,
                                                    xAttrList,
                                                    bFooter, bLeft );
    }
    else
    {
        pContext = SvXMLStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                          xAttrList );
    }

    return pContext;
}

SvXMLImportContext *XMLTextMasterPageContext::CreateHeaderFooterContext(
            sal_uInt16 nPrefix,
            const ::rtl::OUString& rLocalName,
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            const sal_Bool bFooter,
            const sal_Bool bLeft )
{
    Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
    return new XMLTextHeaderFooterContext( GetImport(),
                                                nPrefix, rLocalName,
                                                xAttrList,
                                                xPropSet,
                                                bFooter, bLeft );
}

void XMLTextMasterPageContext::Finish( sal_Bool bOverwrite )
{
    if( xStyle.is() && (IsNew() || bOverwrite) )
    {
        Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
        if( sPageMasterName.getLength() )
        {
            XMLPropStyleContext* pStyle =
                GetImport().GetTextImport()->FindPageMaster( sPageMasterName );
            if (pStyle)
            {
                pStyle->FillPropertySet(xPropSet);
            }
        }

        Reference < XNameContainer > xPageStyles =
            GetImport().GetTextImport()->GetPageStyles();
        if( !xPageStyles.is() )
            return;

        Reference< XPropertySetInfo > xPropSetInfo =
            xPropSet->getPropertySetInfo();
        if( xPropSetInfo->hasPropertyByName( sFollowStyle ) )
        {
            OUString sDisplayFollow(
                GetImport().GetStyleDisplayName(
                        XML_STYLE_FAMILY_MASTER_PAGE, sFollow ) );
            if( !sDisplayFollow.getLength() ||
                !xPageStyles->hasByName( sDisplayFollow ) )
                sDisplayFollow = xStyle->getName();

            Any aAny = xPropSet->getPropertyValue( sFollowStyle );
            OUString sCurrFollow;
            aAny >>= sCurrFollow;
            if( sCurrFollow != sDisplayFollow )
            {
                aAny <<= sDisplayFollow;
                xPropSet->setPropertyValue( sFollowStyle, aAny );
            }
        }
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TransformerTokenMap.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 11:29:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_TRANSFORMERTOKENMAP_HXX
#include "TransformerTokenMap.hxx"
#endif

using namespace ::xmloff::token;

XMLTransformerTokenMap::XMLTransformerTokenMap( XMLTokenEnum *pInit )
{
    if( pInit )
    {
        while( *pInit != XML_TOKEN_END )
        {
            XMLTransformerTokenMap::value_type aVal( GetXMLToken( *pInit ),
                                                        *pInit );
            insert( aVal );
            ++pInit;
        }
    }
}

XMLTransformerTokenMap::~XMLTransformerTokenMap()
{
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.300); FILE MERGED 2008/03/31 16:28:54 rt 1.4.300.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: TransformerTokenMap.cxx,v $
 * $Revision: 1.5 $
 *
 * 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"

#ifndef _XMLOFF_TRANSFORMERTOKENMAP_HXX
#include "TransformerTokenMap.hxx"
#endif

using namespace ::xmloff::token;

XMLTransformerTokenMap::XMLTransformerTokenMap( XMLTokenEnum *pInit )
{
    if( pInit )
    {
        while( *pInit != XML_TOKEN_END )
        {
            XMLTransformerTokenMap::value_type aVal( GetXMLToken( *pInit ),
                                                        *pInit );
            insert( aVal );
            ++pInit;
        }
    }
}

XMLTransformerTokenMap::~XMLTransformerTokenMap()
{
}
<|endoftext|>


<commit_before>#include "mitkDopplerToStrainRateFilter.h"
#include "mitkImageTimeSelector.h"
#include "mitkProperties.h"
#include "mitkPlaneGeometry.h"

#include <iostream.h>
#include <string>

void mitk::DopplerToStrainRateFilter::GenerateOutputInformation()
{
	mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if ((output->IsInitialized()) && (this->GetMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
        return;

    itkDebugMacro(<<"GenerateOutputInformation()");

	unsigned int i;
	unsigned int *tmpDimensions = new unsigned int[input->GetDimension()];

	for(i=0;i<input->GetDimension();++i)
		tmpDimensions[i]=input->GetDimension(i);

  //@todo maybe we should shift the following somehow in ImageToImageFilter
	output->Initialize(input->GetPixelType(),
										input->GetDimension(),
										tmpDimensions,
										input->GetNumberOfChannels());

    output->GetSlicedGeometry()->SetSpacing(input->GetSlicedGeometry()->GetSpacing());

    output->GetSlicedGeometry()->SetGeometry2D(mitk::Image::BuildStandardPlaneGeometry2D(output->GetSlicedGeometry(), tmpDimensions).GetPointer(), 0);
    output->GetSlicedGeometry()->SetEvenlySpaced();
    //set the timebounds - after SetGeometry2D, so that the already created PlaneGeometry will also receive this timebounds.
    output->GetSlicedGeometry()->SetTimeBoundsInMS(input->GetSlicedGeometry()->GetTimeBoundsInMS());

	  output->SetPropertyList(input->GetPropertyList()->Clone());

		delete [] tmpDimensions;

    m_TimeOfHeaderInitialization.Modified();
}

void mitk::DopplerToStrainRateFilter::GenerateData()
{
	mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  mitk::Point3iProperty::Pointer pointProp;
	pointProp = dynamic_cast<mitk::Point3iProperty*>(input->GetProperty("ORIGIN").GetPointer());
	if (pointProp.IsNotNull() )
	{
				m_Origin = pointProp->GetValue();
	}

  std::cout << "compute Strain Rate Image .... " << std::endl;
  std::cout << "  origin.x=" << m_Origin.x << " origin.y=" << m_Origin.y << " origin.z=" << m_Origin.z << std::endl;
	std::cout << "  distance=" << m_Distance << std::endl;
	std::cout << "  NoStrainIntervall=" << m_NoStrainInterval << std::endl;

  const float *spacing = input->GetSlicedGeometry()->GetSpacing();
//	std::cout << "   in: xres=" << spacing[0] << " yres=" << spacing[1] << " zres=" << spacing[2] << std::endl;

	mitk::ImageTimeSelector::Pointer timeSelector=mitk::ImageTimeSelector::New();
	timeSelector->SetInput(input);

	ipPicDescriptor* picStrainRate;
	picStrainRate = ipPicNew();
	picStrainRate->dim=3;
	picStrainRate->bpe  = output->GetPixelType().GetBpe();
	picStrainRate->type = output->GetPixelType().GetType();
	picStrainRate->n[0] = output->GetDimension(0);
	picStrainRate->n[1] = output->GetDimension(1);
	picStrainRate->n[2] = output->GetDimension(2);
	picStrainRate->data=malloc(_ipPicSize(picStrainRate));

	int xDim = picStrainRate->n[0];
	int yDim = picStrainRate->n[1];
	int zDim = picStrainRate->n[2];
	long slice_size = xDim*yDim;
	long vol_size = slice_size*zDim;

  ipPicDescriptor *picDoppler;

 	int x,y,z,time;							// loop-counter
	int strainRate;						// the computed Strain Rate
	int v1,v2;								// velocity and Point p1 and p2

	float alpha;								// the beam-angle, angle betwen current point and beam-point
	float dx, dy;								// projection of this->distance to x- and y-axis
	float weightX, weightY;			// weigth-factors for x-velocity and y-velocity
	int dxFloor, dyFloor;				// floored dx, dy

	int x1, x2, x3, x4;					// a square, where the velocity v1 lies in
	int y1, y2, y3, y4;					// the points are used for interpolation
	int vTmp1, vTmp2;						// velocities used for interpolation
	int vTmp3, vTmp4;

	int minStrainRate=128, maxStrainRate=128;

	int n, nmax;
	int t, tmax;

	t = output->GetRequestedRegion().GetIndex(3);
	n = output->GetRequestedRegion().GetIndex(4);

	tmax = t + output->GetRequestedRegion().GetSize(3);
	nmax = n + output->GetRequestedRegion().GetSize(4);

	if (m_Distance<1) m_Distance=1;

	for(;n<nmax;++n)//output->GetNumberOfChannels();++n)
	{
		timeSelector->SetChannelNr(n);

		for(t=0;t<tmax;++t)
		{

			timeSelector->SetTimeNr(t);
			timeSelector->Update();

			_ipPicFreeTags(picStrainRate->info->tags_head);
			picStrainRate->info->tags_head = _ipPicCloneTags(timeSelector->GetOutput()->GetPic()->info->tags_head);

#define       WRITE_ANGLE_PIC
#ifdef WRITE_ANGLE_PIC
	ipPicDescriptor *anglePic;
	ipBool_t isAnglePicWritten = ipFalse;

	anglePic = ipPicNew();
	anglePic->type = ipPicInt;
  anglePic->bpe = 8;
	anglePic->dim = 2;
	anglePic->n[0] = xDim;
	anglePic->n[1] = yDim;
	anglePic->data = (ipInt1_t *)calloc(xDim*yDim,sizeof(ipInt1_t));
#endif

		picDoppler = timeSelector->GetOutput()->GetPic();

		for (z=0 ; z<zDim ; z++) {

				for (y=1; y<yDim; y++) {

					if (y<m_Origin.y) continue;  // cannot compute StrainRate above Transducer-Position

					for (x=0; x<xDim; x++) {

						if ((m_Origin.x - x)==0) {  // winkelhalbierende

							int yDistanceInUnits = (int)( m_Distance/spacing[1]);
							int yTmp = ( (y-yDistanceInUnits)<0 )  ? 0 : (y-yDistanceInUnits);
							v1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + yTmp*xDim + x] ;
							v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;

						} else {

							// compute angle to transducer position
							// m_Origin is given in units, not in mm
							alpha = atan( (float) (m_Origin.x - x)  / (float) (m_Origin.y - y) );

							// m_Distance is given in mm
							dx = -sin(alpha) * m_Distance;
							dy = -cos(alpha) * m_Distance;

							// convert to units
							dx = dx/spacing[0];
							dy = dy/spacing[1];

//#define WEIGTHED
#ifdef WEIGTHED
							weightX = dx - floor(dx);
							weightY = dy - floor(dy);

							dxFloor = (int) floor(dx);
							dyFloor = (int) floor(dy);

							x1 = x + dxFloor;					// lower left
							y1 = y + dyFloor;

							x2 = x + (dxFloor+1);			// lower right
							y2 = y + dyFloor;

							x3 = x + (dxFloor+1);			// upper right
							y3 = y + (dyFloor+1);

							x4 = x + dxFloor;					// upper left
							y4 = y + (dyFloor+1);

							vTmp1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
							vTmp2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y2*xDim + x2];
							vTmp3 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y3*xDim + x3];
							vTmp4 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y4*xDim + x4];

							v1 = (int) ((1-weightX)*(1-weightY)*vTmp1 + weightX*(1-weightY)*vTmp2 + weightX*weightY*vTmp3 + (1-weightX)*weightY*vTmp4);
							v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;
#else
							x1 = (int)(x + dx);
							y1 = (int)(y + dy);
							if (y1<0) y1=0;

#endif
							v1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
							v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;
						}

						if (v1==128) {  // schaue in Gegenrichtung, falls keine SRI hier berechenbar
							x1 = (int)(x - dx);
							y1 = (int)(y - dy);
							if (y1>yDim) y1=yDim;
							//swap v1 and v2, otherwise StrainRate is calculate in false direction
							v1 = v2;
							v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
						}

						if ( 	(v1==0 ) || (v2==0)  ||	// wenn keine Geschwindigkeit vorhanden
																					// oder wenn nur ganz kleine Geschwindigkeit vorhanden
							(v1>=(128-m_NoStrainInterval) && v1<=(128+m_NoStrainInterval)) ||
							(v2>=(128-m_NoStrainInterval) && v2<=(128+m_NoStrainInterval))) {

							strainRate = 128;  // this means no deformation
							// this is neccessay due to the Cyl2Cart filter

						} else {
							strainRate = (int)( (v1 - v2)/2 + 128 );
							if (strainRate==128) strainRate=129;
						}

						if (strainRate < minStrainRate && strainRate > 0 )
						  minStrainRate = strainRate;

						if (strainRate > maxStrainRate)
						  maxStrainRate = strainRate;

						if (strainRate<0 ) {
							//strainRate = -strainRate;
							std::cout << " error: neg. strainRate ... exit() " << std::endl;
							std::cout << " x=" << x << " y=" << y << " z=" << z << std::endl;
							std::cout << " v1=" << v1 << " v2=" << v2 << " dist=" << m_Distance << std::endl;
							std::cout << " sr=" << strainRate  << std::endl;
							exit(0);
							}

						((ipUInt1_t *)picStrainRate->data)[t*vol_size + z*slice_size + y*xDim + x]=strainRate;

						// cout << "z: " << z << " y: " << y << " x: " << x << " strainrate: " << strainRate << endl;

#ifdef WRITE_ANGLE_PIC
//						if (!isAnglePicWritten)
//					((ipInt1_t *)anglePic->data)[y*xDim + x] = (int) ( (alpha/1.6)*128);
						if (!isAnglePicWritten)
							((ipInt1_t *)anglePic->data)[y*xDim + x] = (int) ( dx);

#endif

					}  // x

				} // y

				//isAnglePicWritten = ipTrue;

			} // z

	//isStrainComputed = ipTrue;
	std::string filenameD;
	filenameD ="doppler.pic";
	ipPicPut(const_cast<char *>(filenameD.c_str()),picDoppler);

#define WRITE_STRAIN_PIC
#ifdef WRITE_STRAIN_PIC
	std::string filename;
	filename ="strain.pic";
	ipPicPut(const_cast<char *>(filename.c_str()),picStrainRate);
#endif

#ifdef WRITE_ANGLE_PIC
	std::string filename2;
	filename2="angle.pic";
	ipPicPut(const_cast<char *>(filename2.c_str()),anglePic);
#endif
		((ipUInt1_t *)picStrainRate->data)[0]=0;
		((ipUInt1_t *)picStrainRate->data)[1]=255;

			output->SetPicVolume(picStrainRate, t, n);
		}
	}
  std::cout << "Strain Rate Image computed.... " << std::endl;
  std::cout << "  minStrainRate: " << minStrainRate << std::endl;
	std::cout << "  maxStrainRate: " << maxStrainRate << std::endl;
}

mitk::DopplerToStrainRateFilter::DopplerToStrainRateFilter()
    : m_Distance(10), m_NoStrainInterval(2)
{

    m_Origin.x = 0;
    m_Origin.y = 0;
    m_Origin.z = 0;

}

float mitk::DopplerToStrainRateFilter::GetLimit()
{	return (128/m_Distance);
}

mitk::DopplerToStrainRateFilter::~DopplerToStrainRateFilter()
{

}

void mitk::DopplerToStrainRateFilter::GenerateInputRequestedRegion()
{
	Superclass::GenerateInputRequestedRegion();

	mitk::ImageToImageFilter::InputImagePointer input =
		const_cast< mitk::ImageToImageFilter::InputImageType * > ( this->GetInput() );
    mitk::Image::Pointer output = this->GetOutput();

	Image::RegionType requestedRegion;
    requestedRegion = output->GetRequestedRegion();
	requestedRegion.SetIndex(0, 0);
	requestedRegion.SetIndex(1, 0);
	requestedRegion.SetIndex(2, 0);
	//requestedRegion.SetIndex(3, 0);
	//requestedRegion.SetIndex(4, 0);
	requestedRegion.SetSize(0, input->GetDimension(0));
	requestedRegion.SetSize(1, input->GetDimension(1));
	requestedRegion.SetSize(2, input->GetDimension(2));
	//requestedRegion.SetSize(3, output->GetDimension(3));
	//requestedRegion.SetSize(4, output->GetNumberOfChannels());

	input->SetRequestedRegion( & requestedRegion );
}
<commit_msg>reformatted<commit_after>#include "mitkDopplerToStrainRateFilter.h"
#include "mitkImageTimeSelector.h"
#include "mitkProperties.h"
#include "mitkPlaneGeometry.h"

#include <iostream.h>
#include <string>

void mitk::DopplerToStrainRateFilter::GenerateOutputInformation()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if ((output->IsInitialized()) && (this->GetMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
    return;

  itkDebugMacro(<<"GenerateOutputInformation()");

  unsigned int i;
  unsigned int *tmpDimensions = new unsigned int[input->GetDimension()];

  for(i=0;i<input->GetDimension();++i)
    tmpDimensions[i]=input->GetDimension(i);

  //@todo maybe we should shift the following somehow in ImageToImageFilter
  output->Initialize(input->GetPixelType(),
    input->GetDimension(),
    tmpDimensions,
    input->GetNumberOfChannels());

  output->GetSlicedGeometry()->SetSpacing(input->GetSlicedGeometry()->GetSpacing());

  output->GetSlicedGeometry()->SetGeometry2D(mitk::Image::BuildStandardPlaneGeometry2D(output->GetSlicedGeometry(), tmpDimensions).GetPointer(), 0);
  output->GetSlicedGeometry()->SetEvenlySpaced();
  //set the timebounds - after SetGeometry2D, so that the already created PlaneGeometry will also receive this timebounds.
  output->GetSlicedGeometry()->SetTimeBoundsInMS(input->GetSlicedGeometry()->GetTimeBoundsInMS());

  output->SetPropertyList(input->GetPropertyList()->Clone());

  delete [] tmpDimensions;

  m_TimeOfHeaderInitialization.Modified();
}

void mitk::DopplerToStrainRateFilter::GenerateData()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  mitk::Point3iProperty::Pointer pointProp;
  pointProp = dynamic_cast<mitk::Point3iProperty*>(input->GetProperty("ORIGIN").GetPointer());
  if (pointProp.IsNotNull() )
  {
    m_Origin = pointProp->GetValue();
  }

  std::cout << "compute Strain Rate Image .... " << std::endl;
  std::cout << "  origin.x=" << m_Origin.x << " origin.y=" << m_Origin.y << " origin.z=" << m_Origin.z << std::endl;
  std::cout << "  distance=" << m_Distance << std::endl;
  std::cout << "  NoStrainIntervall=" << m_NoStrainInterval << std::endl;

  const float *spacing = input->GetSlicedGeometry()->GetSpacing();
  //	std::cout << "   in: xres=" << spacing[0] << " yres=" << spacing[1] << " zres=" << spacing[2] << std::endl;

  mitk::ImageTimeSelector::Pointer timeSelector=mitk::ImageTimeSelector::New();
  timeSelector->SetInput(input);

  ipPicDescriptor* picStrainRate;
  picStrainRate = ipPicNew();
  picStrainRate->dim=3;
  picStrainRate->bpe  = output->GetPixelType().GetBpe();
  picStrainRate->type = output->GetPixelType().GetType();
  picStrainRate->n[0] = output->GetDimension(0);
  picStrainRate->n[1] = output->GetDimension(1);
  picStrainRate->n[2] = output->GetDimension(2);
  picStrainRate->data=malloc(_ipPicSize(picStrainRate));

  int xDim = picStrainRate->n[0];
  int yDim = picStrainRate->n[1];
  int zDim = picStrainRate->n[2];
  long slice_size = xDim*yDim;
  long vol_size = slice_size*zDim;

  ipPicDescriptor *picDoppler;

  int x,y,z,time;							// loop-counter
  int strainRate;						// the computed Strain Rate
  int v1,v2;								// velocity and Point p1 and p2

  float alpha;								// the beam-angle, angle betwen current point and beam-point
  float dx, dy;								// projection of this->distance to x- and y-axis
  float weightX, weightY;			// weigth-factors for x-velocity and y-velocity
  int dxFloor, dyFloor;				// floored dx, dy

  int x1, x2, x3, x4;					// a square, where the velocity v1 lies in
  int y1, y2, y3, y4;					// the points are used for interpolation
  int vTmp1, vTmp2;						// velocities used for interpolation
  int vTmp3, vTmp4;

  int minStrainRate=128, maxStrainRate=128;

  int n, nmax;
  int t, tmax;

  t = output->GetRequestedRegion().GetIndex(3);
  n = output->GetRequestedRegion().GetIndex(4);

  tmax = t + output->GetRequestedRegion().GetSize(3);
  nmax = n + output->GetRequestedRegion().GetSize(4);

  if (m_Distance<1) m_Distance=1;

  for(;n<nmax;++n)//output->GetNumberOfChannels();++n)
  {
    timeSelector->SetChannelNr(n);

    for(t=0;t<tmax;++t)
    {

      timeSelector->SetTimeNr(t);
      timeSelector->Update();

      _ipPicFreeTags(picStrainRate->info->tags_head);
      picStrainRate->info->tags_head = _ipPicCloneTags(timeSelector->GetOutput()->GetPic()->info->tags_head);

#define       WRITE_ANGLE_PIC
#ifdef WRITE_ANGLE_PIC
      ipPicDescriptor *anglePic;
      ipBool_t isAnglePicWritten = ipFalse;

      anglePic = ipPicNew();
      anglePic->type = ipPicInt;
      anglePic->bpe = 8;
      anglePic->dim = 2;
      anglePic->n[0] = xDim;
      anglePic->n[1] = yDim;
      anglePic->data = (ipInt1_t *)calloc(xDim*yDim,sizeof(ipInt1_t));
#endif

      picDoppler = timeSelector->GetOutput()->GetPic();

      for (z=0 ; z<zDim ; z++) {

        for (y=1; y<yDim; y++) {

          if (y<m_Origin.y) continue;  // cannot compute StrainRate above Transducer-Position

          for (x=0; x<xDim; x++) {

            if ((m_Origin.x - x)==0) {  // winkelhalbierende

              int yDistanceInUnits = (int)( m_Distance/spacing[1]);
              int yTmp = ( (y-yDistanceInUnits)<0 )  ? 0 : (y-yDistanceInUnits);
              v1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + yTmp*xDim + x] ;
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;

            } else {

              // compute angle to transducer position
              // m_Origin is given in units, not in mm
              alpha = atan( (float) (m_Origin.x - x)  / (float) (m_Origin.y - y) );

              // m_Distance is given in mm
              dx = -sin(alpha) * m_Distance;
              dy = -cos(alpha) * m_Distance;

              // convert to units
              dx = dx/spacing[0];
              dy = dy/spacing[1];

              //#define WEIGTHED
#ifdef WEIGTHED
              weightX = dx - floor(dx);
              weightY = dy - floor(dy);

              dxFloor = (int) floor(dx);
              dyFloor = (int) floor(dy);

              x1 = x + dxFloor;					// lower left
              y1 = y + dyFloor;

              x2 = x + (dxFloor+1);			// lower right
              y2 = y + dyFloor;

              x3 = x + (dxFloor+1);			// upper right
              y3 = y + (dyFloor+1);

              x4 = x + dxFloor;					// upper left
              y4 = y + (dyFloor+1);

              vTmp1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
              vTmp2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y2*xDim + x2];
              vTmp3 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y3*xDim + x3];
              vTmp4 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y4*xDim + x4];

              v1 = (int) ((1-weightX)*(1-weightY)*vTmp1 + weightX*(1-weightY)*vTmp2 + weightX*weightY*vTmp3 + (1-weightX)*weightY*vTmp4);
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;
#else
              x1 = (int)(x + dx);
              y1 = (int)(y + dy);
              if (y1<0) y1=0;

#endif
              v1 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y*xDim + x] ;
            }

            if (v1==128) {  // schaue in Gegenrichtung, falls keine SRI hier berechenbar
              x1 = (int)(x - dx);
              y1 = (int)(y - dy);
              if (y1>yDim) y1=yDim;
              //swap v1 and v2, otherwise StrainRate is calculate in false direction
              v1 = v2;
              v2 = ((ipUInt1_t *)picDoppler->data)[z*slice_size + y1*xDim + x1];
            }

            if ( 	(v1==0 ) || (v2==0)  ||	// wenn keine Geschwindigkeit vorhanden
              // oder wenn nur ganz kleine Geschwindigkeit vorhanden
              (v1>=(128-m_NoStrainInterval) && v1<=(128+m_NoStrainInterval)) ||
              (v2>=(128-m_NoStrainInterval) && v2<=(128+m_NoStrainInterval))) {

                strainRate = 128;  // this means no deformation
                // this is neccessay due to the Cyl2Cart filter

              } else {
                strainRate = (int)( (v1 - v2)/2 + 128 );
                if (strainRate==128) strainRate=129;
              }

              if (strainRate < minStrainRate && strainRate > 0 )
                minStrainRate = strainRate;

              if (strainRate > maxStrainRate)
                maxStrainRate = strainRate;

              if (strainRate<0 ) {
                //strainRate = -strainRate;
                std::cout << " error: neg. strainRate ... exit() " << std::endl;
                std::cout << " x=" << x << " y=" << y << " z=" << z << std::endl;
                std::cout << " v1=" << v1 << " v2=" << v2 << " dist=" << m_Distance << std::endl;
                std::cout << " sr=" << strainRate  << std::endl;
                exit(0);
              }

              ((ipUInt1_t *)picStrainRate->data)[t*vol_size + z*slice_size + y*xDim + x]=strainRate;

              // cout << "z: " << z << " y: " << y << " x: " << x << " strainrate: " << strainRate << endl;

#ifdef WRITE_ANGLE_PIC
              //						if (!isAnglePicWritten)
              //					((ipInt1_t *)anglePic->data)[y*xDim + x] = (int) ( (alpha/1.6)*128);
              if (!isAnglePicWritten)
                ((ipInt1_t *)anglePic->data)[y*xDim + x] = (int) ( dx);

#endif

          }  // x

        } // y

        //isAnglePicWritten = ipTrue;

      } // z

      //isStrainComputed = ipTrue;
      std::string filenameD;
      filenameD ="doppler.pic";
      ipPicPut(const_cast<char *>(filenameD.c_str()),picDoppler);

#define WRITE_STRAIN_PIC
#ifdef WRITE_STRAIN_PIC
      std::string filename;
      filename ="strain.pic";
      ipPicPut(const_cast<char *>(filename.c_str()),picStrainRate);
#endif

#ifdef WRITE_ANGLE_PIC
      std::string filename2;
      filename2="angle.pic";
      ipPicPut(const_cast<char *>(filename2.c_str()),anglePic);
#endif
      ((ipUInt1_t *)picStrainRate->data)[0]=0;
      ((ipUInt1_t *)picStrainRate->data)[1]=255;

      output->SetPicVolume(picStrainRate, t, n);
    }
  }
  std::cout << "Strain Rate Image computed.... " << std::endl;
  std::cout << "  minStrainRate: " << minStrainRate << std::endl;
  std::cout << "  maxStrainRate: " << maxStrainRate << std::endl;
}

mitk::DopplerToStrainRateFilter::DopplerToStrainRateFilter()
: m_Distance(10), m_NoStrainInterval(2)
{

  m_Origin.x = 0;
  m_Origin.y = 0;
  m_Origin.z = 0;

}

float mitk::DopplerToStrainRateFilter::GetLimit()
{	return (128/m_Distance);
}

mitk::DopplerToStrainRateFilter::~DopplerToStrainRateFilter()
{

}

void mitk::DopplerToStrainRateFilter::GenerateInputRequestedRegion()
{
  Superclass::GenerateInputRequestedRegion();

  mitk::ImageToImageFilter::InputImagePointer input =
    const_cast< mitk::ImageToImageFilter::InputImageType * > ( this->GetInput() );
  mitk::Image::Pointer output = this->GetOutput();

  Image::RegionType requestedRegion;
  requestedRegion = output->GetRequestedRegion();
  requestedRegion.SetIndex(0, 0);
  requestedRegion.SetIndex(1, 0);
  requestedRegion.SetIndex(2, 0);
  //requestedRegion.SetIndex(3, 0);
  //requestedRegion.SetIndex(4, 0);
  requestedRegion.SetSize(0, input->GetDimension(0));
  requestedRegion.SetSize(1, input->GetDimension(1));
  requestedRegion.SetSize(2, input->GetDimension(2));
  //requestedRegion.SetSize(3, output->GetDimension(3));
  //requestedRegion.SetSize(4, output->GetNumberOfChannels());

  input->SetRequestedRegion( & requestedRegion );
}
<|endoftext|>


<commit_before>// Copyright 2014 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 "config.h"
#include "SizesAttributeParser.h"

#include "MediaTypeNames.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/parser/MediaQueryTokenizer.h"
#include "core/css/parser/SizesCalcParser.h"

namespace WebCore {

unsigned SizesAttributeParser::findEffectiveSize(const String& attribute, PassRefPtr<MediaValues> mediaValues)
{
    Vector<MediaQueryToken> tokens;
    SizesAttributeParser parser(mediaValues);

    MediaQueryTokenizer::tokenize(attribute, tokens);
    if (!parser.parse(tokens))
        return parser.effectiveSizeDefaultValue();
    return parser.effectiveSize();
}

bool SizesAttributeParser::calculateLengthInPixels(MediaQueryTokenIterator startToken, MediaQueryTokenIterator endToken, unsigned& result)
{
    MediaQueryTokenType type = startToken->type();
    if (type == DimensionToken) {
        int length;
        if (!CSSPrimitiveValue::isLength(startToken->unitType()))
            return false;
        if ((m_mediaValues->computeLength(startToken->numericValue(), startToken->unitType(), length)) && (length > 0)) {
            result = (unsigned)length;
            return true;
        }
    } else if (type == FunctionToken) {
        return SizesCalcParser::parse(startToken, endToken, m_mediaValues, result);
    }

    return false;
}

static void reverseSkipIrrelevantTokens(MediaQueryTokenIterator& token, MediaQueryTokenIterator startToken)
{
    MediaQueryTokenIterator endToken = token;
    while (token != startToken && (token->type() == WhitespaceToken || token->type() == CommentToken || token->type() == EOFToken))
        --token;
    if (token != endToken)
        ++token;
}

static void reverseSkipUntilComponentStart(MediaQueryTokenIterator& token, MediaQueryTokenIterator startToken)
{
    if (token == startToken)
        return;
    --token;
    if (token->blockType() != MediaQueryToken::BlockEnd)
        return;
    unsigned blockLevel = 0;
    while (token != startToken) {
        if (token->blockType() == MediaQueryToken::BlockEnd) {
            ++blockLevel;
        } else if (token->blockType() == MediaQueryToken::BlockStart) {
            --blockLevel;
            if (!blockLevel)
                break;
        }

        --token;
    }
}

bool SizesAttributeParser::mediaConditionMatches(PassRefPtrWillBeRawPtr<MediaQuerySet> mediaCondition)
{
    // FIXME: How do I handle non-screen media types here?
    MediaQueryEvaluator mediaQueryEvaluator(MediaTypeNames::screen, *m_mediaValues);
    return mediaQueryEvaluator.eval(mediaCondition.get());
}

bool SizesAttributeParser::parseMediaConditionAndLength(MediaQueryTokenIterator startToken, MediaQueryTokenIterator endToken)
{
    MediaQueryTokenIterator lengthTokenStart;
    MediaQueryTokenIterator lengthTokenEnd;

    reverseSkipIrrelevantTokens(endToken, startToken);
    lengthTokenEnd = endToken;
    reverseSkipUntilComponentStart(endToken, startToken);
    lengthTokenStart = endToken;
    unsigned length;
    if (!calculateLengthInPixels(lengthTokenStart, lengthTokenEnd, length))
        return false;
    RefPtrWillBeRawPtr<MediaQuerySet> mediaCondition = MediaQueryParser::parseMediaCondition(startToken, endToken);
    if (mediaCondition && mediaConditionMatches(mediaCondition)) {
        m_length = length;
        return true;
    }
    return false;
}

bool SizesAttributeParser::parse(Vector<MediaQueryToken>& tokens)
{
    if (tokens.isEmpty())
        return false;
    MediaQueryTokenIterator startToken = tokens.begin();
    MediaQueryTokenIterator endToken;
    // Split on a comma token, and send the result tokens to be parsed as (media-condition, length) pairs
    for (MediaQueryTokenIterator token = tokens.begin(); token != tokens.end(); ++token) {
        if (token->type() == CommaToken) {
            endToken = token;
            if (parseMediaConditionAndLength(startToken, endToken))
                return true;
            startToken = token;
            ++startToken;
        }
    }
    endToken = tokens.end();
    return parseMediaConditionAndLength(startToken, --endToken);
}

unsigned SizesAttributeParser::effectiveSize()
{
    if (m_length)
        return m_length;
    return effectiveSizeDefaultValue();
}

unsigned SizesAttributeParser::effectiveSizeDefaultValue()
{
    // Returning the equivalent of "100%"
    return m_mediaValues->viewportWidth();
}

} // namespace

<commit_msg>Replace a stale fixme with a comment<commit_after>// Copyright 2014 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 "config.h"
#include "SizesAttributeParser.h"

#include "MediaTypeNames.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/parser/MediaQueryTokenizer.h"
#include "core/css/parser/SizesCalcParser.h"

namespace WebCore {

unsigned SizesAttributeParser::findEffectiveSize(const String& attribute, PassRefPtr<MediaValues> mediaValues)
{
    Vector<MediaQueryToken> tokens;
    SizesAttributeParser parser(mediaValues);

    MediaQueryTokenizer::tokenize(attribute, tokens);
    if (!parser.parse(tokens))
        return parser.effectiveSizeDefaultValue();
    return parser.effectiveSize();
}

bool SizesAttributeParser::calculateLengthInPixels(MediaQueryTokenIterator startToken, MediaQueryTokenIterator endToken, unsigned& result)
{
    MediaQueryTokenType type = startToken->type();
    if (type == DimensionToken) {
        int length;
        if (!CSSPrimitiveValue::isLength(startToken->unitType()))
            return false;
        if ((m_mediaValues->computeLength(startToken->numericValue(), startToken->unitType(), length)) && (length > 0)) {
            result = (unsigned)length;
            return true;
        }
    } else if (type == FunctionToken) {
        return SizesCalcParser::parse(startToken, endToken, m_mediaValues, result);
    }

    return false;
}

static void reverseSkipIrrelevantTokens(MediaQueryTokenIterator& token, MediaQueryTokenIterator startToken)
{
    MediaQueryTokenIterator endToken = token;
    while (token != startToken && (token->type() == WhitespaceToken || token->type() == CommentToken || token->type() == EOFToken))
        --token;
    if (token != endToken)
        ++token;
}

static void reverseSkipUntilComponentStart(MediaQueryTokenIterator& token, MediaQueryTokenIterator startToken)
{
    if (token == startToken)
        return;
    --token;
    if (token->blockType() != MediaQueryToken::BlockEnd)
        return;
    unsigned blockLevel = 0;
    while (token != startToken) {
        if (token->blockType() == MediaQueryToken::BlockEnd) {
            ++blockLevel;
        } else if (token->blockType() == MediaQueryToken::BlockStart) {
            --blockLevel;
            if (!blockLevel)
                break;
        }

        --token;
    }
}

bool SizesAttributeParser::mediaConditionMatches(PassRefPtrWillBeRawPtr<MediaQuerySet> mediaCondition)
{
    // A Media Condition cannot have a media type other then screen.
    MediaQueryEvaluator mediaQueryEvaluator(MediaTypeNames::screen, *m_mediaValues);
    return mediaQueryEvaluator.eval(mediaCondition.get());
}

bool SizesAttributeParser::parseMediaConditionAndLength(MediaQueryTokenIterator startToken, MediaQueryTokenIterator endToken)
{
    MediaQueryTokenIterator lengthTokenStart;
    MediaQueryTokenIterator lengthTokenEnd;

    reverseSkipIrrelevantTokens(endToken, startToken);
    lengthTokenEnd = endToken;
    reverseSkipUntilComponentStart(endToken, startToken);
    lengthTokenStart = endToken;
    unsigned length;
    if (!calculateLengthInPixels(lengthTokenStart, lengthTokenEnd, length))
        return false;
    RefPtrWillBeRawPtr<MediaQuerySet> mediaCondition = MediaQueryParser::parseMediaCondition(startToken, endToken);
    if (mediaCondition && mediaConditionMatches(mediaCondition)) {
        m_length = length;
        return true;
    }
    return false;
}

bool SizesAttributeParser::parse(Vector<MediaQueryToken>& tokens)
{
    if (tokens.isEmpty())
        return false;
    MediaQueryTokenIterator startToken = tokens.begin();
    MediaQueryTokenIterator endToken;
    // Split on a comma token, and send the result tokens to be parsed as (media-condition, length) pairs
    for (MediaQueryTokenIterator token = tokens.begin(); token != tokens.end(); ++token) {
        if (token->type() == CommaToken) {
            endToken = token;
            if (parseMediaConditionAndLength(startToken, endToken))
                return true;
            startToken = token;
            ++startToken;
        }
    }
    endToken = tokens.end();
    return parseMediaConditionAndLength(startToken, --endToken);
}

unsigned SizesAttributeParser::effectiveSize()
{
    if (m_length)
        return m_length;
    return effectiveSizeDefaultValue();
}

unsigned SizesAttributeParser::effectiveSizeDefaultValue()
{
    // Returning the equivalent of "100%"
    return m_mediaValues->viewportWidth();
}

} // namespace

<|endoftext|>


<commit_before>void AddAnalysisTaskPP(Bool_t isMC = kFALSE, UInt_t offlineTriggerMask, TString description, TString suff = "", TString badmap = "")
{
	AliAnalysisManager * mgr = AliAnalysisManager::GetAnalysisManager();

	// Setup Selections
	TList * selections = new TList();

	AliPP13ClusterCuts cuts_pi0 = AliPP13ClusterCuts::GetClusterCuts();
	AliPP13ClusterCuts cuts_eta = AliPP13ClusterCuts::GetClusterCuts();
	cuts_eta.fAsymmetryCut = 0.7;

	if (!isMC)
	{
		// TODO: Add plain selections
		AliPP13SelectionWeights & data_weights = AliPP13SelectionWeights::Init(AliPP13SelectionWeights::kData);
		AliPP13SelectionWeights & data_weights_plain = AliPP13SelectionWeights::Init(AliPP13SelectionWeights::kPlain);

		selections->Add(new AliPP13PhysPhotonSelection("Phys", "Physics Selection", cuts_pi0, &data_weights));
		selections->Add(new AliPP13PhysPhotonSelection("PhysPlain", "Physics Selection no TOF cut efficiency", cuts_pi0, &data_weights_plain));
		selections->Add(new AliPP13PhotonTimecutStudySelection("Time", "Testing Timing Selection", cuts_pi0, &data_weights));

		selections->Add(new AliPP13PhysPhotonSelection("Eta", "Physics Selection for eta meson", cuts_eta, &data_weights));
		selections->Add(new AliPP13PhysPhotonSelection("EtaPlain", "Physics Selection for eta meson no TOF cut efficiency", cuts_eta, &data_weights_plain));
		selections->Add(new AliPP13PhotonTimecutStudySelection("EtaTime", "Testing Timing Selection for eta meson", cuts_eta, &data_weights));

		selections->Add(new AliPP13TagAndProbeSelection("TagAndProbleTOF", "Cluster p_{T} Selection", cuts_pi0, &data_weights));
		selections->Add(new AliPP13NonlinearitySelection("PhysNonlinEst", "Physics efficiency for neutral particles", cuts_pi0, &data_weights));
		selections->Add(new AliPP13NonlinearitySelection("PhysNonlinEstPlain", "Physics efficiency for neutral particles", cuts_pi0, &data_weights_plain));

		selections->Add(new AliPP13QualityPhotonSelection("Qual", "Cluster quality Selection", cuts_pi0, &data_weights));
		selections->Add(new AliPP13PhotonSpectrumSelection("PhotonsTime", "Cluster p_{T} Selection with timing cut", cuts_pi0, &data_weights, 10., 3.));

		selections->Add(new AliPP13PhotonSpectrumSelection("Photons", "Cluster p_{T} Selection", cuts_pi0, &data_weights));
		selections->Add(new AliPP13PhotonSpectrumSelection("PhotonsPlain", "Cluster p_{T} Selection", cuts_pi0, &data_weights_plain));

	}
	else
	{
		AliPP13SelectionWeightsMC & mc_weights = AliPP13SelectionWeights::Init(AliPP13SelectionWeights::kMC);
		AliPP13SelectionWeightsMC & mc_weights_only = AliPP13SelectionWeights::Init(AliPP13SelectionWeights::kMC);

		// Nonlinearity for zs 20 Run2Default (Daiki's approximation)
		// The pi^0 peak is misplaced in this fit: A * 1.03274e+00 (global energy scale)
		// Calculated for the updated version for the corrected Data
		mc_weights.fNonA = -0.020025549129372242;
		mc_weights.fNonSigma = 1.1154536660217529;
	    mc_weights.fNonGlobal = 1.0493128193171741;

		mc_weights_only.fNonGlobal = 1.0;
		mc_weights_only.fNonA = 0.0;

		selections->Add(new AliPP13EfficiencySelectionMC("PhysEff", "Physics efficiency for neutral particles fully corrected", cuts_pi0, &mc_weights));
		selections->Add(new AliPP13EfficiencySelectionMC("PhysEffPlain", "Physics efficiency for neutral particles, no nonlinearity", cuts_pi0, &mc_weights_only));

		selections->Add(new AliPP13NonlinearitySelection("PhysNonlin", "Physics nonlinearity for neutral particles", cuts_pi0, &mc_weights, kTRUE));
		selections->Add(new AliPP13NonlinearitySelection("PhysNonlinRaw", "Raw nonlinearity for neutral particles", cuts_pi0, &mc_weights_only, kTRUE));

		selections->Add(new AliPP13NonlinearityScanSelection("PhysNonlinScan", "Physics efficiency for neutral particles", cuts_pi0, &mc_weights));
		selections->Add(new AliPP13MesonSelectionMC("MCStudy", "MC Selection with timing cut", cuts_pi0, &mc_weights));
	}

	if (isMC)
	{
		selections->Add(new AliPP13PhysPhotonSelection("Phys", "Physics Selection", cuts_pi0));
		selections->Add(new AliPP13PhotonTimecutStudySelection("Time", "Testing Timing Selection", cuts_pi0));
		selections->Add(new AliPP13TagAndProbeSelection("TagAndProbleTOF", "Cluster P_{t} Selection", cuts_pi0));

		selections->Add(new AliPP13PhysPhotonSelection("Eta", "Physics Selection for eta meson", cuts_eta));
		selections->Add(new AliPP13PhotonTimecutStudySelection("EtaTime", "Testing Timing Selection for eta meson", cuts_eta));

		selections->Add(new AliPP13QualityPhotonSelection("Qual", "Cluster quality Selection", cuts_pi0));
		selections->Add(new AliPP13PhotonSpectrumSelection("Photons", "Cluster P_{t} Selection", cuts_pi0));
		selections->Add(new AliPP13PhotonSpectrumSelection("PhotonsTime", "Cluster P_{t} Selection with timing cut", cuts_pi0, 10., 3.));
	}

	// Nonlinearity for zs 20 Run2Default (Daiki's approximation)
	// The pi^0 peak is misplaced in this fit: A * 1.03274e+00 (global energy scale)
	// Calculated for the updated version for the corrected Data
	Float_t nonlin_a = -0.020025549129372242;
	Float_t nonlin_b = 1.1154536660217529;
	Float_t ge_scale = 1.0493128193171741;

	Float_t weigh_a = -1.063;
	Float_t weigh_b = 0.855;

	if (isMC)
	{
		selections->Add(new AliPP13PhysPhotonSelectionMC("PhysNonlin", "Corrected for nonlinearity Physics Selection", cuts_pi0, nonlin_a, nonlin_b, ge_scale));
		selections->Add(new AliPP13PhysPhotonSelectionMC("PhysRaw", "Raw Physics Selection", cuts_pi0));

		selections->Add(new AliPP13MesonSelectionMC("MCStudy", "MC Selection with timing cut", cuts_pi0,
		                nonlin_a, nonlin_b, ge_scale,
		                weigh_a, weigh_b));

		selections->Add(new AliPP13QualityPhotonSelection("Qual", "Cluster quality Selection", cuts_pi0));

		if (suff.Contains("Only") && IsJetJetMC(description, isMC))
			selections->Add(new AliPP13PythiaInfoSelection("PythiaInfo", "Cross section and ntrials for a pthard bin."));
	}

	// Setup task
	AliAnalysisTaskPP13 * task = new AliAnalysisTaskPP13("PhosProtons", selections);

	if ( !badmap.IsNull() )
		task->SetBadMap(badmap);

	task->SelectCollisionCandidates(offlineTriggerMask);
	mgr->AddTask(task);

	mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
	AliAnalysisDataContainer * coutput = 0;
	for (Int_t i = 0; i < task->GetSelections()->GetEntries(); ++ i)
	{
		AliPP13PhotonSelection * fSel = dynamic_cast<AliPP13PhotonSelection *> (task->GetSelections()->At(i));
		fSel->SetTitle(description);
		cout << fSel->GetTitle() << endl;

		coutput = mgr->CreateContainer(fSel->GetName() + suff,
		                               TList::Class(),
		                               AliAnalysisManager::kOutputContainer,
		                               AliAnalysisManager::GetCommonFileName());
		mgr->ConnectOutput(task, i + 1, coutput);
	}
}

Bool_t IsJetJetMC(TString description, Bool_t isMC)
{
	if (!isMC)
		return kFALSE;

	if (description.Contains("Jet-Jet"))
		return kTRUE;

	cout << "Not Using PythiaInfo!!! " << endl;

	// Don't include Jet-Jet counters by default
	return kFALSE;
}<commit_msg>Update PHOS_LHC16_pp AddTaskMacro<commit_after>AliAnalysisTaskPP13 * AddAnalysisTaskPP(
	Bool_t isMC = kFALSE,
	TString description = "",
	TString suff = "",
	TString badmap = "BadMap_LHC16-updated.root"
)
{
	AliAnalysisManager * mgr = AliAnalysisManager::GetAnalysisManager();

	// Copy necessary map from the private directory
	//

	gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/o/okovalen/maps/%s .",badmap.Data()));

	// Setup Selections
	TList * selections = new TList();

	AliPP13ClusterCuts cuts_pi0 = AliPP13ClusterCuts::GetClusterCuts();
	AliPP13ClusterCuts cuts_eta = AliPP13ClusterCuts::GetClusterCuts();
	cuts_eta.fAsymmetryCut = 0.7;

	if (!isMC)
	{
		// TODO: Add plain selections
		AliPP13SelectionWeights & data_weights = AliPP13SelectionWeights::Init(AliPP13SelectionWeights::kData);
		AliPP13SelectionWeights & data_weights_plain = AliPP13SelectionWeights::Init(AliPP13SelectionWeights::kPlain);

		selections->Add(new AliPP13PhysPhotonSelection("Phys", "Physics Selection", cuts_pi0, &data_weights));
		selections->Add(new AliPP13PhysPhotonSelection("PhysPlain", "Physics Selection no TOF cut efficiency", cuts_pi0, &data_weights_plain));
		selections->Add(new AliPP13PhotonTimecutStudySelection("Time", "Testing Timing Selection", cuts_pi0, &data_weights));

		selections->Add(new AliPP13PhysPhotonSelection("Eta", "Physics Selection for eta meson", cuts_eta, &data_weights));
		selections->Add(new AliPP13PhysPhotonSelection("EtaPlain", "Physics Selection for eta meson no TOF cut efficiency", cuts_eta, &data_weights_plain));
		selections->Add(new AliPP13PhotonTimecutStudySelection("EtaTime", "Testing Timing Selection for eta meson", cuts_eta, &data_weights));

		selections->Add(new AliPP13TagAndProbeSelection("TagAndProbleTOF", "Cluster p_{T} Selection", cuts_pi0, &data_weights));
		selections->Add(new AliPP13NonlinearitySelection("PhysNonlinEst", "Physics efficiency for neutral particles", cuts_pi0, &data_weights));
		selections->Add(new AliPP13NonlinearitySelection("PhysNonlinEstPlain", "Physics efficiency for neutral particles", cuts_pi0, &data_weights_plain));

		selections->Add(new AliPP13QualityPhotonSelection("Qual", "Cluster quality Selection", cuts_pi0, &data_weights));
		selections->Add(new AliPP13PhotonSpectrumSelection("PhotonsTime", "Cluster p_{T} Selection with timing cut", cuts_pi0, &data_weights, 10., 3.));

		selections->Add(new AliPP13PhotonSpectrumSelection("Photons", "Cluster p_{T} Selection", cuts_pi0, &data_weights));
		selections->Add(new AliPP13PhotonSpectrumSelection("PhotonsPlain", "Cluster p_{T} Selection", cuts_pi0, &data_weights_plain));

		delete &data_weights;
		delete &data_weights_plain;
	}

	if (isMC)
	{
		AliPP13SelectionWeightsMC & mc_weights = AliPP13SelectionWeights::Init(AliPP13SelectionWeights::kMC);
		AliPP13SelectionWeightsMC & mc_weights_only = AliPP13SelectionWeights::Init(AliPP13SelectionWeights::kMC);

		// Nonlinearity for zs 20 Run2Default (Daiki's approximation)
		// The pi^0 peak is misplaced in this fit: A * 1.03274e+00 (global energy scale)
		// Calculated for the updated version for the corrected Data
		mc_weights.fNonA = -0.020025549129372242;
		mc_weights.fNonSigma = 1.1154536660217529;
		mc_weights.fNonGlobal = 1.0493128193171741;

		mc_weights_only.fNonGlobal = 1.0;
		mc_weights_only.fNonA = 0.0;

		selections->Add(new AliPP13EfficiencySelectionMC("PhysEff", "Physics efficiency for neutral particles fully corrected", cuts_pi0, &mc_weights));
		selections->Add(new AliPP13EfficiencySelectionMC("PhysEffPlain", "Physics efficiency for neutral particles, no nonlinearity", cuts_pi0, &mc_weights_only));

		selections->Add(new AliPP13NonlinearitySelection("PhysNonlin", "Physics nonlinearity for neutral particles", cuts_pi0, &mc_weights, kTRUE));
		selections->Add(new AliPP13NonlinearitySelection("PhysNonlinRaw", "Raw nonlinearity for neutral particles", cuts_pi0, &mc_weights_only, kTRUE));

		selections->Add(new AliPP13NonlinearityScanSelection("PhysNonlinScan", "Physics efficiency for neutral particles", cuts_pi0, &mc_weights));
		selections->Add(new AliPP13MesonSelectionMC("MCStudy", "MC Selection with timing cut", cuts_pi0, &mc_weights));

		delete & mc_weights;
		delete & mc_weights_only;
	}

	// Setup task
	AliAnalysisTaskPP13 * task = new AliAnalysisTaskPP13("PhosProtons", selections);

	if (!badmap.IsNull())
		task->SetBadMap(badmap);

	mgr->AddTask(task);

	mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
	AliAnalysisDataContainer * coutput = 0;
	for (Int_t i = 0; i < task->GetSelections()->GetEntries(); ++ i)
	{
		AliPP13PhotonSelection * fSel = dynamic_cast<AliPP13PhotonSelection *> (task->GetSelections()->At(i));
		fSel->SetTitle(description);
		cout << fSel->GetTitle() << endl;

		coutput = mgr->CreateContainer(fSel->GetName() + suff,
		                               TList::Class(),
		                               AliAnalysisManager::kOutputContainer,
		                               AliAnalysisManager::GetCommonFileName());
		mgr->ConnectOutput(task, i + 1, coutput);
	}

	return task;
}
<|endoftext|>


<commit_before>#include <aruco/aruco.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstdio>

void Autobalance(cv::Mat* im);
bool DetectArucoMarkers(
    cv::Mat* im,
    std::vector<cv::Point2f>* aruco_marker_detects_2f,
    std::vector<cv::Point3f>* aruco_marker_detects_3f);

struct camera {
  cv::Matx33d K;
  cv::Matx<double, 5, 1> distorsion;
  cv::Size size;
};

aruco::MarkerDetector aruco_detector;
std::vector<int> aruco_marker_map;
std::vector<std::vector<cv::Point3f> > aruco_board_3f;
std::vector<cv::Point3f> aruco_board_pts;

std::vector<std::vector<int> > num_detected_markers;
std::vector<std::vector<std::vector<cv::Point2f> > > marker_pnts_;
std::vector<std::vector<std::vector<cv::Point3f> > > marker_pnts_map_;
std::vector<std::vector<cv::Mat> > rvecs_;
std::vector<std::vector<cv::Mat> > tvecs_;

float square;
//std::vector<cv::Rect> ROIs;

bool AUTOBALANCE = true;
bool DRAWMARKERS = true;

int main(int argc, char *argv[]) {

  if (argc < 3) {
    std::cerr << "Usage: ./fisheye_calibration <Aruco square size> "
              << "<first device #> <OPTIONAL: # cameras>\n";
    return -1;
  }

  /****************************************************************************/
  /* Initialize video streams and camera objects                              */
  /****************************************************************************/
  int num_cameras;
  if (argc == 4) num_cameras = atoi(argv[3]);
  else num_cameras = 1;

  std::vector<cv::VideoCapture> video_stream(num_cameras);
  std::vector<camera> cameras(num_cameras);
  std::vector<int> video_num(num_cameras);
  video_num[0] = atoi(argv[2]);
  //  ROIs.resize(num_cameras);

  for (int i = 0; i < num_cameras; ++i) {
    video_num[i] = video_num[0] + i;
    video_stream[i].open(CV_CAP_FIREWIRE + video_num[i]);
    video_stream[i].set(CV_CAP_PROP_RECTIFICATION, 1);
    video_stream[i].set(CV_CAP_PROP_FPS, 10);
    if (!video_stream[i].isOpened()) {
      std::cerr << "Cannot open firewire video stream: "
                << video_num[i] << std::endl;
      return -1;
    } else {
      std::cout << "Video stream /dev/fw" << video_num[i] << " opened.\n";
    }
    cameras[i].size = cv::Size(0, 0);
    cameras[i].K = cv::Matx33d::eye();
    cameras[i].distorsion = cv::Matx<double, 5, 1>::zeros();
 //    ROIs[i] = cv::Rect(0, 0, frame[i].cols, frame[i].rows);
  }

  /****************************************************************************/
  /* Load Aruco board configuration and necessary members                     */
  /****************************************************************************/
  square = atof(argv[1]);
  {
    aruco::BoardConfiguration aruco_board_config;
    aruco_board_config.readFromFile("../data/aruco20x10_meters.yml");

    aruco_marker_map.resize(1024, -1); // in place of hashtable
    int num_markers = aruco_board_config.size();
    aruco_board_3f.resize(num_markers);
    std::vector<cv::Point3f> aruco_marker_3f(4);

    for (int i = 0; i < num_markers; ++i) {
      aruco_marker_map[aruco_board_config[i].id] = i;
      for (int j = 0; j < 4; ++j )
        aruco_marker_3f[j] = cv::Point3f(aruco_board_config[i][j]) * square;
      aruco_board_3f[i] = aruco_marker_3f;
    }
  }

  std::vector<cv::Point2f> aruco_markers_detected_2f;
  std::vector<cv::Point3f> aruco_markers_detected_3f;
  std::vector<std::vector<cv::Point2f> > single_rig_detections_2f(num_cameras);
  std::vector<std::vector<cv::Point3f> > single_rig_detections_3f(num_cameras);
  std::vector<std::vector<std::vector<cv::Point2f> > > all_rig_detections_2f(num_cameras);
  std::vector<std::vector<std::vector<cv::Point3f> > > all_rig_detections_3f(num_cameras);

  int num_calib = 0;
  char num_calib_buffer[10];

  /****************************************************************************/
  /* Start reading video stream                                               */
  /****************************************************************************/
  std::string window_name = "Video stream";
  cv::namedWindow(window_name, CV_WINDOW_AUTOSIZE);
  cv::Mat frames;
  std::vector<cv::Mat> frame(num_cameras);

  bool FOV_intersect;
  char keypress;

  while(video_stream[0].read(frame[0])) {
    frames = frame[0];
    FOV_intersect = DetectArucoMarkers(&(frame[0]),
                                       &aruco_markers_detected_2f,
                                       &aruco_markers_detected_3f);
    single_rig_detections_2f[0] = aruco_markers_detected_2f;
    single_rig_detections_3f[0] = aruco_markers_detected_3f;

    for (int i = 1; i < num_cameras; ++i) {
      video_stream[i].read(frame[i]);
      FOV_intersect &= DetectArucoMarkers(&(frame[i]),
                                          &aruco_markers_detected_2f,
                                          &aruco_markers_detected_3f);
      single_rig_detections_2f[i] = aruco_markers_detected_2f;
      single_rig_detections_3f[i] = aruco_markers_detected_3f;
      cv::hconcat(frames, frame[i], frames);
    }

    sprintf(num_calib_buffer, "%d", num_calib);
    std::string str(num_calib_buffer);
    cv::putText(frames, "# calibration captures = " + str, cv::Point(50, 50),
                cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255), 8);
    cv::putText(frames, "# calibration captures = " + str, cv::Point(50, 50),
                cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 0, 0), 3);

    cv::imshow(window_name, frames);
    keypress = cv::waitKey(30);

    // Esc key press -- EXIT
    if (keypress == 27) break;
    // SPACEBAR key press -- Collect data
    if (keypress == 32) {
      if (FOV_intersect) {
        for (int i = 0; i < num_cameras; ++i) {
          all_rig_detections_2f[i].push_back(single_rig_detections_2f[i]);
          all_rig_detections_3f[i].push_back(single_rig_detections_3f[i]);
        }
        num_calib++;
      } else {
        std::cout << "Markers not seen by every camera.\n";
      }
    }
    // RETURN key press -- Calibrate
    if (keypress == 10) {
      if (all_rig_detections_2f[0].size() == 0) {
        std::cout << "Cannot calibrate!  No data collected.\n";
      } else {
        std::cout << "Calibrating from " << num_calib
                  << " captured collections.";
        num_calib = 0;
      }
    }
  }

  /****************************************************************************/
  /* Close down                                                               *
  /****************************************************************************/
  for (int i = 0; i < num_cameras; ++i) video_stream[i].release();
  return 0;
}

bool DetectArucoMarkers(
    cv::Mat* im,
    std::vector<cv::Point2f>* aruco_marker_detects_2f,
    std::vector<cv::Point3f>* aruco_marker_detects_3f) {
  cv::Mat im_copy;
  if (!(im == NULL)) {
    cv::cvtColor(*im, im_copy, CV_BGR2GRAY);
    if (AUTOBALANCE) Autobalance(&im_copy);
    aruco_marker_detects_2f->clear();
    aruco_marker_detects_3f->clear();

    std::vector<aruco::Marker> markers;
    aruco_detector.detect(im_copy, markers);
    if (markers.size() == 0) {
      return false;
    } else {
      int marker_idx, i_ = 0;
      aruco_marker_detects_2f->resize(markers.size() * 4);
      aruco_marker_detects_3f->resize(aruco_marker_detects_2f->size());
      for (int i = 0; i < markers.size(); ++i) {
        marker_idx = aruco_marker_map[markers[i].id];
        if (marker_idx >=0) {
          if (DRAWMARKERS) markers[i].draw(*im, cv::Scalar(0, 0, 255), 2);
          for (int j = 0; j < 4; ++j) {
            (*aruco_marker_detects_2f)[i_ + j] =
              cv::Point2f(markers[i][j]);
            (*aruco_marker_detects_3f)[i_ + j] =
              cv::Point3f(aruco_board_3f[aruco_marker_map[markers[i].id]][j]);
          }
          i_ = i + 4;
        }
      }
      return true;
    }
  } else return false;
}

void Autobalance(cv::Mat* im) {
  if (!(im == NULL)) {
    double min_px, max_px;
    cv::minMaxLoc(*im, &min_px, &max_px);
    double d = 255.0f/(max_px - min_px);
    int n = im->rows * im->cols;
    for (int i = 0; i < n; ++i) {
      im->data[i] = static_cast<unsigned char>(
          (static_cast<double>(im->data[i]) - min_px) * d);
    }
  }
}
<commit_msg>working but hobbling<commit_after>#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>

#include <aruco/aruco.h>

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstdio>

void Autobalance(cv::Mat* im);
bool DetectArucoMarkers(
    cv::Mat* im,
    std::vector<cv::Point2f>* aruco_marker_detects_2f,
    std::vector<cv::Point3f>* aruco_marker_detects_3f);

struct Camera {
  cv::Matx33f K;
  cv::Matx<double, 4, 1> distorsion;
  cv::Size size;
};

aruco::MarkerDetector aruco_detector;
std::vector<int> aruco_marker_map;
std::vector<std::vector<cv::Point3f> > aruco_board_3f;
std::vector<cv::Point3f> aruco_board_pts;

std::vector<std::vector<int> > num_detected_markers;
std::vector<std::vector<std::vector<cv::Point2f> > > marker_pnts_;
std::vector<std::vector<std::vector<cv::Point3f> > > marker_pnts_map_;
std::vector<std::vector<cv::Mat> > rvecs_;
std::vector<std::vector<cv::Mat> > tvecs_;

float square;

bool AUTOBALANCE = true;
bool DRAWMARKERS = true;

int main(int argc, char *argv[]) {

  if (argc < 3) {
    std::cerr << "Usage: ./fisheye_calibration <Aruco square size> "
              << "<first device #> <OPTIONAL: # cameras>\n";
    return -1;
  }

  /****************************************************************************/
  /* Initialize video streams and camera objects                              */
  /****************************************************************************/
  int num_cameras;
  if (argc == 4) num_cameras = atoi(argv[3]);
  else num_cameras = 1;

  std::vector<cv::VideoCapture> video_stream(num_cameras);
  std::vector<Camera> cameras(num_cameras);
  std::vector<int> video_num(num_cameras);
  video_num[0] = atoi(argv[2]);

  for (int i = 0; i < num_cameras; ++i) {
    video_num[i] = video_num[0] + i;
    video_stream[i].open(CV_CAP_FIREWIRE + video_num[i]);
    video_stream[i].set(CV_CAP_PROP_RECTIFICATION, 1);
    video_stream[i].set(CV_CAP_PROP_FPS, 10);
    if (!video_stream[i].isOpened()) {
      std::cerr << "Cannot open firewire video stream: "
                << video_num[i] << std::endl;
      return -1;
    } else {
      std::cout << "Video stream /dev/fw" << video_num[i] << " opened.\n";
    }
    cameras[i].size = cv::Size(0, 0);
    cameras[i].K = cv::Matx33f::eye();
    cameras[i].distorsion = cv::Matx<double, 4, 1>::zeros();
  }

  /****************************************************************************/
  /* Load Aruco board configuration and detection data structures             */
  /****************************************************************************/
  square = atof(argv[1]);
  {
    aruco::BoardConfiguration aruco_board_config;
    aruco_board_config.readFromFile("../data/aruco20x10_meters.yml");

    aruco_marker_map.resize(1024, -1); // in place of hashtable
    int num_markers = aruco_board_config.size();
    aruco_board_3f.reserve(num_markers);
    std::vector<cv::Point3f> aruco_marker_3f(4);

    for (int i = 0; i < num_markers; ++i) {
      aruco_marker_map[aruco_board_config[i].id] = i;
      for (int j = 0; j < 4; ++j ) {
        aruco_marker_3f[j] = cv::Point3f(aruco_board_config[i][j]) * square;
        // aruco_marker_3f[j].x = aruco_board_config[i][j].x * square;
        // aruco_marker_3f[j].y = aruco_board_config[i][j].y * square;
        // aruco_marker_3f[j].z = aruco_board_config[i][j].z * square;
      }
      aruco_board_3f.push_back(aruco_marker_3f);
    }
  }

  std::vector<cv::Point2f> aruco_markers_detected_2f;
  std::vector<cv::Point3f> aruco_markers_detected_3f;
  std::vector<std::vector<cv::Point2f> > single_rig_detections_2f(num_cameras);
  std::vector<std::vector<cv::Point3f> > single_rig_detections_3f(num_cameras);
  std::vector<std::vector<std::vector<cv::Point2f> > >
      all_rig_detections_2f(num_cameras);
  std::vector<std::vector<std::vector<cv::Point3f> > >
      all_rig_detections_3f(num_cameras);

  /****************************************************************************/
  /* Initialize camera calibration data structures                            */
  /****************************************************************************/
  std::vector<cv::Mat> Ks(num_cameras, cv::Mat::eye(3,3,CV_64F));
  std::vector<cv::Mat> Ds(num_cameras, cv::Mat::zeros(4,1,CV_64F));
  std::vector<std::vector<cv::Mat> > rvecs(num_cameras);
  std::vector<std::vector<cv::Mat> > tvecs(num_cameras);
  int flag = cv::fisheye::CALIB_RECOMPUTE_EXTRINSIC ||
      cv::fisheye::CALIB_CHECK_COND ||
      cv::fisheye::CALIB_FIX_SKEW;
  double rms;

  /****************************************************************************/
  /* Start reading video stream                                               */
  /****************************************************************************/
  std::string window_name = "Video stream";
  cv::namedWindow(window_name, CV_WINDOW_AUTOSIZE);
  cv::Mat frames;
  std::vector<cv::Mat> frame(num_cameras);

  bool FOV_intersect;
  char keypress;
  int num_calib = 0;
  char num_calib_buffer[10];
  bool sane = false;

  while(video_stream[0].read(frame[0])) {
    // Initalize rig with first camera
    if (!sane) cameras[0].size = frame[0].size();
    FOV_intersect = DetectArucoMarkers(&(frame[0]),
                                       &aruco_markers_detected_2f,
                                       &aruco_markers_detected_3f);
    single_rig_detections_2f[0] = aruco_markers_detected_2f;
    single_rig_detections_3f[0] = aruco_markers_detected_3f;
    frames = frame[0];

    // Read the other cameras
    for (int i = 1; i < num_cameras; ++i) {
      video_stream[i].read(frame[i]);
      if (!sane) cameras[i].size = frame[i].size();
      FOV_intersect &= DetectArucoMarkers(&(frame[i]),
                                          &aruco_markers_detected_2f,
                                          &aruco_markers_detected_3f);
      single_rig_detections_2f[i] = aruco_markers_detected_2f;
      single_rig_detections_3f[i] = aruco_markers_detected_3f;
      cv::hconcat(frames, frame[i], frames);
    }
    if (!sane) sane = true;

    // Display status in window
    sprintf(num_calib_buffer, "%d", num_calib);
    std::string str(num_calib_buffer);
    cv::putText(frames, "# calibration captures = " + str, cv::Point(50, 50),
                cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255), 8);
    cv::putText(frames, "# calibration captures = " + str, cv::Point(50, 50),
                cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 0, 0), 3);

    // Send image to display
    cv::imshow(window_name, frames);
    keypress = cv::waitKey(30);

    // Esc key press -- EXIT
    if (keypress == 27) break;
    // SPACEBAR key press -- Collect data
    if (keypress == 32) {
      if (FOV_intersect) {
        // Aruco markers detected in every camera
        for (int i = 0; i < num_cameras; ++i) {
          all_rig_detections_2f[i].push_back(single_rig_detections_2f[i]);
          all_rig_detections_3f[i].push_back(single_rig_detections_3f[i]);
        }
        num_calib++;
      } else {
        std::cout << "Markers not seen by every camera.\n";
      }
    }
    // RETURN key press -- Calibrate
    if (keypress == 10) {
      if (all_rig_detections_2f[0].size() == 0) {
        std::cout << "Cannot calibrate!  No data collected.\n";
      } else {
        std::cout << "Calibrating from " << num_calib << " "
                  << "captured collections.";

        std::cout << "all 3f: num_cameras = "
                  << all_rig_detections_3f.size() << std::endl;
        std::cout << "all 2f: num_cameras = "
                  << all_rig_detections_2f.size() << std::endl;

        //      for ( int i = 0; i < num_cameras; ++i ) {
          int i = 1;
          cv::Mat K = cv::Mat::eye(3, 3, CV_64F);
          // cv::Mat D = cv::Mat::ones(6,1,CV_64F);
          // std::vector<cv::Mat> rvec;
          // std::vector<cv::Mat> tvec;

          cv::Vec4d D;
          std::vector<cv::Vec3f> rvec;
          std::vector<cv::Vec3f> tvec;

          std::cout << "camera " << i << " 3f: num_captures = "
                    << all_rig_detections_3f[i].size() << std::endl;
          std::cout << "camera " << i << " 2f: num_captures = "
                    << all_rig_detections_2f[i].size() << std::endl;

          std::cout << "camera " << i << " imsize = "
                    << cameras[i].size << std::endl;
          std::cout << "camera " << i << " K = " << K << std::endl;
          std::cout << "camera " << i << " D = " << D << std::endl;
          std::cout << "camera " << i << " rvecs = " << rvec.size() << std::endl;
          std::cout << "camera " << i << " tvecs = " << tvec.size() << std::endl;

          // for (int j = 0; j < all_rig_detections_3f[i].size(); ++j ) {
          //   std::cout << "capture " << j << " 3f num pts = "
          //             << all_rig_detections_3f[i][j].size() << std::endl;
          //   std::cout << "capture " << j << " 2f num pts = "
          //             << all_rig_detections_2f[i][j].size() << std::endl;
          // }
          const std::vector<std::vector<cv::Point3f> > &tmp1 = all_rig_detections_3f[i];
          const std::vector<std::vector<cv::Point2f> > &tmp2 = all_rig_detections_2f[i];

          rms = cv::fisheye::calibrate(tmp1, tmp2,
                                    cameras[i].size,
                                    K, D, rvec, tvec);

          std::cout << "hello!\n";
          std::cout << "camera " << i << " K = " << K << std::endl;
          std::cout << "camera " << i << " D = " << D << std::endl;
          std::cout << "camera " << i << " rvecs = " << rvec.size() << std::endl;
          std::cout << "camera " << i << " tvecs = " << tvec.size() << std::endl;
          // }
        num_calib = 0;
      }
    }

  }

  /****************************************************************************/
  /* Close down                                                               *
  /****************************************************************************/
  for (int i = 0; i < num_cameras; ++i) video_stream[i].release();
  return 0;
}

// This function uses the Aruco library to detect any Aruco markers in image *im
// and collects the corner image locations of the markers detected and the
// corresponding 3F coordinates from the original board configuration.
bool DetectArucoMarkers(
    cv::Mat* im,
    std::vector<cv::Point2f>* aruco_marker_detects_2f,
    std::vector<cv::Point3f>* aruco_marker_detects_3f) {
  cv::Mat im_copy;
  if (!(im == NULL)) {
    cv::cvtColor(*im, im_copy, CV_BGR2GRAY);
    if (AUTOBALANCE) Autobalance(&im_copy);
    aruco_marker_detects_2f->clear();
    aruco_marker_detects_3f->clear();

    std::vector<aruco::Marker> markers;
    aruco_detector.detect(im_copy, markers);
    if (markers.size() == 0) {
      return false;
    } else {
      int marker_idx, i_ = 0;
      aruco_marker_detects_2f->reserve(markers.size() * 4);
      aruco_marker_detects_3f->reserve(aruco_marker_detects_2f->size());
      //      aruco_marker_detects_2f->resize(markers.size() * 4);
      //      aruco_marker_detects_3f->resize(aruco_marker_detects_2f->size());
      for (int i = 0; i < markers.size(); ++i) {
        marker_idx = aruco_marker_map[markers[i].id];
        if (marker_idx >=0) {
          if (DRAWMARKERS) markers[i].draw(*im, cv::Scalar(0, 0, 255), 2);
          for (int j = 0; j < 4; ++j) {
            aruco_marker_detects_2f->push_back(cv::Point2f(markers[i][j].x,
                                                           markers[i][j].y));
            aruco_marker_detects_3f->push_back(aruco_board_3f[aruco_marker_map[markers[i].id]][j]);
            // (*aruco_marker_detects_2f)[i_ + j] =
            //   cv::Point2f(markers[i][j]);
            // (*aruco_marker_detects_3f)[i_ + j] =
            //   cv::Point3f(aruco_board_3f[aruco_marker_map[markers[i].id]][j]);
          }
          i_ = i + 4;
        }
      }
      return true;
    }
  } else return false;
}

// This function normalizes the image intensities over [0, 256)
void Autobalance(cv::Mat* im) {
  if (!(im == NULL)) {
    double min_px, max_px;
    cv::minMaxLoc(*im, &min_px, &max_px);
    double d = 255.0f/(max_px - min_px);
    int n = im->rows * im->cols;
    for (int i = 0; i < n; ++i) {
      im->data[i] = static_cast<unsigned char>(
          (static_cast<double>(im->data[i]) - min_px) * d);
    }
  }
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2015 Colin Hill
//
// 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 <Hect.h>
using namespace hect;

#include <catch.hpp>

Mesh createTestMesh()
{
    Mesh mesh("Test");

    MeshWriter meshWriter(mesh);
    meshWriter.addVertex();
    meshWriter.writeAttributeData(VertexAttributeSemantic::Position, Vector3::UnitX);
    meshWriter.addVertex();
    meshWriter.writeAttributeData(VertexAttributeSemantic::Position, Vector3::UnitY);
    meshWriter.addVertex();
    meshWriter.writeAttributeData(VertexAttributeSemantic::Position, Vector3::UnitZ);
    meshWriter.addIndex(0);
    meshWriter.addIndex(1);
    meshWriter.addIndex(2);

    return mesh;
}

TEST_CASE("Upload and destroy render object", "[Renderer]")
{
    Engine& engine = Engine::instance();
    Renderer& renderer = engine.renderer();

    Mesh mesh = createTestMesh();
    REQUIRE(!mesh.isUploaded());
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());
    renderer.destroyMesh(mesh);
    REQUIRE(!mesh.isUploaded());
}

TEST_CASE("Re-upload destroyed render object", "[Renderer]")
{
    Engine& engine = Engine::instance();
    Renderer& renderer = engine.renderer();

    Mesh mesh = createTestMesh();
    REQUIRE(!mesh.isUploaded());
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());
    renderer.destroyMesh(mesh);
    REQUIRE(!mesh.isUploaded());
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());
}

TEST_CASE("Copy uploaded render object", "[Renderer]")
{
    Engine& engine = Engine::instance();
    Renderer& renderer = engine.renderer();

    Mesh mesh = createTestMesh();
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());

    Mesh meshCopy(mesh);
    REQUIRE(!meshCopy.isUploaded());
    REQUIRE(mesh.isUploaded());

    renderer.destroyMesh(mesh);
    REQUIRE(!mesh.isUploaded());

    REQUIRE(!meshCopy.isUploaded());
}

// Disabled due to Visual Studio 2013 compiler bug (issue #111)
#ifndef HECT_WINDOWS_BUILD

TEST_CASE("Move uploaded render object", "[Renderer]")
{
    Engine& engine = Engine::instance();
    Renderer& renderer = engine.renderer();

    Mesh mesh = createTestMesh();
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());

    Mesh meshMove(std::move(mesh));
    REQUIRE(meshMove.isUploaded());
    REQUIRE(!mesh.isUploaded());

    renderer.destroyMesh(meshMove);
    REQUIRE(!meshMove.isUploaded());
}

#endif
<commit_msg>Re-enabled test that was disabled due to compiler bug (see #111)<commit_after>///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2015 Colin Hill
//
// 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 <Hect.h>
using namespace hect;

#include <catch.hpp>

Mesh createTestMesh()
{
    Mesh mesh("Test");

    MeshWriter meshWriter(mesh);
    meshWriter.addVertex();
    meshWriter.writeAttributeData(VertexAttributeSemantic::Position, Vector3::UnitX);
    meshWriter.addVertex();
    meshWriter.writeAttributeData(VertexAttributeSemantic::Position, Vector3::UnitY);
    meshWriter.addVertex();
    meshWriter.writeAttributeData(VertexAttributeSemantic::Position, Vector3::UnitZ);
    meshWriter.addIndex(0);
    meshWriter.addIndex(1);
    meshWriter.addIndex(2);

    return mesh;
}

TEST_CASE("Upload and destroy render object", "[Renderer]")
{
    Engine& engine = Engine::instance();
    Renderer& renderer = engine.renderer();

    Mesh mesh = createTestMesh();
    REQUIRE(!mesh.isUploaded());
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());
    renderer.destroyMesh(mesh);
    REQUIRE(!mesh.isUploaded());
}

TEST_CASE("Re-upload destroyed render object", "[Renderer]")
{
    Engine& engine = Engine::instance();
    Renderer& renderer = engine.renderer();

    Mesh mesh = createTestMesh();
    REQUIRE(!mesh.isUploaded());
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());
    renderer.destroyMesh(mesh);
    REQUIRE(!mesh.isUploaded());
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());
}

TEST_CASE("Copy uploaded render object", "[Renderer]")
{
    Engine& engine = Engine::instance();
    Renderer& renderer = engine.renderer();

    Mesh mesh = createTestMesh();
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());

    Mesh meshCopy(mesh);
    REQUIRE(!meshCopy.isUploaded());
    REQUIRE(mesh.isUploaded());

    renderer.destroyMesh(mesh);
    REQUIRE(!mesh.isUploaded());

    REQUIRE(!meshCopy.isUploaded());
}

TEST_CASE("Move uploaded render object", "[Renderer]")
{
    Engine& engine = Engine::instance();
    Renderer& renderer = engine.renderer();

    Mesh mesh = createTestMesh();
    renderer.uploadMesh(mesh);
    REQUIRE(mesh.isUploaded());

    Mesh meshMove(std::move(mesh));
    REQUIRE(meshMove.isUploaded());
    REQUIRE(!mesh.isUploaded());

    renderer.destroyMesh(meshMove);
    REQUIRE(!meshMove.isUploaded());
}
<|endoftext|>