<commit_before>/*************************************************************************
 *
 *  $RCSfile: ConnectionLineAccess.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 16:12:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_CONNECTIONLINEACCESS_HXX
#include "ConnectionLineAccess.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_
#include <com/sun/star/accessibility/AccessibleRelationType.hpp>
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef DBAUI_TABLECONNECTION_HXX
#include "TableConnection.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

namespace dbaui
{
    using namespace ::com::sun::star::accessibility;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    //  using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star;

    OConnectionLineAccess::OConnectionLineAccess(OTableConnection* _pLine)
        : VCLXAccessibleComponent(_pLine->GetComponentInterface().is() ? _pLine->GetWindowPeer() : NULL)
        ,m_pLine(_pLine)
    {
    }
    // -----------------------------------------------------------------------------
    void SAL_CALL OConnectionLineAccess::disposing()
    {
        m_pLine = NULL;
        VCLXAccessibleComponent::disposing();
    }
    // -----------------------------------------------------------------------------
    Any SAL_CALL OConnectionLineAccess::queryInterface( const Type& aType ) throw (RuntimeException)
    {
        Any aRet(VCLXAccessibleComponent::queryInterface( aType ));
        return aRet.hasValue() ? aRet : OConnectionLineAccess_BASE::queryInterface( aType );
    }
    // -----------------------------------------------------------------------------
    Sequence< Type > SAL_CALL OConnectionLineAccess::getTypes(  ) throw (RuntimeException)
    {
        return ::comphelper::concatSequences(VCLXAccessibleComponent::getTypes(),OConnectionLineAccess_BASE::getTypes());
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OConnectionLineAccess::getImplementationName() throw(RuntimeException)
    {
        return getImplementationName_Static();
    }
    // -----------------------------------------------------------------------------
    // XServiceInfo - static methods
    // -----------------------------------------------------------------------------
    ::rtl::OUString OConnectionLineAccess::getImplementationName_Static(void) throw( RuntimeException )
    {
        return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.ConnectionLineAccessibility");
    }
    // -----------------------------------------------------------------------------
    // XAccessibleContext
    sal_Int32 SAL_CALL OConnectionLineAccess::getAccessibleChildCount(  ) throw (RuntimeException)
    {
        return 0;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OConnectionLineAccess::getAccessibleChild( sal_Int32 i ) throw (RuntimeException)
    {
        return Reference< XAccessible >();
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OConnectionLineAccess::getAccessibleIndexInParent(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        sal_Int32 nIndex = -1;
        if( m_pLine )
        {
            // search the postion of our table window in the table window map
            nIndex = m_pLine->GetParent()->GetTabWinMap()->size();
            const ::std::vector<OTableConnection*>* pVec = m_pLine->GetParent()->getTableConnections();
            ::std::vector<OTableConnection*>::const_iterator aIter = pVec->begin();
            for (; aIter != pVec->end() && (*aIter) != m_pLine; ++nIndex,++aIter)
                ;
            nIndex = ( aIter != pVec->end() ) ? nIndex : -1;
        }
        return nIndex;
    }
    // -----------------------------------------------------------------------------
    sal_Int16 SAL_CALL OConnectionLineAccess::getAccessibleRole(  ) throw (RuntimeException)
    {
        return AccessibleRole::UNKNOWN; // ? or may be an AccessibleRole::WINDOW
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OConnectionLineAccess::getAccessibleDescription(  ) throw (RuntimeException)
    {
        static ::rtl::OUString sDescription(RTL_CONSTASCII_USTRINGPARAM("Relation"));
        return sDescription;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleRelationSet > SAL_CALL OConnectionLineAccess::getAccessibleRelationSet(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return this;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleComponent
    sal_Bool SAL_CALL OConnectionLineAccess::contains( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(_aPoint.X,_aPoint.Y);
        return m_pLine ? m_pLine->CheckHit(aPoint) : sal_False;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OConnectionLineAccess::getAccessibleAtPoint( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        return Reference< XAccessible >();
    }
    // -----------------------------------------------------------------------------
    awt::Rectangle SAL_CALL OConnectionLineAccess::getBounds(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Rectangle aRect(m_pLine ? m_pLine->GetBoundingRect() : Rectangle());
        return awt::Rectangle(aRect.getX(),aRect.getY(),aRect.getWidth(),aRect.getHeight());
    }
    // -----------------------------------------------------------------------------
    awt::Point SAL_CALL OConnectionLineAccess::getLocation(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(m_pLine ? m_pLine->GetBoundingRect().TopLeft() : Point());
        return awt::Point(aPoint.X(),aPoint.Y());
    }
    // -----------------------------------------------------------------------------
    awt::Point SAL_CALL OConnectionLineAccess::getLocationOnScreen(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(m_pLine ? m_pLine->GetParent()->ScreenToOutputPixel(m_pLine->GetBoundingRect().TopLeft()) : Point());
        return awt::Point(aPoint.X(),aPoint.Y());
    }
    // -----------------------------------------------------------------------------
    awt::Size SAL_CALL OConnectionLineAccess::getSize(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Size aSize(m_pLine ? m_pLine->GetBoundingRect().GetSize() : Size());
        return awt::Size(aSize.Width(),aSize.Height());
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isShowing(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return m_pLine ? m_pLine->GetParent()->GetWindowRegionPixel().IsInside(m_pLine->GetBoundingRect()) : sal_False;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isVisible(  ) throw (RuntimeException)
    {
        return sal_True;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isFocusTraversable(  ) throw (RuntimeException)
    {
        return sal_True;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleRelationSet
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OConnectionLineAccess::getRelationCount(  ) throw (RuntimeException)
    {
        return 1;
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OConnectionLineAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( nIndex < 0 || nIndex >= getRelationCount() )
            throw IndexOutOfBoundsException();

        Sequence< Reference<XInterface> > aSeq(m_pLine ? 2 : 0);
        if( m_pLine )
        {
            aSeq[0] = m_pLine->GetSourceWin()->GetAccessible();
            aSeq[1] = m_pLine->GetDestWin()->GetAccessible();
        }

        return AccessibleRelation(AccessibleRelationType::CONTROLLED_BY,aSeq);
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        return AccessibleRelationType::CONTROLLED_BY == aRelationType;
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OConnectionLineAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        if( AccessibleRelationType::CONTROLLED_BY == aRelationType )
            return getRelation(0);
        return AccessibleRelation();
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > OTableConnection::CreateAccessible()
    {
        return new OConnectionLineAccess(this);
    }
    // -----------------------------------------------------------------------------
    OTableConnection::~OTableConnection()
    {
        DBG_DTOR(OTableConnection,NULL);
        //////////////////////////////////////////////////////////////////////
        // clear vector
        clearLineData();
    }
    // -----------------------------------------------------------------------------
    sal_Bool OConnectionLineAccess::isEditable() const
    {
        return m_pLine ? !m_pLine->GetParent()->getDesignView()->getController()->isReadOnly() : sal_False;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleContext > SAL_CALL OConnectionLineAccess::getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException)
    {
        return this;
    }
    // -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.204); FILE MERGED 2005/09/05 17:35:23 rt 1.8.204.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ConnectionLineAccess.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:18:27 $
 *
 *  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 DBACCESS_CONNECTIONLINEACCESS_HXX
#include "ConnectionLineAccess.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_
#include <com/sun/star/accessibility/AccessibleRelationType.hpp>
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef DBAUI_TABLECONNECTION_HXX
#include "TableConnection.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

namespace dbaui
{
    using namespace ::com::sun::star::accessibility;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    //  using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star;

    OConnectionLineAccess::OConnectionLineAccess(OTableConnection* _pLine)
        : VCLXAccessibleComponent(_pLine->GetComponentInterface().is() ? _pLine->GetWindowPeer() : NULL)
        ,m_pLine(_pLine)
    {
    }
    // -----------------------------------------------------------------------------
    void SAL_CALL OConnectionLineAccess::disposing()
    {
        m_pLine = NULL;
        VCLXAccessibleComponent::disposing();
    }
    // -----------------------------------------------------------------------------
    Any SAL_CALL OConnectionLineAccess::queryInterface( const Type& aType ) throw (RuntimeException)
    {
        Any aRet(VCLXAccessibleComponent::queryInterface( aType ));
        return aRet.hasValue() ? aRet : OConnectionLineAccess_BASE::queryInterface( aType );
    }
    // -----------------------------------------------------------------------------
    Sequence< Type > SAL_CALL OConnectionLineAccess::getTypes(  ) throw (RuntimeException)
    {
        return ::comphelper::concatSequences(VCLXAccessibleComponent::getTypes(),OConnectionLineAccess_BASE::getTypes());
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OConnectionLineAccess::getImplementationName() throw(RuntimeException)
    {
        return getImplementationName_Static();
    }
    // -----------------------------------------------------------------------------
    // XServiceInfo - static methods
    // -----------------------------------------------------------------------------
    ::rtl::OUString OConnectionLineAccess::getImplementationName_Static(void) throw( RuntimeException )
    {
        return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.ConnectionLineAccessibility");
    }
    // -----------------------------------------------------------------------------
    // XAccessibleContext
    sal_Int32 SAL_CALL OConnectionLineAccess::getAccessibleChildCount(  ) throw (RuntimeException)
    {
        return 0;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OConnectionLineAccess::getAccessibleChild( sal_Int32 i ) throw (RuntimeException)
    {
        return Reference< XAccessible >();
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OConnectionLineAccess::getAccessibleIndexInParent(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        sal_Int32 nIndex = -1;
        if( m_pLine )
        {
            // search the postion of our table window in the table window map
            nIndex = m_pLine->GetParent()->GetTabWinMap()->size();
            const ::std::vector<OTableConnection*>* pVec = m_pLine->GetParent()->getTableConnections();
            ::std::vector<OTableConnection*>::const_iterator aIter = pVec->begin();
            for (; aIter != pVec->end() && (*aIter) != m_pLine; ++nIndex,++aIter)
                ;
            nIndex = ( aIter != pVec->end() ) ? nIndex : -1;
        }
        return nIndex;
    }
    // -----------------------------------------------------------------------------
    sal_Int16 SAL_CALL OConnectionLineAccess::getAccessibleRole(  ) throw (RuntimeException)
    {
        return AccessibleRole::UNKNOWN; // ? or may be an AccessibleRole::WINDOW
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OConnectionLineAccess::getAccessibleDescription(  ) throw (RuntimeException)
    {
        static ::rtl::OUString sDescription(RTL_CONSTASCII_USTRINGPARAM("Relation"));
        return sDescription;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleRelationSet > SAL_CALL OConnectionLineAccess::getAccessibleRelationSet(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return this;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleComponent
    sal_Bool SAL_CALL OConnectionLineAccess::contains( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(_aPoint.X,_aPoint.Y);
        return m_pLine ? m_pLine->CheckHit(aPoint) : sal_False;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OConnectionLineAccess::getAccessibleAtPoint( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        return Reference< XAccessible >();
    }
    // -----------------------------------------------------------------------------
    awt::Rectangle SAL_CALL OConnectionLineAccess::getBounds(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Rectangle aRect(m_pLine ? m_pLine->GetBoundingRect() : Rectangle());
        return awt::Rectangle(aRect.getX(),aRect.getY(),aRect.getWidth(),aRect.getHeight());
    }
    // -----------------------------------------------------------------------------
    awt::Point SAL_CALL OConnectionLineAccess::getLocation(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(m_pLine ? m_pLine->GetBoundingRect().TopLeft() : Point());
        return awt::Point(aPoint.X(),aPoint.Y());
    }
    // -----------------------------------------------------------------------------
    awt::Point SAL_CALL OConnectionLineAccess::getLocationOnScreen(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(m_pLine ? m_pLine->GetParent()->ScreenToOutputPixel(m_pLine->GetBoundingRect().TopLeft()) : Point());
        return awt::Point(aPoint.X(),aPoint.Y());
    }
    // -----------------------------------------------------------------------------
    awt::Size SAL_CALL OConnectionLineAccess::getSize(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Size aSize(m_pLine ? m_pLine->GetBoundingRect().GetSize() : Size());
        return awt::Size(aSize.Width(),aSize.Height());
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isShowing(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return m_pLine ? m_pLine->GetParent()->GetWindowRegionPixel().IsInside(m_pLine->GetBoundingRect()) : sal_False;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isVisible(  ) throw (RuntimeException)
    {
        return sal_True;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isFocusTraversable(  ) throw (RuntimeException)
    {
        return sal_True;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleRelationSet
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OConnectionLineAccess::getRelationCount(  ) throw (RuntimeException)
    {
        return 1;
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OConnectionLineAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( nIndex < 0 || nIndex >= getRelationCount() )
            throw IndexOutOfBoundsException();

        Sequence< Reference<XInterface> > aSeq(m_pLine ? 2 : 0);
        if( m_pLine )
        {
            aSeq[0] = m_pLine->GetSourceWin()->GetAccessible();
            aSeq[1] = m_pLine->GetDestWin()->GetAccessible();
        }

        return AccessibleRelation(AccessibleRelationType::CONTROLLED_BY,aSeq);
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        return AccessibleRelationType::CONTROLLED_BY == aRelationType;
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OConnectionLineAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        if( AccessibleRelationType::CONTROLLED_BY == aRelationType )
            return getRelation(0);
        return AccessibleRelation();
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > OTableConnection::CreateAccessible()
    {
        return new OConnectionLineAccess(this);
    }
    // -----------------------------------------------------------------------------
    OTableConnection::~OTableConnection()
    {
        DBG_DTOR(OTableConnection,NULL);
        //////////////////////////////////////////////////////////////////////
        // clear vector
        clearLineData();
    }
    // -----------------------------------------------------------------------------
    sal_Bool OConnectionLineAccess::isEditable() const
    {
        return m_pLine ? !m_pLine->GetParent()->getDesignView()->getController()->isReadOnly() : sal_False;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleContext > SAL_CALL OConnectionLineAccess::getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException)
    {
        return this;
    }
    // -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $
Version:   $Revision: 18127 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkDiffusionFunctionCollection.h"
#include <math.h>
#include "mitkVector.h"

// Namespace ::SH
#include <boost/math/special_functions/legendre.hpp>
#include <boost/math/special_functions/spherical_harmonic.hpp>
#include <boost/version.hpp>

// Namespace ::vnl_function
//#include "vnl/vnl_vector.h"

//------------------------- SH-function ------------------------------------

double mitk::sh::factorial(int number) {
    if(number <= 1) return 1;
    double result = 1.0;
    for(int i=1; i<=number; i++)
        result *= i;
    return result;
}

void mitk::sh::Cart2Sph(double x, double y, double z, double *cart)
{
    double phi, th, rad;
    rad = sqrt(x*x+y*y+z*z);
    if( rad < mitk::eps )
    {
        th = M_PI/2;
        phi = M_PI/2;
    }
    else
    {
        th = acos(z/rad);
        phi = atan2(y, x);
    }
    cart[0] = phi;
    cart[1] = th;
    cart[2] = rad;
}

double mitk::sh::legendre0(int l)
{
    if( l%2 != 0 )
    {
        return 0;
    }
    else
    {
        double prod1 = 1.0;
        for(int i=1;i<l;i+=2) prod1 *= i;
        double prod2 = 1.0;
        for(int i=2;i<=l;i+=2) prod2 *= i;
        return pow(-1.0,l/2.0)*(prod1/prod2);
    }
}

double mitk::sh::Yj(int m, int l, double theta, double phi)
{
  if (m<0)
      return sqrt(2.0)*::boost::math::spherical_harmonic_r(l, -m, theta, phi);
  else if (m==0)
      return ::boost::math::spherical_harmonic_r(l, m, theta, phi);
  else
      return pow(-1.0,m)*sqrt(2.0)*::boost::math::spherical_harmonic_i(l, m, theta, phi);

  return 0;
}

//------------------------- VNL-function ------------------------------------

template<class CurrentValue, class WntValue>
vnl_vector<WntValue> mitk::vnl_function::element_cast (vnl_vector<CurrentValue> const& v1)
{
  vnl_vector<WntValue> result(v1.size());

  for(int i = 0 ; i < v1.size(); i++)
       result[i] = static_cast<WntValue>(v1[i]);

  return result;
}
<commit_msg>COMP: fix M_PI problems<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkDiffusionFunctionCollection.h"
#include <math.h>
#include "mitkVector.h"

// for Windows
#ifndef M_PI
#define M_PI  3.14159265358979323846

// Namespace ::SH
#include <boost/math/special_functions/legendre.hpp>
#include <boost/math/special_functions/spherical_harmonic.hpp>
#include <boost/version.hpp>

// Namespace ::vnl_function
//#include "vnl/vnl_vector.h"

//------------------------- SH-function ------------------------------------

double mitk::sh::factorial(int number) {
    if(number <= 1) return 1;
    double result = 1.0;
    for(int i=1; i<=number; i++)
        result *= i;
    return result;
}

void mitk::sh::Cart2Sph(double x, double y, double z, double *cart)
{
    double phi, th, rad;
    rad = sqrt(x*x+y*y+z*z);
    if( rad < mitk::eps )
    {
        th = M_PI/2;
        phi = M_PI/2;
    }
    else
    {
        th = acos(z/rad);
        phi = atan2(y, x);
    }
    cart[0] = phi;
    cart[1] = th;
    cart[2] = rad;
}

double mitk::sh::legendre0(int l)
{
    if( l%2 != 0 )
    {
        return 0;
    }
    else
    {
        double prod1 = 1.0;
        for(int i=1;i<l;i+=2) prod1 *= i;
        double prod2 = 1.0;
        for(int i=2;i<=l;i+=2) prod2 *= i;
        return pow(-1.0,l/2.0)*(prod1/prod2);
    }
}

double mitk::sh::Yj(int m, int l, double theta, double phi)
{
  if (m<0)
      return sqrt(2.0)*::boost::math::spherical_harmonic_r(l, -m, theta, phi);
  else if (m==0)
      return ::boost::math::spherical_harmonic_r(l, m, theta, phi);
  else
      return pow(-1.0,m)*sqrt(2.0)*::boost::math::spherical_harmonic_i(l, m, theta, phi);

  return 0;
}

//------------------------- VNL-function ------------------------------------

template<class CurrentValue, class WntValue>
vnl_vector<WntValue> mitk::vnl_function::element_cast (vnl_vector<CurrentValue> const& v1)
{
  vnl_vector<WntValue> result(v1.size());

  for(int i = 0 ; i < v1.size(); i++)
       result[i] = static_cast<WntValue>(v1[i]);

  return result;
}
<|endoftext|>


<commit_before>#include "RegisterApplication.h"
#include "itkMetaImageIOFactory.h"
#include "itkPNGImageIO.h"
#include "itkPNGImageIOFactory.h"

RegisterApplication::RegisterApplication()
{
  m_FixedImageReader = ImageReaderType::New() ;
  m_MovingImageReader = ImageReaderType::New() ;
  m_RegisteredImageWriter = ImageWriterType::New() ;

  m_FixedImageReader->SetImageIO( itk::PNGImageIO::New() ) ;
  m_MovingImageReader->SetImageIO(itk::PNGImageIO::New() ) ;
  m_RegisteredImageWriter->SetImageIO(itk::PNGImageIO::New() ) ;

  m_FixedImageFlipper = ImageFlipperType::New() ;
  m_MovingImageFlipper = ImageFlipperType::New() ;
  m_RegisteredImageFlipper = ImageFlipperType::New() ;

  ImageFlipperType::FlipAxesArrayType flipAxes ;
  flipAxes[0] = false ;
  flipAxes[1] = true ;
  m_FixedImageFlipper->SetFlipAxes(flipAxes) ;
  m_MovingImageFlipper->SetFlipAxes(flipAxes) ;
  m_RegisteredImageFlipper->SetFlipAxes(flipAxes) ;

  m_FixedImageLoaded = false ;
  m_MovingImageLoaded = false ;
  m_RegisteredImageAvailable = false ;
  m_DirectoryName = "output" ;

  m_PermutationOrder[0] = 0 ;
  m_PermutationOrder[1] = 1 ;

  m_FlipAxes[0] = 0 ;
  m_FlipAxes[1] = 0 ;

  m_Display = fixedImage ;

  m_Preprocessor = PreprocessorType::New() ;

  m_Registrator = RegistratorType::New() ;

  m_Transform = TransformType::New() ;

  m_Generator = GeneratorType::New() ;

  m_NumberOfIterations = 100 ;
  m_LearningRate = 0.0001 ;
  m_TranslationScale = 0.00001 ;
  m_RotationScale = 1 ;

  // Register a producer of MetaImage and PNG readers
  itk::MetaImageIOFactory::RegisterOneFactory();
  itk::PNGImageIOFactory::RegisterOneFactory();

}

void RegisterApplication::LoadFixedImage()
{
  m_FixedImageReader->SetFileName(m_FixedImageFileName.c_str()) ;
  m_FixedImageReader->Update() ;
  m_FixedImageFlipper->SetInput(m_FixedImageReader->GetOutput()) ;
  m_FixedImageFlipper->Update() ;
  m_FixedImage = m_FixedImageFlipper->GetOutput() ;
  m_FixedImageLoaded = true ;
}

void RegisterApplication::LoadMovingImage()
{
  m_MovingImageReader->SetFileName(m_MovingImageFileName.c_str()) ;
  m_MovingImageReader->Update() ;
  m_MovingImageFlipper->SetInput(m_MovingImageReader->GetOutput()) ;
  m_MovingImageFlipper->Update() ;
  m_MovingImage = m_MovingImageFlipper->GetOutput() ;
  m_MovingImageLoaded = true ;
}

void RegisterApplication::SaveRegisteredImage(const char* filename)
{
  if( !filename )
  {
    return;
  }

  m_RegisteredImageFlipper->SetInput(m_RegisteredImage) ;
  m_RegisteredImageFlipper->Update() ;
  m_RegisteredImageWriter->SetInput(m_RegisteredImageFlipper->GetOutput()) ;
  m_RegisteredImageWriter->SetFileName( filename );
  m_RegisteredImageWriter->Write();
}

void RegisterApplication::Preprocess()
{
  m_Preprocessor->SetInputFixedImage( m_FixedImage );
  m_Preprocessor->SetInputMovingImage( m_MovingImage );

  m_Preprocessor->SetPermuteOrder( m_PermutationOrder );
  m_Preprocessor->SetFlipAxes( m_FlipAxes );

  m_Preprocessor->Execute() ;
}

void RegisterApplication::Register()
{
  m_Registrator->SetFixedImage( m_Preprocessor->GetOutputFixedImage() );
  m_Registrator->SetMovingImage( m_Preprocessor->GetOutputMovingImage() );
  m_Registrator->SetNumberOfIterations( m_NumberOfIterations );
  m_Registrator->SetLearningRates( m_LearningRate );
  m_Registrator->SetRotationScale(m_RotationScale) ;
  m_Registrator->SetTranslationScale(m_TranslationScale);

  m_Registrator->Execute() ;
}

void RegisterApplication::ComputeTransform()
{
  // Get the results
  m_Registrator->GetTransformParameters() ;
  // compose the preprocess and registration transforms
  m_Transform->SetIdentity();
  m_Transform->Compose( m_Preprocessor->GetPostTransform(), true );
  m_Transform->Compose( m_Registrator->GetAffineTransform(), true );
  m_Transform->Compose( m_Preprocessor->GetPreTransform(), true );

  m_Transform->GetMatrix() ;
  m_Transform->GetOffset() ;
}

void RegisterApplication::GenerateOutput()
{
  m_Generator->SetFixedImage( m_FixedImage );
  m_Generator->SetMovingImage( m_MovingImage );
  m_Generator->SetTransform( m_Transform );
  m_Generator->SetDirectoryName( m_DirectoryName.c_str() );

  m_Generator->Execute();

  m_RegisteredImage = m_Generator->GetResampledImage() ;
  m_RegisteredImageAvailable = true ;
}

void RegisterApplication::Execute()
{
  m_Registrator->SetFixedImageRegion(m_SelectedRegion) ;
  this->Preprocess() ;
  this->Register() ;
  this->ComputeTransform() ;
  this->GenerateOutput() ;
}

void RegisterApplication::SelectDisplay(DisplayIdentifier displayId)
{
  m_Display = displayId ;
}

void RegisterApplication::ShowDisplay()
{
  switch( m_Display )
    {
    case fixedImage :
      {
        this->ShowFixedImage() ;
        break ;
      }
    case movingImage :
      {
        this->ShowMovingImage() ;
        break ;
      }

    case registeredImage :
      {
        this->ShowRegisteredImage() ;
        break ;
      }

    case mixedChannel :
      {
        this->ShowMixedChannel() ;
        break ;
      }
    default:
      return ;
    }
}

<commit_msg>FIX: SetImageIO() calls removed from the Reader. ImageIO Factories will take care of selecting an apropriate ImageIO.<commit_after>#include "RegisterApplication.h"
#include "itkMetaImageIOFactory.h"
#include "itkPNGImageIOFactory.h"

RegisterApplication::RegisterApplication()
{
  m_FixedImageReader = ImageReaderType::New() ;
  m_MovingImageReader = ImageReaderType::New() ;
  m_RegisteredImageWriter = ImageWriterType::New() ;

  m_FixedImageFlipper = ImageFlipperType::New() ;
  m_MovingImageFlipper = ImageFlipperType::New() ;
  m_RegisteredImageFlipper = ImageFlipperType::New() ;

  ImageFlipperType::FlipAxesArrayType flipAxes ;
  flipAxes[0] = false ;
  flipAxes[1] = true ;
  m_FixedImageFlipper->SetFlipAxes(flipAxes) ;
  m_MovingImageFlipper->SetFlipAxes(flipAxes) ;
  m_RegisteredImageFlipper->SetFlipAxes(flipAxes) ;

  m_FixedImageLoaded = false ;
  m_MovingImageLoaded = false ;
  m_RegisteredImageAvailable = false ;
  m_DirectoryName = "output" ;

  m_PermutationOrder[0] = 0 ;
  m_PermutationOrder[1] = 1 ;

  m_FlipAxes[0] = 0 ;
  m_FlipAxes[1] = 0 ;

  m_Display = fixedImage ;

  m_Preprocessor = PreprocessorType::New() ;

  m_Registrator = RegistratorType::New() ;

  m_Transform = TransformType::New() ;

  m_Generator = GeneratorType::New() ;

  m_NumberOfIterations = 100 ;
  m_LearningRate = 0.0001 ;
  m_TranslationScale = 0.00001 ;
  m_RotationScale = 1 ;

  // Register a producer of MetaImage and PNG readers
  itk::MetaImageIOFactory::RegisterOneFactory();
  itk::PNGImageIOFactory::RegisterOneFactory();

}

void RegisterApplication::LoadFixedImage()
{
  m_FixedImageReader->SetFileName(m_FixedImageFileName.c_str()) ;
  m_FixedImageReader->Update() ;
  m_FixedImageFlipper->SetInput(m_FixedImageReader->GetOutput()) ;
  m_FixedImageFlipper->Update() ;
  m_FixedImage = m_FixedImageFlipper->GetOutput() ;
  m_FixedImageLoaded = true ;
}

void RegisterApplication::LoadMovingImage()
{
  m_MovingImageReader->SetFileName(m_MovingImageFileName.c_str()) ;
  m_MovingImageReader->Update() ;
  m_MovingImageFlipper->SetInput(m_MovingImageReader->GetOutput()) ;
  m_MovingImageFlipper->Update() ;
  m_MovingImage = m_MovingImageFlipper->GetOutput() ;
  m_MovingImageLoaded = true ;
}

void RegisterApplication::SaveRegisteredImage(const char* filename)
{
  if( !filename )
  {
    return;
  }

  m_RegisteredImageFlipper->SetInput(m_RegisteredImage) ;
  m_RegisteredImageFlipper->Update() ;
  m_RegisteredImageWriter->SetInput(m_RegisteredImageFlipper->GetOutput()) ;
  m_RegisteredImageWriter->SetFileName( filename );
  m_RegisteredImageWriter->Write();
}

void RegisterApplication::Preprocess()
{
  m_Preprocessor->SetInputFixedImage( m_FixedImage );
  m_Preprocessor->SetInputMovingImage( m_MovingImage );

  m_Preprocessor->SetPermuteOrder( m_PermutationOrder );
  m_Preprocessor->SetFlipAxes( m_FlipAxes );

  m_Preprocessor->Execute() ;
}

void RegisterApplication::Register()
{
  m_Registrator->SetFixedImage( m_Preprocessor->GetOutputFixedImage() );
  m_Registrator->SetMovingImage( m_Preprocessor->GetOutputMovingImage() );
  m_Registrator->SetNumberOfIterations( m_NumberOfIterations );
  m_Registrator->SetLearningRates( m_LearningRate );
  m_Registrator->SetRotationScale(m_RotationScale) ;
  m_Registrator->SetTranslationScale(m_TranslationScale);

  m_Registrator->Execute() ;
}

void RegisterApplication::ComputeTransform()
{
  // Get the results
  m_Registrator->GetTransformParameters() ;
  // compose the preprocess and registration transforms
  m_Transform->SetIdentity();
  m_Transform->Compose( m_Preprocessor->GetPostTransform(), true );
  m_Transform->Compose( m_Registrator->GetAffineTransform(), true );
  m_Transform->Compose( m_Preprocessor->GetPreTransform(), true );

  m_Transform->GetMatrix() ;
  m_Transform->GetOffset() ;
}

void RegisterApplication::GenerateOutput()
{
  m_Generator->SetFixedImage( m_FixedImage );
  m_Generator->SetMovingImage( m_MovingImage );
  m_Generator->SetTransform( m_Transform );
  m_Generator->SetDirectoryName( m_DirectoryName.c_str() );

  m_Generator->Execute();

  m_RegisteredImage = m_Generator->GetResampledImage() ;
  m_RegisteredImageAvailable = true ;
}

void RegisterApplication::Execute()
{
  m_Registrator->SetFixedImageRegion(m_SelectedRegion) ;
  this->Preprocess() ;
  this->Register() ;
  this->ComputeTransform() ;
  this->GenerateOutput() ;
}

void RegisterApplication::SelectDisplay(DisplayIdentifier displayId)
{
  m_Display = displayId ;
}

void RegisterApplication::ShowDisplay()
{
  switch( m_Display )
    {
    case fixedImage :
      {
        this->ShowFixedImage() ;
        break ;
      }
    case movingImage :
      {
        this->ShowMovingImage() ;
        break ;
      }

    case registeredImage :
      {
        this->ShowRegisteredImage() ;
        break ;
      }

    case mixedChannel :
      {
        this->ShowMixedChannel() ;
        break ;
      }
    default:
      return ;
    }
}

<|endoftext|>


<commit_before>
//
// Copyright (c) 2012 Jonathan Topf
//
// 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.
//

// Platform-specific configuration.
#define REQUIRE_IOSTREAM
#if defined __APPLE__
    #include <maya/OpenMayaMac.h>
#endif

// Maya headers.
#include <maya/MArgList.h>
#include <maya/MDagPath.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatVector.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MFnMesh.h>
#include <maya/MGlobal.h>
#include <maya/MIntArray.h>
#include <maya/MItMeshPolygon.h>
#include <maya/MObject.h>
#include <maya/MObjectArray.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
#include <maya/MPoint.h>
#include <maya/MPointArray.h>
#include <maya/MSelectionList.h>
#include <maya/MSimple.h>
#include <maya/MStatus.h>
#include <maya/MString.h>

// Standard headers.
#include <fstream>
#include <vector>

#if defined _WIN32
    #if defined ms_export_obj_EXPORTS
        #define DLLSYMBOL __declspec(dllexport)
    #else
        #define DLLSYMBOL __declspec(dllimport)
    #endif
#else
    #define DLLSYMBOL
#endif

using namespace std;

const MString Version("0.1.3");

DLLSYMBOL MStatus initializePlugin(MObject _obj);
DLLSYMBOL MStatus uninitializePlugin(MObject _obj);

DeclareSimpleCommand(ms_export_obj, "mayaseed", Version.asChar());

//
// Reference:
//
//   robthebloke.org, Intermediate Exporter + Viewer:
//   http://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/index.html
//

MStatus ms_export_obj::doIt(const MArgList& args)
{
    // Extract arguments.
    MString mesh_name;
    MString file_path;
    for (unsigned int i = 0; i < args.length(); i++)
    {
        if (args.asString(i) == "-mesh")
            mesh_name = args.asString(++i);
        else if (args.asString(i) == "-filePath")
            file_path = args.asString(++i);
    }

    MString display_info;
    display_info.format("Exporting ^1s to ^2s using ms_export_obj (native)", mesh_name, file_path);
    MGlobal::displayInfo(display_info);

    // Open file for writing, overwriting previous contents.
    ofstream out_file;
    out_file.open(file_path.asChar(), ios::trunc);
    out_file << "# File generated by ms_export_obj (native) version " << Version.asChar() << endl;

    MSelectionList sel;
    sel.add(mesh_name);

    MDagPath mesh_dag_path;
    sel.getDagPath(0, mesh_dag_path);

    MFnMesh mesh(mesh_dag_path);

    // Write vertices.
    MPointArray point_array;
    mesh.getPoints(point_array);
    const unsigned int point_count = point_array.length();
    for (unsigned int i = 0; i < point_count; ++i)
    {
        const MPoint& p = point_array[i];
        out_file << "v " << p.x << ' ' << p.y << ' ' << p.z << endl;
    }

    // Write UV coordinates.
    MFloatArray u_array, v_array;
    mesh.getUVs(u_array, v_array);
    const unsigned int uv_count = u_array.length();
    for (unsigned int i = 0; i < uv_count; ++i)
    {
        out_file << "vt " << u_array[i] << ' ' << v_array[i] << endl;
    }

    // Write normals.
    MFloatVectorArray normal_array;
    mesh.getNormals(normal_array, MSpace::kTransform);
    const unsigned int normal_count = normal_array.length();
    for (unsigned int i = 0; i < normal_count; ++i)
    {
        const MFloatVector& n = normal_array[i];
        out_file << "vn " << n.x << ' ' << n.y <<  ' ' << n.z << endl;
    }

    // Build a list of all surface shaders used on the mesh. Note that
    // the nodes returned are the shading groups, not the material nodes!
    MObjectArray shaders;
    MIntArray shader_indices;
    mesh.getConnectedShaders(0, shaders, shader_indices);

    // Build array of material names.
    vector<MString> material_names;
    for (unsigned int i = 0; i < shaders.length(); ++i)
    {
        const MFnDependencyNode shader(shaders[i]);
        const MPlug surface_shader = shader.findPlug("surfaceShader");

        MPlugArray materials;
        surface_shader.connectedTo(materials, true, true);

        for (unsigned int j = 0; j < materials.length(); ++j)
        {
            const MFnDependencyNode material(materials[j].node());
            material_names.push_back(material.name());
        }
    }

    // Write faces.
    unsigned int face_index = 0;
    unsigned int last_shader_index = ~0;
    MItMeshPolygon poly_it(mesh.object());
    while (!poly_it.isDone())
    {
        const int shader_index = shader_indices[face_index];
        if (shader_index != last_shader_index)
        {
            last_shader_index = shader_index;

            out_file << "usemtl ";
            out_file << (shader_index == -1 ? "no_material" : material_names[shader_index]);
            out_file << endl;
        }

        out_file << 'f';

        const unsigned int vertex_count = poly_it.polygonVertexCount();
        for (unsigned int i = 0; i < vertex_count; ++i)
        {
            out_file << ' ' << (poly_it.vertexIndex(i) + 1);

            if (uv_count > 0 || normal_count > 0)
                out_file << '/';

            if (uv_count > 0)
            {
                int uv_index;
                poly_it.getUVIndex(i, uv_index);
                out_file << (uv_index + 1);
            }

            if (normal_count > 0)
                out_file << '/' << (poly_it.normalIndex(i) + 1);
        }

        out_file << endl;

        ++face_index;
        poly_it.next();
    }

    // Close the file.
    out_file.close();

    return MS::kSuccess;
}
<commit_msg>fixed linking; added missing #include clause.<commit_after>
//
// Copyright (c) 2012 Jonathan Topf
//
// 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.
//

// Platform-specific configuration.
#define REQUIRE_IOSTREAM
#if defined __APPLE__
    #include <maya/OpenMayaMac.h>
#endif

// Maya headers.
#include <maya/MArgList.h>
#include <maya/MDagPath.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatVector.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MFnMesh.h>
#include <maya/MGlobal.h>
#include <maya/MIntArray.h>
#include <maya/MItMeshPolygon.h>
#include <maya/MObject.h>
#include <maya/MObjectArray.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
#include <maya/MPoint.h>
#include <maya/MPointArray.h>
#include <maya/MSelectionList.h>
#include <maya/MSimple.h>
#include <maya/MStatus.h>
#include <maya/MString.h>

// Standard headers.
#include <fstream>
#include <iostream>
#include <vector>

#if defined _WIN32
    #if defined ms_export_obj_EXPORTS
        #define DLLSYMBOL __declspec(dllexport)
    #else
        #define DLLSYMBOL __declspec(dllimport)
    #endif
#else
    #define DLLSYMBOL
#endif

using namespace std;

const MString Version("0.1.3");

DLLSYMBOL MStatus initializePlugin(MObject _obj);
DLLSYMBOL MStatus uninitializePlugin(MObject _obj);

DeclareSimpleCommand(ms_export_obj, "mayaseed", Version.asChar());

//
// Reference:
//
//   robthebloke.org, Intermediate Exporter + Viewer:
//   http://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/index.html
//

MStatus ms_export_obj::doIt(const MArgList& args)
{
    // Extract arguments.
    MString mesh_name;
    MString file_path;
    for (unsigned int i = 0; i < args.length(); i++)
    {
        if (args.asString(i) == "-mesh")
            mesh_name = args.asString(++i);
        else if (args.asString(i) == "-filePath")
            file_path = args.asString(++i);
    }

    MString display_info;
    display_info.format("Exporting ^1s to ^2s using ms_export_obj (native)", mesh_name, file_path);
    MGlobal::displayInfo(display_info);

    // Open file for writing, overwriting previous contents.
    ofstream out_file;
    out_file.open(file_path.asChar(), ios::trunc);
    out_file << "# File generated by ms_export_obj (native) version " << Version.asChar() << endl;

    MSelectionList sel;
    sel.add(mesh_name);

    MDagPath mesh_dag_path;
    sel.getDagPath(0, mesh_dag_path);

    MFnMesh mesh(mesh_dag_path);

    // Write vertices.
    MPointArray point_array;
    mesh.getPoints(point_array);
    const unsigned int point_count = point_array.length();
    for (unsigned int i = 0; i < point_count; ++i)
    {
        const MPoint& p = point_array[i];
        out_file << "v " << p.x << ' ' << p.y << ' ' << p.z << endl;
    }

    // Write UV coordinates.
    MFloatArray u_array, v_array;
    mesh.getUVs(u_array, v_array);
    const unsigned int uv_count = u_array.length();
    for (unsigned int i = 0; i < uv_count; ++i)
    {
        out_file << "vt " << u_array[i] << ' ' << v_array[i] << endl;
    }

    // Write normals.
    MFloatVectorArray normal_array;
    mesh.getNormals(normal_array, MSpace::kTransform);
    const unsigned int normal_count = normal_array.length();
    for (unsigned int i = 0; i < normal_count; ++i)
    {
        const MFloatVector& n = normal_array[i];
        out_file << "vn " << n.x << ' ' << n.y <<  ' ' << n.z << endl;
    }

    // Build a list of all surface shaders used on the mesh. Note that
    // the nodes returned are the shading groups, not the material nodes!
    MObjectArray shaders;
    MIntArray shader_indices;
    mesh.getConnectedShaders(0, shaders, shader_indices);

    // Build array of material names.
    vector<MString> material_names;
    for (unsigned int i = 0; i < shaders.length(); ++i)
    {
        const MFnDependencyNode shader(shaders[i]);
        const MPlug surface_shader = shader.findPlug("surfaceShader");

        MPlugArray materials;
        surface_shader.connectedTo(materials, true, true);

        for (unsigned int j = 0; j < materials.length(); ++j)
        {
            const MFnDependencyNode material(materials[j].node());
            material_names.push_back(material.name());
        }
    }

    // Write faces.
    unsigned int face_index = 0;
    unsigned int last_shader_index = ~0;
    MItMeshPolygon poly_it(mesh.object());
    while (!poly_it.isDone())
    {
        const int shader_index = shader_indices[face_index];
        if (shader_index != last_shader_index)
        {
            last_shader_index = shader_index;

            out_file << "usemtl ";
            out_file << (shader_index == -1 ? "no_material" : material_names[shader_index].asChar());
            out_file << endl;
        }

        out_file << 'f';

        const unsigned int vertex_count = poly_it.polygonVertexCount();
        for (unsigned int i = 0; i < vertex_count; ++i)
        {
            out_file << ' ' << (poly_it.vertexIndex(i) + 1);

            if (uv_count > 0 || normal_count > 0)
                out_file << '/';

            if (uv_count > 0)
            {
                int uv_index;
                poly_it.getUVIndex(i, uv_index);
                out_file << (uv_index + 1);
            }

            if (normal_count > 0)
                out_file << '/' << (poly_it.normalIndex(i) + 1);
        }

        out_file << endl;

        ++face_index;
        poly_it.next();
    }

    // Close the file.
    out_file.close();

    return MS::kSuccess;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbPeriodicSampler.h"
#include "otbMath.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"

namespace otb
{

bool
PeriodicSampler::ParameterType::operator!=(const PeriodicSampler::ParameterType & param) const
{
  return bool((Offset != param.Offset)||
              (MaxJitter != param.MaxJitter) ||
              (MaxBufferSize != param.MaxBufferSize));
}

void
PeriodicSampler::Reset(void)
{
  Superclass::Reset();
  // Detect maximum jitter size, clamp with (T/N - 1)
  m_JitterSize = std::min((double) this->m_Parameters.MaxJitter, 1.0/this->GetRate() - 1.0);
  if (m_JitterSize > 0.0)
    {
    // Using jitter : compute random offset value
    m_JitterValues.resize(std::min(this->GetNeededElements(), this->m_Parameters.MaxBufferSize));
    for (unsigned long i=0UL ; i<m_JitterValues.size() ; i++)
      {
      m_JitterValues[i] = itk::Statistics::MersenneTwisterRandomVariateGenerator::GetInstance()
        ->GetUniformVariate(0.0,m_JitterSize);
      }
    m_OffsetValue = m_JitterValues[0];
    }
  else
    {
    // Using a constant offset value, between 0 and T/N
    m_OffsetValue = (double)this->m_Parameters.Offset;
    while (m_OffsetValue >= 1.0/this->GetRate())
      {
      m_OffsetValue -= 1.0/this->GetRate();
      }
    }
}

bool
PeriodicSampler::TakeSample(void)
{
  bool ret = false;
  // Take p elements among N, while iterating on the full set (current index i)
  // where k elements have already been selected. The offset is in the intervall
  // [0, N/p]
  //   val = (i - offset)*p/N  - k
  //  if ceil(val) > 0; then take the sample
  this->m_ProcessedElements += 1UL;
  double val = ((double)(this->m_ProcessedElements) - m_OffsetValue )*this->GetRate() - (double)(this->m_ChosenElements);
  if (0 < (int)(vcl_ceil(val)))
    {
    this->m_ChosenElements += 1UL;
    if (m_JitterSize > 0.0)
      {
      // Using jitter : compute random offset value
      m_OffsetValue = m_JitterValues[this->m_ChosenElements%m_JitterValues.size()];
      }
    ret = true;
    }
  return ret;
}

PeriodicSampler::PeriodicSampler()
{
  this->m_Parameters.Offset = 0UL;
  this->m_Parameters.MaxJitter = 0UL;
  this->m_Parameters.MaxBufferSize = 100000000UL;
  m_JitterSize = 0.0;
  m_OffsetValue = 0.0;
}

}
<commit_msg>BUG: handle cases with no needed samples<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbPeriodicSampler.h"
#include "otbMath.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"

namespace otb
{

bool
PeriodicSampler::ParameterType::operator!=(const PeriodicSampler::ParameterType & param) const
{
  return bool((Offset != param.Offset)||
              (MaxJitter != param.MaxJitter) ||
              (MaxBufferSize != param.MaxBufferSize));
}

void
PeriodicSampler::Reset(void)
{
  Superclass::Reset();
  // Detect maximum jitter size, clamp with (T/N - 1)
  m_JitterSize = std::min((double) this->m_Parameters.MaxJitter, 1.0/this->GetRate() - 1.0);
  if (m_JitterSize > 0.0)
    {
    // Using jitter : compute random offset value
    m_JitterValues.resize(std::min(this->GetNeededElements(), this->m_Parameters.MaxBufferSize));
    for (unsigned long i=0UL ; i<m_JitterValues.size() ; i++)
      {
      m_JitterValues[i] = itk::Statistics::MersenneTwisterRandomVariateGenerator::GetInstance()
        ->GetUniformVariate(0.0,m_JitterSize);
      }
    if (m_JitterValues.empty())
      {
      m_OffsetValue = 0.0;
      }
    else
      {
      m_OffsetValue = m_JitterValues[0];
      }
    }
  else
    {
    // Using a constant offset value, between 0 and T/N
    m_OffsetValue = (double)this->m_Parameters.Offset;
    while (m_OffsetValue >= 1.0/this->GetRate())
      {
      m_OffsetValue -= 1.0/this->GetRate();
      }
    }
}

bool
PeriodicSampler::TakeSample(void)
{
  bool ret = false;
  // Take p elements among N, while iterating on the full set (current index i)
  // where k elements have already been selected. The offset is in the intervall
  // [0, N/p]
  //   val = (i - offset)*p/N  - k
  //  if ceil(val) > 0; then take the sample
  this->m_ProcessedElements += 1UL;
  double val = ((double)(this->m_ProcessedElements) - m_OffsetValue )*this->GetRate() - (double)(this->m_ChosenElements);
  if (0 < (int)(vcl_ceil(val)))
    {
    this->m_ChosenElements += 1UL;
    if (m_JitterSize > 0.0)
      {
      // Using jitter : compute random offset value
      m_OffsetValue = m_JitterValues[this->m_ChosenElements%m_JitterValues.size()];
      }
    ret = true;
    }
  return ret;
}

PeriodicSampler::PeriodicSampler()
{
  this->m_Parameters.Offset = 0UL;
  this->m_Parameters.MaxJitter = 0UL;
  this->m_Parameters.MaxBufferSize = 100000000UL;
  m_JitterSize = 0.0;
  m_OffsetValue = 0.0;
}

}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkMovieGeneratorOpenCV.h"
#include <GL/gl.h>
#include <iostream>

mitk::MovieGeneratorOpenCV::MovieGeneratorOpenCV()
{
  m_initialized = false;
  m_aviWriter   = NULL;
  m_dwRate = 20;

  m_FourCCCodec = NULL;
  m_RemoveColouredFrame = true;
}

void mitk::MovieGeneratorOpenCV::SetFileName( const char *fileName )
{

  m_sFile = fileName;
}

void mitk::MovieGeneratorOpenCV::SetFrameRate(int rate)
{
  m_dwRate = rate;
}

void mitk::MovieGeneratorOpenCV::SetRemoveColouredFrame(bool RemoveColouredFrame)
{
  m_RemoveColouredFrame = RemoveColouredFrame;
}

bool mitk::MovieGeneratorOpenCV::InitGenerator()
{
  m_width = m_renderer->GetRenderWindow()->GetSize()[0];  // changed from glGetIntegerv( GL_VIEWPORT, viewport );
  m_height = m_renderer->GetRenderWindow()->GetSize()[1]; // due to sometimes strange dimensions

  if(m_RemoveColouredFrame)
  {
    m_width  -= 10;  //remove colored boarders around renderwindows
    m_height -= 10;
  }

  m_width -= m_width % 4; // some video codecs have prerequisites to the image dimensions
  m_height -= m_height % 4;

  m_currentFrame = cvCreateImage(cvSize(m_width,m_height),8,3); // creating image with widget size, 8 bit per pixel and 3 channel r,g,b
  m_currentFrame->origin = 1; // avoid building a video with bottom up

  /*
  m_sFile = Name of the output video file.
  CV_FOURCC = 4-character code of codec used to compress the frames. For example, CV_FOURCC('P','I','M','1') is MPEG-1 codec,
  CV_FOURCC('M','J','P','G') is motion-jpeg codec etc.
   CV_FOURCC('P','I','M','1')    = MPEG-1 codec
  CV_FOURCC('M','J','P','G')    = motion-jpeg codec (does not work well)
  CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
  CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
  CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
  CV_FOURCC('U', '2', '6', '3') = H263 codec
  CV_FOURCC('I', '2', '6', '3') = H263I codec
  CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec

  List of FOURCC codes is available at http://msdn2.microsoft.com/en-us/library/ms867195.aspx

  Under Win32 it is possible to pass -1 in order to choose compression
  method and additional compression parameters from dialog.
  m_dwRate = Framerate of the created video stream.
  frame_size Size of video frames. InitGenerator
  1 = If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames
  (the flag is currently supported on Windows only).*/

  if(m_FourCCCodec != NULL)
  {
    #ifdef WIN32
      m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC(m_FourCCCodec[0],m_FourCCCodec[1],m_FourCCCodec[2],
                                        m_FourCCCodec[3]),m_dwRate,cvSize(m_width,m_height),1); //initializing video writer
    #else
      m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC(m_FourCCCodec[0],m_FourCCCodec[1],m_FourCCCodec[2],
                                        m_FourCCCodec[3]),m_dwRate,cvSize(m_width,m_height)); //initializing video writer
    #endif
  }
  else
  {
    #ifdef WIN32
      m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),-1,m_dwRate,cvSize(m_width,m_height),1); //initializing video writer
    #else
      m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC('X','V','I','D'),m_dwRate,cvSize(m_width,m_height)); //initializing video writer
    #endif
  }

  if(!m_aviWriter)
  {
    std::cout << "errors initializing video writer...correct video file path? on linux: ffmpeg must be included in OpenCV.";
    return false;
  }

  return true;
}

