<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: attributeproperties.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-21 16:43:05 $
 *
 *  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 _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX
#define _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX

#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif

#ifndef _SDR_PROPERTIES_DEFAULTPROPERTIES_HXX
#include <svx/sdr/properties/defaultproperties.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace properties
    {
        class SVX_DLLPUBLIC AttributeProperties : public DefaultProperties, public SfxListener
        {
            // add style sheet, do all the necessary handling
            void ImpAddStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);

            // remove StyleSheet, do all the necessary handling
            void ImpRemoveStyleSheet();

        protected:
            // the SytleSheet of this object
            SfxStyleSheet*                                  mpStyleSheet;

            // create a new itemset
            virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& pPool);

            // Do the ItemChange, may do special handling
            virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0);

            // react on ItemSet changes
            virtual void ItemSetChanged(const SfxItemSet& rSet);

        public:
            // basic constructor
            AttributeProperties(SdrObject& rObj);

            // constructor for copying, but using new object
            AttributeProperties(const AttributeProperties& rProps, SdrObject& rObj);

            // Clone() operator, normally just calls the local copy constructor
            virtual BaseProperties& Clone(SdrObject& rObj) const;

            // destructor
            virtual ~AttributeProperties();

            // set a new StyleSheet and broadcast
            virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);

            // get the installed StyleSheet
            virtual SfxStyleSheet* GetStyleSheet() const;

            // Move properties to a new ItemPool.
            virtual void MoveToItemPool(SfxItemPool* pSrcPool, SfxItemPool* pDestPool, SdrModel* pNewModel = 0L);

            // Set new model.
            virtual void SetModel(SdrModel* pOldModel, SdrModel* pNewModel);

            // force all attributes which come from styles to hard attributes
            // to be able to live without the style.
            virtual void ForceStyleToHardAttributes();

            // This is the Notify(...) from 2nd base class SfxListener
            virtual void Notify(SfxBroadcaster& rBC, const SfxHint& rHint);
        };
    } // end of namespace properties
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

#endif //_SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX

// eof
<commit_msg>INTEGRATION: CWS changefileheader (1.7.622); FILE MERGED 2008/04/01 15:50:06 thb 1.7.622.3: #i85898# Stripping all external header guards 2008/04/01 12:47:54 thb 1.7.622.2: #i85898# Stripping all external header guards 2008/03/31 14:19:05 rt 1.7.622.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: attributeproperties.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX
#define _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX

#include <svtools/lstner.hxx>
#include <svx/sdr/properties/defaultproperties.hxx>
#include "svx/svxdllapi.h"

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace properties
    {
        class SVX_DLLPUBLIC AttributeProperties : public DefaultProperties, public SfxListener
        {
            // add style sheet, do all the necessary handling
            void ImpAddStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);

            // remove StyleSheet, do all the necessary handling
            void ImpRemoveStyleSheet();

        protected:
            // the SytleSheet of this object
            SfxStyleSheet*                                  mpStyleSheet;

            // create a new itemset
            virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& pPool);

            // Do the ItemChange, may do special handling
            virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0);

            // react on ItemSet changes
            virtual void ItemSetChanged(const SfxItemSet& rSet);

        public:
            // basic constructor
            AttributeProperties(SdrObject& rObj);

            // constructor for copying, but using new object
            AttributeProperties(const AttributeProperties& rProps, SdrObject& rObj);

            // Clone() operator, normally just calls the local copy constructor
            virtual BaseProperties& Clone(SdrObject& rObj) const;

            // destructor
            virtual ~AttributeProperties();

            // set a new StyleSheet and broadcast
            virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);

            // get the installed StyleSheet
            virtual SfxStyleSheet* GetStyleSheet() const;

            // Move properties to a new ItemPool.
            virtual void MoveToItemPool(SfxItemPool* pSrcPool, SfxItemPool* pDestPool, SdrModel* pNewModel = 0L);

            // Set new model.
            virtual void SetModel(SdrModel* pOldModel, SdrModel* pNewModel);

            // force all attributes which come from styles to hard attributes
            // to be able to live without the style.
            virtual void ForceStyleToHardAttributes();

            // This is the Notify(...) from 2nd base class SfxListener
            virtual void Notify(SfxBroadcaster& rBC, const SfxHint& rHint);
        };
    } // end of namespace properties
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

#endif //_SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX

// eof
<|endoftext|>


<commit_before>/*******************************************************************************
**                                                                            **
**  SWoOz is a software platform written in C++ used for behavioral           **
**  experiments based on interactions between people and robots               **
**  or 3D avatars.                                                            **
**                                                                            **
**  This program is free software: you can redistribute it and/or modify      **
**  it under the terms of the GNU Lesser General Public License as published  **
**  by the Free Software Foundation, either version 3 of the License, or      **
**  (at your option) any later version.                                       **
**                                                                            **
**  This program is distributed in the hope that it will be useful,           **
**  but WITHOUT ANY WARRANTY; without even the implied warranty of            **
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             **
**  GNU Lesser General Public License for more details.                       **
**                                                                            **
**  You should have received a copy of the GNU Lesser General Public License  **
**  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.           **
**                                                                            **
** *****************************************************************************
**          Authors: Guillaume Gibert, Florian Lance                          **
**  Website/Contact: http://swooz.free.fr/                                    **
**       Repository: https://github.com/GuillaumeGibert/swooz                 **
********************************************************************************/

/**
 * \file OpenNITracking.cpp
 * \brief Defines OpenNITracking class
 * \author Emmanuel Body
 * \date 07/01/13
 */

#include "rgbd/SWOpenNITracking.h"
#include "SWTrackingDevice.h"

// SWOOZ Toolkit
#include "geometryUtility.h"
#include "SWExceptions.h"

SWOpenNITracking::SWOpenNITracking()
    :m_IsOpenNiInitialized(false)
{
    std::string l_DeviceName  = "rgbd";
    std::string l_LibraryName = "openni";

    m_sHeadTrackingPortName		= "/tracking/" + l_DeviceName + "/"+ l_LibraryName + "/head";
    m_sTorsoTrackingPortName    = "/tracking/" + l_DeviceName + "/"+ l_LibraryName + "/torso";
    m_sLeftArmTrackingPortName	= "/tracking/" + l_DeviceName + "/"+ l_LibraryName + "/left_arm";
    m_sRightArmTrackingPortName	= "/tracking/" + l_DeviceName + "/"+ l_LibraryName + "/right_arm";

    m_oHeadTrackingPort.open(m_sHeadTrackingPortName.c_str());
    m_oTorsoTrackingPort.open(m_sTorsoTrackingPortName.c_str());
    m_oLeftArmTrackingPort.open(m_sLeftArmTrackingPortName.c_str());
    m_oRightArmTrackingPort.open(m_sRightArmTrackingPortName.c_str());
    m_oAllJointsTrackingPort.open("/tracking/joints:o");

    initOpenNi();
}

SWOpenNITracking::~SWOpenNITracking()
{
    m_oHeadTrackingPort.close();
    m_oTorsoTrackingPort.close();
    m_oLeftArmTrackingPort.close();
    m_oRightArmTrackingPort.close();
    m_oAllJointsTrackingPort.close();
}

void SWOpenNITracking::initOpenNi()
{
    m_oKinectSkeleton.reset(swDevice::SWKinectSkeleton::getInstance());

    if (m_oKinectSkeleton->init() == 0)
	{
        m_oKinectSkeleton->selectProfile(swDevice::SWKinectSkeleton::UpperBody);
        m_IsOpenNiInitialized = true;

        std::cout << "OpenNI skeleton initialized. " << std::endl;
	}
	else
	{
        std::cerr << "-ERROR : OpenNI initialisation failure. " << std::endl;
	}
}

bool SWOpenNITracking::isOpenNIInitialized() const
{
	return m_IsOpenNiInitialized;
}

double SWOpenNITracking::getPeriod()
{
	// module periodicity (seconds), called implicitly by myModule
    return 0.001/30.;
}

bool SWOpenNITracking::interruptModule() {
    m_oHeadTrackingPort		.interrupt();
    m_oTorsoTrackingPort    .interrupt();
    m_oLeftArmTrackingPort	.interrupt();
    m_oRightArmTrackingPort	.interrupt();
    m_oAllJointsTrackingPort	.interrupt();
	return true;
}

bool SWOpenNITracking::configure(yarp::os::ResourceFinder & rf)
{
	// nothing
	return true;
}

