<commit_before>/*************************************************************************
 *
 *  $RCSfile: configureucb.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-16 15:43:26 $
 *
 *  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 _UCBHELPER_CONFIGUREUCB_HXX_
#define _UCBHELPER_CONFIGUREUCB_HXX_

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#include <vector>
#ifndef INCLUDED_UCBHELPERDLLAPI_H
#include "ucbhelper/ucbhelperdllapi.h"
#endif

namespace com { namespace sun { namespace star {
    namespace lang { class XMultiServiceFactory; }
    namespace ucb {
        class XContentProvider;
        class XContentProviderManager;
    }
    namespace uno { class Any; }
} } }

namespace ucb {

//============================================================================
/** Information about a registered content provider, passed from
    <method>configureUcb</method> to <method>unconfigureUcb</method> (and from
    <method>registerAtUcb</method> to <method>deregisterFromUcb</method>).
 */
struct ContentProviderRegistrationInfo
{
    /** The registered content provider (or null if registration failed).
     */
    com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider >
        m_xProvider;

    /** The arguments the content provider was instantiated with.
     */
    rtl::OUString m_aArguments;

    /** The URL template the content provider is registered on.
     */
    rtl::OUString m_aTemplate;
};
    //@@@ if registerucb.hxx were exported, too, this might better reside in
    // there...

typedef std::vector< ContentProviderRegistrationInfo >
                                    ContentProviderRegistrationInfoList;

//============================================================================
/** Information about a content provider, passed to
    <method>configureUcb</method>.
 */
struct ContentProviderData
{
    /** The UNO service name to use to instanciate the content provider.
     */
    rtl::OUString ServiceName;

    /** The URL template to use to instanciate the content provider.
     */
    rtl::OUString URLTemplate;

    /** The arguments to use to instanciate the content provider.
     */
    rtl::OUString Arguments;

    ContentProviderData() {};
    ContentProviderData( const rtl::OUString & rService,
                         const rtl::OUString & rTemplate,
                         const rtl::OUString & rArgs )
    : ServiceName( rService ), URLTemplate( rTemplate ), Arguments( rArgs ) {}
};

typedef std::vector< ContentProviderData > ContentProviderDataList;

//============================================================================
/** Configure a (newly instantiated) Universal Content Broker.

    @descr  This function tries to register at the given content provider
    manager all the content provider services listed under a given key in the
    configuration database.

    @param rManager  A content provider manager (normally, this would be a
    newly intantiated UCB).

    @param rServiceFactory  A service factory through which to obtain the
    various services required.

    @param rData  A list containing the data for the content providers for
    the UCB to configure.

    @pInfos  If not null, an entry will be added to this vector for every
    content provider that is registered (sucessfully or not).

    @return  True if the UCB has successfuly been configured (though not all
    content providers have necessarily been registered due to individual
    problems).
 */
bool
configureUcb(
    com::sun::star::uno::Reference<
            com::sun::star::ucb::XContentProviderManager > const &
        rManager,
    com::sun::star::uno::Reference<
            com::sun::star::lang::XMultiServiceFactory > const &
        rServiceFactory,
    ContentProviderDataList const & rData,
    ContentProviderRegistrationInfoList * pInfos)
    throw (com::sun::star::uno::RuntimeException);

//============================================================================
/** Configure a (newly instantiated) Universal Content Broker.

    @descr  This function tries to register at the given content provider
    manager all the content provider services listed under a given key in the
    configuration database.

    @param rManager  A content provider manager (normally, this would be a
    newly intantiated UCB).

    @param rServiceFactory  A service factory through which to obtain the
    various services required.

    @param rArguments  A sequence of at least two strings: the primary and
    secondary key addressing a chosen UCB configuration in the configuration
    database.  The sequence can be longer, in which case the excess elements
    must be strings that form key/value pairs.  These key/value pairs will be
    used to replace placeholders in the data from the configuration database
    with (dynamic) values.  This is a (rather unstructured) sequence of
    <type>Any<type/>s, since normally this parameter will simply be forwarded
    by the UCB's <method>initialize<method/> method, which has a parameter of
    the same type.

    @pInfos  If not null, an entry will be added to this vector for every
    content provider that is registered (sucessfully or not).

    @return  True if the UCB has successfuly been configured (though not all
    content providers have necessarily been registered due to individual
    problems).
 */
UCBHELPER_DLLPUBLIC bool
configureUcb(
    com::sun::star::uno::Reference<
            com::sun::star::ucb::XContentProviderManager > const &
        rManager,
    com::sun::star::uno::Reference<
            com::sun::star::lang::XMultiServiceFactory > const &
        rServiceFactory,
    com::sun::star::uno::Sequence< com::sun::star::uno::Any > const &
        rArguments,
    std::vector< ContentProviderRegistrationInfo > * pInfos)
    throw (com::sun::star::uno::RuntimeException);

//============================================================================
/** Undo the configuration of a Universal Content Broker.

    @descr  This function is the reverse of <method>configureUcb</method>.

    @param rManager  A content provider manager.

    @param rInfos  Information about all the registered content providers.
 */
void
unconfigureUcb(
    com::sun::star::uno::Reference<
            com::sun::star::ucb::XContentProviderManager > const &
        rManager,
    std::vector< ContentProviderRegistrationInfo > const & rInfos)
    throw (com::sun::star::uno::RuntimeException);

}

#endif // _UCBHELPER_CONFIGUREUCB_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.14); FILE MERGED 2005/09/05 13:13:43 rt 1.5.14.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: configureucb.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 16:26:11 $
 *
 *  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 _UCBHELPER_CONFIGUREUCB_HXX_
#define _UCBHELPER_CONFIGUREUCB_HXX_

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#include <vector>
#ifndef INCLUDED_UCBHELPERDLLAPI_H
#include "ucbhelper/ucbhelperdllapi.h"
#endif

namespace com { namespace sun { namespace star {
    namespace lang { class XMultiServiceFactory; }
    namespace ucb {
        class XContentProvider;
        class XContentProviderManager;
    }
    namespace uno { class Any; }
} } }

namespace ucb {

//============================================================================
/** Information about a registered content provider, passed from
    <method>configureUcb</method> to <method>unconfigureUcb</method> (and from
    <method>registerAtUcb</method> to <method>deregisterFromUcb</method>).
 */
struct ContentProviderRegistrationInfo
{
    /** The registered content provider (or null if registration failed).
     */
    com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider >
        m_xProvider;

    /** The arguments the content provider was instantiated with.
     */
    rtl::OUString m_aArguments;

    /** The URL template the content provider is registered on.
     */
    rtl::OUString m_aTemplate;
};
    //@@@ if registerucb.hxx were exported, too, this might better reside in
    // there...

typedef std::vector< ContentProviderRegistrationInfo >
                                    ContentProviderRegistrationInfoList;

//============================================================================
/** Information about a content provider, passed to
    <method>configureUcb</method>.
 */
struct ContentProviderData
{
    /** The UNO service name to use to instanciate the content provider.
     */
    rtl::OUString ServiceName;

    /** The URL template to use to instanciate the content provider.
     */
    rtl::OUString URLTemplate;

    /** The arguments to use to instanciate the content provider.
     */
    rtl::OUString Arguments;

    ContentProviderData() {};
    ContentProviderData( const rtl::OUString & rService,
                         const rtl::OUString & rTemplate,
                         const rtl::OUString & rArgs )
    : ServiceName( rService ), URLTemplate( rTemplate ), Arguments( rArgs ) {}
};

typedef std::vector< ContentProviderData > ContentProviderDataList;

//============================================================================
/** Configure a (newly instantiated) Universal Content Broker.

    @descr  This function tries to register at the given content provider
    manager all the content provider services listed under a given key in the
    configuration database.

    @param rManager  A content provider manager (normally, this would be a
    newly intantiated UCB).

    @param rServiceFactory  A service factory through which to obtain the
    various services required.

    @param rData  A list containing the data for the content providers for
    the UCB to configure.

    @pInfos  If not null, an entry will be added to this vector for every
    content provider that is registered (sucessfully or not).

    @return  True if the UCB has successfuly been configured (though not all
    content providers have necessarily been registered due to individual
    problems).
 */
bool
configureUcb(
    com::sun::star::uno::Reference<
            com::sun::star::ucb::XContentProviderManager > const &
        rManager,
    com::sun::star::uno::Reference<
            com::sun::star::lang::XMultiServiceFactory > const &
        rServiceFactory,
    ContentProviderDataList const & rData,
    ContentProviderRegistrationInfoList * pInfos)
    throw (com::sun::star::uno::RuntimeException);

//============================================================================
/** Configure a (newly instantiated) Universal Content Broker.

    @descr  This function tries to register at the given content provider
    manager all the content provider services listed under a given key in the
    configuration database.

    @param rManager  A content provider manager (normally, this would be a
    newly intantiated UCB).

    @param rServiceFactory  A service factory through which to obtain the
    various services required.

    @param rArguments  A sequence of at least two strings: the primary and
    secondary key addressing a chosen UCB configuration in the configuration
    database.  The sequence can be longer, in which case the excess elements
    must be strings that form key/value pairs.  These key/value pairs will be
    used to replace placeholders in the data from the configuration database
    with (dynamic) values.  This is a (rather unstructured) sequence of
    <type>Any<type/>s, since normally this parameter will simply be forwarded
    by the UCB's <method>initialize<method/> method, which has a parameter of
    the same type.

    @pInfos  If not null, an entry will be added to this vector for every
    content provider that is registered (sucessfully or not).

    @return  True if the UCB has successfuly been configured (though not all
    content providers have necessarily been registered due to individual
    problems).
 */
UCBHELPER_DLLPUBLIC bool
configureUcb(
    com::sun::star::uno::Reference<
            com::sun::star::ucb::XContentProviderManager > const &
        rManager,
    com::sun::star::uno::Reference<
            com::sun::star::lang::XMultiServiceFactory > const &
        rServiceFactory,
    com::sun::star::uno::Sequence< com::sun::star::uno::Any > const &
        rArguments,
    std::vector< ContentProviderRegistrationInfo > * pInfos)
    throw (com::sun::star::uno::RuntimeException);

//============================================================================
/** Undo the configuration of a Universal Content Broker.

    @descr  This function is the reverse of <method>configureUcb</method>.

    @param rManager  A content provider manager.

    @param rInfos  Information about all the registered content providers.
 */
void
unconfigureUcb(
    com::sun::star::uno::Reference<
            com::sun::star::ucb::XContentProviderManager > const &
        rManager,
    std::vector< ContentProviderRegistrationInfo > const & rInfos)
    throw (com::sun::star::uno::RuntimeException);

}