bool mitk::MovieGeneratorOpenCV::AddFrame( void *data )
{
  //cvSetImageData(m_currentFrame,data,m_width*3);
  memcpy(m_currentFrame->imageData,data,m_width*m_height*3);
  cvWriteFrame(m_aviWriter,m_currentFrame);
  return true;
}

bool mitk::MovieGeneratorOpenCV::TerminateGenerator()
{
  if (m_aviWriter)
  {
    cvReleaseVideoWriter(&m_aviWriter);
  }
  return true;
}
<commit_msg>modified include path for gl.h cuz on OSX previous given path does not exist.<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkMovieGeneratorOpenCV.h"
//#include <GL/gl.h>
#include "mitkgl.h"
#include <iostream>

mitk::MovieGeneratorOpenCV::MovieGeneratorOpenCV()
{
  m_initialized = false;
  m_aviWriter   = NULL;
  m_dwRate = 20;

  m_FourCCCodec = NULL;
  m_RemoveColouredFrame = true;
}

void mitk::MovieGeneratorOpenCV::SetFileName( const char *fileName )
{

  m_sFile = fileName;
}

void mitk::MovieGeneratorOpenCV::SetFrameRate(int rate)
{
  m_dwRate = rate;
}

void mitk::MovieGeneratorOpenCV::SetRemoveColouredFrame(bool RemoveColouredFrame)
{
  m_RemoveColouredFrame = RemoveColouredFrame;
}