bool SWOpenNITracking::updateModule()
{
	if (!m_IsOpenNiInitialized)
	{
		return false;
	}

	std::vector<swDevice::SWKinectSkeleton::Coordinates> l_values;
    if (m_oKinectSkeleton->grab(l_values) == 0)
	{
		swDevice::SWKinectSkeleton::Coordinates l_pointTorso		= l_values[0];
		swDevice::SWKinectSkeleton::Coordinates l_pointNeck		= l_values[1];
		swDevice::SWKinectSkeleton::Coordinates l_pointHead		= l_values[2];
		swDevice::SWKinectSkeleton::Coordinates l_pointLShoulder		= l_values[3];
		swDevice::SWKinectSkeleton::Coordinates l_pointRShoulder		= l_values[4];
		swDevice::SWKinectSkeleton::Coordinates l_pointLElbow		= l_values[5];
		swDevice::SWKinectSkeleton::Coordinates l_pointRElbow		= l_values[6];
		swDevice::SWKinectSkeleton::Coordinates l_pointLHand		= l_values[7];
		swDevice::SWKinectSkeleton::Coordinates l_pointRHand		= l_values[8];
		swDevice::SWKinectSkeleton::Coordinates l_pointLHip			= l_values[9];
		swDevice::SWKinectSkeleton::Coordinates l_pointRHip			= l_values[10];

        yarp::os::Bottle & l_HeadBottle		= m_oHeadTrackingPort.prepare();
		l_HeadBottle.clear();
			l_HeadBottle.addInt(swTracking::OPENNI_LIB);
			l_HeadBottle.addDouble(l_pointNeck.X);			l_HeadBottle.addDouble(l_pointNeck.Y);			l_HeadBottle.addDouble(l_pointNeck.Z);
			l_HeadBottle.addDouble(l_pointHead.X);			l_HeadBottle.addDouble(l_pointHead.Y);			l_HeadBottle.addDouble(l_pointHead.Z);
			l_HeadBottle.addDouble(l_pointLShoulder.X);		l_HeadBottle.addDouble(l_pointLShoulder.Y);		l_HeadBottle.addDouble(l_pointLShoulder.Z);
			l_HeadBottle.addDouble(l_pointRShoulder.X);		l_HeadBottle.addDouble(l_pointRShoulder.Y);		l_HeadBottle.addDouble(l_pointRShoulder.Z);
        m_oHeadTrackingPort.write();

        yarp::os::Bottle & l_TorsoBottle 	= m_oTorsoTrackingPort.prepare();
		l_TorsoBottle.clear();
			l_TorsoBottle.addInt(swTracking::OPENNI_LIB);
			l_TorsoBottle.addDouble(l_pointTorso.X);		l_TorsoBottle.addDouble(l_pointTorso.Y);		l_TorsoBottle.addDouble(l_pointTorso.Z);
			l_TorsoBottle.addDouble(l_pointNeck.X);			l_TorsoBottle.addDouble(l_pointNeck.Y);			l_TorsoBottle.addDouble(l_pointNeck.Z);
			l_TorsoBottle.addDouble(l_pointLShoulder.X);	l_TorsoBottle.addDouble(l_pointLShoulder.Y);	l_TorsoBottle.addDouble(l_pointLShoulder.Z);
			l_TorsoBottle.addDouble(l_pointRShoulder.X);	l_TorsoBottle.addDouble(l_pointRShoulder.Y);	l_TorsoBottle.addDouble(l_pointRShoulder.Z);
        m_oTorsoTrackingPort.write();

        yarp::os::Bottle & l_LeftArmBottle 	= m_oLeftArmTrackingPort.prepare();
		l_LeftArmBottle.clear();
			l_LeftArmBottle.addInt(swTracking::OPENNI_LIB);
			l_LeftArmBottle.addDouble(l_pointTorso.X);		l_LeftArmBottle.addDouble(l_pointTorso.Y);		l_LeftArmBottle.addDouble(l_pointTorso.Z);
			l_LeftArmBottle.addDouble(l_pointNeck.X);		l_LeftArmBottle.addDouble(l_pointNeck.Y);		l_LeftArmBottle.addDouble(l_pointNeck.Z);
			l_LeftArmBottle.addDouble(l_pointLShoulder.X);	l_LeftArmBottle.addDouble(l_pointLShoulder.Y);	l_LeftArmBottle.addDouble(l_pointLShoulder.Z);
			l_LeftArmBottle.addDouble(l_pointLElbow.X);		l_LeftArmBottle.addDouble(l_pointLElbow.Y);		l_LeftArmBottle.addDouble(l_pointLElbow.Z);
			l_LeftArmBottle.addDouble(l_pointLHand.X);		l_LeftArmBottle.addDouble(l_pointLHand.Y);		l_LeftArmBottle.addDouble(l_pointLHand.Z);
        m_oLeftArmTrackingPort.write();

        yarp::os::Bottle & l_RightArmBottle = m_oRightArmTrackingPort.prepare();
		l_RightArmBottle.clear();
			l_RightArmBottle.addInt(swTracking::OPENNI_LIB);
			l_RightArmBottle.addDouble(l_pointTorso.X);		l_RightArmBottle.addDouble(l_pointTorso.Y);		l_RightArmBottle.addDouble(l_pointTorso.Z);
			l_RightArmBottle.addDouble(l_pointNeck.X);		l_RightArmBottle.addDouble(l_pointNeck.Y);		l_RightArmBottle.addDouble(l_pointNeck.Z);
			l_RightArmBottle.addDouble(l_pointRShoulder.X);	l_RightArmBottle.addDouble(l_pointRShoulder.Y);	l_RightArmBottle.addDouble(l_pointRShoulder.Z);
			l_RightArmBottle.addDouble(l_pointRElbow.X);	l_RightArmBottle.addDouble(l_pointRElbow.Y);	l_RightArmBottle.addDouble(l_pointRElbow.Z);
			l_RightArmBottle.addDouble(l_pointRHand.X);		l_RightArmBottle.addDouble(l_pointRHand.Y);		l_RightArmBottle.addDouble(l_pointRHand.Z);
        m_oRightArmTrackingPort.write();

        yarp::os::Bottle &l_allJointsBottle = m_oAllJointsTrackingPort.prepare();
        l_allJointsBottle.clear();
            l_HeadBottle.addDouble(l_pointNeck.X);			l_HeadBottle.addDouble(l_pointNeck.Y);			l_HeadBottle.addDouble(l_pointNeck.Z);
            l_HeadBottle.addDouble(l_pointHead.X);			l_HeadBottle.addDouble(l_pointHead.Y);			l_HeadBottle.addDouble(l_pointHead.Z);
            l_HeadBottle.addDouble(l_pointLShoulder.X);		l_HeadBottle.addDouble(l_pointLShoulder.Y);		l_HeadBottle.addDouble(l_pointLShoulder.Z);
            l_HeadBottle.addDouble(l_pointRShoulder.X);		l_HeadBottle.addDouble(l_pointRShoulder.Y);		l_HeadBottle.addDouble(l_pointRShoulder.Z);
            l_TorsoBottle.addDouble(l_pointTorso.X);		l_TorsoBottle.addDouble(l_pointTorso.Y);		l_TorsoBottle.addDouble(l_pointTorso.Z);
            l_LeftArmBottle.addDouble(l_pointLElbow.X);		l_LeftArmBottle.addDouble(l_pointLElbow.Y);		l_LeftArmBottle.addDouble(l_pointLElbow.Z);
            l_RightArmBottle.addDouble(l_pointRElbow.X);	l_RightArmBottle.addDouble(l_pointRElbow.Y);	l_RightArmBottle.addDouble(l_pointRElbow.Z);
            l_LeftArmBottle.addDouble(l_pointLHand.X);		l_LeftArmBottle.addDouble(l_pointLHand.Y);		l_LeftArmBottle.addDouble(l_pointLHand.Z);
            l_RightArmBottle.addDouble(l_pointRHand.X);		l_RightArmBottle.addDouble(l_pointRHand.Y);		l_RightArmBottle.addDouble(l_pointRHand.Z);
        m_oAllJointsTrackingPort.write();
	}

	return true; // RF Module OK
}

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

    yarp::os::Network netwotk;
    if (!netwotk.checkNetwork())
    {
        std::cerr << "/!\\ Problem connecting to YARP server." << std::endl;
        return -1;
    }

    std::cout << "Starting the OpenNI Skeleton capture module.." << std::endl;
    SWOpenNITracking l_OpenNITracking;

    // prepare and configure the resource finder
//    yarp::os::ResourceFinder rf;
//    rf.setVerbose(true);
//    rf.setDefaultConfigFile("openniTracking.ini");
//    rf.setDefaultContext("swtracking/conf");
//    rf.configure("YARP_DIR", argc, argv);

//    if(l_OpenNITracking.configure(rf))
//    {
         l_OpenNITracking.runModule();
//    }

    std::cout << "Ending OpenNI Skeleton capture module..." << std::endl;
}
<commit_msg>* Modify the frame rate of the openNI module to 30 fps<commit_after>/*******************************************************************************
**                                                                            **
**  SWoOz is a software platform written in C++ used for behavioral           **
**  experiments based on interactions between people and robots               **
**  or 3D avatars.                                                            **
**                                                                            **
**  This program is free software: you can redistribute it and/or modify      **
**  it under the terms of the GNU Lesser General Public License as published  **
**  by the Free Software Foundation, either version 3 of the License, or      **
**  (at your option) any later version.                                       **
**                                                                            **
**  This program is distributed in the hope that it will be useful,           **
**  but WITHOUT ANY WARRANTY; without even the implied warranty of            **
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             **
**  GNU Lesser General Public License for more details.                       **
**                                                                            **
**  You should have received a copy of the GNU Lesser General Public License  **
**  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.           **
**                                                                            **
** *****************************************************************************
**          Authors: Guillaume Gibert, Florian Lance                          **
**  Website/Contact: http://swooz.free.fr/                                    **
**       Repository: https://github.com/GuillaumeGibert/swooz                 **
********************************************************************************/

/**
 * \file OpenNITracking.cpp
 * \brief Defines OpenNITracking class
 * \author Emmanuel Body
 * \date 07/01/13
 */

#include "rgbd/SWOpenNITracking.h"
#include "SWTrackingDevice.h"

// SWOOZ Toolkit
#include "geometryUtility.h"
#include "SWExceptions.h"

SWOpenNITracking::SWOpenNITracking()
    :m_IsOpenNiInitialized(false)
{
    std::string l_DeviceName  = "rgbd";
    std::string l_LibraryName = "openni";

    m_sHeadTrackingPortName		= "/tracking/" + l_DeviceName + "/"+ l_LibraryName + "/head";
    m_sTorsoTrackingPortName    = "/tracking/" + l_DeviceName + "/"+ l_LibraryName + "/torso";
    m_sLeftArmTrackingPortName	= "/tracking/" + l_DeviceName + "/"+ l_LibraryName + "/left_arm";
    m_sRightArmTrackingPortName	= "/tracking/" + l_DeviceName + "/"+ l_LibraryName + "/right_arm";

    m_oHeadTrackingPort.open(m_sHeadTrackingPortName.c_str());
    m_oTorsoTrackingPort.open(m_sTorsoTrackingPortName.c_str());
    m_oLeftArmTrackingPort.open(m_sLeftArmTrackingPortName.c_str());
    m_oRightArmTrackingPort.open(m_sRightArmTrackingPortName.c_str());
    m_oAllJointsTrackingPort.open("/tracking/joints:o");

    initOpenNi();
}