#endif // _UCBHELPER_CONFIGUREUCB_HXX_
<|endoftext|>


<commit_before>#include "Power.h"
#include "Serializer.h"
#include <cstdio>

namespace ugly
{
    namespace FreeMarket
    {
        PowerParameter::PowerParameter()
            : quantity()
            , resource()
            , buildingSource()
        { }

        Power::Power()
            : type()
            , quantity()
            , quantityForced()
            , resource()
            , resourceForced()
            , buildingSource()
        { }

        Action::Action()
            : id()
            , power()
            , actionPoint()
            , priority()
        { }

        bool ActionPrivate::Execute(const GameConfig& gameSetup, const PlayerConfig& playerSetup, GameState& gameState, PlayerState& playerState, const Action& action, const PowerParameter& parameter, std::unique_ptr<ActionSource> source)
        {
            if (!source->TryConsumeActionPoints(action.actionPoint))
                return false;

            ResolvedPowerParameter resolved;
            resolved.powerOwner = std::move(source);
            switch (action.power.buildingSource)
            {
            case ParameterType::Self:
                resolved.source = resolved.powerOwner;
                break;
            case ParameterType::Choice:
                resolved.source = std::shared_ptr<ActionSource>(new BuildingActionSource(*parameter.buildingSource));
                break;
            }
            switch (action.power.quantity)
            {
            case ParameterType::Forced:
                resolved.quantity = action.power.quantityForced;
                break;
            case ParameterType::Choice:
                resolved.quantity = parameter.quantity;
                if (resolved.quantity < 0)
                    resolved.quantity = 0;
                if (action.power.quantityForced > 0 && resolved.quantity > action.power.quantityForced)
                    resolved.quantity = action.power.quantityForced;
                break;
            case ParameterType::All:
                resolved.quantity = ParameterConstant::All;
                break;
            }

            switch (action.power.type)
            {
            case PowerType::ProduceResource:
                return ExecuteSellResource(gameSetup, playerSetup, gameState, playerState, resolved);
            case PowerType::SellResource:
                return ExecuteProduceResource(gameSetup, playerSetup, gameState, playerState, resolved);
            default:
                return false;
            }
        }

        bool ActionPrivate::ExecuteProduceResource(const GameConfig& gameSetup, const PlayerConfig& playerSetup, GameState& gameState, PlayerState& playerState, const ResolvedPowerParameter& parameter)
        {
            return false;
        }

        bool ActionPrivate::ExecuteSellResource(const GameConfig& gameSetup, const PlayerConfig& playerSetup, GameState& gameState, PlayerState& playerState, const ResolvedPowerParameter& parameter)
        {
            return false;
        }
    }
}<commit_msg>Add resource type resolution<commit_after>#include "Power.h"
#include "Serializer.h"
#include <cstdio>

namespace ugly
{
    namespace FreeMarket
    {
        PowerParameter::PowerParameter()
            : quantity()
            , resource()
            , buildingSource()
        { }

        Power::Power()
            : type()
            , quantity()
            , quantityForced()
            , resource()
            , resourceForced()
            , buildingSource()
        { }

        Action::Action()
            : id()
            , power()
            , actionPoint()
            , priority()
        { }

        bool ActionPrivate::Execute(const GameConfig& gameSetup, const PlayerConfig& playerSetup, GameState& gameState, PlayerState& playerState, const Action& action, const PowerParameter& parameter, std::unique_ptr<ActionSource> source)
        {
            if (!source->TryConsumeActionPoints(action.actionPoint))
                return false;

            ResolvedPowerParameter resolved;
            resolved.powerOwner = std::move(source);
            switch (action.power.buildingSource)
            {
            case ParameterType::Self:
                resolved.source = resolved.powerOwner;
                break;
            case ParameterType::Choice:
                resolved.source = std::shared_ptr<ActionSource>(new BuildingActionSource(*parameter.buildingSource));
                break;
            }
            switch (action.power.quantity)
            {
            case ParameterType::Forced:
                resolved.quantity = action.power.quantityForced;
                break;
            case ParameterType::Choice:
                resolved.quantity = parameter.quantity;
                if (resolved.quantity < 0)
                    resolved.quantity = 0;
                if (action.power.quantityForced > 0 && resolved.quantity > action.power.quantityForced)
                    resolved.quantity = action.power.quantityForced;
                break;
            case ParameterType::All:
                resolved.quantity = ParameterConstant::All;
                break;
            }
            switch (action.power.resource)
            {
            case ParameterType::All:
                resolved.resource = ParameterConstant::All;
                break;
            case ParameterType::Choice:
                resolved.resource = parameter.resource;
                if (resolved.resource < 0 || resolved.resource > gameSetup.resourceCount)
                    resolved.resource = ParameterConstant::None;
                break;
            case ParameterType::Forced:
                resolved.resource = action.power.resourceForced;
                break;
            }

            switch (action.power.type)
            {
            case PowerType::ProduceResource:
                return ExecuteSellResource(gameSetup, playerSetup, gameState, playerState, resolved);
            case PowerType::SellResource:
                return ExecuteProduceResource(gameSetup, playerSetup, gameState, playerState, resolved);
            default:
                return false;
            }
        }

        bool ActionPrivate::ExecuteProduceResource(const GameConfig& gameSetup, const PlayerConfig& playerSetup, GameState& gameState, PlayerState& playerState, const ResolvedPowerParameter& parameter)
        {
            return false;
        }

        bool ActionPrivate::ExecuteSellResource(const GameConfig& gameSetup, const PlayerConfig& playerSetup, GameState& gameState, PlayerState& playerState, const ResolvedPowerParameter& parameter)
        {
            return false;
        }
    }
}<|endoftext|>


<commit_before>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

/* $Id: AliTRDarrayDictionary.cxx 25392 2008-04-23 19:40:29Z cblume $ */

/////////////////////////////////////////////////////////
//                                                     //
// Container Class for Dictionary Info                 //
//                                                     //
// Author:                                             //
//   Hermes Leon Vargas (hleon@ikf.uni-frankfurt.de)   //
//                                                     //
/////////////////////////////////////////////////////////

#include <TArray.h>

#include "AliTRDarrayDictionary.h"
#include "AliTRDfeeParam.h"

ClassImp(AliTRDarrayDictionary)

Short_t *AliTRDarrayDictionary::fgLutPadNumbering = 0x0;

//________________________________________________________________________________
AliTRDarrayDictionary::AliTRDarrayDictionary()
                      :TObject()
                      ,fNdet(0)
                      ,fNrow(0)
                      ,fNcol(0)
	              ,fNumberOfChannels(0)
                      ,fNtime(0)
                      ,fNDdim(0)
                      ,fDictionary(0)
                      ,fFlag(kTRUE)
{
  //
  // AliTRDarrayDictionary default contructor
  //

  CreateLut();

}

//________________________________________________________________________________
AliTRDarrayDictionary::AliTRDarrayDictionary(Int_t nrow, Int_t ncol, Int_t ntime)
                      :TObject()
		      ,fNdet(0)
                      ,fNrow(0)
                      ,fNcol(0)
          	      ,fNumberOfChannels(0)
                      ,fNtime(0)
		      ,fNDdim(0)
		      ,fDictionary(0)
                      ,fFlag(kTRUE)

{
  //
  // AliTRDarrayDictionary contructor
  //

  CreateLut();
  Allocate(nrow,ncol,ntime);

}

//________________________________________________________________________________
AliTRDarrayDictionary::AliTRDarrayDictionary(const AliTRDarrayDictionary &a)
                      :TObject()
		      ,fNdet(a.fNdet)
                      ,fNrow(a.fNrow)
                      ,fNcol(a.fNcol)
	              ,fNumberOfChannels(a.fNumberOfChannels)
                      ,fNtime(a.fNtime)
		      ,fNDdim(a.fNDdim)
		      ,fDictionary(0)
                      ,fFlag(a.fFlag)
{
  //
  // AliTRDarrayDictionary copy constructor
  //

  fDictionary = new Int_t[fNDdim];
  for(Int_t i=0; i<fNDdim; i++)
    {
      fDictionary[i]=a.fDictionary[i];
    }

}

//________________________________________________________________________________
AliTRDarrayDictionary::~AliTRDarrayDictionary()
{
  //
  //   AliTRDarrayDictionary destructor
  //

  if(fDictionary)
    {
      delete [] fDictionary;
      fDictionary=0;
    }

}

//________________________________________________________________________________
AliTRDarrayDictionary &AliTRDarrayDictionary::operator=(const AliTRDarrayDictionary &a)
{
  //
  // Assignment operator
  //

  if(this==&a)
    {
      return *this;
    }

  if(fDictionary)
    {
      delete [] fDictionary;
    }
  fNdet=a.fNdet;
  fNDdim=a.fNDdim;
  fNrow=a.fNrow;
  fNcol=a.fNcol;
  fNumberOfChannels = a.fNumberOfChannels;
  fNtime=a.fNtime;
  fDictionary = new Int_t[fNDdim];
  for(Int_t i=0; i<fNDdim; i++)
    {
      fDictionary[i]=a.fDictionary[i];
    }
  fFlag=a.fFlag;
  return *this;

}

//________________________________________________________________________________
void AliTRDarrayDictionary::Allocate(Int_t nrow, Int_t ncol, Int_t ntime)
{
  //
  // Allocates memory for the dictionary array with dimensions
  // Row*NumberOfNecessaryMCMs*ADCchannelsInMCM*Time
  // To be consistent with AliTRDarrayADC
  // Object initialized to -1
  //

  fNrow=nrow;
  fNcol=ncol;
  fNtime=ntime;
  Int_t adcchannelspermcm = AliTRDfeeParam::GetNadcMcm();
  Int_t padspermcm = AliTRDfeeParam::GetNcolMcm();
  Int_t numberofmcms = fNcol/padspermcm;
  fNumberOfChannels = numberofmcms*adcchannelspermcm;
  fNDdim=nrow*fNumberOfChannels*ntime;
  if(fDictionary)
    {
      delete [] fDictionary;
      fDictionary=0;
    }
  fDictionary = new Int_t[fNDdim];
  for(Int_t i=0; i<fNDdim; i++)
    {
      fDictionary[i] = -1;
    }

}