bool mitk::MovieGeneratorOpenCV::InitGenerator()
{
  m_width = m_renderer->GetRenderWindow()->GetSize()[0];  // changed from glGetIntegerv( GL_VIEWPORT, viewport );
  m_height = m_renderer->GetRenderWindow()->GetSize()[1]; // due to sometimes strange dimensions

  if(m_RemoveColouredFrame)
  {
    m_width  -= 10;  //remove colored boarders around renderwindows
    m_height -= 10;
  }

  m_width -= m_width % 4; // some video codecs have prerequisites to the image dimensions
  m_height -= m_height % 4;

  m_currentFrame = cvCreateImage(cvSize(m_width,m_height),8,3); // creating image with widget size, 8 bit per pixel and 3 channel r,g,b
  m_currentFrame->origin = 1; // avoid building a video with bottom up

  /*
  m_sFile = Name of the output video file.
  CV_FOURCC = 4-character code of codec used to compress the frames. For example, CV_FOURCC('P','I','M','1') is MPEG-1 codec,
  CV_FOURCC('M','J','P','G') is motion-jpeg codec etc.
   CV_FOURCC('P','I','M','1')    = MPEG-1 codec
  CV_FOURCC('M','J','P','G')    = motion-jpeg codec (does not work well)
  CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
  CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
  CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
  CV_FOURCC('U', '2', '6', '3') = H263 codec
  CV_FOURCC('I', '2', '6', '3') = H263I codec
  CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec

  List of FOURCC codes is available at http://msdn2.microsoft.com/en-us/library/ms867195.aspx

  Under Win32 it is possible to pass -1 in order to choose compression
  method and additional compression parameters from dialog.
  m_dwRate = Framerate of the created video stream.
  frame_size Size of video frames. InitGenerator
  1 = If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames
  (the flag is currently supported on Windows only).*/

  if(m_FourCCCodec != NULL)
  {
    #ifdef WIN32
      m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC(m_FourCCCodec[0],m_FourCCCodec[1],m_FourCCCodec[2],
                                        m_FourCCCodec[3]),m_dwRate,cvSize(m_width,m_height),1); //initializing video writer
    #else
      m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC(m_FourCCCodec[0],m_FourCCCodec[1],m_FourCCCodec[2],
                                        m_FourCCCodec[3]),m_dwRate,cvSize(m_width,m_height)); //initializing video writer
    #endif
  }
  else
  {
    #ifdef WIN32
      m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),-1,m_dwRate,cvSize(m_width,m_height),1); //initializing video writer
    #else
      m_aviWriter = cvCreateVideoWriter(m_sFile.c_str(),CV_FOURCC('X','V','I','D'),m_dwRate,cvSize(m_width,m_height)); //initializing video writer
    #endif
  }

  if(!m_aviWriter)
  {
    std::cout << "errors initializing video writer...correct video file path? on linux: ffmpeg must be included in OpenCV.";
    return false;
  }

  return true;
}