SWOpenNITracking::~SWOpenNITracking()
{
    m_oHeadTrackingPort.close();
    m_oTorsoTrackingPort.close();
    m_oLeftArmTrackingPort.close();
    m_oRightArmTrackingPort.close();
    m_oAllJointsTrackingPort.close();
}

void SWOpenNITracking::initOpenNi()
{
    m_oKinectSkeleton.reset(swDevice::SWKinectSkeleton::getInstance());

    if (m_oKinectSkeleton->init() == 0)
	{
        m_oKinectSkeleton->selectProfile(swDevice::SWKinectSkeleton::UpperBody);
        m_IsOpenNiInitialized = true;

        std::cout << "OpenNI skeleton initialized. " << std::endl;
	}
	else
	{
        std::cerr << "-ERROR : OpenNI initialisation failure. " << std::endl;
	}
}

bool SWOpenNITracking::isOpenNIInitialized() const
{
	return m_IsOpenNiInitialized;
}

double SWOpenNITracking::getPeriod()
{
	// module periodicity (seconds), called implicitly by myModule
    return 1/30.;
}

bool SWOpenNITracking::interruptModule() {
    m_oHeadTrackingPort		.interrupt();
    m_oTorsoTrackingPort    .interrupt();
    m_oLeftArmTrackingPort	.interrupt();
    m_oRightArmTrackingPort	.interrupt();
    m_oAllJointsTrackingPort	.interrupt();
	return true;
}

bool SWOpenNITracking::configure(yarp::os::ResourceFinder & rf)
{
	// nothing
	return true;
}

bool SWOpenNITracking::updateModule()
{
	if (!m_IsOpenNiInitialized)
	{
		return false;
	}

	std::vector<swDevice::SWKinectSkeleton::Coordinates> l_values;
    if (m_oKinectSkeleton->grab(l_values) == 0)
	{
		swDevice::SWKinectSkeleton::Coordinates l_pointTorso		= l_values[0];
		swDevice::SWKinectSkeleton::Coordinates l_pointNeck		= l_values[1];
		swDevice::SWKinectSkeleton::Coordinates l_pointHead		= l_values[2];
		swDevice::SWKinectSkeleton::Coordinates l_pointLShoulder		= l_values[3];
		swDevice::SWKinectSkeleton::Coordinates l_pointRShoulder		= l_values[4];
		swDevice::SWKinectSkeleton::Coordinates l_pointLElbow		= l_values[5];
		swDevice::SWKinectSkeleton::Coordinates l_pointRElbow		= l_values[6];
		swDevice::SWKinectSkeleton::Coordinates l_pointLHand		= l_values[7];
		swDevice::SWKinectSkeleton::Coordinates l_pointRHand		= l_values[8];
		swDevice::SWKinectSkeleton::Coordinates l_pointLHip			= l_values[9];
		swDevice::SWKinectSkeleton::Coordinates l_pointRHip			= l_values[10];

        yarp::os::Bottle & l_HeadBottle		= m_oHeadTrackingPort.prepare();
		l_HeadBottle.clear();
			l_HeadBottle.addInt(swTracking::OPENNI_LIB);
			l_HeadBottle.addDouble(l_pointNeck.X);			l_HeadBottle.addDouble(l_pointNeck.Y);			l_HeadBottle.addDouble(l_pointNeck.Z);
			l_HeadBottle.addDouble(l_pointHead.X);			l_HeadBottle.addDouble(l_pointHead.Y);			l_HeadBottle.addDouble(l_pointHead.Z);
			l_HeadBottle.addDouble(l_pointLShoulder.X);		l_HeadBottle.addDouble(l_pointLShoulder.Y);		l_HeadBottle.addDouble(l_pointLShoulder.Z);
			l_HeadBottle.addDouble(l_pointRShoulder.X);		l_HeadBottle.addDouble(l_pointRShoulder.Y);		l_HeadBottle.addDouble(l_pointRShoulder.Z);
        m_oHeadTrackingPort.write();

        yarp::os::Bottle & l_TorsoBottle 	= m_oTorsoTrackingPort.prepare();
		l_TorsoBottle.clear();
			l_TorsoBottle.addInt(swTracking::OPENNI_LIB);
			l_TorsoBottle.addDouble(l_pointTorso.X);		l_TorsoBottle.addDouble(l_pointTorso.Y);		l_TorsoBottle.addDouble(l_pointTorso.Z);
			l_TorsoBottle.addDouble(l_pointNeck.X);			l_TorsoBottle.addDouble(l_pointNeck.Y);			l_TorsoBottle.addDouble(l_pointNeck.Z);
			l_TorsoBottle.addDouble(l_pointLShoulder.X);	l_TorsoBottle.addDouble(l_pointLShoulder.Y);	l_TorsoBottle.addDouble(l_pointLShoulder.Z);
			l_TorsoBottle.addDouble(l_pointRShoulder.X);	l_TorsoBottle.addDouble(l_pointRShoulder.Y);	l_TorsoBottle.addDouble(l_pointRShoulder.Z);
        m_oTorsoTrackingPort.write();

        yarp::os::Bottle & l_LeftArmBottle 	= m_oLeftArmTrackingPort.prepare();
		l_LeftArmBottle.clear();
			l_LeftArmBottle.addInt(swTracking::OPENNI_LIB);
			l_LeftArmBottle.addDouble(l_pointTorso.X);		l_LeftArmBottle.addDouble(l_pointTorso.Y);		l_LeftArmBottle.addDouble(l_pointTorso.Z);
			l_LeftArmBottle.addDouble(l_pointNeck.X);		l_LeftArmBottle.addDouble(l_pointNeck.Y);		l_LeftArmBottle.addDouble(l_pointNeck.Z);
			l_LeftArmBottle.addDouble(l_pointLShoulder.X);	l_LeftArmBottle.addDouble(l_pointLShoulder.Y);	l_LeftArmBottle.addDouble(l_pointLShoulder.Z);
			l_LeftArmBottle.addDouble(l_pointLElbow.X);		l_LeftArmBottle.addDouble(l_pointLElbow.Y);		l_LeftArmBottle.addDouble(l_pointLElbow.Z);
			l_LeftArmBottle.addDouble(l_pointLHand.X);		l_LeftArmBottle.addDouble(l_pointLHand.Y);		l_LeftArmBottle.addDouble(l_pointLHand.Z);
        m_oLeftArmTrackingPort.write();

        yarp::os::Bottle & l_RightArmBottle = m_oRightArmTrackingPort.prepare();
		l_RightArmBottle.clear();
			l_RightArmBottle.addInt(swTracking::OPENNI_LIB);
			l_RightArmBottle.addDouble(l_pointTorso.X);		l_RightArmBottle.addDouble(l_pointTorso.Y);		l_RightArmBottle.addDouble(l_pointTorso.Z);
			l_RightArmBottle.addDouble(l_pointNeck.X);		l_RightArmBottle.addDouble(l_pointNeck.Y);		l_RightArmBottle.addDouble(l_pointNeck.Z);
			l_RightArmBottle.addDouble(l_pointRShoulder.X);	l_RightArmBottle.addDouble(l_pointRShoulder.Y);	l_RightArmBottle.addDouble(l_pointRShoulder.Z);
			l_RightArmBottle.addDouble(l_pointRElbow.X);	l_RightArmBottle.addDouble(l_pointRElbow.Y);	l_RightArmBottle.addDouble(l_pointRElbow.Z);
			l_RightArmBottle.addDouble(l_pointRHand.X);		l_RightArmBottle.addDouble(l_pointRHand.Y);		l_RightArmBottle.addDouble(l_pointRHand.Z);
        m_oRightArmTrackingPort.write();

        yarp::os::Bottle &l_allJointsBottle = m_oAllJointsTrackingPort.prepare();
        l_allJointsBottle.clear();
            l_HeadBottle.addDouble(l_pointNeck.X);			l_HeadBottle.addDouble(l_pointNeck.Y);			l_HeadBottle.addDouble(l_pointNeck.Z);
            l_HeadBottle.addDouble(l_pointHead.X);			l_HeadBottle.addDouble(l_pointHead.Y);			l_HeadBottle.addDouble(l_pointHead.Z);
            l_HeadBottle.addDouble(l_pointLShoulder.X);		l_HeadBottle.addDouble(l_pointLShoulder.Y);		l_HeadBottle.addDouble(l_pointLShoulder.Z);
            l_HeadBottle.addDouble(l_pointRShoulder.X);		l_HeadBottle.addDouble(l_pointRShoulder.Y);		l_HeadBottle.addDouble(l_pointRShoulder.Z);
            l_TorsoBottle.addDouble(l_pointTorso.X);		l_TorsoBottle.addDouble(l_pointTorso.Y);		l_TorsoBottle.addDouble(l_pointTorso.Z);
            l_LeftArmBottle.addDouble(l_pointLElbow.X);		l_LeftArmBottle.addDouble(l_pointLElbow.Y);		l_LeftArmBottle.addDouble(l_pointLElbow.Z);
            l_RightArmBottle.addDouble(l_pointRElbow.X);	l_RightArmBottle.addDouble(l_pointRElbow.Y);	l_RightArmBottle.addDouble(l_pointRElbow.Z);
            l_LeftArmBottle.addDouble(l_pointLHand.X);		l_LeftArmBottle.addDouble(l_pointLHand.Y);		l_LeftArmBottle.addDouble(l_pointLHand.Z);
            l_RightArmBottle.addDouble(l_pointRHand.X);		l_RightArmBottle.addDouble(l_pointRHand.Y);		l_RightArmBottle.addDouble(l_pointRHand.Z);
        m_oAllJointsTrackingPort.write();
	}

	return true; // RF Module OK
}

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

    yarp::os::Network netwotk;
    if (!netwotk.checkNetwork())
    {
        std::cerr << "/!\\ Problem connecting to YARP server." << std::endl;
        return -1;
    }

    std::cout << "Starting the OpenNI Skeleton capture module.." << std::endl;
    SWOpenNITracking l_OpenNITracking;

    // prepare and configure the resource finder