//________________________________________________________________________________
void AliTRDarrayDictionary::Compress()
{
  //
  // Compress the array
  //

  //  AliDebug(1,"Compressing");
  Int_t counter=0;
  Int_t newDim=0;
  Int_t j;
  Int_t r=0;
  Int_t k=0;

  Int_t *longArr = new Int_t[fNDdim];

  if(longArr)
    {

      memset(longArr,0,sizeof(Int_t)*fNDdim);

      for(Int_t i=0;i<fNDdim; i++)
        {
          j=0;
          if(fDictionary[i]==-1)
   	    {
	      for(k=i;k<fNDdim;k++)
	        {
	          if(fDictionary[k]==-1)
		    {
		      j=j+1;
		      longArr[r]=j;
		    }
	          else
		    {
		      break;
		    }
	        }
	      r=r+1;
	    }
          i=i+j;
        }

      //Calculate the size of the compressed array
      for(Int_t i=0; i<fNDdim;i++)
        {
          if(longArr[i]!=0)
	    {
	      counter=counter+longArr[i]-1;
	    }
        }
      newDim=fNDdim-counter;   //Size of the compressed array

      //Set the flag if the array has no data
      if(newDim==1)
	fFlag=kFALSE;

      //Fill the buffer of the compressed array
      Int_t* buffer = new Int_t[newDim];
      Int_t counterTwo=0;
      Int_t g=0;
      if(buffer)
        {
          for(Int_t i=0; i<newDim; i++)
            {
              if(counterTwo<fNDdim)
	        {
	          if(fDictionary[counterTwo]!=-1)
	            {
	              buffer[i]=fDictionary[counterTwo];
	            }
	          if(fDictionary[counterTwo]==-1)
	            {
	              buffer[i]=-(longArr[g]);
	              counterTwo=counterTwo+longArr[g]-1;
	              g++;
	            }
	          counterTwo++;
	        }
            }

          //Copy the buffer
          if(fDictionary)
            {
              delete [] fDictionary;
              fDictionary=0;
            }
          fDictionary = new Int_t[newDim];
          fNDdim = newDim;
          for(Int_t i=0; i<newDim; i++)
            {
              fDictionary[i] = buffer[i];
            }

          delete [] buffer;
          buffer=0;

        }

      delete [] longArr;
      longArr=0;

    }

}

//________________________________________________________________________________
void AliTRDarrayDictionary::Expand()
{
  //
  //  Expand the array
  //

  Int_t dimexp=0;

  if(!HasData()) //if the array has no data
    {
      if(fDictionary)
	{
	  dimexp = -fDictionary[0];
	  delete [] fDictionary;
	  fDictionary=0;
	  fDictionary = new Int_t[dimexp];
	  fNDdim = dimexp;
	  // Re-initialize the array
	  for(Int_t i=0; i<dimexp; i++)
	    fDictionary[i] = -1;
	}
      return;
    }

  Int_t *longArr = new Int_t[fNDdim];
  if(longArr && fDictionary)
    {

      //Initialize the array
      memset(longArr,0,sizeof(Int_t)*fNDdim);

      Int_t r2=0;
      for(Int_t i=0; i<fNDdim;i++)
        {
          if((fDictionary[i]<0)&&(fDictionary[i]!=-1))
	    {
	      longArr[r2]=-fDictionary[i];
	      r2++;
	    }
        }

      //Calculate new dimensions
      for(Int_t i=0; i<fNDdim;i++)
        {
          if(longArr[i]!=0)
	    {
	      dimexp=dimexp+longArr[i]-1;
  	    }
        }
      dimexp=dimexp+fNDdim;

      //Write in the buffer the new array
      Int_t contaexp =0;
      Int_t h=0;
      Int_t* bufferE = new Int_t[dimexp];

      if(bufferE)
	{

          for(Int_t i=0; i<dimexp; i++)
            {
              if(fDictionary[contaexp]>=-1)
	        {
	          bufferE[i]=fDictionary[contaexp];
	        }
              if(fDictionary[contaexp]<-1)
	        {
	          for(Int_t j=0; j<longArr[h];j++)
	            {
	              bufferE[i+j]=-1;
	            }
	          i=i+longArr[h]-1;
	          h++;
	        }
              contaexp++;
            }

          //Copy the buffer
          delete [] fDictionary;
          fDictionary=0;
          fDictionary = new Int_t[dimexp];
          fNDdim = dimexp;
          for(Int_t i=0; i<dimexp; i++)
            {
              fDictionary[i] = bufferE[i];
            }
          delete [] bufferE;

	}

    }

  if (longArr)
    {
      delete [] longArr;
    }

}
//________________________________________________________________________________
void AliTRDarrayDictionary::Reset()
{
  //
  // Reset the array, the old contents are deleted
  // and the data array elements are set to zero.
  //

  memset(fDictionary,0,sizeof(Int_t)*fNDdim);

}
//________________________________________________________________________________
Int_t AliTRDarrayDictionary::GetData(Int_t nrow, Int_t ncol, Int_t ntime) const
{
  //
  // Get the data using the pad numbering.
  // To access data using the mcm scheme use instead
  // the method GetDataByAdcCol
  //

  Int_t corrcolumn = fgLutPadNumbering[ncol];

  return fDictionary[(nrow*fNumberOfChannels+corrcolumn)*fNtime+ntime];

}
//________________________________________________________________________________
void AliTRDarrayDictionary::SetData(Int_t nrow, Int_t ncol, Int_t ntime, Int_t value)
{
  //
  // Set the data using the pad numbering.
  // To write data using the mcm scheme use instead
  // the method SetDataByAdcCol
  //

  Int_t colnumb = fgLutPadNumbering[ncol];

  fDictionary[(nrow*fNumberOfChannels+colnumb)*fNtime+ntime]=value;

}

//________________________________________________________________________________
void AliTRDarrayDictionary::CreateLut()
{
  //
  // Initializes the Look Up Table to relate
  // pad numbering and mcm channel numbering
  //

  if(fgLutPadNumbering)  return;

   fgLutPadNumbering = new Short_t[AliTRDfeeParam::GetNcol()];
   memset(fgLutPadNumbering,0,sizeof(Short_t)*AliTRDfeeParam::GetNcol());

  for(Int_t mcm=0; mcm<8; mcm++)
    {
      Int_t lowerlimit=0+mcm*18;
      Int_t upperlimit=18+mcm*18;
      Int_t shiftposition = 1+3*mcm;
      for(Int_t index=lowerlimit;index<upperlimit;index++)
	{
	  fgLutPadNumbering[index]=index+shiftposition;
	}
    }
}
<commit_msg>-Remove the use of additional memory by the buffer -Made an internal array smaller by using an array of UShort_t instead of Int_t -Removed two loops and substitute them by memset -Another loop now should be faster<commit_after>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

/* $Id: AliTRDarrayDictionary.cxx 25392 2008-04-23 19:40:29Z cblume $ */

/////////////////////////////////////////////////////////
//                                                     //
// Container Class for Dictionary Info                 //
//                                                     //
// Author:                                             //
//   Hermes Leon Vargas (hleon@ikf.uni-frankfurt.de)   //
//                                                     //
/////////////////////////////////////////////////////////

#include <TArray.h>

#include "AliTRDarrayDictionary.h"
#include "AliTRDfeeParam.h"

ClassImp(AliTRDarrayDictionary)

Short_t *AliTRDarrayDictionary::fgLutPadNumbering = 0x0;

//________________________________________________________________________________
AliTRDarrayDictionary::AliTRDarrayDictionary()
                      :TObject()
                      ,fNdet(0)
                      ,fNrow(0)
                      ,fNcol(0)
	              ,fNumberOfChannels(0)
                      ,fNtime(0)
                      ,fNDdim(0)
                      ,fDictionary(0)
                      ,fFlag(kTRUE)
{
  //
  // AliTRDarrayDictionary default contructor
  //

  CreateLut();

}

//________________________________________________________________________________
AliTRDarrayDictionary::AliTRDarrayDictionary(Int_t nrow, Int_t ncol, Int_t ntime)
                      :TObject()
		      ,fNdet(0)
                      ,fNrow(0)
                      ,fNcol(0)
          	      ,fNumberOfChannels(0)
                      ,fNtime(0)
		      ,fNDdim(0)
		      ,fDictionary(0)
                      ,fFlag(kTRUE)

{
  //
  // AliTRDarrayDictionary contructor
  //

  CreateLut();
  Allocate(nrow,ncol,ntime);

}

//________________________________________________________________________________
AliTRDarrayDictionary::AliTRDarrayDictionary(const AliTRDarrayDictionary &a)
                      :TObject()
		      ,fNdet(a.fNdet)
                      ,fNrow(a.fNrow)
                      ,fNcol(a.fNcol)
	              ,fNumberOfChannels(a.fNumberOfChannels)
                      ,fNtime(a.fNtime)
		      ,fNDdim(a.fNDdim)
		      ,fDictionary(0)
                      ,fFlag(a.fFlag)
{
  //
  // AliTRDarrayDictionary copy constructor
  //

  fDictionary = new Int_t[fNDdim];
  for(Int_t i=0; i<fNDdim; i++)
    {
      fDictionary[i]=a.fDictionary[i];
    }

}

//________________________________________________________________________________
AliTRDarrayDictionary::~AliTRDarrayDictionary()
{
  //
  //   AliTRDarrayDictionary destructor
  //

  if(fDictionary)
    {
      delete [] fDictionary;
      fDictionary=0;
    }

}

//________________________________________________________________________________
AliTRDarrayDictionary &AliTRDarrayDictionary::operator=(const AliTRDarrayDictionary &a)
{
  //
  // Assignment operator
  //

  if(this==&a)
    {
      return *this;
    }

  if(fDictionary)
    {
      delete [] fDictionary;
    }
  fNdet=a.fNdet;
  fNDdim=a.fNDdim;
  fNrow=a.fNrow;
  fNcol=a.fNcol;
  fNumberOfChannels = a.fNumberOfChannels;
  fNtime=a.fNtime;
  fDictionary = new Int_t[fNDdim];
  for(Int_t i=0; i<fNDdim; i++)
    {
      fDictionary[i]=a.fDictionary[i];
    }
  fFlag=a.fFlag;
  return *this;

}