bool mitk::MovieGeneratorOpenCV::AddFrame( void *data )
{
  //cvSetImageData(m_currentFrame,data,m_width*3);
  memcpy(m_currentFrame->imageData,data,m_width*m_height*3);
  cvWriteFrame(m_aviWriter,m_currentFrame);
  return true;
}

bool mitk::MovieGeneratorOpenCV::TerminateGenerator()
{
  if (m_aviWriter)
  {
    cvReleaseVideoWriter(&m_aviWriter);
  }
  return true;
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2009 Torus Knot Software Ltd

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 "OgreGLSLESLinkProgram.h"
#include "OgreGLSLESExtSupport.h"
#include "OgreGLSLESGpuProgram.h"
#include "OgreGLSLESProgram.h"
#include "OgreGLSLESLinkProgramManager.h"
#include "OgreStringVector.h"
#include "OgreLogManager.h"

namespace Ogre {

	//  a  builtin				custom attrib name
	// ----------------------------------------------
	//	0  gl_Vertex			vertex
	//  1  n/a					blendWeights
	//	2  gl_Normal			normal
	//	3  gl_Color				colour
	//	4  gl_SecondaryColor	secondary_colour
	//	5  gl_FogCoord			fog_coord
	//  7  n/a					blendIndices
	//	8  gl_MultiTexCoord0	uv0
	//	9  gl_MultiTexCoord1	uv1
	//	10 gl_MultiTexCoord2	uv2
	//	11 gl_MultiTexCoord3	uv3
	//	12 gl_MultiTexCoord4	uv4
	//	13 gl_MultiTexCoord5	uv5
	//	14 gl_MultiTexCoord6	uv6, tangent
	//	15 gl_MultiTexCoord7	uv7, binormal
	GLSLESLinkProgram::CustomAttribute GLSLESLinkProgram::msCustomAttributes[] = {
		CustomAttribute("vertex", GLES2GpuProgram::getFixedAttributeIndex(VES_POSITION, 0)),
		CustomAttribute("blendWeights", GLES2GpuProgram::getFixedAttributeIndex(VES_BLEND_WEIGHTS, 0)),
		CustomAttribute("normal", GLES2GpuProgram::getFixedAttributeIndex(VES_NORMAL, 0)),
		CustomAttribute("colour", GLES2GpuProgram::getFixedAttributeIndex(VES_DIFFUSE, 0)),
		CustomAttribute("secondary_colour", GLES2GpuProgram::getFixedAttributeIndex(VES_SPECULAR, 0)),
		CustomAttribute("blendIndices", GLES2GpuProgram::getFixedAttributeIndex(VES_BLEND_INDICES, 0)),
		CustomAttribute("uv0", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 0)),
		CustomAttribute("uv1", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 1)),
		CustomAttribute("uv2", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 2)),
		CustomAttribute("uv3", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 3)),
		CustomAttribute("uv4", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 4)),
		CustomAttribute("uv5", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 5)),
		CustomAttribute("uv6", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 6)),
		CustomAttribute("uv7", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 7)),
		CustomAttribute("tangent", GLES2GpuProgram::getFixedAttributeIndex(VES_TANGENT, 0)),
		CustomAttribute("binormal", GLES2GpuProgram::getFixedAttributeIndex(VES_BINORMAL, 0)),
	};

	//-----------------------------------------------------------------------
	GLSLESLinkProgram::GLSLESLinkProgram(GLSLESGpuProgram* vertexProgram, GLSLESGpuProgram* fragmentProgram)
        : mVertexProgram(vertexProgram)
		, mFragmentProgram(fragmentProgram)
		, mUniformRefsBuilt(false)
        , mLinked(false)
	{
        glGetError(); // Clean up the error. Otherwise will flood log.
        mGLHandle = glCreateProgram();
        GL_CHECK_ERROR

        // Tell shaders to attach themselves to the LinkProgram
        // let the shaders do the attaching since they may have several children to attach
        if (mVertexProgram)
        {
            mVertexProgram->getGLSLProgram()->attachToProgramObject(mGLHandle);
            setSkeletalAnimationIncluded(mVertexProgram->isSkeletalAnimationIncluded());
        }

        if (mFragmentProgram)
        {
            mFragmentProgram->getGLSLProgram()->attachToProgramObject(mGLHandle);
        }
	}

	//-----------------------------------------------------------------------
	GLSLESLinkProgram::~GLSLESLinkProgram(void)
	{
		glDeleteProgram(mGLHandle);
        GL_CHECK_ERROR;
	}

	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::activate(void)
	{
		if (!mLinked)
		{
			if (mVertexProgram)
			{
				// Some drivers (e.g. OS X on nvidia) incorrectly determine the attribute binding automatically
				// and end up aliasing existing built-ins. So avoid!
				// Bind all used attribs - not all possible ones otherwise we'll get
				// lots of warnings in the log, and also may end up aliasing names used
				// as varyings by accident
				// Because we can't ask GL whether an attribute is used in the shader
				// until it is linked (chicken and egg!) we have to parse the source

				size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute);
				const String& vpSource = mVertexProgram->getGLSLProgram()->getSource();
				for (size_t i = 0; i < numAttribs; ++i)
				{
					const CustomAttribute& a = msCustomAttributes[i];

					// We're looking for either:
					//   attribute vec<n> <semantic_name>
					//   in vec<n> <semantic_name>
					// The latter is recommended in GLSL 1.3 onwards
					// be slightly flexible about formatting
					String::size_type pos = vpSource.find(a.name);
					if (pos != String::npos)
					{
						String::size_type startpos = vpSource.find("attribute", pos < 20 ? 0 : pos-20);
						if (startpos == String::npos)
							startpos = vpSource.find("in", pos-20);
						if (startpos != String::npos && startpos < pos)
						{
							// final check
							String expr = vpSource.substr(startpos, pos + a.name.length() - startpos);
							StringVector vec = StringUtil::split(expr);
                            if ((vec[0] == "in" || vec[0] == "attribute") && vec[2] == a.name)
								glBindAttribLocation(mGLHandle, a.attrib, a.name.c_str());
                            GL_CHECK_ERROR;
						}
					}
				}
			}

			glLinkProgram( mGLHandle );
            GL_CHECK_ERROR
			glGetProgramiv( mGLHandle, GL_LINK_STATUS, &mLinked );
            GL_CHECK_ERROR

            logObjectInfo( String("GLSL link result : "), mGLHandle );
			if(mLinked)
			{
				buildGLUniformReferences();
				extractAttributes();
			}
		}

		if (mLinked)
		{
            GL_CHECK_ERROR
            glUseProgram( mGLHandle );
            GL_CHECK_ERROR
		}
	}

	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::extractAttributes(void)
	{
		size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute);

		for (size_t i = 0; i < numAttribs; ++i)
		{
			const CustomAttribute& a = msCustomAttributes[i];
			GLint attrib = glGetAttribLocation(mGLHandle, a.name.c_str());
            GL_CHECK_ERROR;

			if (attrib != -1)
			{
				mValidAttributes.insert(a.attrib);
			}
		}
	}
	//-----------------------------------------------------------------------
	GLuint GLSLESLinkProgram::getAttributeIndex(VertexElementSemantic semantic, uint index)
	{
		return GLES2GpuProgram::getFixedAttributeIndex(semantic, index);
	}
	//-----------------------------------------------------------------------
	bool GLSLESLinkProgram::isAttributeValid(VertexElementSemantic semantic, uint index)
	{
		return mValidAttributes.find(getAttributeIndex(semantic, index)) != mValidAttributes.end();
	}
	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::buildGLUniformReferences(void)
	{
		if (!mUniformRefsBuilt)
		{
			const GpuConstantDefinitionMap* vertParams = 0;
			const GpuConstantDefinitionMap* fragParams = 0;
			if (mVertexProgram)
			{
				vertParams = &(mVertexProgram->getGLSLProgram()->getConstantDefinitions().map);
			}
			if (mFragmentProgram)
			{
				fragParams = &(mFragmentProgram->getGLSLProgram()->getConstantDefinitions().map);
			}

			GLSLESLinkProgramManager::getSingleton().extractUniforms(
				mGLHandle, vertParams, fragParams, mGLUniformReferences);

			mUniformRefsBuilt = true;
		}
	}

	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::updateUniforms(GpuProgramParametersSharedPtr params,
		uint16 mask, GpuProgramType fromProgType)
	{
		// Iterate through uniform reference list and update uniform values
		GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin();
		GLUniformReferenceIterator endUniform = mGLUniformReferences.end();

		for (;currentUniform != endUniform; ++currentUniform)
		{
			// Only pull values from buffer it's supposed to be in (vertex or fragment)
			// This method will be called twice, once for vertex program params,
			// and once for fragment program params.
			if (fromProgType == currentUniform->mSourceProgType)
			{
				const GpuConstantDefinition* def = currentUniform->mConstantDef;
				if (def->variability & mask)
				{
					GLsizei glArraySize = (GLsizei)def->arraySize;

					// Get the index in the parameter real list
					switch (def->constType)
					{
					case GCT_FLOAT1:
						glUniform1fv(currentUniform->mLocation, glArraySize,
							params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_FLOAT2:
						glUniform2fv(currentUniform->mLocation, glArraySize,
							params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_FLOAT3:
						glUniform3fv(currentUniform->mLocation, glArraySize,
							params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_FLOAT4:
						glUniform4fv(currentUniform->mLocation, glArraySize,
							params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_MATRIX_2X2:
						glUniformMatrix2fv(currentUniform->mLocation, glArraySize,
							GL_FALSE, params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_MATRIX_3X3:
						glUniformMatrix3fv(currentUniform->mLocation, glArraySize,
							GL_FALSE, params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_MATRIX_4X4:
						glUniformMatrix4fv(currentUniform->mLocation, glArraySize,
							GL_FALSE, params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_INT1:
						glUniform1iv(currentUniform->mLocation, glArraySize,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_INT2:
						glUniform2iv(currentUniform->mLocation, glArraySize,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_INT3:
						glUniform3iv(currentUniform->mLocation, glArraySize,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_INT4:
						glUniform4iv(currentUniform->mLocation, glArraySize,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_SAMPLER1D:
					case GCT_SAMPLER1DSHADOW:
					case GCT_SAMPLER2D:
					case GCT_SAMPLER2DSHADOW:
					case GCT_SAMPLER3D:
					case GCT_SAMPLERCUBE:
						// Samplers handled like 1-element ints
						glUniform1iv(currentUniform->mLocation, 1,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_MATRIX_2X3:
					case GCT_MATRIX_2X4:
					case GCT_MATRIX_3X2:
					case GCT_MATRIX_3X4:
					case GCT_MATRIX_4X2:
					case GCT_MATRIX_4X3:
                    case GCT_UNKNOWN:
                        break;

					} // End switch
                    GL_CHECK_ERROR;
				} // Variability & mask
			} // fromProgType == currentUniform->mSourceProgType

  		} // End for
	}

	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::updatePassIterationUniforms(GpuProgramParametersSharedPtr params)
	{
		if (params->hasPassIterationNumber())
		{
			size_t index = params->getPassIterationNumberIndex();

			GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin();
			GLUniformReferenceIterator endUniform = mGLUniformReferences.end();

			// Need to find the uniform that matches the multi pass entry
			for (;currentUniform != endUniform; ++currentUniform)
			{
				// Get the index in the parameter real list
				if (index == currentUniform->mConstantDef->physicalIndex)
				{
					glUniform1fv(currentUniform->mLocation, 1, params->getFloatPointer(index));
                    GL_CHECK_ERROR;
					// There will only be one multipass entry
					return;
				}
			}
		}

    }
} // namespace Ogre
<commit_msg>GLES2: throw an exception if a program is created without a vertex/fragment shader pair.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2009 Torus Knot Software Ltd

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 "OgreGLSLESLinkProgram.h"
#include "OgreGLSLESExtSupport.h"
#include "OgreGLSLESGpuProgram.h"
#include "OgreGLSLESProgram.h"
#include "OgreGLSLESLinkProgramManager.h"
#include "OgreStringVector.h"
#include "OgreLogManager.h"

namespace Ogre {

	//  a  builtin				custom attrib name
	// ----------------------------------------------
	//	0  gl_Vertex			vertex
	//  1  n/a					blendWeights
	//	2  gl_Normal			normal
	//	3  gl_Color				colour
	//	4  gl_SecondaryColor	secondary_colour
	//	5  gl_FogCoord			fog_coord
	//  7  n/a					blendIndices
	//	8  gl_MultiTexCoord0	uv0
	//	9  gl_MultiTexCoord1	uv1
	//	10 gl_MultiTexCoord2	uv2
	//	11 gl_MultiTexCoord3	uv3
	//	12 gl_MultiTexCoord4	uv4
	//	13 gl_MultiTexCoord5	uv5
	//	14 gl_MultiTexCoord6	uv6, tangent
	//	15 gl_MultiTexCoord7	uv7, binormal
	GLSLESLinkProgram::CustomAttribute GLSLESLinkProgram::msCustomAttributes[] = {
		CustomAttribute("vertex", GLES2GpuProgram::getFixedAttributeIndex(VES_POSITION, 0)),
		CustomAttribute("blendWeights", GLES2GpuProgram::getFixedAttributeIndex(VES_BLEND_WEIGHTS, 0)),
		CustomAttribute("normal", GLES2GpuProgram::getFixedAttributeIndex(VES_NORMAL, 0)),
		CustomAttribute("colour", GLES2GpuProgram::getFixedAttributeIndex(VES_DIFFUSE, 0)),
		CustomAttribute("secondary_colour", GLES2GpuProgram::getFixedAttributeIndex(VES_SPECULAR, 0)),
		CustomAttribute("blendIndices", GLES2GpuProgram::getFixedAttributeIndex(VES_BLEND_INDICES, 0)),
		CustomAttribute("uv0", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 0)),
		CustomAttribute("uv1", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 1)),
		CustomAttribute("uv2", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 2)),
		CustomAttribute("uv3", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 3)),
		CustomAttribute("uv4", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 4)),
		CustomAttribute("uv5", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 5)),
		CustomAttribute("uv6", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 6)),
		CustomAttribute("uv7", GLES2GpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 7)),
		CustomAttribute("tangent", GLES2GpuProgram::getFixedAttributeIndex(VES_TANGENT, 0)),
		CustomAttribute("binormal", GLES2GpuProgram::getFixedAttributeIndex(VES_BINORMAL, 0)),
	};

	//-----------------------------------------------------------------------
	GLSLESLinkProgram::GLSLESLinkProgram(GLSLESGpuProgram* vertexProgram, GLSLESGpuProgram* fragmentProgram)
        : mVertexProgram(vertexProgram)
		, mFragmentProgram(fragmentProgram)
		, mUniformRefsBuilt(false)
        , mLinked(false)
	{
        glGetError(); // Clean up the error. Otherwise will flood log.
        mGLHandle = glCreateProgram();
        GL_CHECK_ERROR

        // Tell shaders to attach themselves to the LinkProgram
        // let the shaders do the attaching since they may have several children to attach
        if (mVertexProgram)
        {
            mVertexProgram->getGLSLProgram()->attachToProgramObject(mGLHandle);
            setSkeletalAnimationIncluded(mVertexProgram->isSkeletalAnimationIncluded());
        }

        if (mFragmentProgram)
        {
            mFragmentProgram->getGLSLProgram()->attachToProgramObject(mGLHandle);
        }

        if (!mVertexProgram && !mFragmentProgram)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Attempted to create a shader program without both a vertex and fragment program.",
                        "GLSLESLinkProgram::GLSLESLinkProgram");
        }
	}

	//-----------------------------------------------------------------------
	GLSLESLinkProgram::~GLSLESLinkProgram(void)
	{
		glDeleteProgram(mGLHandle);
        GL_CHECK_ERROR;
	}

	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::activate(void)
	{
		if (!mLinked)
		{
			if (mVertexProgram)
			{
				// Some drivers (e.g. OS X on nvidia) incorrectly determine the attribute binding automatically
				// and end up aliasing existing built-ins. So avoid!
				// Bind all used attribs - not all possible ones otherwise we'll get
				// lots of warnings in the log, and also may end up aliasing names used
				// as varyings by accident
				// Because we can't ask GL whether an attribute is used in the shader
				// until it is linked (chicken and egg!) we have to parse the source

				size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute);
				const String& vpSource = mVertexProgram->getGLSLProgram()->getSource();
				for (size_t i = 0; i < numAttribs; ++i)
				{
					const CustomAttribute& a = msCustomAttributes[i];

					// We're looking for either:
					//   attribute vec<n> <semantic_name>
					//   in vec<n> <semantic_name>
					// The latter is recommended in GLSL 1.3 onwards
					// be slightly flexible about formatting
					String::size_type pos = vpSource.find(a.name);
					if (pos != String::npos)
					{
						String::size_type startpos = vpSource.find("attribute", pos < 20 ? 0 : pos-20);
						if (startpos == String::npos)
							startpos = vpSource.find("in", pos-20);
						if (startpos != String::npos && startpos < pos)
						{
							// final check
							String expr = vpSource.substr(startpos, pos + a.name.length() - startpos);
							StringVector vec = StringUtil::split(expr);
                            if ((vec[0] == "in" || vec[0] == "attribute") && vec[2] == a.name)
								glBindAttribLocation(mGLHandle, a.attrib, a.name.c_str());
                            GL_CHECK_ERROR;
						}
					}
				}
			}

			glLinkProgram( mGLHandle );
            GL_CHECK_ERROR
			glGetProgramiv( mGLHandle, GL_LINK_STATUS, &mLinked );
            GL_CHECK_ERROR

            logObjectInfo( String("GLSL link result : "), mGLHandle );
			if(mLinked)
			{
				buildGLUniformReferences();
				extractAttributes();
			}
		}

		if (mLinked)
		{
            GL_CHECK_ERROR
            glUseProgram( mGLHandle );
            GL_CHECK_ERROR
		}
	}

	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::extractAttributes(void)
	{
		size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute);

		for (size_t i = 0; i < numAttribs; ++i)
		{
			const CustomAttribute& a = msCustomAttributes[i];
			GLint attrib = glGetAttribLocation(mGLHandle, a.name.c_str());
            GL_CHECK_ERROR;

			if (attrib != -1)
			{
				mValidAttributes.insert(a.attrib);
			}
		}
	}
	//-----------------------------------------------------------------------
	GLuint GLSLESLinkProgram::getAttributeIndex(VertexElementSemantic semantic, uint index)
	{
		return GLES2GpuProgram::getFixedAttributeIndex(semantic, index);
	}
	//-----------------------------------------------------------------------
	bool GLSLESLinkProgram::isAttributeValid(VertexElementSemantic semantic, uint index)
	{
		return mValidAttributes.find(getAttributeIndex(semantic, index)) != mValidAttributes.end();
	}
	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::buildGLUniformReferences(void)
	{
		if (!mUniformRefsBuilt)
		{
			const GpuConstantDefinitionMap* vertParams = 0;
			const GpuConstantDefinitionMap* fragParams = 0;
			if (mVertexProgram)
			{
				vertParams = &(mVertexProgram->getGLSLProgram()->getConstantDefinitions().map);
			}
			if (mFragmentProgram)
			{
				fragParams = &(mFragmentProgram->getGLSLProgram()->getConstantDefinitions().map);
			}

			GLSLESLinkProgramManager::getSingleton().extractUniforms(
				mGLHandle, vertParams, fragParams, mGLUniformReferences);

			mUniformRefsBuilt = true;
		}
	}

	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::updateUniforms(GpuProgramParametersSharedPtr params,
		uint16 mask, GpuProgramType fromProgType)
	{
		// Iterate through uniform reference list and update uniform values
		GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin();
		GLUniformReferenceIterator endUniform = mGLUniformReferences.end();

		for (;currentUniform != endUniform; ++currentUniform)
		{
			// Only pull values from buffer it's supposed to be in (vertex or fragment)
			// This method will be called twice, once for vertex program params,
			// and once for fragment program params.
			if (fromProgType == currentUniform->mSourceProgType)
			{
				const GpuConstantDefinition* def = currentUniform->mConstantDef;
				if (def->variability & mask)
				{
					GLsizei glArraySize = (GLsizei)def->arraySize;

					// Get the index in the parameter real list
					switch (def->constType)
					{
					case GCT_FLOAT1:
						glUniform1fv(currentUniform->mLocation, glArraySize,
							params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_FLOAT2:
						glUniform2fv(currentUniform->mLocation, glArraySize,
							params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_FLOAT3:
						glUniform3fv(currentUniform->mLocation, glArraySize,
							params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_FLOAT4:
						glUniform4fv(currentUniform->mLocation, glArraySize,
							params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_MATRIX_2X2:
						glUniformMatrix2fv(currentUniform->mLocation, glArraySize,
							GL_FALSE, params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_MATRIX_3X3:
						glUniformMatrix3fv(currentUniform->mLocation, glArraySize,
							GL_FALSE, params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_MATRIX_4X4:
						glUniformMatrix4fv(currentUniform->mLocation, glArraySize,
							GL_FALSE, params->getFloatPointer(def->physicalIndex));
						break;
					case GCT_INT1:
						glUniform1iv(currentUniform->mLocation, glArraySize,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_INT2:
						glUniform2iv(currentUniform->mLocation, glArraySize,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_INT3:
						glUniform3iv(currentUniform->mLocation, glArraySize,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_INT4:
						glUniform4iv(currentUniform->mLocation, glArraySize,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_SAMPLER1D:
					case GCT_SAMPLER1DSHADOW:
					case GCT_SAMPLER2D:
					case GCT_SAMPLER2DSHADOW:
					case GCT_SAMPLER3D:
					case GCT_SAMPLERCUBE:
						// Samplers handled like 1-element ints
						glUniform1iv(currentUniform->mLocation, 1,
							(GLint*)params->getIntPointer(def->physicalIndex));
						break;
					case GCT_MATRIX_2X3:
					case GCT_MATRIX_2X4:
					case GCT_MATRIX_3X2:
					case GCT_MATRIX_3X4:
					case GCT_MATRIX_4X2:
					case GCT_MATRIX_4X3:
                    case GCT_UNKNOWN:
                        break;

					} // End switch
                    GL_CHECK_ERROR;
				} // Variability & mask
			} // fromProgType == currentUniform->mSourceProgType

  		} // End for
	}

	//-----------------------------------------------------------------------
	void GLSLESLinkProgram::updatePassIterationUniforms(GpuProgramParametersSharedPtr params)
	{
		if (params->hasPassIterationNumber())
		{
			size_t index = params->getPassIterationNumberIndex();

			GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin();
			GLUniformReferenceIterator endUniform = mGLUniformReferences.end();

			// Need to find the uniform that matches the multi pass entry
			for (;currentUniform != endUniform; ++currentUniform)
			{
				// Get the index in the parameter real list
				if (index == currentUniform->mConstantDef->physicalIndex)
				{
					glUniform1fv(currentUniform->mLocation, 1, params->getFloatPointer(index));
                    GL_CHECK_ERROR;
					// There will only be one multipass entry
					return;
				}
			}
		}

    }
} // namespace Ogre
<|endoftext|>