//    yarp::os::ResourceFinder rf;
//    rf.setVerbose(true);
//    rf.setDefaultConfigFile("openniTracking.ini");
//    rf.setDefaultContext("swtracking/conf");
//    rf.configure("YARP_DIR", argc, argv);

//    if(l_OpenNITracking.configure(rf))
//    {
         l_OpenNITracking.runModule();
//    }

    std::cout << "Ending OpenNI Skeleton capture module..." << std::endl;
}
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright © 2017-2018 Ruben Van Boxem
 *
 * 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 "gui/events/xcb.h++"

#include "gui/native_window/xcb.h++"
#include "gui/native_window/xlib.h++"
#include "gui/window.h++"

#include <core/debug.h++>

namespace
{
  using namespace skui::gui::input;

  std::uint8_t mask_send_event_bit(std::uint8_t response_type)
  {
    return response_type & 0b0111'1111;
  }

  std::optional<button> get_button(xcb_button_t xcb_button)
  {
    switch(xcb_button)
    {
      case 1:
        return button::primary;
      case 2:
        return button::middle;
      case 3:
        return button::secondary;
      default:
        return {};
    }
  }

  std::optional<scroll> get_scroll(xcb_button_t xcb_button)
  {
    switch(xcb_button)
    {
      case 4:
        return scroll::up;
      case 5:
        return scroll::down;
      case 6:
        return scroll::left; //?
      case 7:
        return scroll::right; //?
      default:
        return {};
    }
  }
}

namespace skui
{
  namespace gui
  {
    namespace events
    {
      xcb::xcb(gui::window& window)
        : base{window}
      {
        auto native_xcb_window = dynamic_cast<native_window::xcb*>(&window.get_native_window());
        if(!native_xcb_window)
          core::debug_print("events::xcb requires a native_window::xcb or native_window::xlib.\n");

        connection = native_xcb_window->get_connection();
        xcb_window = native_xcb_window->get_window();

        // The magic incantation to receive and be able to check for the "window was closed" event
        xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, true, 12, "WM_PROTOCOLS");
        core::unique_free_ptr<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(connection, cookie, nullptr));

        xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, false, 16, "WM_DELETE_WINDOW");
        wm_delete_window.reset(xcb_intern_atom_reply(connection, cookie2, nullptr));

        xcb_change_property(connection,
                            XCB_PROP_MODE_REPLACE,
                            xcb_window,
                            reply->atom, 4, 32, 1, &wm_delete_window->atom);
        // end magic

        xcb_flush(connection);
      }

      xcb::~xcb() = default;

      void xcb::exec()
      {
        bool running = true;

        while(running)
        {
          core::unique_free_ptr<const xcb_generic_event_t> event_ptr(xcb_wait_for_event(connection));
          if(!event_ptr)
          {
            core::debug_print("Call to xcb_wait_for_event failed. Most likely an I/O error.\n");
            running = false;
            break;
          }

          switch(mask_send_event_bit(event_ptr->response_type))
          {
            case XCB_EXPOSE:
            {
              const auto& expose = reinterpret_cast<const xcb_expose_event_t&>(*event_ptr);
              if(expose.count>0)
                continue;

              window.repaint();

              break;
            }
            case XCB_UNMAP_NOTIFY:
            {
              //const auto& unmap = reinterpret_cast<const xcb_unmap_notify_event_t&>(*event_ptr);
              break;
            }
            case XCB_MAP_NOTIFY:
            {
              //const auto& map = reinterpret_cast<const xcb_map_notify_event_t&>(*event_ptr);
              window.state = window_state::windowed;

              // Force a repaint on map. This ensures a unminized window is properly displayed.
              window.repaint(true);

              break;
            }
            case XCB_BUTTON_PRESS:
            {
              const auto& button_press = reinterpret_cast<const xcb_button_press_event_t&>(*event_ptr);

              const graphics::pixel_position position{button_press.event_x,
                                                      button_press.event_y};

              if(const auto button = get_button(button_press.detail); button)
              {
                pressed_buttons.set(*button);

                window.pointer.pressed(*button, position);
              }
              else if(const auto scroll = get_scroll(button_press.detail); scroll)
              {
                window.pointer.scroll(*scroll, position);
              }

              break;
            }
            case XCB_BUTTON_RELEASE:
            {
              const auto& button_release = reinterpret_cast<const xcb_button_release_event_t&>(*event_ptr);

              const graphics::pixel_position position{button_release.event_x,
                                                      button_release.event_y};

              if(const auto button = get_button(button_release.detail); button)
              {
                const bool click = pressed_buttons.test(*button);
                pressed_buttons.unset(*button);

                window.pointer.released(*button, position);
                if(click)
                  window.pointer.clicked(*button, position);
              }

              break;
            }
            case XCB_MOTION_NOTIFY:
            {
              const auto& motion = reinterpret_cast<const xcb_motion_notify_event_t&>(*event_ptr);

              const graphics::pixel_position position{motion.event_x,
                                                      motion.event_y};
              window.pointer.moved(position);

              break;
            }
            case XCB_ENTER_NOTIFY:
            {
              const auto& enter = reinterpret_cast<const xcb_enter_notify_event_t&>(*event_ptr);

              const graphics::pixel_position position{enter.event_x,
                                                      enter.event_y};
              window.pointer.entered(position);

              break;
            }
            case XCB_LEAVE_NOTIFY:
            {
              const auto& leave = reinterpret_cast<const xcb_leave_notify_event_t&>(*event_ptr);

              const graphics::pixel_position position{leave.event_x,
                                                      leave.event_y};
              window.pointer.left(position);

              break;
            }
            case XCB_KEY_PRESS:
            {
              //const auto& key_press = reinterpret_cast<xcb_key_press_event_t&>(*event_ptr);
              //implementation::print_modifiers(key_press->state);
              break;
            }
            case XCB_KEY_RELEASE:
            {
              //const auto& key_release = reinterpret_cast<xcb_key_release_event_t*>(*event_ptr);
              //implementation::print_modifiers(key_release->state);
              break;
            }
            case XCB_CONFIGURE_NOTIFY:
            {
              //const auto& configure_notify = reinterpret_cast<const xcb_configure_notify_event_t&>(*event_ptr);

              window.repaint(true);

              break;
            }
            case XCB_CLIENT_MESSAGE:
            {
              const auto& client_message = reinterpret_cast<const xcb_client_message_event_t&>(*event_ptr);

              if(client_message.data.data32[0] == wm_delete_window->atom)
              {
                core::debug_print("WM_DELETE_WINDOW received.\n");
                window.close();
              }
              break;
            }
            case XCB_DESTROY_NOTIFY:
            {
              running = false;
              break;
            }
            case XCB_REPARENT_NOTIFY:
            {
              //const auto& reparent = reinterpret_cast<const xcb_reparent_notify_event_t&>(*event_ptr);

              break;
            }
            default:
              if(const auto* xlib_window = dynamic_cast<native_window::xlib*>(&window.get_native_window());
                 xlib_window)
              {
                xlib_window->handle_dri2_events(const_cast<xcb_generic_event_t&>(*event_ptr));
                break;
              }
              core::debug_print("Unknown event: ", (int)mask_send_event_bit(event_ptr->response_type), ".\n");
              break;
          }
        }
      }
    }
  }
}
<commit_msg>It is better to force repaint on expose instead of configure events. Some extra painting could be seen after resizing fast for some time before this change.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright © 2017-2018 Ruben Van Boxem
 *
 * 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 "gui/events/xcb.h++"

#include "gui/native_window/xcb.h++"
#include "gui/native_window/xlib.h++"
#include "gui/window.h++"

#include <core/debug.h++>

namespace
{
  using namespace skui::gui::input;

  std::uint8_t mask_send_event_bit(std::uint8_t response_type)
  {
    return response_type & 0b0111'1111;
  }

  std::optional<button> get_button(xcb_button_t xcb_button)
  {
    switch(xcb_button)
    {
      case 1:
        return button::primary;
      case 2:
        return button::middle;
      case 3:
        return button::secondary;
      default:
        return {};
    }
  }

  std::optional<scroll> get_scroll(xcb_button_t xcb_button)
  {
    switch(xcb_button)
    {
      case 4:
        return scroll::up;
      case 5:
        return scroll::down;
      case 6:
        return scroll::left; //?
      case 7:
        return scroll::right; //?
      default:
        return {};
    }
  }
}

namespace skui
{
  namespace gui
  {
    namespace events
    {
      xcb::xcb(gui::window& window)
        : base{window}
      {
        auto native_xcb_window = dynamic_cast<native_window::xcb*>(&window.get_native_window());
        if(!native_xcb_window)
          core::debug_print("events::xcb requires a native_window::xcb or native_window::xlib.\n");

        connection = native_xcb_window->get_connection();
        xcb_window = native_xcb_window->get_window();

        // The magic incantation to receive and be able to check for the "window was closed" event
        xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, true, 12, "WM_PROTOCOLS");
        core::unique_free_ptr<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(connection, cookie, nullptr));

        xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, false, 16, "WM_DELETE_WINDOW");
        wm_delete_window.reset(xcb_intern_atom_reply(connection, cookie2, nullptr));

        xcb_change_property(connection,
                            XCB_PROP_MODE_REPLACE,
                            xcb_window,
                            reply->atom, 4, 32, 1, &wm_delete_window->atom);
        // end magic