//________________________________________________________________________________
void AliTRDarrayDictionary::Allocate(Int_t nrow, Int_t ncol, Int_t ntime)
{
  //
  // Allocates memory for the dictionary array with dimensions
  // Row*NumberOfNecessaryMCMs*ADCchannelsInMCM*Time
  // To be consistent with AliTRDarrayADC
  // Object initialized to -1
  //

  fNrow=nrow;
  fNcol=ncol;
  fNtime=ntime;
  Int_t adcchannelspermcm = AliTRDfeeParam::GetNadcMcm();
  Int_t padspermcm = AliTRDfeeParam::GetNcolMcm();
  Int_t numberofmcms = fNcol/padspermcm;
  fNumberOfChannels = numberofmcms*adcchannelspermcm;
  fNDdim=nrow*fNumberOfChannels*ntime;
  if(fDictionary)
    {
      delete [] fDictionary;
      fDictionary=0;
    }
  fDictionary = new Int_t[fNDdim];
  memset(fDictionary,-1,sizeof(Int_t)*fNDdim);

}

//________________________________________________________________________________
void AliTRDarrayDictionary::Compress()
{
  //
  // Compress the array
  //

  //  AliDebug(1,"Compressing");
  Int_t counter=0;
  Int_t newDim=0;
  Int_t j;
  Int_t r=0;
  Int_t k=0;

  Int_t *longArr = new Int_t[fNDdim];

  if(longArr)
    {

      memset(longArr,0,sizeof(Int_t)*fNDdim);

      for(Int_t i=0;i<fNDdim; i++)
        {
          j=0;
          if(fDictionary[i]==-1)
   	    {
	      for(k=i;k<fNDdim;k++)
	        {
	          if(fDictionary[k]==-1)
		    {
		      j=j+1;
		      longArr[r]=j;
		    }
	          else
		    {
		      break;
		    }
	        }
	      r=r+1;
	    }
          i=i+j;
        }

      //Calculate the size of the compressed array
      for(Int_t i=0; i<fNDdim;i++)
        {
          if(longArr[i]!=0)
	    {
	      counter=counter+longArr[i]-1;
	    }
        }
      newDim=fNDdim-counter;   //Size of the compressed array

      //Set the flag if the array has no data
      if(newDim==1)
	fFlag=kFALSE;

      //Fill the buffer of the compressed array
      Int_t* buffer = new Int_t[newDim];
      Int_t counterTwo=0;
      Int_t g=0;
      if(buffer)
        {
          for(Int_t i=0; i<newDim; i++)
            {
              if(counterTwo<fNDdim)
	        {
	          if(fDictionary[counterTwo]!=-1)
	            {
	              buffer[i]=fDictionary[counterTwo];
	            }
	          if(fDictionary[counterTwo]==-1)
	            {
	              buffer[i]=-(longArr[g]);
	              counterTwo=counterTwo+longArr[g]-1;
	              g++;
	            }
	          counterTwo++;
	        }
            }

          //Copy the buffer
          if(fDictionary)
            {
              delete [] fDictionary;
              fDictionary=0;
            }
	  fDictionary = buffer;
          fNDdim = newDim;
        }

      delete [] longArr;
      longArr=0;

    }

}

//________________________________________________________________________________
void AliTRDarrayDictionary::Expand()
{
  //
  //  Expand the array
  //

  Int_t dimexp=0;

  if(!HasData()) //if the array has no data (only -1's)
    {
      if(fDictionary&&fNDdim==1)
	{
	  dimexp = -fDictionary[0];
	  delete [] fDictionary;
	  fDictionary=0;
	  fDictionary = new Int_t[dimexp];
	  fNDdim = dimexp;
	  // Re-initialize the array
	  memset(fDictionary,-1,sizeof(Int_t)*dimexp);
	}
      return;
    }

  UShort_t *longArr = new UShort_t[fNDdim];
  if(longArr && fDictionary)
    {
      //Initialize the array
      memset(longArr,0,sizeof(UShort_t)*fNDdim);

      UShort_t r2=0;
      for(Int_t i=0; i<fNDdim;i++)
        {
          if((fDictionary[i]<0)&&(fDictionary[i]!=-1))
	    {
	      longArr[r2]=-fDictionary[i];
	      r2++;
	    }
        }

      //Calculate new dimensions
      for(Int_t i=0; i<fNDdim;i++)
        {
          if(longArr[i]!=0)
	    dimexp=dimexp+longArr[i]-1;
	  if(longArr[i]==0)
	    break;
        }
      dimexp=dimexp+fNDdim;

      //Write in the buffer the new array
      Int_t contaexp =0;
      Int_t h=0;
      Int_t* bufferE = new Int_t[dimexp];
      memset(bufferE,-1,sizeof(Int_t)*dimexp);

      if(bufferE)
	{

          for(Int_t i=0; i<dimexp; i++)
            {
              if(fDictionary[contaexp]>=-1)
	        {
	          bufferE[i]=fDictionary[contaexp];
	        }
              if(fDictionary[contaexp]<-1)
	        {
	          i=i+longArr[h]-1;
	          h++;
	        }
              contaexp++;
            }

          //Copy the buffer
          delete [] fDictionary;
          fDictionary=bufferE;
          fNDdim = dimexp;
	}
    }
  if (longArr)
    {
      delete [] longArr;
    }

}
//________________________________________________________________________________
void AliTRDarrayDictionary::Reset()
{
  //
  // Reset the array, the old contents are deleted
  // and the data array elements are set to zero.
  //

  memset(fDictionary,0,sizeof(Int_t)*fNDdim);

}
//________________________________________________________________________________
Int_t AliTRDarrayDictionary::GetData(Int_t nrow, Int_t ncol, Int_t ntime) const
{
  //
  // Get the data using the pad numbering.
  // To access data using the mcm scheme use instead
  // the method GetDataByAdcCol
  //

  Int_t corrcolumn = fgLutPadNumbering[ncol];

  return fDictionary[(nrow*fNumberOfChannels+corrcolumn)*fNtime+ntime];

}
//________________________________________________________________________________
void AliTRDarrayDictionary::SetData(Int_t nrow, Int_t ncol, Int_t ntime, Int_t value)
{
  //
  // Set the data using the pad numbering.
  // To write data using the mcm scheme use instead
  // the method SetDataByAdcCol
  //

  Int_t colnumb = fgLutPadNumbering[ncol];

  fDictionary[(nrow*fNumberOfChannels+colnumb)*fNtime+ntime]=value;

}

//________________________________________________________________________________
void AliTRDarrayDictionary::CreateLut()
{
  //
  // Initializes the Look Up Table to relate
  // pad numbering and mcm channel numbering
  //

  if(fgLutPadNumbering)  return;

   fgLutPadNumbering = new Short_t[AliTRDfeeParam::GetNcol()];
   memset(fgLutPadNumbering,0,sizeof(Short_t)*AliTRDfeeParam::GetNcol());

  for(Int_t mcm=0; mcm<8; mcm++)
    {
      Int_t lowerlimit=0+mcm*18;
      Int_t upperlimit=18+mcm*18;
      Int_t shiftposition = 1+3*mcm;
      for(Int_t index=lowerlimit;index<upperlimit;index++)
	{
	  fgLutPadNumbering[index]= index+shiftposition;
	}
    }
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestGPURayCastMIPToComposite.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

// This test covers vtkVolumeTextureMapper3D with a light where diffuse and
// specular components are different.
// This test volume renders a synthetic dataset with unsigned char values,
// with the composite method. The diffuse light component is gray, the
// light specular component is blue.

#include "vtkSphere.h"
#include "vtkSampleFunction.h"

#include "vtkTestUtilities.h"
#include "vtkColorTransferFunction.h"
#include "vtkPiecewiseFunction.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkVolumeProperty.h"
#include "vtkCamera.h"
#include "vtkRegressionTestImage.h"
#include "vtkImageShiftScale.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkDataArray.h"
#include "vtkLight.h"
#include "vtkLightCollection.h"
#include <cassert>
#include "vtkVolumeTextureMapper3D.h"

int TestTM3DLightComponents(int argc,
                            char *argv[])
{
  cout << "CTEST_FULL_OUTPUT (Avoid ctest truncation of output)" << endl;

  // Create a spherical implicit function.
  vtkSphere *shape=vtkSphere::New();
  shape->SetRadius(0.1);
  shape->SetCenter(0.0,0.0,0.0);

  vtkSampleFunction *source=vtkSampleFunction::New();
  source->SetImplicitFunction(shape);
  shape->Delete();
  source->SetOutputScalarTypeToDouble();
  source->SetSampleDimensions(127,127,127); // intentional NPOT dimensions.
  source->SetModelBounds(-100.0,100.0,-100.0,100.0,-100.0,100.0);
  source->SetCapping(false);
  source->SetComputeNormals(false);
  source->SetScalarArrayName("values");

  source->Update();

  vtkDataArray *a=source->GetOutput()->GetPointData()->GetScalars("values");
  double range[2];
  a->GetRange(range);

  vtkImageShiftScale *t=vtkImageShiftScale::New();
  t->SetInputConnection(source->GetOutputPort());
  source->Delete();
  t->SetShift(-range[0]);
  double magnitude=range[1]-range[0];
  if(magnitude==0.0)
    {
    magnitude=1.0;
    }
  t->SetScale(255.0/magnitude);
  t->SetOutputScalarTypeToUnsignedChar();

  t->Update();

  vtkRenderWindow *renWin=vtkRenderWindow::New();
  vtkRenderer *ren1=vtkRenderer::New();
  ren1->SetBackground(0.1,0.4,0.2);

  renWin->AddRenderer(ren1);
  ren1->Delete();
  renWin->SetSize(301,300); // intentional odd and NPOT  width/height

  vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);
  renWin->Delete();

  vtkLightCollection *lights=ren1->GetLights();
  assert("check: lights_empty" && lights->GetNumberOfItems()==0);
  vtkLight *light=vtkLight::New();
  light->SetAmbientColor(0.0,0.0,0.0);
  light->SetDiffuseColor(0.5,0.5,0.5);
  light->SetSpecularColor(0.0,0.0,1.0);
  light->SetIntensity(1.0);
  // positional light is not supported by vtkFixedPointVolumeRayCastMapper
  light->SetLightTypeToHeadlight();
  lights->AddItem(light);
  light->Delete();

  vtkVolumeProperty *volumeProperty;
  vtkVolume *volume;

  vtkVolumeTextureMapper3D *volumeMapper=vtkVolumeTextureMapper3D::New();
  volumeMapper->SetSampleDistance(1.0);

  volumeMapper->SetInputConnection(
    t->GetOutputPort());

  volumeProperty=vtkVolumeProperty::New();
  volumeMapper->SetBlendModeToComposite();
  volumeProperty->ShadeOn();
  volumeProperty->SetSpecularPower(128.0);
  volumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION);

  vtkPiecewiseFunction *compositeOpacity = vtkPiecewiseFunction::New();
  compositeOpacity->AddPoint(0.0,1.0); // 1.0
  compositeOpacity->AddPoint(80.0,1.0); // 1.0
  compositeOpacity->AddPoint(80.1,0.0); // 0.0
  compositeOpacity->AddPoint(255.0,0.0); // 0.0
  volumeProperty->SetScalarOpacity(compositeOpacity);

  vtkColorTransferFunction *color=vtkColorTransferFunction::New();
  color->AddRGBPoint(0.0  ,1.0,1.0,1.0); // blue
  color->AddRGBPoint(40.0  ,1.0,1.0,1.0); // red
  color->AddRGBPoint(255.0,1.0,1.0,1.0); // white
  volumeProperty->SetColor(color);
  color->Delete();

  volume=vtkVolume::New();
  volume->SetMapper(volumeMapper);
  volume->SetProperty(volumeProperty);
  ren1->AddViewProp(volume);

  int retVal;

  ren1->ResetCamera();
  renWin->Render();

  retVal = vtkTesting::Test(argc, argv, renWin, 75);
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  volumeMapper->Delete();
  volumeProperty->Delete();
  volume->Delete();
  iren->Delete();
  t->Delete();
  compositeOpacity->Delete();

  return !((retVal == vtkTesting::PASSED) || (retVal == vtkTesting::DO_INTERACTOR));
}
<commit_msg>ENH:Make TestTM3DLightComponents.cxx passing on old configurations.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestGPURayCastMIPToComposite.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