        xcb_flush(connection);
      }

      xcb::~xcb() = default;

      void xcb::exec()
      {
        bool running = true;

        while(running)
        {
          core::unique_free_ptr<const xcb_generic_event_t> event_ptr(xcb_wait_for_event(connection));
          if(!event_ptr)
          {
            core::debug_print("Call to xcb_wait_for_event failed. Most likely an I/O error.\n");
            running = false;
            break;
          }

          switch(mask_send_event_bit(event_ptr->response_type))
          {
            case XCB_EXPOSE:
            {
              const auto& expose = reinterpret_cast<const xcb_expose_event_t&>(*event_ptr);
              if(expose.count>0)
                continue;

              window.repaint(true);

              break;
            }
            case XCB_UNMAP_NOTIFY:
            {
              //const auto& unmap = reinterpret_cast<const xcb_unmap_notify_event_t&>(*event_ptr);
              break;
            }
            case XCB_MAP_NOTIFY:
            {
              //const auto& map = reinterpret_cast<const xcb_map_notify_event_t&>(*event_ptr);
              window.state = window_state::windowed;

              // Force a repaint on map. This ensures a unminized window is properly displayed.
              window.repaint(true);

              break;
            }
            case XCB_BUTTON_PRESS:
            {
              const auto& button_press = reinterpret_cast<const xcb_button_press_event_t&>(*event_ptr);

              const graphics::pixel_position position{button_press.event_x,
                                                      button_press.event_y};

              if(const auto button = get_button(button_press.detail); button)
              {
                pressed_buttons.set(*button);

                window.pointer.pressed(*button, position);
              }
              else if(const auto scroll = get_scroll(button_press.detail); scroll)
              {
                window.pointer.scroll(*scroll, position);
              }

              break;
            }
            case XCB_BUTTON_RELEASE:
            {
              const auto& button_release = reinterpret_cast<const xcb_button_release_event_t&>(*event_ptr);

              const graphics::pixel_position position{button_release.event_x,
                                                      button_release.event_y};

              if(const auto button = get_button(button_release.detail); button)
              {
                const bool click = pressed_buttons.test(*button);
                pressed_buttons.unset(*button);

                window.pointer.released(*button, position);
                if(click)
                  window.pointer.clicked(*button, position);
              }

              break;
            }
            case XCB_MOTION_NOTIFY:
            {
              const auto& motion = reinterpret_cast<const xcb_motion_notify_event_t&>(*event_ptr);

              const graphics::pixel_position position{motion.event_x,
                                                      motion.event_y};
              window.pointer.moved(position);

              break;
            }
            case XCB_ENTER_NOTIFY:
            {
              const auto& enter = reinterpret_cast<const xcb_enter_notify_event_t&>(*event_ptr);

              const graphics::pixel_position position{enter.event_x,
                                                      enter.event_y};
              window.pointer.entered(position);

              break;
            }
            case XCB_LEAVE_NOTIFY:
            {
              const auto& leave = reinterpret_cast<const xcb_leave_notify_event_t&>(*event_ptr);

              const graphics::pixel_position position{leave.event_x,
                                                      leave.event_y};
              window.pointer.left(position);

              break;
            }
            case XCB_KEY_PRESS:
            {
              //const auto& key_press = reinterpret_cast<xcb_key_press_event_t&>(*event_ptr);
              //implementation::print_modifiers(key_press->state);
              break;
            }
            case XCB_KEY_RELEASE:
            {
              //const auto& key_release = reinterpret_cast<xcb_key_release_event_t*>(*event_ptr);
              //implementation::print_modifiers(key_release->state);
              break;
            }
            case XCB_CONFIGURE_NOTIFY:
            {
              //const auto& configure_notify = reinterpret_cast<const xcb_configure_notify_event_t&>(*event_ptr);

              window.repaint();

              break;
            }
            case XCB_CLIENT_MESSAGE:
            {
              const auto& client_message = reinterpret_cast<const xcb_client_message_event_t&>(*event_ptr);

              if(client_message.data.data32[0] == wm_delete_window->atom)
              {
                core::debug_print("WM_DELETE_WINDOW received.\n");
                window.close();
              }
              break;
            }
            case XCB_DESTROY_NOTIFY:
            {
              running = false;
              break;
            }
            case XCB_REPARENT_NOTIFY:
            {
              //const auto& reparent = reinterpret_cast<const xcb_reparent_notify_event_t&>(*event_ptr);

              break;
            }
            default:
              if(const auto* xlib_window = dynamic_cast<native_window::xlib*>(&window.get_native_window());
                 xlib_window)
              {
                xlib_window->handle_dri2_events(const_cast<xcb_generic_event_t&>(*event_ptr));
                break;
              }
              core::debug_print("Unknown event: ", (int)mask_send_event_bit(event_ptr->response_type), ".\n");
              break;
          }
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __itkGradientRecursiveGaussianImageFilter_hxx
#define __itkGradientRecursiveGaussianImageFilter_hxx

#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIterator.h"

namespace itk
{
/**
 * Constructor
 */
template< typename TInputImage, typename TOutputImage >
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GradientRecursiveGaussianImageFilter()
{
  m_NormalizeAcrossScale = false;
  this->m_UseImageDirection = true;

  unsigned int imageDimensionMinus1 = ImageDimension - 1;
  if ( ImageDimension > 1 )
    {
    m_SmoothingFilters.resize(imageDimensionMinus1);
    }

  for ( unsigned int i = 0; i < imageDimensionMinus1; i++ )
    {
    m_SmoothingFilters[i] = GaussianFilterType::New();
    m_SmoothingFilters[i]->SetOrder(GaussianFilterType::ZeroOrder);
    m_SmoothingFilters[i]->SetNormalizeAcrossScale(m_NormalizeAcrossScale);
    m_SmoothingFilters[i]->InPlaceOn();
    m_SmoothingFilters[i]->ReleaseDataFlagOn();
    }

  m_DerivativeFilter = DerivativeFilterType::New();
  m_DerivativeFilter->SetOrder(DerivativeFilterType::FirstOrder);
  m_DerivativeFilter->SetNormalizeAcrossScale(m_NormalizeAcrossScale);
  m_DerivativeFilter->ReleaseDataFlagOn();
  m_DerivativeFilter->InPlaceOff();
  m_DerivativeFilter->SetInput( this->GetInput() );

  if ( ImageDimension > 1 )
    {
    m_SmoothingFilters[0]->SetInput( m_DerivativeFilter->GetOutput() );
    }

  for ( unsigned int i = 1; i < imageDimensionMinus1; i++ )
    {
    m_SmoothingFilters[i]->SetInput(
      m_SmoothingFilters[i - 1]->GetOutput() );
    }

  m_ImageAdaptor = OutputImageAdaptorType::New();

  this->SetSigma(1.0);
}

/**
 * Set value of Sigma
 */
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::SetSigma(ScalarRealType sigma)
{
  int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;

  for ( int i = 0; i < imageDimensionMinus1; i++ )
    {
    m_SmoothingFilters[i]->SetSigma(sigma);
    }
  m_DerivativeFilter->SetSigma(sigma);

  this->Modified();
}

/**
 * Get value of Sigma
 */
template< typename TInputImage, typename TOutputImage >
typename GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::RealType
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GetSigma() const
{
  return m_DerivativeFilter->GetSigma();
}

/**
 * Set Normalize Across Scale Space
 */
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::SetNormalizeAcrossScale(bool normalize)
{
  m_NormalizeAcrossScale = normalize;

  int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;
  for ( int i = 0; i < imageDimensionMinus1; i++ )
    {
    m_SmoothingFilters[i]->SetNormalizeAcrossScale(normalize);
    }
  m_DerivativeFilter->SetNormalizeAcrossScale(normalize);

  this->Modified();
}

//
//
//
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
  // call the superclass' implementation of this method. this should
  // copy the output requested region to the input requested region
  Superclass::GenerateInputRequestedRegion();

  // This filter needs all of the input
  typename GradientRecursiveGaussianImageFilter< TInputImage,
                                                 TOutputImage >::InputImagePointer image =
    const_cast< InputImageType * >( this->GetInput() );
  if ( image )
    {
    image->SetRequestedRegion( this->GetInput()->GetLargestPossibleRegion() );
    }
}

//
//
//
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::EnlargeOutputRequestedRegion(DataObject *output)
{
  TOutputImage *out = dynamic_cast< TOutputImage * >( output );

  if ( out )
    {
    out->SetRequestedRegion( out->GetLargestPossibleRegion() );
    }
}

/**
 * Compute filter for Gaussian kernel
 */
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GenerateData(void)
{
  // Create a process accumulator for tracking the progress of this
  // minipipeline
  ProgressAccumulator::Pointer progress = ProgressAccumulator::New();
  progress->SetMiniPipelineFilter(this);

  // Compute the contribution of each filter to the total progress.
  const double weight = 1.0 / ( ImageDimension * ImageDimension );

  unsigned int imageDimensionMinus1 = ImageDimension - 1;
  for ( unsigned int i = 0; i < imageDimensionMinus1; i++ )
    {
    progress->RegisterInternalFilter(m_SmoothingFilters[i], weight);
    }

  progress->RegisterInternalFilter(m_DerivativeFilter, weight);

  const typename TInputImage::ConstPointer inputImage( this->GetInput() );
  typename TOutputImage::Pointer           outputImage( this->GetOutput() );

  unsigned int nComponents = inputImage->GetNumberOfComponentsPerPixel();
  /* An Image of VariableLengthVectors will return 0 */
  if (nComponents == 0 )
    {
    const typename InputImageType::IndexType idx = inputImage->GetLargestPossibleRegion().GetIndex();
    nComponents = NumericTraits<typename InputImageType::PixelType>::GetLength( inputImage->GetPixel(idx) );
    }

  m_ImageAdaptor->SetImage( outputImage );

  m_ImageAdaptor->SetLargestPossibleRegion(
    inputImage->GetLargestPossibleRegion() );

  m_ImageAdaptor->SetBufferedRegion(
    inputImage->GetBufferedRegion() );

  m_ImageAdaptor->SetRequestedRegion(
    inputImage->GetRequestedRegion() );

  m_ImageAdaptor->Allocate();

  m_DerivativeFilter->SetInput(inputImage);

  // For variable length output pixel types
  ImageRegionIteratorWithIndex<OutputImageType> initGradIt(
    outputImage, this->m_ImageAdaptor->GetRequestedRegion() );

  for ( unsigned int nc = 0; nc < nComponents; nc++ )
    {
    for ( unsigned int dim = 0; dim < ImageDimension; dim++ )
      {
      unsigned int i = 0;
      unsigned int j = 0;
      while (  i < imageDimensionMinus1 )
        {
        if ( i == dim )
          {
          j++;
        }
        m_SmoothingFilters[i]->SetDirection(j);
        i++;
        j++;
        }
      m_DerivativeFilter->SetDirection(dim);

      GaussianFilterPointer lastFilter;

      if ( ImageDimension > 1 )
        {
        const unsigned int imageDimensionMinus2 = static_cast< unsigned int >( ImageDimension - 2 );
        lastFilter = m_SmoothingFilters[imageDimensionMinus2];
        lastFilter->UpdateLargestPossibleRegion();
        }
      else
        {
        m_DerivativeFilter->UpdateLargestPossibleRegion();
        }

      // Copy the results to the corresponding component
      // on the output image of vectors
      m_ImageAdaptor->SelectNthElement(nc*ImageDimension + dim);

      typename RealImageType::Pointer derivativeImage;
      if ( ImageDimension > 1 )
        {
        derivativeImage = lastFilter->GetOutput();
        }
      else
        {
        derivativeImage = m_DerivativeFilter->GetOutput();
        }

      ImageRegionIteratorWithIndex< RealImageType > it(
        derivativeImage,
        derivativeImage->GetRequestedRegion() );

      ImageRegionIteratorWithIndex< OutputImageAdaptorType > ot(
        m_ImageAdaptor,
        m_ImageAdaptor->GetRequestedRegion() );

      const ScalarRealType spacing = inputImage->GetSpacing()[dim];

      it.GoToBegin();
      ot.GoToBegin();
      while ( !it.IsAtEnd() )
        {
        OutputComponentType outValue = static_cast<OutputComponentType>( DefaultConvertPixelTraits<InternalRealType>::GetNthComponent( nc, it.Get() / spacing ) );
        ot.Set( outValue );
        ++it;
        ++ot;
        }
      }
    }

  // manually release memory in last filter in the mini-pipeline
  if ( ImageDimension > 1 )
    {
    int temp_dim = static_cast< int >( ImageDimension ) - 2;
    m_SmoothingFilters[temp_dim]->GetOutput()->ReleaseData();
    }
  else
    {
    m_DerivativeFilter->GetOutput()->ReleaseData();
    }

  // If the flag for using the input image direction is ON,
  // then we apply the direction correction to all the pixels
  // of the output gradient image.
  if ( this->m_UseImageDirection )
    {

    OutputImageType *gradientImage = outputImage;
    ImageRegionIterator< OutputImageType > itr( gradientImage,
                                                gradientImage->GetRequestedRegion() );

    while ( !itr.IsAtEnd() )
      {

      TransformOutputPixel( itr );
      ++itr;
      }

    }
}

template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GenerateOutputInformation()
{
  // this methods is overloaded so that if the output image is a
  // VectorImage then the correct number of components are set.

  Superclass::GenerateOutputInformation();

  OutputImageType* output = this->GetOutput();
  const typename TInputImage::ConstPointer inputImage( this->GetInput() );

  unsigned int nComponents = inputImage->GetNumberOfComponentsPerPixel() * ImageDimension;

  output->SetNumberOfComponentsPerPixel( nComponents );
}

template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  os << indent << "NormalizeAcrossScale: " << m_NormalizeAcrossScale << std::endl;
  os << indent << "UseImageDirection :   "
     << ( this->m_UseImageDirection ? "On" : "Off" ) << std::endl;
}
} // end namespace itk

#endif
<commit_msg>COMP: Improve const correctness of GradientRecursiveGaussianImageFilter.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __itkGradientRecursiveGaussianImageFilter_hxx
#define __itkGradientRecursiveGaussianImageFilter_hxx

#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIterator.h"

namespace itk
{
/**
 * Constructor
 */
template< typename TInputImage, typename TOutputImage >
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GradientRecursiveGaussianImageFilter()
{
  m_NormalizeAcrossScale = false;
  this->m_UseImageDirection = true;

  const int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;
  if ( ImageDimension > 1 )
    {
    m_SmoothingFilters.resize(imageDimensionMinus1);

    for ( int i = 0; i < imageDimensionMinus1; ++i )
      {
      m_SmoothingFilters[i] = GaussianFilterType::New();
      m_SmoothingFilters[i]->SetOrder(GaussianFilterType::ZeroOrder);
      m_SmoothingFilters[i]->SetNormalizeAcrossScale(m_NormalizeAcrossScale);
      m_SmoothingFilters[i]->InPlaceOn();
      m_SmoothingFilters[i]->ReleaseDataFlagOn();
      }
    }

  m_DerivativeFilter = DerivativeFilterType::New();
  m_DerivativeFilter->SetOrder(DerivativeFilterType::FirstOrder);
  m_DerivativeFilter->SetNormalizeAcrossScale(m_NormalizeAcrossScale);
  m_DerivativeFilter->ReleaseDataFlagOn();
  m_DerivativeFilter->InPlaceOff();
  m_DerivativeFilter->SetInput( this->GetInput() );

  if ( ImageDimension > 1 )
    {
    m_SmoothingFilters[0]->SetInput( m_DerivativeFilter->GetOutput() );

    for ( int i = 1; i < imageDimensionMinus1; ++i )
      {
      m_SmoothingFilters[i]->SetInput(
        m_SmoothingFilters[i - 1]->GetOutput() );
      }
    }

  m_ImageAdaptor = OutputImageAdaptorType::New();

  this->SetSigma(1.0);
}

/**
 * Set value of Sigma
 */
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::SetSigma(ScalarRealType sigma)
{
  if (ImageDimension > 1)
    {
    const int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;
    for ( int i = 0; i < imageDimensionMinus1; ++i )
      {
      m_SmoothingFilters[i]->SetSigma(sigma);
      }
    }
  m_DerivativeFilter->SetSigma(sigma);
  this->Modified();
}

/**
 * Get value of Sigma
 */
template< typename TInputImage, typename TOutputImage >
typename GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::RealType
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GetSigma() const
{
  return m_DerivativeFilter->GetSigma();
}

/**
 * Set Normalize Across Scale Space
 */
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::SetNormalizeAcrossScale(bool normalize)
{
  m_NormalizeAcrossScale = normalize;

  const int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;
  for ( int i = 0; i < imageDimensionMinus1; i++ )
    {
    m_SmoothingFilters[i]->SetNormalizeAcrossScale(normalize);
    }
  m_DerivativeFilter->SetNormalizeAcrossScale(normalize);

  this->Modified();
}

//
//
//
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
  // call the superclass' implementation of this method. this should
  // copy the output requested region to the input requested region
  Superclass::GenerateInputRequestedRegion();

  // This filter needs all of the input
  typename GradientRecursiveGaussianImageFilter< TInputImage,
                                                 TOutputImage >::InputImagePointer image =
    const_cast< InputImageType * >( this->GetInput() );
  if ( image )
    {
    image->SetRequestedRegion( this->GetInput()->GetLargestPossibleRegion() );
    }
}

//
//
//
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::EnlargeOutputRequestedRegion(DataObject *output)
{
  TOutputImage *out = dynamic_cast< TOutputImage * >( output );

  if ( out )
    {
    out->SetRequestedRegion( out->GetLargestPossibleRegion() );
    }
}

/**
 * Compute filter for Gaussian kernel
 */