// This test covers vtkVolumeTextureMapper3D with a light where diffuse and
// specular components are different.
// This test volume renders a synthetic dataset with unsigned char values,
// with the composite method. The diffuse light component is gray, the
// light specular component is blue.

#include "vtkSphere.h"
#include "vtkSampleFunction.h"

#include "vtkTestUtilities.h"
#include "vtkColorTransferFunction.h"
#include "vtkPiecewiseFunction.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkVolumeProperty.h"
#include "vtkCamera.h"
#include "vtkRegressionTestImage.h"
#include "vtkImageShiftScale.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkDataArray.h"
#include "vtkLight.h"
#include "vtkLightCollection.h"
#include <cassert>
#include "vtkVolumeTextureMapper3D.h"

int TestTM3DLightComponents(int argc,
                            char *argv[])
{
  cout << "CTEST_FULL_OUTPUT (Avoid ctest truncation of output)" << endl;

  // Create a spherical implicit function.
  vtkSphere *shape=vtkSphere::New();
  shape->SetRadius(0.1);
  shape->SetCenter(0.0,0.0,0.0);

  vtkSampleFunction *source=vtkSampleFunction::New();
  source->SetImplicitFunction(shape);
  shape->Delete();
  source->SetOutputScalarTypeToDouble();
  source->SetSampleDimensions(127,127,127); // intentional NPOT dimensions.
  source->SetModelBounds(-100.0,100.0,-100.0,100.0,-100.0,100.0);
  source->SetCapping(false);
  source->SetComputeNormals(false);
  source->SetScalarArrayName("values");

  source->Update();

  vtkDataArray *a=source->GetOutput()->GetPointData()->GetScalars("values");
  double range[2];
  a->GetRange(range);

  vtkImageShiftScale *t=vtkImageShiftScale::New();
  t->SetInputConnection(source->GetOutputPort());
  source->Delete();
  t->SetShift(-range[0]);
  double magnitude=range[1]-range[0];
  if(magnitude==0.0)
    {
    magnitude=1.0;
    }
  t->SetScale(255.0/magnitude);
  t->SetOutputScalarTypeToUnsignedChar();

  t->Update();

  vtkRenderWindow *renWin=vtkRenderWindow::New();
  vtkRenderer *ren1=vtkRenderer::New();
  ren1->SetBackground(0.1,0.4,0.2);

  renWin->AddRenderer(ren1);
  ren1->Delete();
  renWin->SetSize(301,300); // intentional odd and NPOT  width/height

  vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);
  renWin->Delete();

  vtkLightCollection *lights=ren1->GetLights();
  assert("check: lights_empty" && lights->GetNumberOfItems()==0);
  vtkLight *light=vtkLight::New();
  light->SetAmbientColor(0.0,0.0,0.0);
  light->SetDiffuseColor(0.5,0.5,0.5);
  light->SetSpecularColor(0.0,0.0,1.0);
  light->SetIntensity(1.0);
  // positional light is not supported by vtkFixedPointVolumeRayCastMapper
  light->SetLightTypeToHeadlight();
  lights->AddItem(light);
  light->Delete();

  renWin->Render(); // make sure we have an OpenGL context.

  vtkVolumeProperty *volumeProperty;
  vtkVolume *volume;

  vtkVolumeTextureMapper3D *volumeMapper=vtkVolumeTextureMapper3D::New();
  volumeMapper->SetSampleDistance(1.0);

  volumeMapper->SetInputConnection(
    t->GetOutputPort());

  volumeProperty=vtkVolumeProperty::New();
  volumeMapper->SetBlendModeToComposite();
  volumeProperty->ShadeOn();
  volumeProperty->SetSpecularPower(128.0);
  volumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION);

  vtkPiecewiseFunction *compositeOpacity = vtkPiecewiseFunction::New();
  compositeOpacity->AddPoint(0.0,1.0); // 1.0
  compositeOpacity->AddPoint(80.0,1.0); // 1.0
  compositeOpacity->AddPoint(80.1,0.0); // 0.0
  compositeOpacity->AddPoint(255.0,0.0); // 0.0
  volumeProperty->SetScalarOpacity(compositeOpacity);

  vtkColorTransferFunction *color=vtkColorTransferFunction::New();
  color->AddRGBPoint(0.0  ,1.0,1.0,1.0); // blue
  color->AddRGBPoint(40.0  ,1.0,1.0,1.0); // red
  color->AddRGBPoint(255.0,1.0,1.0,1.0); // white
  volumeProperty->SetColor(color);
  color->Delete();

  volume=vtkVolume::New();
  volume->SetMapper(volumeMapper);
  volume->SetProperty(volumeProperty);
  ren1->AddViewProp(volume);

  int valid=volumeMapper->IsRenderSupported(volumeProperty,ren1);

  int retVal;
  if(valid)
    {
    ren1->ResetCamera();
    renWin->Render();

    retVal = vtkTesting::Test(argc, argv, renWin, 75);
    if (retVal == vtkRegressionTester::DO_INTERACTOR)
      {
      iren->Start();
      }
    }
  else
    {
    retVal=vtkTesting::PASSED;
    cout << "Required extensions not supported." << endl;
    }

  volumeMapper->Delete();
  volumeProperty->Delete();
  volume->Delete();
  iren->Delete();
  t->Delete();
  compositeOpacity->Delete();

  return !((retVal == vtkTesting::PASSED) || (retVal == vtkTesting::DO_INTERACTOR));
}
<|endoftext|>


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

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.commontk.org/LICENSE

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QDir>
#include <QDebug>

// CTK includes
#include "ctkAbstractPythonManager.h"
#include "ctkScriptingPythonCoreConfigure.h"

// PythonQT includes
#include <PythonQt.h>

// STD includes
#include <csignal>

#ifdef __GNUC__
// Disable warnings related to signal() function
// See http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html
// Note: Ideally the incriminated functions and macros should be fixed upstream ...
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif

#ifdef CTK_PYTHONQT_WRAP_QTCORE
void PythonQt_init_QtCore(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTGUI
void PythonQt_init_QtGui(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTNETWORK
void PythonQt_init_QtNetwork(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTOPENGL
void PythonQt_init_QtOpenGL(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTSQL
void PythonQt_init_QtSql(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTSVG
void PythonQt_init_QtSvg(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTUITOOLS
void PythonQt_init_QtUiTools(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTWEBKIT
void PythonQt_init_QtWebKit(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTXML
void PythonQt_init_QtXml(PyObject*);
#endif

#ifdef CTK_PYTHONQT_WRAP_QTXMLPATTERNS
void PythonQt_init_QtXmlPatterns(PyObject*);
#endif

//-----------------------------------------------------------------------------
ctkAbstractPythonManager::ctkAbstractPythonManager(QObject* _parent) : Superclass(_parent)
{
  this->InitFunction = 0;
}

//-----------------------------------------------------------------------------
ctkAbstractPythonManager::~ctkAbstractPythonManager()
{
  PyThreadState* state = PyThreadState_Get();
  Py_EndInterpreter(state);
  PythonQt::cleanup();
}

//-----------------------------------------------------------------------------
PythonQtObjectPtr ctkAbstractPythonManager::mainContext()
{
  if (!PythonQt::self())
    {
    this->initPythonQt();
    }
  if (PythonQt::self())
    {
    return PythonQt::self()->getMainModule();
    }
  return PythonQtObjectPtr();
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::initPythonQt()
{
  PythonQt::init(PythonQt::IgnoreSiteModule | PythonQt::RedirectStdOut);

  // Python maps SIGINT (control-c) to its own handler.  We will remap it
  // to the default so that control-c works.
  #ifdef SIGINT
  signal(SIGINT, SIG_DFL);
  #endif

  PythonQtObjectPtr _mainContext = PythonQt::self()->getMainModule();

  this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
                SLOT(printStdout(const QString&)));
  this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
                SLOT(printStderr(const QString&)));

  #ifdef CTK_PYTHONQT_WRAP_QTCORE
  PythonQt_init_QtCore(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTGUI
  PythonQt_init_QtGui(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTNETWORK
  PythonQt_init_QtNetwork(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTOPENGL
  PythonQt_init_QtOpenGL(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTSQL
  PythonQt_init_QtSql(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTSVG
  PythonQt_init_QtSvg(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTUITOOLS
  PythonQt_init_QtUiTools(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTWEBKIT
  PythonQt_init_QtWebKit(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTXML
  PythonQt_init_QtXml(0);
  #endif

  #ifdef CTK_PYTHONQT_WRAP_QTXMLPATTERNS
  PythonQt_init_QtXmlPatterns(0);
  #endif

  QStringList initCode;
  initCode << "import sys";
  foreach (QString path, this->pythonPaths())
    {
    initCode << QString("sys.path.append('%1')").arg(QDir::fromNativeSeparators(path));
    }

  _mainContext.evalScript(initCode.join("\n"));

  this->preInitialization();
  if (this->InitFunction)
    {
    (*this->InitFunction)();
    }
  emit this->pythonPreInitialized();

  this->executeInitializationScripts();
  emit this->pythonInitialized();
}

//-----------------------------------------------------------------------------
QStringList ctkAbstractPythonManager::pythonPaths()
{
  return QStringList();
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::preInitialization()
{
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::executeInitializationScripts()
{
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::registerPythonQtDecorator(QObject* decorator)
{
  PythonQt::self()->addDecorators(decorator);
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::registerClassForPythonQt(const QMetaObject* metaobject)
{
  PythonQt::self()->registerClass(metaobject);
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::registerCPPClassForPythonQt(const char* name)
{
  PythonQt::self()->registerCPPClass(name);
}

//-----------------------------------------------------------------------------
QVariant ctkAbstractPythonManager::executeString(const QString& code)
{
  QVariant ret;
  PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  if (main)
    {
    ret = main.evalScript(code, Py_single_input);
    }
  return ret;
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::executeFile(const QString& filename)
{
  PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  if (main)
    {
    main.evalFile(filename);
    }
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::setInitializationFunction(void (*initFunction)())
{
  this->InitFunction = initFunction;
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::addObjectToPythonMain(const QString& name, QObject* obj)
{
  PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  if (main && obj)
    {
    main.addObject(name, obj);
    }
}

//-----------------------------------------------------------------------------
QVariant ctkAbstractPythonManager::getVariable(const QString& name)
{
  PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  if (main)
    {
    return PythonQt::self()->getVariable(main, name);
    }
  return QVariant();
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::printStdout(const QString& text)
{
  std::cout << qPrintable(text);
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::printStderr(const QString& text)
{
  std::cout << qPrintable(text);
}
<commit_msg>Initialization of enabled bindings is delegated to a single function<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.commontk.org/LICENSE

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QDir>
#include <QDebug>

// CTK includes
#include "ctkAbstractPythonManager.h"
#include "ctkScriptingPythonCoreConfigure.h"

// PythonQT includes
#include <PythonQt.h>
#include <PythonQt_QtBindings.h>

// STD includes
#include <csignal>

#ifdef __GNUC__
// Disable warnings related to signal() function
// See http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html
// Note: Ideally the incriminated functions and macros should be fixed upstream ...
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif

//-----------------------------------------------------------------------------
ctkAbstractPythonManager::ctkAbstractPythonManager(QObject* _parent) : Superclass(_parent)
{
  this->InitFunction = 0;
}

//-----------------------------------------------------------------------------
ctkAbstractPythonManager::~ctkAbstractPythonManager()
{
  PyThreadState* state = PyThreadState_Get();
  Py_EndInterpreter(state);
  PythonQt::cleanup();
}

//-----------------------------------------------------------------------------
PythonQtObjectPtr ctkAbstractPythonManager::mainContext()
{
  if (!PythonQt::self())
    {
    this->initPythonQt();
    }
  if (PythonQt::self())
    {
    return PythonQt::self()->getMainModule();
    }
  return PythonQtObjectPtr();
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::initPythonQt()
{
  PythonQt::init(PythonQt::IgnoreSiteModule | PythonQt::RedirectStdOut);

  // Python maps SIGINT (control-c) to its own handler.  We will remap it
  // to the default so that control-c works.
  #ifdef SIGINT
  signal(SIGINT, SIG_DFL);
  #endif

  PythonQtObjectPtr _mainContext = PythonQt::self()->getMainModule();

  this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
                SLOT(printStdout(const QString&)));
  this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
                SLOT(printStderr(const QString&)));

  PythonQt_init_QtBindings();

  QStringList initCode;
  initCode << "import sys";
  foreach (QString path, this->pythonPaths())
    {
    initCode << QString("sys.path.append('%1')").arg(QDir::fromNativeSeparators(path));
    }

  _mainContext.evalScript(initCode.join("\n"));

  this->preInitialization();
  if (this->InitFunction)
    {
    (*this->InitFunction)();
    }
  emit this->pythonPreInitialized();

  this->executeInitializationScripts();
  emit this->pythonInitialized();
}

//-----------------------------------------------------------------------------
QStringList ctkAbstractPythonManager::pythonPaths()
{
  return QStringList();
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::preInitialization()
{
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::executeInitializationScripts()
{
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::registerPythonQtDecorator(QObject* decorator)
{
  PythonQt::self()->addDecorators(decorator);
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::registerClassForPythonQt(const QMetaObject* metaobject)
{
  PythonQt::self()->registerClass(metaobject);
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::registerCPPClassForPythonQt(const char* name)
{
  PythonQt::self()->registerCPPClass(name);
}

//-----------------------------------------------------------------------------
QVariant ctkAbstractPythonManager::executeString(const QString& code)
{
  QVariant ret;
  PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  if (main)
    {
    ret = main.evalScript(code, Py_single_input);
    }
  return ret;
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::executeFile(const QString& filename)
{
  PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  if (main)
    {
    main.evalFile(filename);
    }
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::setInitializationFunction(void (*initFunction)())
{
  this->InitFunction = initFunction;
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::addObjectToPythonMain(const QString& name, QObject* obj)
{
  PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  if (main && obj)
    {
    main.addObject(name, obj);
    }
}

//-----------------------------------------------------------------------------
QVariant ctkAbstractPythonManager::getVariable(const QString& name)
{
  PythonQtObjectPtr main = ctkAbstractPythonManager::mainContext();
  if (main)
    {
    return PythonQt::self()->getVariable(main, name);
    }
  return QVariant();
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::printStdout(const QString& text)
{
  std::cout << qPrintable(text);
}

//-----------------------------------------------------------------------------
void ctkAbstractPythonManager::printStderr(const QString& text)
{
  std::cout << qPrintable(text);
}
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include <fstream>
#include <dynamicsJRLJapan/dynamicsJRLJapanFactory.h>

using namespace std;
using namespace dynamicsJRLJapan;
void dv3d(vector3d &av3d, ostream &os)
{
  for(unsigned int i=0;i<3;i++)
    os << av3d(i) << " ";
  os << endl;
}

void dm3d(const matrix3d &todisplay, ostream &os, string shifttab)
{
  for(unsigned int i=0;i<3;i++)
    {
      for(unsigned int j=0;j<3;j++)
	{
	  os << MAL_S4x4_MATRIX_ACCESS_I_J(todisplay,i,j) << " " ;
	}
      os << endl;
      if (i!=2)
	os << shifttab;
    }
}

void dm4d(const matrix4d &todisplay, ostream &os, string shifttab)
{
  for(unsigned int i=0;i<4;i++)
    {
      for(unsigned int j=0;j<4;j++)
	{
	  os << MAL_S4x4_MATRIX_ACCESS_I_J(todisplay,i,j) << " " ;
	}
      os << endl;
      if (i!=3)
	os << shifttab;
    }
}

void DisplayBody(CjrlBody *aBody, string &shifttab)
{

  cout << shifttab << "Related body informations" << endl;
  vector3d alcm = aBody->localCenterOfMass();
  cout << shifttab << "Local center of Mass : ";
  dv3d(alcm,cout);
  matrix3d aim = aBody->inertiaMatrix();
  cout << shifttab << "Inertia Matrix: " ;
  dm3d(aim,cout,shifttab);
  cout << shifttab << "mass: " << aBody->mass() << endl;

}
void RecursiveDisplayOfJoints(CjrlJoint *aJoint,
			      unsigned int verbosedisplay=0,
			      unsigned int ldepth=0)
{
  if (aJoint==0)
    return;

  int NbChildren = aJoint->countChildJoints();
  string shifttab="";
  for(unsigned int i=0;i<ldepth;i++)
	shifttab+=" ";

  cout << shifttab << "Rank : "
       << aJoint->rankInConfiguration() << endl;
  cout << shifttab << "Number of child  :"
       << aJoint->countChildJoints() << endl;
  cout << shifttab << "Nb of degree of freedom "
       <<  aJoint->numberDof() << endl;

  if (verbosedisplay>3)
    {
      cout << shifttab << "Initial Position " ;
      matrix4d iP = aJoint->initialPosition();
      dm4d(iP,cout,shifttab);

      cout << shifttab << "CurrentTransformation ";
      matrix4d cT = aJoint->currentTransformation();
      dm4d(cT,cout,shifttab);

      // Limits
      std::cout << shifttab << "llimit: "
		<< aJoint->lowerBound(0)*180/M_PI << " "
		<< shifttab << "ulimit: "
		<< aJoint->upperBound(0)*180/M_PI << " " << endl;

      std::cout << shifttab << "lvlimit: "
		<< aJoint->lowerVelocityBound(0)*180/M_PI << " "
		<< shifttab << "uvlimit: "
		<< aJoint->upperVelocityBound(0)*180/M_PI << " " << endl;

      // Path from the root to this joint.
      std::vector<CjrlJoint*> JointsFromRootToHere = aJoint->jointsFromRootToThis();
      cout << shifttab << "Nb of nodes: " << JointsFromRootToHere.size() << endl
	   << shifttab << "Joint from root to here:" << endl << shifttab;
      for(unsigned int i=0;i<JointsFromRootToHere.size();i++)
	cout << JointsFromRootToHere[i]->rankInConfiguration() << " ";
      cout << endl;

      // Current state of the joint.

      // Rigid velocity:
      CjrlRigidVelocity aRV = aJoint->jointVelocity();
      cout << shifttab << "Linear Velocity ";
      vector3d av3d = aRV.linearVelocity();
      dv3d(av3d,cout);
      cout << shifttab << "Angular Velocity ";
      av3d = aRV.rotationVelocity();
      dv3d(av3d,cout);

      // Rigit Acceleration.
      CjrlRigidAcceleration aRA = aJoint->jointAcceleration();
      cout << shifttab << "Linear Acceleration ";
      av3d = aRA.linearAcceleration();
      dv3d(av3d,cout);
      cout << shifttab << "Angular Acceleration ";
      av3d = aRA.rotationAcceleration();
      dv3d(av3d,cout);

      CjrlBody * aBody = aJoint->linkedBody();
      DisplayBody(aBody,shifttab);
    }

  if (NbChildren!=0)
    {
      cout << shifttab << "***********************************************" << endl;
      cout << shifttab << " Display Now information related to children :" << endl;

      for(int i=0;i<NbChildren;i++)
	{
	  // Returns a const so we have to force the casting/
	  RecursiveDisplayOfJoints(aJoint->childJoint(i),verbosedisplay,ldepth+1);
	}
    }
}

void DisplayDynamicRobotInformation(CjrlDynamicRobot *aDynamicRobot)
{
  std::vector<CjrlJoint *> aVec = aDynamicRobot->jointVector();
  int r = aVec.size();
  cout << "Number of joints :" << r << endl;

}

void DisplayMatrix(MAL_MATRIX(,double) &aJ)
{
  for(int i=0;i<6;i++)
    {
      for(unsigned int j=0;j<MAL_MATRIX_NB_COLS(aJ);j++)
	{
	  if (aJ(i,j)==0.0)
	    printf("0 ");
	  else
	    printf("%10.5f ",aJ(i,j));
	}
      printf("\n");
    }

}

void GoDownTree(const CjrlJoint * startJoint)
{
  std::cout << "joint ranked :" << startJoint->rankInConfiguration() << std::endl;
  std::cout << "llimit: " << startJoint->lowerBound(0)*180/M_PI << " "
	    << "ulimit: " << startJoint->upperBound(0)*180/M_PI << " " << endl;
  std::cout << startJoint->currentTransformation() << std::endl;

  if (startJoint->countChildJoints()!=0)
    {
      const CjrlJoint * childJoint = startJoint->childJoint(0);
      GoDownTree(childJoint);
    }
}

int main(int argc, char *argv[])
{
  string aSpecificitiesFileName;
  string aPath;
  string aName;
  string aMapFromJointToRank;

  if (argc!=5)
    {
      aPath="./";
      aName="sample.wrl";
      aSpecificitiesFileName = "sampleSpecificities.xml";
      aMapFromJointToRank = "sampleLinkJointRank.xml";
    }
  else
    {
      aSpecificitiesFileName = argv[3];
      aPath=argv[1];
      aName=argv[2];
      aMapFromJointToRank=argv[4];
    }
  dynamicsJRLJapan::ObjectFactory aRobotDynamicsObjectConstructor;

  CjrlHumanoidDynamicRobot * aHDR = aRobotDynamicsObjectConstructor.createHumanoidDynamicRobot();

  if (aHDR==0)
    {
      cerr<< "Dynamic cast on HDR failed " << endl;
      exit(-1);
    }
  string RobotFileName = aPath+aName;
  dynamicsJRLJapan::parseOpenHRPVRMLFile(*aHDR,RobotFileName,aMapFromJointToRank,aSpecificitiesFileName);

  // Display tree of the joints.
  CjrlJoint* rootJoint = aHDR->rootJoint();

  int NbOfDofs = aHDR->numberDof();
  std::cout << "NbOfDofs :" << NbOfDofs << std::endl;
  if (NbOfDofs==0)
    {
      cerr << "Empty Robot..."<< endl;
      return -1;
    }
  MAL_VECTOR_DIM(aCurrentConf,double,NbOfDofs);
  int lindex=0;
  for(int i=0;i<6;i++)
    aCurrentConf[lindex++] = 0.0;

  for(int i=0;i<(NbOfDofs-6 < 40 ? NbOfDofs-6 : 40) ;i++)
    aCurrentConf[lindex++] = 0.0;

  aHDR->currentConfiguration(aCurrentConf);

  MAL_VECTOR_DIM(aCurrentVel,double,NbOfDofs);
  lindex=0;
  for(int i=0;i<NbOfDofs;i++)
    aCurrentVel[lindex++] = 0.0;

  MAL_S3_VECTOR(ZMPval,double);

  aHDR->currentVelocity(aCurrentVel);
  //  aHDR->setComputeZMP(true);
  string inProperty="ComputeZMP"; string aValue="true";
  aHDR->setProperty(inProperty,aValue);
  aHDR->computeForwardKinematics();
  ZMPval = aHDR->zeroMomentumPoint();
  cout << "First value of ZMP : " << ZMPval <<endl;
  cout << "Should be equal to the CoM: " << aHDR->positionCenterOfMass() << endl;

  matrixNxP InertiaMatrix;
  aHDR->computeInertiaMatrix();
  InertiaMatrix = aHDR->inertiaMatrix();

  cout << "InertiaMatrix("
       << MAL_MATRIX_NB_ROWS(InertiaMatrix)<< ","
       << MAL_MATRIX_NB_COLS(InertiaMatrix)<< ")"<< endl;

  cout << InertiaMatrix << endl;
  matrixNxP IMt;
  MAL_TRANSPOSE_A_in_At(InertiaMatrix,IMt);
  matrixNxP IMxIMt;
  MAL_C_eq_A_by_B(IMxIMt,InertiaMatrix,IMt);
  cout << IMxIMt << endl;

  ofstream aof;
  aof.open("InertiaMatrix.dat");
  for(unsigned int i=0;i<MAL_MATRIX_NB_ROWS(InertiaMatrix);i++)
    {
      for(unsigned int j=0;j<MAL_MATRIX_NB_COLS(InertiaMatrix);j++)
       {
         aof << InertiaMatrix(i,j) << " ";
       }
      aof << endl;
    }
  aof.close();

  std::vector<CjrlJoint *> aVec = aHDR->jointVector();

  CjrlJoint  * aJoint = aVec[3]; // Try to get the hand.
  aJoint->computeJacobianJointWrtConfig();

  MAL_MATRIX(,double) aJ = aJoint->jacobianJointWrtConfig();

  //  DisplayMatrix(aJ);
  cout << "****************************" << endl;
  rootJoint->computeJacobianJointWrtConfig();
  aJ = rootJoint->jacobianJointWrtConfig();
  cout << "Rank of Root: " << rootJoint->rankInConfiguration() << endl;

  //  DisplayMatrix(aJ);

  aJoint = aHDR->waist();
  cout << "****************************" << endl;
  aHDR->computeJacobianCenterOfMass();
  cout << "Value of the CoM's Jacobian:" << endl
       << aHDR->jacobianCenterOfMass() << endl;
  cout << "****************************" << endl;
  RecursiveDisplayOfJoints(rootJoint,10);

  cout << "****************************" << endl;
  // Test rank of the left hand.
  cout << "Rank of the left hand "<< endl;
  cout << aHDR->leftWrist()->rankInConfiguration() << endl;

  MAL_VECTOR_FILL(aCurrentVel,0.0);
  MAL_VECTOR_DIM(aCurrentAcc,double,NbOfDofs);
  MAL_VECTOR_FILL(aCurrentAcc,0.0);

  // This is mandatory for this implementation of computeForwardKinematics
  // to compute the derivative of the momentum.
  {
    string inProperty[4]={"TimeStep","ComputeAcceleration",
			  "ComputeBackwardDynamics", "ComputeZMP"};
    string inValue[4]={"0.005","false","false","true"};
    for(unsigned int i=0;i<4;i++)
      aHDR->setProperty(inProperty[i],inValue[i]);

  }
  for(int i=0;i<4;i++)
    {
      aHDR->currentVelocity(aCurrentVel);
      aHDR->currentAcceleration(aCurrentAcc);
      aHDR->computeForwardKinematics();
      ZMPval = aHDR->zeroMomentumPoint();
      cout << i << "-th value of ZMP : " << ZMPval <<endl;
      cout << "Should be equal to the CoM: " << aHDR->positionCenterOfMass() << endl;
    }

  delete aHDR;

}
<commit_msg>Fix a bug in access to matrix3d elements.<commit_after>#include <string>
#include <iostream>
#include <fstream>
#include <dynamicsJRLJapan/dynamicsJRLJapanFactory.h>

using namespace std;
using namespace dynamicsJRLJapan;
void dv3d(vector3d &av3d, ostream &os)
{
  for(unsigned int i=0;i<3;i++)
    os << av3d(i) << " ";
  os << endl;
}

void dm3d(const matrix3d &todisplay, ostream &os, string shifttab)
{
  for(unsigned int i=0;i<3;i++)
    {
      for(unsigned int j=0;j<3;j++)
	{
	  os << MAL_S3x3_MATRIX_ACCESS_I_J(todisplay,i,j) << " " ;
	}
      os << endl;
      if (i!=2)
	os << shifttab;
    }
}

void dm4d(const matrix4d &todisplay, ostream &os, string shifttab)
{
  for(unsigned int i=0;i<4;i++)
    {
      for(unsigned int j=0;j<4;j++)
	{
	  os << MAL_S4x4_MATRIX_ACCESS_I_J(todisplay,i,j) << " " ;
	}
      os << endl;
      if (i!=3)
	os << shifttab;
    }
}

void DisplayBody(CjrlBody *aBody, string &shifttab)
{

  cout << shifttab << "Related body informations" << endl;
  vector3d alcm = aBody->localCenterOfMass();
  cout << shifttab << "Local center of Mass : ";
  dv3d(alcm,cout);
  matrix3d aim = aBody->inertiaMatrix();
  cout << shifttab << "Inertia Matrix: " ;
  dm3d(aim,cout,shifttab);
  cout << shifttab << "mass: " << aBody->mass() << endl;

}
void RecursiveDisplayOfJoints(CjrlJoint *aJoint,
			      unsigned int verbosedisplay=0,
			      unsigned int ldepth=0)
{
  if (aJoint==0)
    return;

  int NbChildren = aJoint->countChildJoints();
  string shifttab="";
  for(unsigned int i=0;i<ldepth;i++)
	shifttab+=" ";

  cout << shifttab << "Rank : "
       << aJoint->rankInConfiguration() << endl;
  cout << shifttab << "Number of child  :"
       << aJoint->countChildJoints() << endl;
  cout << shifttab << "Nb of degree of freedom "
       <<  aJoint->numberDof() << endl;

  if (verbosedisplay>3)
    {
      cout << shifttab << "Initial Position " ;
      matrix4d iP = aJoint->initialPosition();
      dm4d(iP,cout,shifttab);

      cout << shifttab << "CurrentTransformation ";
      matrix4d cT = aJoint->currentTransformation();
      dm4d(cT,cout,shifttab);

      // Limits
      std::cout << shifttab << "llimit: "
		<< aJoint->lowerBound(0)*180/M_PI << " "
		<< shifttab << "ulimit: "
		<< aJoint->upperBound(0)*180/M_PI << " " << endl;

      std::cout << shifttab << "lvlimit: "
		<< aJoint->lowerVelocityBound(0)*180/M_PI << " "
		<< shifttab << "uvlimit: "
		<< aJoint->upperVelocityBound(0)*180/M_PI << " " << endl;

      // Path from the root to this joint.
      std::vector<CjrlJoint*> JointsFromRootToHere = aJoint->jointsFromRootToThis();
      cout << shifttab << "Nb of nodes: " << JointsFromRootToHere.size() << endl
	   << shifttab << "Joint from root to here:" << endl << shifttab;
      for(unsigned int i=0;i<JointsFromRootToHere.size();i++)
	cout << JointsFromRootToHere[i]->rankInConfiguration() << " ";
      cout << endl;

      // Current state of the joint.

      // Rigid velocity:
      CjrlRigidVelocity aRV = aJoint->jointVelocity();
      cout << shifttab << "Linear Velocity ";
      vector3d av3d = aRV.linearVelocity();
      dv3d(av3d,cout);
      cout << shifttab << "Angular Velocity ";
      av3d = aRV.rotationVelocity();
      dv3d(av3d,cout);

      // Rigit Acceleration.
      CjrlRigidAcceleration aRA = aJoint->jointAcceleration();
      cout << shifttab << "Linear Acceleration ";
      av3d = aRA.linearAcceleration();
      dv3d(av3d,cout);
      cout << shifttab << "Angular Acceleration ";
      av3d = aRA.rotationAcceleration();
      dv3d(av3d,cout);

      CjrlBody * aBody = aJoint->linkedBody();
      DisplayBody(aBody,shifttab);
    }

  if (NbChildren!=0)
    {
      cout << shifttab << "***********************************************" << endl;
      cout << shifttab << " Display Now information related to children :" << endl;

      for(int i=0;i<NbChildren;i++)
	{
	  // Returns a const so we have to force the casting/
	  RecursiveDisplayOfJoints(aJoint->childJoint(i),verbosedisplay,ldepth+1);
	}
    }
}

void DisplayDynamicRobotInformation(CjrlDynamicRobot *aDynamicRobot)
{
  std::vector<CjrlJoint *> aVec = aDynamicRobot->jointVector();
  int r = aVec.size();
  cout << "Number of joints :" << r << endl;

}

void DisplayMatrix(MAL_MATRIX(,double) &aJ)
{
  for(int i=0;i<6;i++)
    {
      for(unsigned int j=0;j<MAL_MATRIX_NB_COLS(aJ);j++)
	{
	  if (aJ(i,j)==0.0)
	    printf("0 ");
	  else
	    printf("%10.5f ",aJ(i,j));
	}
      printf("\n");
    }

}

void GoDownTree(const CjrlJoint * startJoint)
{
  std::cout << "joint ranked :" << startJoint->rankInConfiguration() << std::endl;
  std::cout << "llimit: " << startJoint->lowerBound(0)*180/M_PI << " "
	    << "ulimit: " << startJoint->upperBound(0)*180/M_PI << " " << endl;
  std::cout << startJoint->currentTransformation() << std::endl;

  if (startJoint->countChildJoints()!=0)
    {
      const CjrlJoint * childJoint = startJoint->childJoint(0);
      GoDownTree(childJoint);
    }
}

int main(int argc, char *argv[])
{
  string aSpecificitiesFileName;
  string aPath;
  string aName;
  string aMapFromJointToRank;

  if (argc!=5)
    {
      aPath="./";
      aName="sample.wrl";
      aSpecificitiesFileName = "sampleSpecificities.xml";
      aMapFromJointToRank = "sampleLinkJointRank.xml";
    }
  else
    {
      aSpecificitiesFileName = argv[3];
      aPath=argv[1];
      aName=argv[2];
      aMapFromJointToRank=argv[4];
    }
  dynamicsJRLJapan::ObjectFactory aRobotDynamicsObjectConstructor;

  CjrlHumanoidDynamicRobot * aHDR = aRobotDynamicsObjectConstructor.createHumanoidDynamicRobot();

  if (aHDR==0)
    {
      cerr<< "Dynamic cast on HDR failed " << endl;
      exit(-1);
    }
  string RobotFileName = aPath+aName;
  dynamicsJRLJapan::parseOpenHRPVRMLFile(*aHDR,RobotFileName,aMapFromJointToRank,aSpecificitiesFileName);

  // Display tree of the joints.
  CjrlJoint* rootJoint = aHDR->rootJoint();

  int NbOfDofs = aHDR->numberDof();
  std::cout << "NbOfDofs :" << NbOfDofs << std::endl;
  if (NbOfDofs==0)
    {
      cerr << "Empty Robot..."<< endl;
      return -1;
    }
  MAL_VECTOR_DIM(aCurrentConf,double,NbOfDofs);
  int lindex=0;
  for(int i=0;i<6;i++)
    aCurrentConf[lindex++] = 0.0;

  for(int i=0;i<(NbOfDofs-6 < 40 ? NbOfDofs-6 : 40) ;i++)
    aCurrentConf[lindex++] = 0.0;

  aHDR->currentConfiguration(aCurrentConf);

  MAL_VECTOR_DIM(aCurrentVel,double,NbOfDofs);
  lindex=0;
  for(int i=0;i<NbOfDofs;i++)
    aCurrentVel[lindex++] = 0.0;

  MAL_S3_VECTOR(ZMPval,double);

  aHDR->currentVelocity(aCurrentVel);
  //  aHDR->setComputeZMP(true);
  string inProperty="ComputeZMP"; string aValue="true";
  aHDR->setProperty(inProperty,aValue);
  aHDR->computeForwardKinematics();
  ZMPval = aHDR->zeroMomentumPoint();
  cout << "First value of ZMP : " << ZMPval <<endl;
  cout << "Should be equal to the CoM: " << aHDR->positionCenterOfMass() << endl;

  matrixNxP InertiaMatrix;
  aHDR->computeInertiaMatrix();
  InertiaMatrix = aHDR->inertiaMatrix();

  cout << "InertiaMatrix("
       << MAL_MATRIX_NB_ROWS(InertiaMatrix)<< ","
       << MAL_MATRIX_NB_COLS(InertiaMatrix)<< ")"<< endl;

  cout << InertiaMatrix << endl;
  matrixNxP IMt;
  MAL_TRANSPOSE_A_in_At(InertiaMatrix,IMt);
  matrixNxP IMxIMt;
  MAL_C_eq_A_by_B(IMxIMt,InertiaMatrix,IMt);
  cout << IMxIMt << endl;

  ofstream aof;
  aof.open("InertiaMatrix.dat");
  for(unsigned int i=0;i<MAL_MATRIX_NB_ROWS(InertiaMatrix);i++)
    {
      for(unsigned int j=0;j<MAL_MATRIX_NB_COLS(InertiaMatrix);j++)
       {
         aof << InertiaMatrix(i,j) << " ";
       }
      aof << endl;
    }
  aof.close();

  std::vector<CjrlJoint *> aVec = aHDR->jointVector();

  CjrlJoint  * aJoint = aVec[3]; // Try to get the hand.
  aJoint->computeJacobianJointWrtConfig();

  MAL_MATRIX(,double) aJ = aJoint->jacobianJointWrtConfig();

  //  DisplayMatrix(aJ);
  cout << "****************************" << endl;
  rootJoint->computeJacobianJointWrtConfig();
  aJ = rootJoint->jacobianJointWrtConfig();
  cout << "Rank of Root: " << rootJoint->rankInConfiguration() << endl;

  //  DisplayMatrix(aJ);

  aJoint = aHDR->waist();
  cout << "****************************" << endl;
  aHDR->computeJacobianCenterOfMass();
  cout << "Value of the CoM's Jacobian:" << endl
       << aHDR->jacobianCenterOfMass() << endl;
  cout << "****************************" << endl;
  RecursiveDisplayOfJoints(rootJoint,10);

  cout << "****************************" << endl;
  // Test rank of the left hand.
  cout << "Rank of the left hand "<< endl;
  cout << aHDR->leftWrist()->rankInConfiguration() << endl;

  MAL_VECTOR_FILL(aCurrentVel,0.0);
  MAL_VECTOR_DIM(aCurrentAcc,double,NbOfDofs);
  MAL_VECTOR_FILL(aCurrentAcc,0.0);

  // This is mandatory for this implementation of computeForwardKinematics
  // to compute the derivative of the momentum.
  {
    string inProperty[4]={"TimeStep","ComputeAcceleration",
			  "ComputeBackwardDynamics", "ComputeZMP"};
    string inValue[4]={"0.005","false","false","true"};
    for(unsigned int i=0;i<4;i++)
      aHDR->setProperty(inProperty[i],inValue[i]);

  }
  for(int i=0;i<4;i++)
    {
      aHDR->currentVelocity(aCurrentVel);
      aHDR->currentAcceleration(aCurrentAcc);
      aHDR->computeForwardKinematics();
      ZMPval = aHDR->zeroMomentumPoint();
      cout << i << "-th value of ZMP : " << ZMPval <<endl;
      cout << "Should be equal to the CoM: " << aHDR->positionCenterOfMass() << endl;
    }

  delete aHDR;

}
<|endoftext|>