template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GenerateData(void)
{
  // Create a process accumulator for tracking the progress of this
  // minipipeline
  ProgressAccumulator::Pointer progress = ProgressAccumulator::New();
  progress->SetMiniPipelineFilter(this);

  // Compute the contribution of each filter to the total progress.
  const double weight = 1.0 / ( ImageDimension * ImageDimension );

  const int imageDimensionMinus1 = static_cast< int >( ImageDimension ) - 1;
  if( ImageDimension > 1 )
    {
    for( int i = 0; i < imageDimensionMinus1; ++i )
      {
      progress->RegisterInternalFilter(m_SmoothingFilters[i], weight);
      }
    }

  progress->RegisterInternalFilter(m_DerivativeFilter, weight);

  const typename TInputImage::ConstPointer inputImage( this->GetInput() );
  typename TOutputImage::Pointer           outputImage( this->GetOutput() );

  unsigned int nComponents = inputImage->GetNumberOfComponentsPerPixel();
  /* An Image of VariableLengthVectors will return 0 */
  if (nComponents == 0 )
    {
    const typename InputImageType::IndexType idx = inputImage->GetLargestPossibleRegion().GetIndex();
    nComponents = NumericTraits<typename InputImageType::PixelType>::GetLength( inputImage->GetPixel(idx) );
    }

  m_ImageAdaptor->SetImage( outputImage );

  m_ImageAdaptor->SetLargestPossibleRegion(
    inputImage->GetLargestPossibleRegion() );

  m_ImageAdaptor->SetBufferedRegion(
    inputImage->GetBufferedRegion() );

  m_ImageAdaptor->SetRequestedRegion(
    inputImage->GetRequestedRegion() );

  m_ImageAdaptor->Allocate();

  m_DerivativeFilter->SetInput(inputImage);

  // For variable length output pixel types
  ImageRegionIteratorWithIndex<OutputImageType> initGradIt(
    outputImage, this->m_ImageAdaptor->GetRequestedRegion() );

  for ( unsigned int nc = 0; nc < nComponents; ++nc )
    {
    for ( int dim = 0; dim < ImageDimension; ++dim )
      {
      int i = 0;
      int j = 0;
      while( i < imageDimensionMinus1 )
        {
        if( i == dim )
          {
          ++j;
          }
        m_SmoothingFilters[i]->SetDirection(j);
        ++i;
        ++j;
        }
      m_DerivativeFilter->SetDirection(dim);

      GaussianFilterPointer lastFilter;

      if ( ImageDimension > 1 )
        {
        const unsigned int imageDimensionMinus2 = static_cast< unsigned int >( ImageDimension - 2 );
        lastFilter = m_SmoothingFilters[imageDimensionMinus2];
        lastFilter->UpdateLargestPossibleRegion();
        }
      else
        {
        m_DerivativeFilter->UpdateLargestPossibleRegion();
        }

      // Copy the results to the corresponding component
      // on the output image of vectors
      m_ImageAdaptor->SelectNthElement(nc*ImageDimension + dim);

      typename RealImageType::Pointer derivativeImage;
      if ( ImageDimension > 1 )
        {
        derivativeImage = lastFilter->GetOutput();
        }
      else
        {
        derivativeImage = m_DerivativeFilter->GetOutput();
        }

      ImageRegionIteratorWithIndex< RealImageType > it(
        derivativeImage,
        derivativeImage->GetRequestedRegion() );

      ImageRegionIteratorWithIndex< OutputImageAdaptorType > ot(
        m_ImageAdaptor,
        m_ImageAdaptor->GetRequestedRegion() );

      const ScalarRealType spacing = inputImage->GetSpacing()[dim];

      it.GoToBegin();
      ot.GoToBegin();
      while ( !it.IsAtEnd() )
        {
        OutputComponentType outValue = static_cast<OutputComponentType>( DefaultConvertPixelTraits<InternalRealType>::GetNthComponent( nc, it.Get() / spacing ) );
        ot.Set( outValue );
        ++it;
        ++ot;
        }
      }
    }

  // manually release memory in last filter in the mini-pipeline
  if ( ImageDimension > 1 )
    {
    int temp_dim = static_cast< int >( ImageDimension ) - 2;
    m_SmoothingFilters[temp_dim]->GetOutput()->ReleaseData();
    }
  else
    {
    m_DerivativeFilter->GetOutput()->ReleaseData();
    }

  // If the flag for using the input image direction is ON,
  // then we apply the direction correction to all the pixels
  // of the output gradient image.
  if ( this->m_UseImageDirection )
    {

    OutputImageType *gradientImage = outputImage;
    ImageRegionIterator< OutputImageType > itr( gradientImage,
                                                gradientImage->GetRequestedRegion() );

    while ( !itr.IsAtEnd() )
      {

      TransformOutputPixel( itr );
      ++itr;
      }

    }
}

template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::GenerateOutputInformation()
{
  // this methods is overloaded so that if the output image is a
  // VectorImage then the correct number of components are set.

  Superclass::GenerateOutputInformation();

  OutputImageType* output = this->GetOutput();
  const typename TInputImage::ConstPointer inputImage( this->GetInput() );

  const unsigned int nComponents = inputImage->GetNumberOfComponentsPerPixel() * ImageDimension;

  output->SetNumberOfComponentsPerPixel( nComponents );
}

template< typename TInputImage, typename TOutputImage >
void
GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  os << indent << "NormalizeAcrossScale: " << m_NormalizeAcrossScale << std::endl;
  os << indent << "UseImageDirection :   "
     << ( this->m_UseImageDirection ? "On" : "Off" ) << std::endl;
}

} // end namespace itk

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperMapProjectionParametersHandler.h"

// Needed for methods relative to projections
#include "otbMapProjections.h"
#include "otbImageToGenericRSOutputParameters.h"
#include "otbWrapperInputImageListParameter.h"

namespace otb
{
namespace Wrapper
{

void MapProjectionParametersHandler::AddMapProjectionParameters( Application::Pointer app, const std::string & key)
{
  app->AddParameter(ParameterType_Choice, key, "Output Cartographic Map Projection");
  app->SetParameterDescription(key,"Parameters of the output map projection to be used.");

  // utm
  std::ostringstream oss;
  oss << key<<".utm";
  app->AddChoice(oss.str(),   "Universal Trans-Mercator (UTM)");
  app->SetParameterDescription(oss.str(),"A system of transverse mercator projections dividing the surface of Earth between 80S and 84N latitude.");

  oss << ".zone";
  app->AddParameter(ParameterType_Int, oss.str(), "Zone number");
  app->SetParameterDescription(oss.str(),"The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere)");
  app->SetMinimumParameterIntValue(oss.str(), 1);
  app->SetDefaultParameterInt(oss.str(), 31);

  oss.str("");
  oss <<key<<".utm" <<".northhem";
  app->AddParameter(ParameterType_Empty, oss.str(),  "Northern Hemisphere");
  app->SetParameterDescription(oss.str(),"The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.");

  // lambert2
  oss.str("");
  oss << key<<".lambert2";
  app->AddChoice(oss.str(),  "Lambert II Etendu");
  app->SetParameterDescription(oss.str(),"This is a Lambert Conformal Conic projection mainly used in France.");

  // lambert93
  oss.str("");
  oss << key<<".lambert93";
  app->AddChoice(oss.str(),  "Lambert93");
  app->SetParameterDescription(oss.str(), "This is a Lambert 93 projection mainly used in France.");

  // Transmercator
  /*oss.str("");
  oss << key<<".transmercator";
  app->AddChoice(oss.str(),  "Transmercator");
  app->SetParameterDescription(oss.str(),
                               "This is a Transverse Mercator, a cylindrical projection widely used. The required values are set by default.");

  std::ostringstream subParamKey;
  subParamKey<<oss.str()<<".falseeasting";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "False easting");
  app->SetParameterDescription( subParamKey.str(), " Transmercator false easting value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 0.);

  subParamKey.str("");
  subParamKey<<oss.str()<<".falsenorthing";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "False northing");
  app->SetParameterDescription(subParamKey.str(), " Transmercator false northing value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 0.);

  subParamKey.str("");
  subParamKey<<oss.str()<<".scale";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "Scale factor");
  app->SetParameterDescription(subParamKey.str(), " Transmercator scale factor value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 1.);
  */
  // wgs84
  oss.str("");
  oss << key<<".wgs";
  app->AddChoice(oss.str(),  "WGS 84");
  app->SetParameterDescription(oss.str(),"This is a Geographical projection");

  // epsg code
  oss.str("");
  oss<<key<<".epsg";
  app->AddChoice(oss.str(),"EPSG Code");
  app->SetParameterDescription(oss.str(),
                               "This code is a generic way of identifying map projections, and allows specifying a large amount of them. See www.spatialreference.org to find which EPSG code is associated to your projection;");

  oss <<".code";
  app->AddParameter(ParameterType_Int, oss.str(), "EPSG Code");
  app->SetParameterDescription(oss.str(),"See www.spatialreference.org to find which EPSG code is associated to your projection");
  app->SetDefaultParameterInt(oss.str(), 4326);

  app->SetParameterString(key, "utm");
}

/**
    * Helper method : Compute the ProjectionRef knowing the map
    * projection picked up by the user
    *
    */
const std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(const Application::Pointer app,
                                                                   const std::string & key)
{
  std::ostringstream zoneKey;
  zoneKey << key<<".utm.zone";

  std::ostringstream hemKey;
  hemKey << key<<".utm.northhem";

  std::ostringstream  epsgKey;
  epsgKey << key <<".epsg.code";

  // Get the user choice
  switch ( app->GetParameterInt(key) )
    {
    case Map_Utm:
    {
    otb::UtmInverseProjection::Pointer utmProjection =
     otb::UtmInverseProjection::New();

    // Set the zone
    utmProjection->SetZone(app->GetParameterInt(zoneKey.str()));

    // Set the hem
    char hem = 'N';
    if (!app->IsParameterEnabled(hemKey.str()))
      hem = 'S';
    utmProjection->SetHemisphere(hem);

    // Get the projection ref
    return utmProjection->GetWkt();
    }
    break;
    case Map_Lambert2:
    {
    otb::Lambert2EtenduForwardProjection::Pointer lambert2Projection =
      otb::Lambert2EtenduForwardProjection::New();
    return lambert2Projection->GetWkt();
    }
    break;
    case Map_Lambert93:
    {
    otb::Lambert93InverseProjection::Pointer lambert93Projection =
      otb::Lambert93InverseProjection::New();
    return lambert93Projection->GetWkt();
    }
    break;
    /*case Map_Transmercator:
    {
    typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;
    TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();

    // Get the Transmercator parameters
    std::ostringstream falseeasting;
    std::ostringstream falsenorthing;
    std::ostringstream scale;

    falseeasting  <<key <<".transmercator.falseeasting";
    falsenorthing <<key <<".transmercator.falsenorthing";
    scale         <<key <<".transmercator.scale";

    transMercatorProjection->SetParameters(app->GetParameterFloat( falseeasting.str() ),
                                           app->GetParameterFloat( falsenorthing.str() ),
                                           app->GetParameterFloat( scale.str()) );
    return transMercatorProjection->GetWkt();
    }
    break; */
    case Map_WGS84:
    {
    return otb::GeoInformationConversion::ToWKT(4326);
    }
    break;
    case Map_Epsg:
    {
    return otb::GeoInformationConversion::ToWKT(app->GetParameterInt(epsgKey.str()));
    }
    break;
    }

  return "";
}

/**
    * Helper method : Compute the UTM parameters relative to an image Origin
    * Note: The key of the image must be set to be able to get the image.
    *       The key must be totally if the InputImageParameter belongs
    *       to a ParameterGroup, ie set io.in
    */
void MapProjectionParametersHandler::InitializeUTMParameters(Application::Pointer app,
                                                   const std::string & imageKey,
                                                   const std::string & mapKey )
{
  // Get the UTM params keys
  std::ostringstream zoneKey;
  zoneKey << mapKey << ".utm.zone";

  std::ostringstream hemKey;
  hemKey << mapKey << ".utm.northhem";

  // Compute the zone and the hemisphere if not UserValue defined
  if (!app->HasUserValue(zoneKey.str()) && app->HasValue(imageKey))
    {
    // Compute the Origin lat/long coordinate
    typedef otb::ImageToGenericRSOutputParameters<FloatVectorImageType> OutputParametersEstimatorType;
    OutputParametersEstimatorType::Pointer genericRSEstimator = OutputParametersEstimatorType::New();

    Parameter* param = app->GetParameterByKey(imageKey);
    if (dynamic_cast<InputImageParameter*> (param))
      {
      genericRSEstimator->SetInput(app->GetParameterImage(imageKey));
      }
    else
      if (dynamic_cast<InputImageListParameter*> (param))
        {
        genericRSEstimator->SetInput(app->GetParameterImageList(imageKey)->GetNthElement(0));
        }

    genericRSEstimator->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326));
    genericRSEstimator->Compute();

    int zone = otb::Utils::GetZoneFromGeoPoint(genericRSEstimator->GetOutputOrigin()[0],
                                               genericRSEstimator->GetOutputOrigin()[1]);
    // Update the UTM Gui fields
    app->SetParameterInt(zoneKey.str(), zone);
    if (genericRSEstimator->GetOutputOrigin()[1] > 0.)
      {
      app->EnableParameter(hemKey.str());
      }
    else
      {
      app->DisableParameter(hemKey.str());
      }

    app->AutomaticValueOn(zoneKey.str());
    app->AutomaticValueOn(hemKey.str());
    }
}

}// End namespace Wrapper
}// End namespace otb
<commit_msg>DOC: Enhance generic documentation for map projection parameters group<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperMapProjectionParametersHandler.h"

// Needed for methods relative to projections
#include "otbMapProjections.h"
#include "otbImageToGenericRSOutputParameters.h"
#include "otbWrapperInputImageListParameter.h"

namespace otb
{
namespace Wrapper
{

void MapProjectionParametersHandler::AddMapProjectionParameters( Application::Pointer app, const std::string & key)
{
  app->AddParameter(ParameterType_Choice, key, "Map Projection");
  app->SetParameterDescription(key,"Defines the map projection to be used.");

  // utm
  std::ostringstream oss;
  oss << key<<".utm";
  app->AddChoice(oss.str(),   "Universal Trans-Mercator (UTM)");
  app->SetParameterDescription(oss.str(),"A system of transverse mercator projections dividing the surface of Earth between 80S and 84N latitude.");

  oss << ".zone";
  app->AddParameter(ParameterType_Int, oss.str(), "Zone number");
  app->SetParameterDescription(oss.str(),"The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere)");
  app->SetMinimumParameterIntValue(oss.str(), 1);
  app->SetDefaultParameterInt(oss.str(), 31);

  oss.str("");
  oss <<key<<".utm" <<".northhem";
  app->AddParameter(ParameterType_Empty, oss.str(),  "Northern Hemisphere");
  app->SetParameterDescription(oss.str(),"The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.");

  // lambert2
  oss.str("");
  oss << key<<".lambert2";
  app->AddChoice(oss.str(),  "Lambert II Etendu");
  app->SetParameterDescription(oss.str(),"This is a Lambert Conformal Conic projection mainly used in France.");

  // lambert93
  oss.str("");
  oss << key<<".lambert93";
  app->AddChoice(oss.str(),  "Lambert93");
  app->SetParameterDescription(oss.str(), "This is a Lambert 93 projection mainly used in France.");

  // Transmercator
  /*oss.str("");
  oss << key<<".transmercator";
  app->AddChoice(oss.str(),  "Transmercator");
  app->SetParameterDescription(oss.str(),
                               "This is a Transverse Mercator, a cylindrical projection widely used. The required values are set by default.");

  std::ostringstream subParamKey;
  subParamKey<<oss.str()<<".falseeasting";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "False easting");
  app->SetParameterDescription( subParamKey.str(), " Transmercator false easting value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 0.);

  subParamKey.str("");
  subParamKey<<oss.str()<<".falsenorthing";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "False northing");
  app->SetParameterDescription(subParamKey.str(), " Transmercator false northing value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 0.);

  subParamKey.str("");
  subParamKey<<oss.str()<<".scale";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "Scale factor");
  app->SetParameterDescription(subParamKey.str(), " Transmercator scale factor value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 1.);
  */
  // wgs84
  oss.str("");
  oss << key<<".wgs";
  app->AddChoice(oss.str(),  "WGS 84");
  app->SetParameterDescription(oss.str(),"This is a Geographical projection");

  // epsg code
  oss.str("");
  oss<<key<<".epsg";
  app->AddChoice(oss.str(),"EPSG Code");
  app->SetParameterDescription(oss.str(),
                               "This code is a generic way of identifying map projections, and allows specifying a large amount of them. See www.spatialreference.org to find which EPSG code is associated to your projection;");

  oss <<".code";
  app->AddParameter(ParameterType_Int, oss.str(), "EPSG Code");
  app->SetParameterDescription(oss.str(),"See www.spatialreference.org to find which EPSG code is associated to your projection");
  app->SetDefaultParameterInt(oss.str(), 4326);

  app->SetParameterString(key, "utm");
}

/**
    * Helper method : Compute the ProjectionRef knowing the map
    * projection picked up by the user
    *
    */
const std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(const Application::Pointer app,
                                                                   const std::string & key)
{
  std::ostringstream zoneKey;
  zoneKey << key<<".utm.zone";

  std::ostringstream hemKey;
  hemKey << key<<".utm.northhem";

  std::ostringstream  epsgKey;
  epsgKey << key <<".epsg.code";

  // Get the user choice
  switch ( app->GetParameterInt(key) )
    {
    case Map_Utm:
    {
    otb::UtmInverseProjection::Pointer utmProjection =
     otb::UtmInverseProjection::New();

    // Set the zone
    utmProjection->SetZone(app->GetParameterInt(zoneKey.str()));

    // Set the hem
    char hem = 'N';
    if (!app->IsParameterEnabled(hemKey.str()))
      hem = 'S';
    utmProjection->SetHemisphere(hem);

    // Get the projection ref
    return utmProjection->GetWkt();
    }
    break;
    case Map_Lambert2:
    {
    otb::Lambert2EtenduForwardProjection::Pointer lambert2Projection =
      otb::Lambert2EtenduForwardProjection::New();
    return lambert2Projection->GetWkt();
    }
    break;
    case Map_Lambert93:
    {
    otb::Lambert93InverseProjection::Pointer lambert93Projection =
      otb::Lambert93InverseProjection::New();
    return lambert93Projection->GetWkt();
    }
    break;
    /*case Map_Transmercator:
    {
    typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;
    TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();

    // Get the Transmercator parameters
    std::ostringstream falseeasting;
    std::ostringstream falsenorthing;
    std::ostringstream scale;

    falseeasting  <<key <<".transmercator.falseeasting";
    falsenorthing <<key <<".transmercator.falsenorthing";
    scale         <<key <<".transmercator.scale";

    transMercatorProjection->SetParameters(app->GetParameterFloat( falseeasting.str() ),
                                           app->GetParameterFloat( falsenorthing.str() ),
                                           app->GetParameterFloat( scale.str()) );
    return transMercatorProjection->GetWkt();
    }
    break; */
    case Map_WGS84:
    {
    return otb::GeoInformationConversion::ToWKT(4326);
    }
    break;
    case Map_Epsg:
    {
    return otb::GeoInformationConversion::ToWKT(app->GetParameterInt(epsgKey.str()));
    }
    break;
    }

  return "";
}

/**
    * Helper method : Compute the UTM parameters relative to an image Origin
    * Note: The key of the image must be set to be able to get the image.
    *       The key must be totally if the InputImageParameter belongs
    *       to a ParameterGroup, ie set io.in
    */
void MapProjectionParametersHandler::InitializeUTMParameters(Application::Pointer app,
                                                   const std::string & imageKey,
                                                   const std::string & mapKey )
{
  // Get the UTM params keys
  std::ostringstream zoneKey;
  zoneKey << mapKey << ".utm.zone";

  std::ostringstream hemKey;
  hemKey << mapKey << ".utm.northhem";

  // Compute the zone and the hemisphere if not UserValue defined
  if (!app->HasUserValue(zoneKey.str()) && app->HasValue(imageKey))
    {
    // Compute the Origin lat/long coordinate
    typedef otb::ImageToGenericRSOutputParameters<FloatVectorImageType> OutputParametersEstimatorType;
    OutputParametersEstimatorType::Pointer genericRSEstimator = OutputParametersEstimatorType::New();

    Parameter* param = app->GetParameterByKey(imageKey);
    if (dynamic_cast<InputImageParameter*> (param))
      {
      genericRSEstimator->SetInput(app->GetParameterImage(imageKey));
      }
    else
      if (dynamic_cast<InputImageListParameter*> (param))
        {
        genericRSEstimator->SetInput(app->GetParameterImageList(imageKey)->GetNthElement(0));
        }

    genericRSEstimator->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326));
    genericRSEstimator->Compute();

    int zone = otb::Utils::GetZoneFromGeoPoint(genericRSEstimator->GetOutputOrigin()[0],
                                               genericRSEstimator->GetOutputOrigin()[1]);
    // Update the UTM Gui fields
    app->SetParameterInt(zoneKey.str(), zone);
    if (genericRSEstimator->GetOutputOrigin()[1] > 0.)
      {
      app->EnableParameter(hemKey.str());
      }
    else
      {
      app->DisableParameter(hemKey.str());
      }

    app->AutomaticValueOn(zoneKey.str());
    app->AutomaticValueOn(hemKey.str());
    }
}

}// End namespace Wrapper
}// End namespace otb
<|endoftext|>