<commit_before>// --------------------------------------------------------------------------------------
// File:          bspline_field.cxx
// Date:          Mar 5, 2014
// Author:        code@oscaresteban.es (Oscar Esteban)
// Version:       1.0 beta
// License:       GPLv3 - 29 June 2007
// Short Summary:
// --------------------------------------------------------------------------------------
//

#include "bspline_field.h"

#include <vnl/vnl_matrix.h>
#include <vnl/vnl_diag_matrix.h>
#include <sstream>

int main(int argc, char *argv[]) {
	std::string outPrefix = "";
	std::string maskfile;
	std::vector< std::string > fixedImageNames, movingSurfaceNames,coefficientImageNames;
	std::vector<size_t> grid_size;

	bpo::options_description all_desc("Usage");
	all_desc.add_options()
			("help,h", "show help message")
			("coeff-images,C", bpo::value < std::vector<std::string> > (&coefficientImageNames )->multitoken(), "coefficient image(s)" )
			("images,I", bpo::value < std::vector<std::string>	> (&fixedImageNames)->multitoken()->required(), "fixed image file")
			("surfaces,S", bpo::value < std::vector<std::string>	> (&movingSurfaceNames)->multitoken(),	"moving image file")
			("mask,M", bpo::value< std::string >(&maskfile), "mask file" )
			("output-prefix,o", bpo::value < std::string > (&outPrefix), "prefix for output files")
			("num-threads", bpo::value < unsigned int >()->default_value(NUM_THREADS), "use num-threads")
			("grid-size,g", bpo::value< std::vector<size_t> >(&grid_size)->multitoken(), "size of grid of bspline control points (default is 10x10x10)")
			("mask-inputs", bpo::bool_switch(), "use deformed mask to filter input files");

	bpo::variables_map vm;
	bpo::store(	bpo::parse_command_line( argc, argv, all_desc ), vm);
	bpo::notify(vm);

	if (vm.count("help") || vm.size() == 0 ) {
		std::cout << all_desc << std::endl;
		return 1;
	}

	ReaderPointer readref = ReaderType::New();
	readref->SetFileName( fixedImageNames[0] );
	readref->Update();
	ChannelPointer ref = readref->GetOutput();
	typename ChannelType::DirectionType ref_dir(ref->GetDirection());
	typename ChannelType::PointType ref_orig = ref->GetOrigin();

	typename ChannelType::DirectionType itk;
	itk.SetIdentity();
	itk(0,0)=-1.0;
	itk(1,1)=-1.0;

	typename ChannelType::DirectionType int_dir(itk * ref_dir);
	typename ChannelType::PointType int_orig( itk * ref_orig );
	ref->SetDirection( int_dir );
	ref->SetOrigin( int_orig );

	typename CoefficientsType::SizeType size;
	typename CoefficientsType::SpacingType spacing;

	size.Fill(10);
	CoefficientsImageArray coeffs;

	TPointer transform = Transform::New();

#ifndef NDEBUG
	transform->SetNumberOfThreads( 2 );
#endif

	if (vm.count("coeff-images")) {
		std::cout << "coefficient images mode not implemented" << std::endl;
		// set size
		return 0;
	} else {
		if( vm.count("grid-size") ){
			if( grid_size.size() == 1 ) {
				size.Fill( grid_size[0] );
			}
			else if ( grid_size.size() == DIMENSION ) {
				for( size_t i = 0; i < DIMENSION; i++) size[i] = grid_size[i];
			}
			else {
				std::cout << "error with grid size" << std::endl;
				return 1;
			}
		}

		transform->SetControlPointsSize( size );
		transform->SetPhysicalDomainInformation( ref );
		transform->SetOutputReference( ref );
		transform->UpdateField();
		coeffs = transform->GetCoefficientsImages();
		spacing = coeffs[0]->GetSpacing();
		size_t numPix = coeffs[0]->GetLargestPossibleRegion().GetNumberOfPixels();

		typename CoefficientsType::RegionType region;
		typename CoefficientsType::IndexType start;
		typename CoefficientsType::SizeType regionSize;

		for( size_t i = 0; i<DIMENSION; i++ ) {
			start[i] = static_cast<size_t>( floor( size[i] * 0.35 + 0.5f ) ) -1;
			regionSize[i] = size[i] - 2.0 * start[i];
		}
		region.SetIndex( start );
		region.SetSize( regionSize );

		for( size_t i = 0; i< DIMENSION; i++) {
			RandomIterator rndit( coeffs[i], region );
#ifdef NDEBUG
			rndit.ReinitializeSeed();
#endif
			rndit.SetNumberOfSamples( static_cast<size_t>( floor( numPix * 0.08 + 0.5f ) ) );

			for(rndit.GoToBegin(); !rndit.IsAtEnd(); ++rndit){
				float r = -1.0 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/2.0));
				rndit.Set( r );
			}

			SigmaArrayType sigma;
			sigma.Fill(12.0);

			SmoothingFilterPointer s = SmoothingFilterType::New();
			s->SetInput( coeffs[i] );
			s->SetSigmaArray( sigma );
			s->Update();
			coeffs[i] = s->GetOutput();

			ScalarType *buff = coeffs[i]->GetBufferPointer();
			std::vector< ScalarType > sample;

			for( size_t j = 0; j < numPix; j++ ) {
				sample.push_back( *(buff + j) );
			}

			std::sort( sample.begin(), sample.end() );

			SubtractPointer sub = SubtractFilter::New();
			sub->SetInput1( coeffs[i] );
			sub->SetConstant( sample[ static_cast<size_t>( floor( 0.5 * numPix + 0.5f ) ) ] );
			sub->Update();
			coeffs[i] = sub->GetOutput();

			MaxCalcPointer max = MaxCalc::New();
			max->SetImage( coeffs[i] );
			max->Compute();

			float immax = max->GetMaximum();
			if ( fabs( max->GetMinimum() ) > fabs(immax) ) {
				immax = fabs( max->GetMinimum() );
			}

			float scale = (spacing[i] * 0.35) / immax;

			MultiplyPointer m = MultiplyFilter::New();
			m->SetInput1( coeffs[i] );
			m->SetConstant( scale );
			m->Update();
			coeffs[i] = m->GetOutput();

			CoefficientsWriterPointer w = CoefficientsWriterType::New();
			std::stringstream ss;
			ss << outPrefix << "_coeffs_" << i << ".nii.gz";
			w->SetFileName( ss.str().c_str() );
			w->SetInput( coeffs[i] );
			w->Update();
		}
	}

	// Set coefficients
	transform->SetCoefficientsImages( coeffs );
	transform->UpdateField();

	typename ComponentsWriter::Pointer f = ComponentsWriter::New();
	std::stringstream ss;
	ss << outPrefix << "_field";
	f->SetFileName( ss.str().c_str() );
	f->SetInput( transform->GetField() );
	f->Update();

	transform->Interpolate();

	typename FieldType::Pointer field = transform->GetDisplacementField();
	typename FieldWriter::Pointer ff = FieldWriter::New();
	ff->SetInput( field );
	ff->SetFileName( (outPrefix + "_dispfield.nii.gz").c_str() );
	ff->Update();

	// Read and transform mask, if present
	MaskPointer mask;

	if (vm.count( "mask" ) ) {
		typename ReaderType::Pointer rmask = ReaderType::New();
		rmask->SetFileName( maskfile );
		rmask->Update();

		typename ChannelType::Pointer im = rmask->GetOutput();
		im->SetDirection( int_dir );
		im->SetOrigin( int_orig );

		typename Binarize::Pointer bin = Binarize::New();
		bin->SetInput( im );
		bin->SetLowerThreshold( 0.01 );
		bin->SetOutsideValue( 0 );
		bin->SetInsideValue( 1 );
		bin->Update();

		WarpMaskFilterPointer wrp = WarpMaskFilter::New();
		wrp->SetInterpolator( WarpMaskInterpolator::New() );
		wrp->SetOutputParametersFromImage( bin->GetOutput() );
		wrp->SetInput( bin->GetOutput() );
		wrp->SetDisplacementField( field );
		wrp->Update();
		mask = wrp->GetOutput();

		mask->SetDirection( ref_dir );
		mask->SetOrigin( ref_orig );

		typename MaskWriter::Pointer wm = MaskWriter::New();
		wm->SetInput( mask );
		wm->SetFileName( (outPrefix + "_mask_warped.nii.gz").c_str() );
		wm->Update();
	}

	// Read and transform images if present
	for( size_t i = 0; i<fixedImageNames.size(); i++) {
		std::stringstream ss;
		typename WriterType::Pointer w = WriterType::New();

		typename ReaderType::Pointer r = ReaderType::New();
		r->SetFileName( fixedImageNames[i] );
		r->Update();

		typename ChannelType::Pointer im = r->GetOutput();
		im->SetDirection( int_dir );
		im->SetOrigin( int_orig );

		WarpFilterPointer wrp = WarpFilter::New();
		wrp->SetInterpolator( WarpInterpolator::New() );
		wrp->SetOutputParametersFromImage( im );
		wrp->SetInput( im );
		wrp->SetDisplacementField( field );
		wrp->Update();

		ThresholdPointer th = ThresholdFilter::New();
		th->SetInput( wrp->GetOutput() );
		th->ThresholdBelow( 0.0 );
		th->SetOutsideValue( 0.0 );
		th->Update();

		typename ChannelType::Pointer im_wrp = th->GetOutput();
		im_wrp->SetDirection( ref_dir );
		im_wrp->SetOrigin( ref_orig );

		if (mask.IsNotNull() && vm.count("mask-inputs")) {
			typename MaskFilter::Pointer mm = MaskFilter::New();
			mm->SetMaskImage( mask );
			mm->SetInput( im_wrp );
			mm->Update();
			im_wrp = mm->GetOutput();
		}

		ss.str("");
		ss << outPrefix << "_warped_" << i << ".nii.gz";
		w->SetInput( im_wrp );
		w->SetFileName( ss.str().c_str() );
		w->Update();
	}

	// Warp surfaces --------------------------------------------------
	DisplacementFieldTransformPointer tf_inv = DisplacementFieldTransformType::New();
	tf_inv->SetDisplacementField( transform->GetInverseDisplacementField() );

	for( size_t i = 0; i<movingSurfaceNames.size(); i++){
		MeshReaderPointer r = MeshReaderType::New();
		r->SetFileName( movingSurfaceNames[i] );
		r->Update();

		MeshPointer mesh = r->GetOutput();

		PointsIterator p_it = mesh->GetPoints()->Begin();
		PointsIterator p_end = mesh->GetPoints()->End();

		MeshPointType p;
		while ( p_it!=p_end ) {
			p = p_it.Value();
			p_it.Value() = tf_inv->TransformPoint( p );
			++p_it;
		}

		MeshWriterPointer wmesh = MeshWriterType::New();
		ss.str("");
		ss << outPrefix << "_warped_" << i << ".vtk";
		wmesh->SetFileName( ss.str().c_str() );
		wmesh->SetInput( mesh );
		wmesh->Update();
	}
}
<commit_msg>A working workflow with transforms<commit_after>// --------------------------------------------------------------------------------------
// File:          bspline_field.cxx
// Date:          Mar 5, 2014
// Author:        code@oscaresteban.es (Oscar Esteban)
// Version:       1.0 beta
// License:       GPLv3 - 29 June 2007
// Short Summary:
// --------------------------------------------------------------------------------------
//

#include "bspline_field.h"

#include <vnl/vnl_matrix.h>
#include <vnl/vnl_diag_matrix.h>
#include <sstream>

int main(int argc, char *argv[]) {
	std::string outPrefix = "";
	std::string maskfile;
	std::vector< std::string > fixedImageNames, movingSurfaceNames,coefficientImageNames;
	std::vector<size_t> grid_size;

	bpo::options_description all_desc("Usage");
	all_desc.add_options()
			("help,h", "show help message")
			("coeff-images,C", bpo::value < std::vector<std::string> > (&coefficientImageNames )->multitoken(), "coefficient image(s)" )
			("images,I", bpo::value < std::vector<std::string>	> (&fixedImageNames)->multitoken()->required(), "fixed image file")
			("surfaces,S", bpo::value < std::vector<std::string>	> (&movingSurfaceNames)->multitoken(),	"moving image file")
			("mask,M", bpo::value< std::string >(&maskfile), "mask file" )
			("output-prefix,o", bpo::value < std::string > (&outPrefix), "prefix for output files")
			("num-threads", bpo::value < unsigned int >()->default_value(NUM_THREADS), "use num-threads")
			("grid-size,g", bpo::value< std::vector<size_t> >(&grid_size)->multitoken(), "size of grid of bspline control points (default is 10x10x10)")
			("mask-inputs", bpo::bool_switch(), "use deformed mask to filter input files");

	bpo::variables_map vm;

	try {
		bpo::store(	bpo::parse_command_line( argc, argv, all_desc ), vm);

		if (vm.count("help")) {
			std::cout << all_desc << std::endl;
			return 1;
		}

		bpo::notify(vm);
	} catch ( bpo::error& e ) {
		std::cerr << "Error: " << e.what() << std::endl << std::endl;
		std::cerr << all_desc << std::endl;
		return 1;
	}

	ReaderPointer readref = ReaderType::New();
	readref->SetFileName( fixedImageNames[0] );
	readref->Update();
	ChannelPointer ref = readref->GetOutput();
	typename ChannelType::DirectionType ref_dir(ref->GetDirection());
	typename ChannelType::PointType ref_orig = ref->GetOrigin();

	typename ChannelType::DirectionType itk;
	itk.SetIdentity();
	itk(0,0)=-1.0;
	itk(1,1)=-1.0;

	typename ChannelType::DirectionType int_dir(itk * ref_dir);
	typename ChannelType::PointType int_orig( itk * ref_orig );
	ref->SetDirection( int_dir );
	ref->SetOrigin( int_orig );

	typename CoefficientsType::SizeType size;
	typename CoefficientsType::SpacingType spacing;

	size.Fill(10);
	CoefficientsImageArray coeffs;

	TPointer transform = Transform::New();

#ifndef NDEBUG
	transform->SetNumberOfThreads( 2 );
#endif

	if (vm.count("coeff-images")) {
		std::cout << "coefficient images mode not implemented" << std::endl;
		// set size
		return 0;
	} else {
		if( vm.count("grid-size") ){
			if( grid_size.size() == 1 ) {
				size.Fill( grid_size[0] );
			}
			else if ( grid_size.size() == DIMENSION ) {
				for( size_t i = 0; i < DIMENSION; i++) size[i] = grid_size[i];
			}
			else {
				std::cout << "error with grid size" << std::endl;
				return 1;
			}
		}

		transform->SetControlPointsSize( size );
		transform->SetPhysicalDomainInformation( ref );
		transform->SetOutputReference( ref );
		transform->UpdateField();
		coeffs = transform->GetCoefficientsImages();
		spacing = coeffs[0]->GetSpacing();
		size_t numPix = coeffs[0]->GetLargestPossibleRegion().GetNumberOfPixels();

		typename CoefficientsType::RegionType region;
		typename CoefficientsType::IndexType start;
		typename CoefficientsType::SizeType regionSize;

		for( size_t i = 0; i<DIMENSION; i++ ) {
			start[i] = static_cast<size_t>( floor( size[i] * 0.35 + 0.5f ) ) -1;
			regionSize[i] = size[i] - 2.0 * start[i];
		}
		region.SetIndex( start );
		region.SetSize( regionSize );

		for( size_t i = 0; i< DIMENSION; i++) {
			RandomIterator rndit( coeffs[i], region );
#ifdef NDEBUG
			rndit.ReinitializeSeed();
#endif
			rndit.SetNumberOfSamples( static_cast<size_t>( floor( numPix * 0.08 + 0.5f ) ) );

			for(rndit.GoToBegin(); !rndit.IsAtEnd(); ++rndit){
				float r = -1.0 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/2.0));
				rndit.Set( r );
			}

			SigmaArrayType sigma;
			sigma.Fill(12.0);

			SmoothingFilterPointer s = SmoothingFilterType::New();
			s->SetInput( coeffs[i] );
			s->SetSigmaArray( sigma );
			s->Update();
			coeffs[i] = s->GetOutput();

			ScalarType *buff = coeffs[i]->GetBufferPointer();
			std::vector< ScalarType > sample;

			for( size_t j = 0; j < numPix; j++ ) {
				sample.push_back( *(buff + j) );
			}

			std::sort( sample.begin(), sample.end() );

			SubtractPointer sub = SubtractFilter::New();
			sub->SetInput1( coeffs[i] );
			sub->SetConstant( sample[ static_cast<size_t>( floor( 0.5 * numPix + 0.5f ) ) ] );
			sub->Update();
			coeffs[i] = sub->GetOutput();

			MaxCalcPointer max = MaxCalc::New();
			max->SetImage( coeffs[i] );
			max->Compute();

			float immax = max->GetMaximum();
			if ( fabs( max->GetMinimum() ) > fabs(immax) ) {
				immax = fabs( max->GetMinimum() );
			}

			float scale = (spacing[i] * 0.35) / immax;

			MultiplyPointer m = MultiplyFilter::New();
			m->SetInput1( coeffs[i] );
			m->SetConstant( scale );
			m->Update();
			coeffs[i] = m->GetOutput();

			CoefficientsWriterPointer w = CoefficientsWriterType::New();
			std::stringstream ss;
			ss << outPrefix << "_coeffs_" << i << ".nii.gz";
			w->SetFileName( ss.str().c_str() );
			w->SetInput( coeffs[i] );
			w->Update();
		}
	}

	// Set coefficients
	transform->SetCoefficientsImages( coeffs );
	transform->UpdateField();

	typename ComponentsWriter::Pointer f = ComponentsWriter::New();
	std::stringstream ss;
	ss << outPrefix << "_field";
	f->SetFileName( ss.str().c_str() );
	f->SetInput( transform->GetField() );
	f->Update();

	transform->Interpolate();

	typename FieldType::Pointer field = transform->GetDisplacementField();
	typename FieldWriter::Pointer ff = FieldWriter::New();
	ff->SetInput( field );
	ff->SetFileName( (outPrefix + "_dispfield.nii.gz").c_str() );
	ff->Update();

	// Read and transform mask, if present
	MaskPointer mask;

	if (vm.count( "mask" ) ) {
		typename ReaderType::Pointer rmask = ReaderType::New();
		rmask->SetFileName( maskfile );
		rmask->Update();

		typename ChannelType::Pointer im = rmask->GetOutput();
		im->SetDirection( int_dir );
		im->SetOrigin( int_orig );

		typename Binarize::Pointer bin = Binarize::New();
		bin->SetInput( im );
		bin->SetLowerThreshold( 0.01 );
		bin->SetOutsideValue( 0 );
		bin->SetInsideValue( 1 );
		bin->Update();

		WarpMaskFilterPointer wrp = WarpMaskFilter::New();
		wrp->SetInterpolator( WarpMaskInterpolator::New() );
		wrp->SetOutputParametersFromImage( bin->GetOutput() );
		wrp->SetInput( bin->GetOutput() );
		wrp->SetDisplacementField( field );
		wrp->Update();
		mask = wrp->GetOutput();

		mask->SetDirection( ref_dir );
		mask->SetOrigin( ref_orig );

		typename MaskWriter::Pointer wm = MaskWriter::New();
		wm->SetInput( mask );
		wm->SetFileName( (outPrefix + "_mask_warped.nii.gz").c_str() );
		wm->Update();
	}

	// Read and transform images if present
	for( size_t i = 0; i<fixedImageNames.size(); i++) {
		std::stringstream ss;
		typename WriterType::Pointer w = WriterType::New();

		typename ReaderType::Pointer r = ReaderType::New();
		r->SetFileName( fixedImageNames[i] );
		r->Update();

		typename ChannelType::Pointer im = r->GetOutput();
		im->SetDirection( int_dir );
		im->SetOrigin( int_orig );

		WarpFilterPointer wrp = WarpFilter::New();
		wrp->SetInterpolator( WarpInterpolator::New() );
		wrp->SetOutputParametersFromImage( im );
		wrp->SetInput( im );
		wrp->SetDisplacementField( field );
		wrp->Update();

		ThresholdPointer th = ThresholdFilter::New();
		th->SetInput( wrp->GetOutput() );
		th->ThresholdBelow( 0.0 );
		th->SetOutsideValue( 0.0 );
		th->Update();

		typename ChannelType::Pointer im_wrp = th->GetOutput();
		im_wrp->SetDirection( ref_dir );
		im_wrp->SetOrigin( ref_orig );

		if (mask.IsNotNull() && (vm.count("mask-inputs") && vm["mask-inputs"].as<bool>() ) ) {
			typename MaskFilter::Pointer mm = MaskFilter::New();
			mm->SetMaskImage( mask );
			mm->SetInput( im_wrp );
			mm->Update();
			im_wrp = mm->GetOutput();
		}

		ss.str("");
		ss << outPrefix << "_warped_" << i << ".nii.gz";
		w->SetInput( im_wrp );
		w->SetFileName( ss.str().c_str() );
		w->Update();
	}

	// Warp surfaces --------------------------------------------------
	DisplacementFieldTransformPointer tf_inv = DisplacementFieldTransformType::New();
	tf_inv->SetDisplacementField( transform->GetInverseDisplacementField() );

	for( size_t i = 0; i<movingSurfaceNames.size(); i++){
		MeshReaderPointer r = MeshReaderType::New();
		r->SetFileName( movingSurfaceNames[i] );
		r->Update();

		MeshPointer mesh = r->GetOutput();

		PointsIterator p_it = mesh->GetPoints()->Begin();
		PointsIterator p_end = mesh->GetPoints()->End();

		MeshPointType p;
		while ( p_it!=p_end ) {
			p = p_it.Value();
			p_it.Value() = tf_inv->TransformPoint( p );
			++p_it;
		}

		MeshWriterPointer wmesh = MeshWriterType::New();
		ss.str("");
		ss << outPrefix << "_warped_" << i << ".vtk";
		wmesh->SetFileName( ss.str().c_str() );
		wmesh->SetInput( mesh );
		wmesh->Update();
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: webdavprovider.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 16:17:04 $
 *
 *  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 _WEBDAV_UCP_PROVIDER_HXX
#define _WEBDAV_UCP_PROVIDER_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif

#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif

#ifndef _UCBHELPER_PROVIDERHELPER_HXX
#include <ucbhelper/providerhelper.hxx>
#endif

#ifndef _WEBDAV_UCP_PROPERTYMAP_HXX
#include "PropertyMap.hxx"
#endif

namespace webdav_ucp {

//=========================================================================

// UNO service name for the provider. This name will be used by the UCB to
// create instances of the provider.
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \
                "com.sun.star.ucb.WebDAVContentProvider"
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38

// URL scheme. This is the scheme the provider will be able to create
// contents for. The UCB will select the provider ( i.e. in order to create
// contents ) according to this scheme.
#define WEBDAV_URL_SCHEME \
                "vnd.sun.star.webdav"
#define WEBDAV_URL_SCHEME_LENGTH    19

#define HTTP_URL_SCHEME         "http"
#define HTTP_URL_SCHEME_LENGTH  4

#define HTTPS_URL_SCHEME        "https"
#define HTTPS_URL_SCHEME_LENGTH 5

#define FTP_URL_SCHEME "ftp"

#define HTTP_CONTENT_TYPE \
                "application/" HTTP_URL_SCHEME "-content"

#define WEBDAV_CONTENT_TYPE    HTTP_CONTENT_TYPE
#define WEBDAV_COLLECTION_TYPE \
                "application/" WEBDAV_URL_SCHEME "-collection"

//=========================================================================

class ContentProvider : public ::ucb::ContentProviderImplHelper
{
    rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;
    PropertyMap * m_pProps;

public:
    ContentProvider( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& rSMgr );
    virtual ~ContentProvider();

    // XInterface
    XINTERFACE_DECL()

    // XTypeProvider
    XTYPEPROVIDER_DECL()

    // XServiceInfo
    XSERVICEINFO_DECL()

    // XContentProvider
    virtual ::com::sun::star::uno::Reference<
                ::com::sun::star::ucb::XContent > SAL_CALL
    queryContent( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XContentIdentifier >& Identifier )
        throw( ::com::sun::star::ucb::IllegalIdentifierException,
               ::com::sun::star::uno::RuntimeException );

    //////////////////////////////////////////////////////////////////////
    // Additional interfaces
    //////////////////////////////////////////////////////////////////////

    //////////////////////////////////////////////////////////////////////
    // Non-interface methods.
    //////////////////////////////////////////////////////////////////////

    rtl::Reference< DAVSessionFactory > getDAVSessionFactory()
    { return m_xDAVSessionFactory; }

    bool getProperty( const ::rtl::OUString & rPropName,
                      ::com::sun::star::beans::Property & rProp,
                      bool bStrict = false );
};

}

#endif
<commit_msg>INTEGRATION: CWS bgdlremove (1.8.108); FILE MERGED 2007/05/18 11:37:19 kso 1.8.108.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: webdavprovider.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 18:22:16 $
 *
 *  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 _WEBDAV_UCP_PROVIDER_HXX
#define _WEBDAV_UCP_PROVIDER_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif

#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif

#ifndef _UCBHELPER_PROVIDERHELPER_HXX
#include <ucbhelper/providerhelper.hxx>
#endif

#ifndef _WEBDAV_UCP_PROPERTYMAP_HXX
#include "PropertyMap.hxx"
#endif

namespace webdav_ucp {

//=========================================================================

// UNO service name for the provider. This name will be used by the UCB to
// create instances of the provider.
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \
                "com.sun.star.ucb.WebDAVContentProvider"
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38

// URL scheme. This is the scheme the provider will be able to create
// contents for. The UCB will select the provider ( i.e. in order to create
// contents ) according to this scheme.
#define WEBDAV_URL_SCHEME \
                "vnd.sun.star.webdav"
#define WEBDAV_URL_SCHEME_LENGTH    19

#define HTTP_URL_SCHEME         "http"
#define HTTP_URL_SCHEME_LENGTH  4

#define HTTPS_URL_SCHEME        "https"
#define HTTPS_URL_SCHEME_LENGTH 5

#define FTP_URL_SCHEME "ftp"

#define HTTP_CONTENT_TYPE \
                "application/" HTTP_URL_SCHEME "-content"

#define WEBDAV_CONTENT_TYPE    HTTP_CONTENT_TYPE
#define WEBDAV_COLLECTION_TYPE \
                "application/" WEBDAV_URL_SCHEME "-collection"

//=========================================================================

class ContentProvider : public ::ucbhelper::ContentProviderImplHelper
{
    rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;
    PropertyMap * m_pProps;

public:
    ContentProvider( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& rSMgr );
    virtual ~ContentProvider();

    // XInterface
    XINTERFACE_DECL()

    // XTypeProvider
    XTYPEPROVIDER_DECL()

    // XServiceInfo
    XSERVICEINFO_DECL()

    // XContentProvider
    virtual ::com::sun::star::uno::Reference<
                ::com::sun::star::ucb::XContent > SAL_CALL
    queryContent( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XContentIdentifier >& Identifier )
        throw( ::com::sun::star::ucb::IllegalIdentifierException,
               ::com::sun::star::uno::RuntimeException );

    //////////////////////////////////////////////////////////////////////
    // Additional interfaces
    //////////////////////////////////////////////////////////////////////

    //////////////////////////////////////////////////////////////////////
    // Non-interface methods.
    //////////////////////////////////////////////////////////////////////

    rtl::Reference< DAVSessionFactory > getDAVSessionFactory()
    { return m_xDAVSessionFactory; }

    bool getProperty( const ::rtl::OUString & rPropName,
                      ::com::sun::star::beans::Property & rProp,
                      bool bStrict = false );
};

}

#endif
<|endoftext|>


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

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

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

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

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

#include "otbMapProjectionWrapper.h"

#include <cassert>

#include "otbMacro.h"
#include "otbUtils.h"

#include "projection/ossimMapProjection.h"
#include "projection/ossimMapProjectionFactory.h"
#include "projection/ossimMapProjection.h"
#include "base/ossimGpt.h"
#include "base/ossimDpt.h"
#include "projection/ossimProjection.h"
#include "base/ossimEllipsoid.h"
#include "base/ossimEllipsoidFactory.h"
#include "base/ossimString.h"
#include "gdal/ossimOgcWktTranslator.h"

#include "projection/ossimUtmProjection.h"
#include "projection/ossimLambertConformalConicProjection.h"
#include "projection/ossimTransMercatorProjection.h"

namespace otb
{

MapProjectionWrapper::MapProjectionWrapper():
  m_MapProjection(NULL), m_ProjectionRefWkt(""), m_ReinstanciateProjection(true)
{
}

MapProjectionWrapper::~MapProjectionWrapper()
{
  if (m_MapProjection != NULL)
    {
    delete m_MapProjection;
    }
}

MapProjectionWrapper::InternalMapProjectionPointer MapProjectionWrapper::GetMapProjection()
{
  itkDebugMacro("returning MapProjection address " << this->m_MapProjection);
  if ((m_ReinstanciateProjection) || (m_MapProjection == NULL))
    {
    this->InstanciateProjection();
    }

  return this->m_MapProjection;
}

MapProjectionWrapper::InternalMapProjectionConstPointer MapProjectionWrapper::GetMapProjection() const
{
  itkDebugMacro("returning MapProjection address " << this->m_MapProjection);
  if ((m_ReinstanciateProjection) || (m_MapProjection == NULL))
    {
    itkExceptionMacro(<< "m_MapProjection not up-to-date, call InstanciateProjection() first");
    }

  return this->m_MapProjection;
}

std::string MapProjectionWrapper::GetWkt() const
{
  ossimKeywordlist kwl;
  this->GetMapProjection();
  if (m_MapProjection == NULL)
    {
    return "";
    }
  m_MapProjection->saveState(kwl);
  ossimOgcWktTranslator wktTranslator;
  std::string           wkt;
  wkt = wktTranslator.fromOssimKwl(kwl);
  return wkt;
}

void MapProjectionWrapper::SetWkt(std::string projectionRefWkt)
{
  this->m_ProjectionRefWkt = projectionRefWkt;
  m_ReinstanciateProjection = true;
  this->InstanciateProjection(); //Should not be needed, but it is...
  this->Modified();
}

void MapProjectionWrapper::SetParameter(std::string key, std::string value)
{
  m_ParameterStore[key] = value;
  m_ReinstanciateProjection = true;
  this->InstanciateProjection(); //Should not be needed, but it is...
  this->Modified();
}

std::string MapProjectionWrapper::GetParameter(std::string key) const
{
  // Please refer to the note in the header filer
  // we do NOT want to read from m_ParameterStore here!

  std::string projectionName = this->GetMapProjection()->getClassName();

  // Start by matching generic parameters
  const ossimMapProjection* projection = dynamic_cast<const ossimMapProjection*>(this->GetMapProjection());
  if (key.compare("Origin") == 0)
    {
    return Utils::ConvertToString(projection->origin());
    }
  if (key.compare("FalseNorthing") == 0)
    {
    return Utils::ConvertToString(projection->getFalseNorthing());
    }
  if (key.compare("FalseEasting") == 0)
    {
    return Utils::ConvertToString(projection->getFalseEasting());
    }
  if (key.compare("StandardParallel1") == 0)
    {
    return Utils::ConvertToString(projection->getStandardParallel1());
    }
  if (key.compare("StandardParallel2") == 0)
    {
    return Utils::ConvertToString(projection->getStandardParallel2());
    }
  if (key.compare("A") == 0)
    {
    return Utils::ConvertToString(projection->getA());
    }
  if (key.compare("B") == 0)
    {
    return Utils::ConvertToString(projection->getB());
    }
  if (key.compare("F") == 0)
    {
    return Utils::ConvertToString(projection->getF());
    }
  if (key.compare("MetersPerPixel") == 0)
    {
    return Utils::ConvertToString(projection->getMetersPerPixel());
    }
  if (key.compare("DecimalDegreesPerPixel") == 0)
    {
    return Utils::ConvertToString(projection->getDecimalDegreesPerPixel());
    }

  // Apply parameters to transmercator
  if (projectionName.compare("ossimTransMercatorProjection") == 0)
    {
    const ossimTransMercatorProjection* projection = dynamic_cast<const ossimTransMercatorProjection*>(this->GetMapProjection());
    if (key.compare("ScaleFactor") == 0)
      {
      return Utils::ConvertToString(projection->getScaleFactor());
      }
    }

  // Apply parameters to Utm
  if (projectionName.compare("ossimUtmProjection") == 0)
    {
    const ossimUtmProjection* projection = dynamic_cast<const ossimUtmProjection*>(this->GetMapProjection());
    if (key.compare("Zone") == 0)
      {
      return Utils::ConvertToString(projection->getZone());
      }
    if (key.compare("Hemisphere") == 0)
      {
      return Utils::ConvertToString(projection->getHemisphere());
      }
    }

  return "";
}

bool MapProjectionWrapper::InstanciateProjection()
{
  if ((this->m_ReinstanciateProjection) || (m_MapProjection == NULL))
    {
    ossimKeywordlist      kwl;
    ossimOgcWktTranslator wktTranslator;

    bool projectionInformationAvailable = wktTranslator.toOssimKwl(m_ProjectionRefWkt, kwl);

    if (projectionInformationAvailable)
      {
      //we don't want to have a ossimEquDistCylProjection here:
      //see discussion in May 2009 on ossim list;
      //a better solution might be available...
      std::string projectionString(kwl.find("type"));
      if (projectionString.find("ossimEquDistCylProjection") != string::npos)
        {
        otbMsgDevMacro(<< "WARNING: Not instanciating a ossimEquDistCylProjection: " << projectionString);
        otbMsgDevMacro(<< "Wkt was: " << kwl);
        otbMsgDevMacro(<< "From RefWkt: " << m_ProjectionRefWkt);
        return false;
        }

      m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(kwl);

      }
    else
      {
      otbMsgDevMacro(<< "WARNING: Impossible to create the projection from Wkt: " << m_ProjectionRefWkt);
      otbMsgDevMacro(<< "Trying with string as a string (ossimUtmProjection or Utm would qualify");
      // Trying directly with the m_ProjectionRefWkt (is
      // ossimUtmProjection for example)
      ossimString name(m_ProjectionRefWkt);
      m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(name);
      if (m_MapProjection == NULL)
        {
        // Trying directly extending the m_ProjectionRefWkt (convert the
        // Utm to ossimUtmProjection for example)
        ossimString extendedName("ossim");
        extendedName += m_ProjectionRefWkt;
        extendedName += "Projection";
        m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(extendedName);
        }

      if (m_MapProjection == NULL) return false;

      }

    this->m_ReinstanciateProjection = false;
    this->ApplyParametersToProjection();
    return true;
    }
  return false;
}

void MapProjectionWrapper::InverseTransform(double x, double y, double z,
                                       double& lon, double& lat, double& h)
{
  if (m_MapProjection == NULL)
    {
    otbMsgDevMacro(<< "WARNING: Using identity");
    lon = x;
    lat = y;
    h = z;
    return;
    }

  ossimDpt ossimDPoint(x, y);

  //map projection
  ossimGpt ossimGPoint;
  ossimGPoint = this->GetMapProjection()->inverse(ossimDPoint);
  ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84());

  lon = ossimGPoint.lon;
  lat = ossimGPoint.lat;
  h = z;
}

void MapProjectionWrapper::ForwardTransform(double lon, double lat, double h,
                                       double& x, double& y, double& z)
{
  if (m_MapProjection == NULL)
    {
    otbMsgDevMacro(<< "WARNING: Using identity");
    x = lon;
    y = lat;
    z = h;
    return;
    }

  ossimGpt ossimGPoint(lat, lon, h);

  //map projection
  ossimDpt ossimDPoint;
  ossimDPoint = this->GetMapProjection()->forward(ossimGPoint);

  x = ossimDPoint.x;
  y = ossimDPoint.y;
  z = h;
}

void MapProjectionWrapper::ApplyParametersToProjection()
{
  // Start by identifying the projection, that will be necessary for
  // the casting.
  std::string projectionName = this->GetMapProjection()->getClassName();

  StoreType::const_iterator it;

  // Apply standard map projection parameters
  ossimMapProjection* projection = dynamic_cast<ossimMapProjection*>(this->GetMapProjection());
  // Set up origin

  const ossimDatum* datum = ossimDatumFactory::instance()->wgs84(); //default value
  it = m_ParameterStore.find("Datum");
  if (it != m_ParameterStore.end())
    {
    datum = ossimDatumFactory::instance()->create((*it).second);
    projection->setDatum(datum);
    }

  StoreType::const_iterator itX = m_ParameterStore.find("OriginX");
  StoreType::const_iterator itY = m_ParameterStore.find("OriginY");
  StoreType::const_iterator itZ = m_ParameterStore.find("OriginZ");

  if (itX != m_ParameterStore.end() && itY != m_ParameterStore.end())
    {
    double originX = atof((*itX).second.c_str());
    double originY = atof((*itY).second.c_str());
    double originZ = 0;
    if (itZ != m_ParameterStore.end())
      {
      originZ = atof((*itZ).second.c_str());
      }
    ossimGpt origin(originY, originX, originZ, datum);
    projection->setOrigin(origin);
    }

  // Apply parameters to LambertConformalConic
  if (projectionName.compare("ossimLambertConformalConicProjection") == 0)
    {
    ossimLambertConformalConicProjection* projection = dynamic_cast<ossimLambertConformalConicProjection*>(this->GetMapProjection());

    it = m_ParameterStore.find("FalseNorthing");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseNorthing(value);
      }
    it = m_ParameterStore.find("FalseEasting");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseEasting(value);
      }
    it = m_ParameterStore.find("StandardParallel1");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setStandardParallel1(value);
      }
    it = m_ParameterStore.find("StandardParallel2");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setStandardParallel2(value);
      }
    }

  // Apply parameters to trasnmercator
  if (projectionName.compare("ossimTransMercatorProjection") == 0)
    {
    ossimTransMercatorProjection* projection = dynamic_cast<ossimTransMercatorProjection*>(this->GetMapProjection());
    it = m_ParameterStore.find("ScaleFactor");
    if (it != m_ParameterStore.end())
      {
      double scale = atof((*it).second.c_str());
      projection->setScaleFactor(scale);
      }
    }

  // Apply parameters to Utm
  if (projectionName.compare("ossimUtmProjection") == 0)
    {
    ossimUtmProjection* projection = dynamic_cast<ossimUtmProjection*>(this->GetMapProjection());
    it = m_ParameterStore.find("Zone");
    if (it != m_ParameterStore.end())
      {
      int zone = atoi((*it).second.c_str());
      projection->setZone(zone);
      }
    it = m_ParameterStore.find("Hemisphere");
    if (it != m_ParameterStore.end())
      {
      projection->setHemisphere((*it).second[0]);
      }
    }
}

void MapProjectionWrapper::PrintMap() const
{
  std::cout << m_MapProjection->print(std::cout);
  std::cout << "Parameter store:\n";
  for (StoreType::const_iterator it = m_ParameterStore.begin();
       it != m_ParameterStore.end();
       ++it)
    {
    std::cout << "  " << (*it).first << ": " << (*it).second << "\n";
    }
}

namespace Utils
{

int GetZoneFromGeoPoint(double lon, double lat)
{
  //use ossim to handle the special case of UTM
  ossimGpt point(lat, lon);
  ossimUtmProjection projection;
  int zone = projection.computeZone(point);
  return zone;
}

}

} // namespace otb
<commit_msg>BUG: fix parameter setting<commit_after>/*=========================================================================

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

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

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

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

#include "otbMapProjectionWrapper.h"

#include <cassert>

#include "otbMacro.h"
#include "otbUtils.h"

#include "projection/ossimMapProjection.h"
#include "projection/ossimMapProjectionFactory.h"
#include "projection/ossimMapProjection.h"
#include "base/ossimGpt.h"
#include "base/ossimDpt.h"
#include "projection/ossimProjection.h"
#include "base/ossimEllipsoid.h"
#include "base/ossimEllipsoidFactory.h"
#include "base/ossimString.h"
#include "gdal/ossimOgcWktTranslator.h"

#include "projection/ossimUtmProjection.h"
#include "projection/ossimLambertConformalConicProjection.h"
#include "projection/ossimTransMercatorProjection.h"
#include "projection/ossimEckert4Projection.h"
#include "projection/ossimMollweidProjection.h"
#include "projection/ossimSinusoidalProjection.h"

namespace otb
{

MapProjectionWrapper::MapProjectionWrapper():
  m_MapProjection(NULL), m_ProjectionRefWkt(""), m_ReinstanciateProjection(true)
{
}

MapProjectionWrapper::~MapProjectionWrapper()
{
  if (m_MapProjection != NULL)
    {
    delete m_MapProjection;
    }
}

MapProjectionWrapper::InternalMapProjectionPointer MapProjectionWrapper::GetMapProjection()
{
  itkDebugMacro("returning MapProjection address " << this->m_MapProjection);
  if ((m_ReinstanciateProjection) || (m_MapProjection == NULL))
    {
    this->InstanciateProjection();
    }

  return this->m_MapProjection;
}

MapProjectionWrapper::InternalMapProjectionConstPointer MapProjectionWrapper::GetMapProjection() const
{
  itkDebugMacro("returning MapProjection address " << this->m_MapProjection);
  if ((m_ReinstanciateProjection) || (m_MapProjection == NULL))
    {
    itkExceptionMacro(<< "m_MapProjection not up-to-date, call InstanciateProjection() first");
    }

  return this->m_MapProjection;
}

std::string MapProjectionWrapper::GetWkt() const
{
  ossimKeywordlist kwl;
  this->GetMapProjection();
  if (m_MapProjection == NULL)
    {
    return "";
    }
  m_MapProjection->saveState(kwl);
  ossimOgcWktTranslator wktTranslator;
  std::string           wkt;
  wkt = wktTranslator.fromOssimKwl(kwl);
  return wkt;
}

void MapProjectionWrapper::SetWkt(std::string projectionRefWkt)
{
  this->m_ProjectionRefWkt = projectionRefWkt;
  m_ReinstanciateProjection = true;
  this->InstanciateProjection(); //Should not be needed, but it is...
  this->Modified();
}

void MapProjectionWrapper::SetParameter(std::string key, std::string value)
{
  m_ParameterStore[key] = value;
  m_ReinstanciateProjection = true;
  this->InstanciateProjection(); //Should not be needed, but it is...
  this->Modified();
}

std::string MapProjectionWrapper::GetParameter(std::string key) const
{
  // Please refer to the note in the header filer
  // we do NOT want to read from m_ParameterStore here!

  std::string projectionName = this->GetMapProjection()->getClassName();

  // Start by matching generic parameters
  const ossimMapProjection* projection = dynamic_cast<const ossimMapProjection*>(this->GetMapProjection());
  if (key.compare("Origin") == 0)
    {
    return Utils::ConvertToString(projection->origin());
    }
  if (key.compare("FalseNorthing") == 0)
    {
    return Utils::ConvertToString(projection->getFalseNorthing());
    }
  if (key.compare("FalseEasting") == 0)
    {
    return Utils::ConvertToString(projection->getFalseEasting());
    }
  if (key.compare("StandardParallel1") == 0)
    {
    return Utils::ConvertToString(projection->getStandardParallel1());
    }
  if (key.compare("StandardParallel2") == 0)
    {
    return Utils::ConvertToString(projection->getStandardParallel2());
    }
  if (key.compare("A") == 0)
    {
    return Utils::ConvertToString(projection->getA());
    }
  if (key.compare("B") == 0)
    {
    return Utils::ConvertToString(projection->getB());
    }
  if (key.compare("F") == 0)
    {
    return Utils::ConvertToString(projection->getF());
    }
  if (key.compare("MetersPerPixel") == 0)
    {
    return Utils::ConvertToString(projection->getMetersPerPixel());
    }
  if (key.compare("DecimalDegreesPerPixel") == 0)
    {
    return Utils::ConvertToString(projection->getDecimalDegreesPerPixel());
    }

  // Apply parameters to transmercator
  if (projectionName.compare("ossimTransMercatorProjection") == 0)
    {
    const ossimTransMercatorProjection* projection = dynamic_cast<const ossimTransMercatorProjection*>(this->GetMapProjection());
    if (key.compare("ScaleFactor") == 0)
      {
      return Utils::ConvertToString(projection->getScaleFactor());
      }
    }

  // Apply parameters to Utm
  if (projectionName.compare("ossimUtmProjection") == 0)
    {
    const ossimUtmProjection* projection = dynamic_cast<const ossimUtmProjection*>(this->GetMapProjection());
    if (key.compare("Zone") == 0)
      {
      return Utils::ConvertToString(projection->getZone());
      }
    if (key.compare("Hemisphere") == 0)
      {
      return Utils::ConvertToString(projection->getHemisphere());
      }
    }

  return "";
}

bool MapProjectionWrapper::InstanciateProjection()
{
  if ((this->m_ReinstanciateProjection) || (m_MapProjection == NULL))
    {
    ossimKeywordlist      kwl;
    ossimOgcWktTranslator wktTranslator;

    bool projectionInformationAvailable = wktTranslator.toOssimKwl(m_ProjectionRefWkt, kwl);

    if (projectionInformationAvailable)
      {
      //we don't want to have a ossimEquDistCylProjection here:
      //see discussion in May 2009 on ossim list;
      //a better solution might be available...
      std::string projectionString(kwl.find("type"));
      if (projectionString.find("ossimEquDistCylProjection") != string::npos)
        {
        otbMsgDevMacro(<< "WARNING: Not instanciating a ossimEquDistCylProjection: " << projectionString);
        otbMsgDevMacro(<< "Wkt was: " << kwl);
        otbMsgDevMacro(<< "From RefWkt: " << m_ProjectionRefWkt);
        return false;
        }

      m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(kwl);

      }
    else
      {
      otbMsgDevMacro(<< "WARNING: Impossible to create the projection from Wkt: " << m_ProjectionRefWkt);
      otbMsgDevMacro(<< "Trying with string as a string (ossimUtmProjection or Utm would qualify");
      // Trying directly with the m_ProjectionRefWkt (is
      // ossimUtmProjection for example)
      ossimString name(m_ProjectionRefWkt);
      m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(name);
      if (m_MapProjection == NULL)
        {
        // Trying directly extending the m_ProjectionRefWkt (convert the
        // Utm to ossimUtmProjection for example)
        ossimString extendedName("ossim");
        extendedName += m_ProjectionRefWkt;
        extendedName += "Projection";
        m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(extendedName);
        }

      if (m_MapProjection == NULL) return false;

      }

    this->m_ReinstanciateProjection = false;
    this->ApplyParametersToProjection();
    return true;
    }
  return false;
}

void MapProjectionWrapper::InverseTransform(double x, double y, double z,
                                       double& lon, double& lat, double& h)
{
  if (m_MapProjection == NULL)
    {
    otbMsgDevMacro(<< "WARNING: Using identity");
    lon = x;
    lat = y;
    h = z;
    return;
    }

  ossimDpt ossimDPoint(x, y);

  //map projection
  ossimGpt ossimGPoint;
  ossimGPoint = this->GetMapProjection()->inverse(ossimDPoint);
  ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84());

  lon = ossimGPoint.lon;
  lat = ossimGPoint.lat;
  h = z;
}

void MapProjectionWrapper::ForwardTransform(double lon, double lat, double h,
                                       double& x, double& y, double& z)
{
  if (m_MapProjection == NULL)
    {
    otbMsgDevMacro(<< "WARNING: Using identity");
    x = lon;
    y = lat;
    z = h;
    return;
    }

  ossimGpt ossimGPoint(lat, lon, h);

  //map projection
  ossimDpt ossimDPoint;
  ossimDPoint = this->GetMapProjection()->forward(ossimGPoint);

  x = ossimDPoint.x;
  y = ossimDPoint.y;
  z = h;
}

void MapProjectionWrapper::ApplyParametersToProjection()
{
  // Start by identifying the projection, that will be necessary for
  // the casting.
  std::string projectionName = this->GetMapProjection()->getClassName();

  StoreType::const_iterator it;

  // Apply standard map projection parameters
  ossimMapProjection* projection = dynamic_cast<ossimMapProjection*>(this->GetMapProjection());
  // Set up origin

  const ossimDatum* datum = ossimDatumFactory::instance()->wgs84(); //default value
  it = m_ParameterStore.find("Datum");
  if (it != m_ParameterStore.end())
    {
    datum = ossimDatumFactory::instance()->create((*it).second);
    projection->setDatum(datum);
    }

  StoreType::const_iterator itX = m_ParameterStore.find("OriginX");
  StoreType::const_iterator itY = m_ParameterStore.find("OriginY");
  StoreType::const_iterator itZ = m_ParameterStore.find("OriginZ");

  if (itX != m_ParameterStore.end() && itY != m_ParameterStore.end())
    {
    double originX = atof((*itX).second.c_str());
    double originY = atof((*itY).second.c_str());
    double originZ = 0;
    if (itZ != m_ParameterStore.end())
      {
      originZ = atof((*itZ).second.c_str());
      }
    ossimGpt origin(originY, originX, originZ, datum);
    projection->setOrigin(origin);
    }

  // Apply parameters to LambertConformalConic
  if (projectionName.compare("ossimLambertConformalConicProjection") == 0)
    {
    ossimLambertConformalConicProjection* projection = dynamic_cast<ossimLambertConformalConicProjection*>(this->GetMapProjection());

    it = m_ParameterStore.find("FalseNorthing");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseNorthing(value);
      }
    it = m_ParameterStore.find("FalseEasting");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseEasting(value);
      }
    it = m_ParameterStore.find("StandardParallel1");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setStandardParallel1(value);
      }
    it = m_ParameterStore.find("StandardParallel2");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setStandardParallel2(value);
      }
    }

  // Apply parameters to Eckert4
  if (projectionName.compare("ossimEckert4Projection") == 0)
    {
    ossimEckert4Projection* projection = dynamic_cast<ossimEckert4Projection*>(this->GetMapProjection());

    it = m_ParameterStore.find("FalseNorthing");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseNorthing(value);
      }
    it = m_ParameterStore.find("FalseEasting");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseEasting(value);
      }
    }

  // Apply parameters to Mollweid
  if (projectionName.compare("ossimMollweidProjection") == 0)
    {
    ossimMollweidProjection* projection = dynamic_cast<ossimMollweidProjection*>(this->GetMapProjection());

    it = m_ParameterStore.find("FalseNorthing");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseNorthing(value);
      }
    it = m_ParameterStore.find("FalseEasting");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseEasting(value);
      }
    }

  // Apply parameters to Sinusoidal
  if (projectionName.compare("ossimSinusoidalProjection") == 0)
    {
    ossimSinusoidalProjection* projection = dynamic_cast<ossimSinusoidalProjection*>(this->GetMapProjection());

    it = m_ParameterStore.find("FalseNorthing");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseNorthing(value);
      }
    it = m_ParameterStore.find("FalseEasting");
    if (it != m_ParameterStore.end())
      {
      double value = atof((*it).second.c_str());
      projection->setFalseEasting(value);
      }
    }

  // Apply parameters to trasnmercator
  if (projectionName.compare("ossimTransMercatorProjection") == 0)
    {
    ossimTransMercatorProjection* projection = dynamic_cast<ossimTransMercatorProjection*>(this->GetMapProjection());
    it = m_ParameterStore.find("ScaleFactor");
    if (it != m_ParameterStore.end())
      {
      double scale = atof((*it).second.c_str());
      projection->setScaleFactor(scale);
      }
    }

  // Apply parameters to Utm
  if (projectionName.compare("ossimUtmProjection") == 0)
    {
    ossimUtmProjection* projection = dynamic_cast<ossimUtmProjection*>(this->GetMapProjection());
    it = m_ParameterStore.find("Zone");
    if (it != m_ParameterStore.end())
      {
      int zone = atoi((*it).second.c_str());
      projection->setZone(zone);
      }
    it = m_ParameterStore.find("Hemisphere");
    if (it != m_ParameterStore.end())
      {
      projection->setHemisphere((*it).second[0]);
      }
    }
}

void MapProjectionWrapper::PrintMap() const
{
  std::cout << m_MapProjection->print(std::cout);
  std::cout << "Parameter store:\n";
  for (StoreType::const_iterator it = m_ParameterStore.begin();
       it != m_ParameterStore.end();
       ++it)
    {
    std::cout << "  " << (*it).first << ": " << (*it).second << "\n";
    }
}

namespace Utils
{

int GetZoneFromGeoPoint(double lon, double lat)
{
  //use ossim to handle the special case of UTM
  ossimGpt point(lat, lon);
  ossimUtmProjection projection;
  int zone = projection.computeZone(point);
  return zone;
}

}

} // namespace otb
<|endoftext|>


<commit_before>#include "MessageHandler.h"
#include "IqrfCdcChannel.h"
#include "IqrfSpiChannel.h"
#include "UdpChannel.h"
#include "UdpMessage.h"
#include "helpers.h"
#include "MessageQueue.h"
#include "IqrfLogging.h"
#include "PlatformDep.h"
#include <climits>

enum IqrfWriteResults {
  wr_OK = 0x50,
  wr_Error_Len = 0x60, //(number of data = 0 or more than TR buffer COM length)
  wr_Error_SPI = 0x61, //(SPI bus busy)
  wr_Error_IQRF = 0x62 //(IQRF - CRCM Error)
};

int MessageHandler::handleMessageFromUdp(const ustring& udpMessage)
{
  TRC_DBG("Received from UDP: " << std::endl << FORM_HEX(udpMessage.data(), udpMessage.size()));

  size_t msgSize = udpMessage.size();
  std::basic_string<unsigned char> message;

  try {
    decodeMessageUdp(udpMessage, message);
  }
  catch (UdpChannelException& e) {
    TRC_DBG("Wrong message: " << e.what());
    return -1;
  }

  switch (udpMessage[cmd])
  {
  case IQRF_UDP_GET_GW_INFO:          // --- Returns GW identification ---
  {
    std::basic_string<unsigned char> udpResponse(udpMessage);
    udpResponse[cmd] = (unsigned char)IQRF_UDP_GET_GW_INFO | 0x80;
    encodeMessageUdp(getGwIdent(), udpResponse);
    m_toUdpMessageQueue->pushToQueue(udpResponse);
  }
  return 0;

  case IQRF_UDP_WRITE_IQRF:       // --- Writes data to the TR module ---
  {
    m_toIqrfMessageQueue->pushToQueue(message);

    //send response
    std::basic_string<unsigned char> udpResponse(udpMessage.substr(0, IQRF_UDP_HEADER_SIZE));
    std::basic_string<unsigned char> message;
    udpResponse[cmd] = (unsigned char)IQRF_UDP_WRITE_IQRF | 0x80;
    encodeMessageUdp(message, udpResponse);
    //TODO it is required to send back via subcmd write result - implement sync write with appropriate ret code
    udpResponse[subcmd] = (unsigned char)IQRF_UDP_ACK;
    m_toUdpMessageQueue->pushToQueue(udpResponse);
  }
  return 0;

  default:
    break;
  }
  return -1;
}

int MessageHandler::handleMessageFromIqrf(const ustring& iqrfMessage)
{
  TRC_DBG("Received from to IQRF: " << std::endl << FORM_HEX(iqrfMessage.data(), iqrfMessage.size()));

  std::basic_string<unsigned char> udpMessage;
  std::basic_string<unsigned char> message(iqrfMessage);
  encodeMessageUdp(message, udpMessage);
  udpMessage[cmd] = (unsigned char)IQRF_UDP_IQRF_SPI_DATA;
  m_toUdpMessageQueue->pushToQueue(udpMessage);

  //std::basic_string<unsigned char> udpMessage;
  //encodeMessageUdp(iqrfMessage, udpMessage);
  //m_toUdpMessageQueue->pushToQueue(udpMessage);
  return 0;
}

void MessageHandler::encodeMessageUdp(const ustring& message, ustring& udpMessage)
{
  unsigned short dlen = (unsigned short)message.size();
  udpMessage.resize(IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE, '\0');
  udpMessage[gwAddr] = IQRF_UDP_GW_ADR;
  udpMessage[dlen_H] = (unsigned char)((dlen >> 8) & 0xFF);
  udpMessage[dlen_L] = (unsigned char)(dlen & 0xFF);

  udpMessage.insert(IQRF_UDP_HEADER_SIZE, message);

  uint16_t crc = GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE);
  udpMessage[dlen + IQRF_UDP_HEADER_SIZE] = (unsigned char)((crc >> 8) & 0xFF);
  udpMessage[dlen + IQRF_UDP_HEADER_SIZE + 1] = (unsigned char)(crc & 0xFF);
}

void MessageHandler::decodeMessageUdp(const ustring& udpMessage, ustring& message)
{
  unsigned short dlen = 0;

  // Min. packet length check
  if (udpMessage.size() < IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE)
    THROW_EX(UdpChannelException, "Message is too short: " << FORM_HEX(udpMessage.data(), udpMessage.size()));

  // GW_ADR check
  if (udpMessage[gwAddr] != IQRF_UDP_GW_ADR)
    THROW_EX(UdpChannelException, "Message is has wrong GW_ADDR: " << PAR_HEX(udpMessage[gwAddr]));

  //iqrf data length
  dlen = (udpMessage[dlen_H] << 8) + udpMessage[dlen_L];

  // Max. packet length check
  if ((dlen + IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE) > IQRF_UDP_BUFFER_SIZE)
    THROW_EX(UdpChannelException, "Message is too long: " << PAR(dlen));

  // CRC check
  unsigned short crc = (udpMessage[IQRF_UDP_HEADER_SIZE + dlen] << 8) + udpMessage[IQRF_UDP_HEADER_SIZE + dlen + 1];
  if (crc != GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE))
    THROW_EX(UdpChannelException, "Message has wrong CRC");

  message = udpMessage.substr(IQRF_UDP_HEADER_SIZE, dlen);
}

MessageHandler::MessageHandler(const std::string& iqrf_port_name, const std::string& remote_ip_port, const std::string& local_ip_port)
  :m_iqrfChannel(nullptr)
  , m_udpChannel(nullptr)
  , m_toUdpMessageQueue(nullptr)
  , m_toIqrfMessageQueue(nullptr)
  , m_iqrfPortName(iqrf_port_name)
{
  m_remotePort = strtoul(remote_ip_port.c_str(), nullptr, 0);
  if (0 == m_remotePort || ULONG_MAX == m_remotePort)
    m_remotePort = 55000;
  m_localPort = strtoul(local_ip_port.c_str(), nullptr, 0);
  if (0 == m_localPort || ULONG_MAX == m_localPort)
    m_localPort = 55300;
}

MessageHandler::~MessageHandler()
{
}

std::basic_string<unsigned char> MessageHandler::getGwIdent()
{
  //1. - GW type e.g.: �GW - ETH - 02A�
  //2. - FW version e.g. : �2.50�
  //3. - MAC address e.g. : �00 11 22 33 44 55�
  //4. - TCP / IP Stack version e.g. : �5.42�
  //5. - IP address of GW e.g. : �192.168.2.100�
  //6. - Net BIOS Name e.g. : �iqrf_xxxx � 15 characters
  //7. - IQRF module OS version e.g. : �3.06D�
  //8. - Public IP address e.g. : �213.214.215.120�
  //std::basic_ostringstream<unsigned char> os;
  std::basic_ostringstream<char> ostring;
  ostring <<
    "\x0D\x0A" << "udp-daemon-01" << "\x0D\x0A" <<
    "2.50" << "\x0D\x0A" <<
    "00 11 22 33 44 55" << "\x0D\x0A" <<
    "5.42" << "\x0D\x0A" <<
    "192.168.1.11" << "\x0D\x0A" <<
    "iqrf_xxxx" << "\x0D\x0A" <<
    "3.06D" << "\x0D\x0A" <<
    "192.168.1.11" << "\x0D\x0A";

  ustring res((unsigned char*)ostring.str().data(), ostring.str().size());
  //TRC_DBG("retval:" << PAR(res.size()) << std::endl << FORM_HEX(res.data(),res.size()));
  return res;
}

void MessageHandler::watchDog()
{
  TRC_ENTER("");
  m_running = true;
  try {
    start();
    while (m_running)
    {
      //TODO
      //watch worker threads
      std::this_thread::sleep_for(std::chrono::milliseconds(3000));
    }
  }
  catch (std::exception& e) {
    CATCH_EX("error", std::exception, e);
  }

  stop();
  TRC_LEAVE("");
}

void MessageHandler::start()
{
  TRC_ENTER("");
  size_t found = m_iqrfPortName.find("spi");
  if (found != std::string::npos)
    m_iqrfChannel = ant_new IqrfSpiChannel(m_iqrfPortName);
  else
    m_iqrfChannel = ant_new IqrfCdcChannel(m_iqrfPortName);

  m_udpChannel = ant_new UdpChannel((unsigned short)m_remotePort, (unsigned short)m_localPort, IQRF_UDP_BUFFER_SIZE);

  //Messages from IQRF are sent via MessageQueue to UDP channel
  m_toUdpMessageQueue = ant_new MessageQueue(m_udpChannel);

  //Messages from UDP are sent via MessageQueue to IQRF channel
  m_toIqrfMessageQueue = ant_new MessageQueue(m_iqrfChannel);

  //Received messages from IQRF channel are pushed to UDP MessageQueue
  m_iqrfChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int {
    return handleMessageFromIqrf(msg); });

  //Received messages from UDP channel are pushed to IQRF MessageQueue
  m_udpChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int {
    return handleMessageFromUdp(msg); });

  std::cout << "udp-daemon started" << std::endl;
  TRC_LEAVE("");
}

void MessageHandler::stop()
{
  TRC_ENTER("");
  std::cout << "udp-daemon stops" << std::endl;
  delete m_iqrfChannel;
  delete m_udpChannel;
  delete m_toUdpMessageQueue;
  delete m_toIqrfMessageQueue;
  TRC_LEAVE("");
}

void MessageHandler::exit()
{
  TRC_WAR("exiting ...");
  std::cout << "udp-daemon exits" << std::endl;
  m_running = false;
}
<commit_msg>Fixed CRC bug in responses<commit_after>#include "MessageHandler.h"
#include "IqrfCdcChannel.h"
#include "IqrfSpiChannel.h"
#include "UdpChannel.h"
#include "UdpMessage.h"
#include "helpers.h"
#include "MessageQueue.h"
#include "IqrfLogging.h"
#include "PlatformDep.h"
#include <climits>

enum IqrfWriteResults {
  wr_OK = 0x50,
  wr_Error_Len = 0x60, //(number of data = 0 or more than TR buffer COM length)
  wr_Error_SPI = 0x61, //(SPI bus busy)
  wr_Error_IQRF = 0x62 //(IQRF - CRCM Error)
};

int MessageHandler::handleMessageFromUdp(const ustring& udpMessage)
{
  TRC_DBG("Received from UDP: " << std::endl << FORM_HEX(udpMessage.data(), udpMessage.size()));

  size_t msgSize = udpMessage.size();
  std::basic_string<unsigned char> message;

  try {
    decodeMessageUdp(udpMessage, message);
  }
  catch (UdpChannelException& e) {
    TRC_DBG("Wrong message: " << e.what());
    return -1;
  }

  switch (udpMessage[cmd])
  {
  case IQRF_UDP_GET_GW_INFO:          // --- Returns GW identification ---
  {
    std::basic_string<unsigned char> udpResponse(udpMessage);
    udpResponse[cmd] = (unsigned char)IQRF_UDP_GET_GW_INFO | 0x80;
    encodeMessageUdp(getGwIdent(), udpResponse);
    m_toUdpMessageQueue->pushToQueue(udpResponse);
  }
  return 0;

  case IQRF_UDP_WRITE_IQRF:       // --- Writes data to the TR module ---
  {
    m_toIqrfMessageQueue->pushToQueue(message);

    //send response
    std::basic_string<unsigned char> udpResponse(udpMessage.substr(0, IQRF_UDP_HEADER_SIZE));
    std::basic_string<unsigned char> message;
    udpResponse[cmd] = (unsigned char)IQRF_UDP_WRITE_IQRF | 0x80;
    udpResponse[subcmd] = (unsigned char)IQRF_UDP_ACK;
    encodeMessageUdp(message, udpResponse);
    //TODO it is required to send back via subcmd write result - implement sync write with appropriate ret code
    m_toUdpMessageQueue->pushToQueue(udpResponse);
  }
  return 0;

  default:
    break;
  }
  return -1;
}

int MessageHandler::handleMessageFromIqrf(const ustring& iqrfMessage)
{
  TRC_DBG("Received from to IQRF: " << std::endl << FORM_HEX(iqrfMessage.data(), iqrfMessage.size()));

  std::basic_string<unsigned char> udpMessage;
  std::basic_string<unsigned char> message(iqrfMessage);
  encodeMessageUdp(message, udpMessage);
  udpMessage[cmd] = (unsigned char)IQRF_UDP_IQRF_SPI_DATA;
  m_toUdpMessageQueue->pushToQueue(udpMessage);

  //std::basic_string<unsigned char> udpMessage;
  //encodeMessageUdp(iqrfMessage, udpMessage);
  //m_toUdpMessageQueue->pushToQueue(udpMessage);
  return 0;
}

void MessageHandler::encodeMessageUdp(const ustring& message, ustring& udpMessage)
{
  unsigned short dlen = (unsigned short)message.size();
  udpMessage.resize(IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE, '\0');
  udpMessage[gwAddr] = IQRF_UDP_GW_ADR;
  udpMessage[dlen_H] = (unsigned char)((dlen >> 8) & 0xFF);
  udpMessage[dlen_L] = (unsigned char)(dlen & 0xFF);

  udpMessage.insert(IQRF_UDP_HEADER_SIZE, message);

  uint16_t crc = GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE);
  udpMessage[dlen + IQRF_UDP_HEADER_SIZE] = (unsigned char)((crc >> 8) & 0xFF);
  udpMessage[dlen + IQRF_UDP_HEADER_SIZE + 1] = (unsigned char)(crc & 0xFF);
}

void MessageHandler::decodeMessageUdp(const ustring& udpMessage, ustring& message)
{
  unsigned short dlen = 0;

  // Min. packet length check
  if (udpMessage.size() < IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE)
    THROW_EX(UdpChannelException, "Message is too short: " << FORM_HEX(udpMessage.data(), udpMessage.size()));

  // GW_ADR check
  if (udpMessage[gwAddr] != IQRF_UDP_GW_ADR)
    THROW_EX(UdpChannelException, "Message is has wrong GW_ADDR: " << PAR_HEX(udpMessage[gwAddr]));

  //iqrf data length
  dlen = (udpMessage[dlen_H] << 8) + udpMessage[dlen_L];

  // Max. packet length check
  if ((dlen + IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE) > IQRF_UDP_BUFFER_SIZE)
    THROW_EX(UdpChannelException, "Message is too long: " << PAR(dlen));

  // CRC check
  unsigned short crc = (udpMessage[IQRF_UDP_HEADER_SIZE + dlen] << 8) + udpMessage[IQRF_UDP_HEADER_SIZE + dlen + 1];
  if (crc != GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE))
    THROW_EX(UdpChannelException, "Message has wrong CRC");

  message = udpMessage.substr(IQRF_UDP_HEADER_SIZE, dlen);
}

MessageHandler::MessageHandler(const std::string& iqrf_port_name, const std::string& remote_ip_port, const std::string& local_ip_port)
  :m_iqrfChannel(nullptr)
  , m_udpChannel(nullptr)
  , m_toUdpMessageQueue(nullptr)
  , m_toIqrfMessageQueue(nullptr)
  , m_iqrfPortName(iqrf_port_name)
{
  m_remotePort = strtoul(remote_ip_port.c_str(), nullptr, 0);
  if (0 == m_remotePort || ULONG_MAX == m_remotePort)
    m_remotePort = 55000;
  m_localPort = strtoul(local_ip_port.c_str(), nullptr, 0);
  if (0 == m_localPort || ULONG_MAX == m_localPort)
    m_localPort = 55300;
}

MessageHandler::~MessageHandler()
{
}

std::basic_string<unsigned char> MessageHandler::getGwIdent()
{
  //1. - GW type e.g.: �GW - ETH - 02A�
  //2. - FW version e.g. : �2.50�
  //3. - MAC address e.g. : �00 11 22 33 44 55�
  //4. - TCP / IP Stack version e.g. : �5.42�
  //5. - IP address of GW e.g. : �192.168.2.100�
  //6. - Net BIOS Name e.g. : �iqrf_xxxx � 15 characters
  //7. - IQRF module OS version e.g. : �3.06D�
  //8. - Public IP address e.g. : �213.214.215.120�
  //std::basic_ostringstream<unsigned char> os;
  std::basic_ostringstream<char> ostring;
  ostring <<
    "\x0D\x0A" << "udp-daemon-01" << "\x0D\x0A" <<
    "2.50" << "\x0D\x0A" <<
    "00 11 22 33 44 55" << "\x0D\x0A" <<
    "5.42" << "\x0D\x0A" <<
    "192.168.1.11" << "\x0D\x0A" <<
    "iqrf_xxxx" << "\x0D\x0A" <<
    "3.06D" << "\x0D\x0A" <<
    "192.168.1.11" << "\x0D\x0A";

  ustring res((unsigned char*)ostring.str().data(), ostring.str().size());
  //TRC_DBG("retval:" << PAR(res.size()) << std::endl << FORM_HEX(res.data(),res.size()));
  return res;
}

void MessageHandler::watchDog()
{
  TRC_ENTER("");
  m_running = true;
  try {
    start();
    while (m_running)
    {
      //TODO
      //watch worker threads
      std::this_thread::sleep_for(std::chrono::milliseconds(3000));
    }
  }
  catch (std::exception& e) {
    CATCH_EX("error", std::exception, e);
  }

  stop();
  TRC_LEAVE("");
}

void MessageHandler::start()
{
  TRC_ENTER("");
  size_t found = m_iqrfPortName.find("spi");
  if (found != std::string::npos)
    m_iqrfChannel = ant_new IqrfSpiChannel(m_iqrfPortName);
  else
    m_iqrfChannel = ant_new IqrfCdcChannel(m_iqrfPortName);

  m_udpChannel = ant_new UdpChannel((unsigned short)m_remotePort, (unsigned short)m_localPort, IQRF_UDP_BUFFER_SIZE);

  //Messages from IQRF are sent via MessageQueue to UDP channel
  m_toUdpMessageQueue = ant_new MessageQueue(m_udpChannel);

  //Messages from UDP are sent via MessageQueue to IQRF channel
  m_toIqrfMessageQueue = ant_new MessageQueue(m_iqrfChannel);

  //Received messages from IQRF channel are pushed to UDP MessageQueue
  m_iqrfChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int {
    return handleMessageFromIqrf(msg); });

  //Received messages from UDP channel are pushed to IQRF MessageQueue
  m_udpChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int {
    return handleMessageFromUdp(msg); });

  std::cout << "udp-daemon started" << std::endl;
  TRC_LEAVE("");
}

void MessageHandler::stop()
{
  TRC_ENTER("");
  std::cout << "udp-daemon stops" << std::endl;
  delete m_iqrfChannel;
  delete m_udpChannel;
  delete m_toUdpMessageQueue;
  delete m_toIqrfMessageQueue;
  TRC_LEAVE("");
}

void MessageHandler::exit()
{
  TRC_WAR("exiting ...");
  std::cout << "udp-daemon exits" << std::endl;
  m_running = false;
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX600 グループ　DMACAa 定義
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
#include "RX600/peripheral.hpp"
#include "RX600/icu.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  DMA コントローラ（DMACAa）
		@param[in]	base	ベース・アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t base>
	struct dmaca_core_t {

	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	DMA コントローラ（DMACAa）
		@param[in]	base	ベース・アドレス
		@param[in]	t		ペリフェラル型
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t base, peripheral t>
	struct dmaca_t : public dmaca_core_t<base> {

	};

	typedef dmaca_t<0x00820000, peripheral::DMACA0>    DMACA0;
	typedef dmaca_t<0x00820040, peripheral::DMACA1>    DMACA1;
	typedef dmaca_t<0x00820080, peripheral::DMACA2>    DMACA2;
	typedef dmaca_t<0x008200C0, peripheral::DMACA3>    DMACA3;
	typedef dmaca_t<0x00820100, peripheral::DMACA4>    DMACA4;
	typedef dmaca_t<0x00820140, peripheral::DMACA5>    DMACA5;
	typedef dmaca_t<0x00820180, peripheral::DMACA6>    DMACA6;
	typedef dmaca_t<0x008201C0, peripheral::DMACA7>    DMACA7;
}
<commit_msg>remove: rename<commit_after><|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.
*
*=========================================================================*/

#include "sitkImageReaderBase.h"
#include "sitkMacro.h"
#include "sitkExceptionObject.h"

#include <itksys/SystemTools.hxx>

// Include the Transform IO here, so that the IO factory registration
// will occur.
#include <itkTransformFileReader.h>
#include <itkTransformFileWriter.h>

#include <string>

#include <itkImage.h>
#include <itkImageIOBase.h>
#include <itkImageIOFactory.h>
#include <itkGDCMImageIO.h>

namespace itk {
namespace simple {

ImageReaderBase
::~ImageReaderBase()
{
}

ImageReaderBase
::ImageReaderBase()
  : m_OutputPixelType(sitkUnknown),
    m_LoadPrivateTags(false)
{
}

std::string
ImageReaderBase
::ToString() const
{
  std::ostringstream out;
  out << "  OutputPixelType: ";
  this->ToStringHelper(out, this->m_OutputPixelType) << std::endl;
  out << "  LoadPrivateTags: ";
  this->ToStringHelper(out, this->m_LoadPrivateTags) << std::endl;
  out << ProcessObject::ToString();
  return out.str();
}

itk::SmartPointer<ImageIOBase>
ImageReaderBase
::GetImageIOBase(const std::string &fileName)
{
  itk::ImageIOBase::Pointer iobase =
    itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode);

  if ( iobase.IsNull() )
     {
     if ( !itksys::SystemTools::FileExists( fileName.c_str() ) )
       {
       sitkExceptionMacro( "The file \"" << fileName << "\" does not exist." );
       }

     if ( !bool(std::ifstream( fileName.c_str() )) )
       {
       sitkExceptionMacro( "Unable to open \"" << fileName << "\" for reading." );
       }

     sitkExceptionMacro( "Unable to determine ImageIO reader for \"" << fileName << "\"" );
    }

  // Try additional parameters
  GDCMImageIO *ioGDCMImage = dynamic_cast<GDCMImageIO*>(iobase.GetPointer());
  if (ioGDCMImage)
    {
    ioGDCMImage->SetLoadPrivateTags(this->m_LoadPrivateTags);
    }

  // Read the image information
  iobase->SetFileName( fileName );
  iobase->ReadImageInformation();

  return iobase;
}

ImageReaderBase::Self&
ImageReaderBase
::SetOutputPixelType( PixelIDValueEnum pixelID )
{
  this->m_OutputPixelType = pixelID;
  return *this;
}

PixelIDValueEnum
ImageReaderBase
::GetOutputPixelType( void ) const
{
  return this->m_OutputPixelType;
}

ImageReaderBase::Self&
ImageReaderBase
::SetLoadPrivateTags(bool loadPrivateTags)
{
  this->m_LoadPrivateTags = loadPrivateTags;
  return *this;
}

bool
ImageReaderBase
::GetLoadPrivateTags() const
{
  return this->m_LoadPrivateTags;
}

void
ImageReaderBase
::LoadPrivateTagsOn()
{
  this->SetLoadPrivateTags(true);
}

void
ImageReaderBase
::LoadPrivateTagsOff()
{
  this->SetLoadPrivateTags(false);
}

void
ImageReaderBase
::GetPixelIDFromImageIO( const std::string &fileName,
                         PixelIDValueType &outPixelType,
                         unsigned int & outDimensions )
{
  itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName);

  this->GetPixelIDFromImageIO(iobase, outPixelType, outDimensions);
}

void
ImageReaderBase
::GetPixelIDFromImageIO( const ImageIOBase *iobase,
                         PixelIDValueType &outPixelType,
                         unsigned int & outDimensions )
{

  // get output information about input image
  unsigned int dimension = iobase->GetNumberOfDimensions();
  itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType();
  itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType();
  unsigned int numberOfComponents = iobase->GetNumberOfComponents();

  outDimensions = dimension;

  if (numberOfComponents == 1 &&
      ( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) )
    {
    outPixelType = this->ExecuteInternalReadScalar( componentType );
    return;
    }
  // we try to load anything else into a VectorImage
  else if  (pixelType == itk::ImageIOBase::RGB ||
            pixelType == itk::ImageIOBase::RGBA ||
            pixelType == itk::ImageIOBase::VECTOR ||
            pixelType == itk::ImageIOBase::COVARIANTVECTOR ||
            pixelType == itk::ImageIOBase::FIXEDARRAY ||
            pixelType == itk::ImageIOBase::POINT ||
            pixelType == itk::ImageIOBase::OFFSET )
    {
    outPixelType = this->ExecuteInternalReadVector( componentType );
    return;
    }
  else if ( pixelType == itk::ImageIOBase::COMPLEX )
    {
    outPixelType = this->ExecuteInternalReadComplex( componentType );
    return;
    }
  else
    {
    sitkExceptionMacro(  "Unknown PixelType: "  << (int) componentType );
    }

  sitkExceptionMacro( "Unable to load image." );
}

unsigned int
ImageReaderBase
::GetDimensionFromImageIO( const itk::ImageIOBase* iobase, unsigned int i)
{
  return iobase->GetDimensions(i);
}

unsigned int
ImageReaderBase
::GetDimensionFromImageIO(const std::string &filename, unsigned int i)
{
  itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(filename);

  return this->GetDimensionFromImageIO(iobase.GetPointer(), i);
}

PixelIDValueType
ImageReaderBase
::ExecuteInternalReadScalar( int componentType )
{
  const unsigned int UnusedDimension = 2;

  switch(componentType)
    {
    case itk::ImageIOBase::CHAR:
      return ImageTypeToPixelIDValue< itk::Image<int8_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UCHAR:
      return ImageTypeToPixelIDValue< itk::Image<uint8_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::SHORT:
      return ImageTypeToPixelIDValue< itk::Image<int16_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::USHORT:
      return ImageTypeToPixelIDValue< itk::Image<uint16_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::INT:
      return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UINT:
      return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::LONG:
      if (sizeof(long) == 4 )
        return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result;
      else
        return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::ULONG:
      if (sizeof(unsigned long) == 4 )
        return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result;
      else
        return ImageTypeToPixelIDValue< itk::Image<uint64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::LONGLONG:
      return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::ULONGLONG:
      return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::FLOAT:
      return ImageTypeToPixelIDValue< itk::Image<float, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::DOUBLE:
      return ImageTypeToPixelIDValue< itk::Image<double, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
    default:
      assert( false ); // should never get here unless we forgot a type
      sitkExceptionMacro( "Logic error!" );
    }
}

PixelIDValueType
ImageReaderBase
::ExecuteInternalReadComplex( int componentType )
{
  const unsigned int UnusedDimension = 2;

  switch(componentType)
    {
    case itk::ImageIOBase::FLOAT:
      return ImageTypeToPixelIDValue< itk::Image<std::complex<float>, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::DOUBLE:
      return ImageTypeToPixelIDValue< itk::Image<std::complex<double>, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
    default:
      sitkExceptionMacro( "Only Complex image with float and double are supported!" );
    }
}

PixelIDValueType
ImageReaderBase
::ExecuteInternalReadVector( int componentType )
{
  const unsigned int UnusedDimension = 2;

  switch(componentType)
    {
    case itk::ImageIOBase::CHAR:
      return ImageTypeToPixelIDValue< itk::VectorImage<int8_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UCHAR:
      return ImageTypeToPixelIDValue< itk::VectorImage<uint8_t , UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::SHORT:
      return ImageTypeToPixelIDValue< itk::VectorImage<int16_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::USHORT:
      return ImageTypeToPixelIDValue< itk::VectorImage<uint16_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::INT:
      return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UINT:
      return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::LONG:
      if (sizeof(long) == 4 )
        return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result;
      else
        return ImageTypeToPixelIDValue< itk::VectorImage<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::ULONG:
      if (sizeof(unsigned long) == 4 )
        return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result;
      else
        return ImageTypeToPixelIDValue< itk::VectorImage<uint64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::LONGLONG:
      return ImageTypeToPixelIDValue< itk::VectorImage<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::ULONGLONG:
      return ImageTypeToPixelIDValue< itk::VectorImage<uint64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::FLOAT:
      return ImageTypeToPixelIDValue< itk::VectorImage<float, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::DOUBLE:
      return ImageTypeToPixelIDValue< itk::VectorImage<double, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
    default:
      assert( false ); // should never get here unless we forgot a type
      sitkExceptionMacro( "Logic error!" );
    }
}

}
}
<commit_msg>Improve error message with unexpected component type<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.
*
*=========================================================================*/

#include "sitkImageReaderBase.h"
#include "sitkMacro.h"
#include "sitkExceptionObject.h"

#include <itksys/SystemTools.hxx>

// Include the Transform IO here, so that the IO factory registration
// will occur.
#include <itkTransformFileReader.h>
#include <itkTransformFileWriter.h>

#include <string>

#include <itkImage.h>
#include <itkImageIOBase.h>
#include <itkImageIOFactory.h>
#include <itkGDCMImageIO.h>

namespace itk {
namespace simple {

ImageReaderBase
::~ImageReaderBase()
{
}

ImageReaderBase
::ImageReaderBase()
  : m_OutputPixelType(sitkUnknown),
    m_LoadPrivateTags(false)
{
}

std::string
ImageReaderBase
::ToString() const
{
  std::ostringstream out;
  out << "  OutputPixelType: ";
  this->ToStringHelper(out, this->m_OutputPixelType) << std::endl;
  out << "  LoadPrivateTags: ";
  this->ToStringHelper(out, this->m_LoadPrivateTags) << std::endl;
  out << ProcessObject::ToString();
  return out.str();
}

itk::SmartPointer<ImageIOBase>
ImageReaderBase
::GetImageIOBase(const std::string &fileName)
{
  itk::ImageIOBase::Pointer iobase =
    itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode);

  if ( iobase.IsNull() )
     {
     if ( !itksys::SystemTools::FileExists( fileName.c_str() ) )
       {
       sitkExceptionMacro( "The file \"" << fileName << "\" does not exist." );
       }

     if ( !bool(std::ifstream( fileName.c_str() )) )
       {
       sitkExceptionMacro( "Unable to open \"" << fileName << "\" for reading." );
       }

     sitkExceptionMacro( "Unable to determine ImageIO reader for \"" << fileName << "\"" );
    }

  // Try additional parameters
  GDCMImageIO *ioGDCMImage = dynamic_cast<GDCMImageIO*>(iobase.GetPointer());
  if (ioGDCMImage)
    {
    ioGDCMImage->SetLoadPrivateTags(this->m_LoadPrivateTags);
    }

  // Read the image information
  iobase->SetFileName( fileName );
  iobase->ReadImageInformation();

  return iobase;
}

ImageReaderBase::Self&
ImageReaderBase
::SetOutputPixelType( PixelIDValueEnum pixelID )
{
  this->m_OutputPixelType = pixelID;
  return *this;
}

PixelIDValueEnum
ImageReaderBase
::GetOutputPixelType( void ) const
{
  return this->m_OutputPixelType;
}

ImageReaderBase::Self&
ImageReaderBase
::SetLoadPrivateTags(bool loadPrivateTags)
{
  this->m_LoadPrivateTags = loadPrivateTags;
  return *this;
}

bool
ImageReaderBase
::GetLoadPrivateTags() const
{
  return this->m_LoadPrivateTags;
}

void
ImageReaderBase
::LoadPrivateTagsOn()
{
  this->SetLoadPrivateTags(true);
}

void
ImageReaderBase
::LoadPrivateTagsOff()
{
  this->SetLoadPrivateTags(false);
}

void
ImageReaderBase
::GetPixelIDFromImageIO( const std::string &fileName,
                         PixelIDValueType &outPixelType,
                         unsigned int & outDimensions )
{
  itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName);

  this->GetPixelIDFromImageIO(iobase, outPixelType, outDimensions);
}

void
ImageReaderBase
::GetPixelIDFromImageIO( const ImageIOBase *iobase,
                         PixelIDValueType &outPixelType,
                         unsigned int & outDimensions )
{

  // get output information about input image
  unsigned int dimension = iobase->GetNumberOfDimensions();
  itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType();
  itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType();
  unsigned int numberOfComponents = iobase->GetNumberOfComponents();

  outDimensions = dimension;

  if (numberOfComponents == 1 &&
      ( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) )
    {
    outPixelType = this->ExecuteInternalReadScalar( componentType );
    return;
    }
  // we try to load anything else into a VectorImage
  else if  (pixelType == itk::ImageIOBase::RGB ||
            pixelType == itk::ImageIOBase::RGBA ||
            pixelType == itk::ImageIOBase::VECTOR ||
            pixelType == itk::ImageIOBase::COVARIANTVECTOR ||
            pixelType == itk::ImageIOBase::FIXEDARRAY ||
            pixelType == itk::ImageIOBase::POINT ||
            pixelType == itk::ImageIOBase::OFFSET )
    {
    outPixelType = this->ExecuteInternalReadVector( componentType );
    return;
    }
  else if ( pixelType == itk::ImageIOBase::COMPLEX )
    {
    outPixelType = this->ExecuteInternalReadComplex( componentType );
    return;
    }
  else
    {
    sitkExceptionMacro(  "Unknown PixelType: "
                         << itk::ImageIOBase::GetComponentTypeAsString(componentType)
                         << "(" <<(int) componentType << ")" );
    }

  sitkExceptionMacro( "Unable to load image." );
}

unsigned int
ImageReaderBase
::GetDimensionFromImageIO( const itk::ImageIOBase* iobase, unsigned int i)
{
  return iobase->GetDimensions(i);
}

unsigned int
ImageReaderBase
::GetDimensionFromImageIO(const std::string &filename, unsigned int i)
{
  itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(filename);

  return this->GetDimensionFromImageIO(iobase.GetPointer(), i);
}

PixelIDValueType
ImageReaderBase
::ExecuteInternalReadScalar( int componentType )
{
  const unsigned int UnusedDimension = 2;

  switch(componentType)
    {
    case itk::ImageIOBase::CHAR:
      return ImageTypeToPixelIDValue< itk::Image<int8_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UCHAR:
      return ImageTypeToPixelIDValue< itk::Image<uint8_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::SHORT:
      return ImageTypeToPixelIDValue< itk::Image<int16_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::USHORT:
      return ImageTypeToPixelIDValue< itk::Image<uint16_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::INT:
      return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UINT:
      return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::LONG:
      if (sizeof(long) == 4 )
        return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result;
      else
        return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::ULONG:
      if (sizeof(unsigned long) == 4 )
        return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result;
      else
        return ImageTypeToPixelIDValue< itk::Image<uint64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::LONGLONG:
      return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::ULONGLONG:
      return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::FLOAT:
      return ImageTypeToPixelIDValue< itk::Image<float, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::DOUBLE:
      return ImageTypeToPixelIDValue< itk::Image<double, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
    default:
      assert( false ); // should never get here unless we forgot a type
      sitkExceptionMacro( "Logic error!" );
    }
}

PixelIDValueType
ImageReaderBase
::ExecuteInternalReadComplex( int componentType )
{
  const unsigned int UnusedDimension = 2;

  switch(componentType)
    {
    case itk::ImageIOBase::FLOAT:
      return ImageTypeToPixelIDValue< itk::Image<std::complex<float>, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::DOUBLE:
      return ImageTypeToPixelIDValue< itk::Image<std::complex<double>, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
    default:
      sitkExceptionMacro( "Only Complex image with float and double are supported!" );
    }
}

PixelIDValueType
ImageReaderBase
::ExecuteInternalReadVector( int componentType )
{
  const unsigned int UnusedDimension = 2;

  switch(componentType)
    {
    case itk::ImageIOBase::CHAR:
      return ImageTypeToPixelIDValue< itk::VectorImage<int8_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UCHAR:
      return ImageTypeToPixelIDValue< itk::VectorImage<uint8_t , UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::SHORT:
      return ImageTypeToPixelIDValue< itk::VectorImage<int16_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::USHORT:
      return ImageTypeToPixelIDValue< itk::VectorImage<uint16_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::INT:
      return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UINT:
      return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::LONG:
      if (sizeof(long) == 4 )
        return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result;
      else
        return ImageTypeToPixelIDValue< itk::VectorImage<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::ULONG:
      if (sizeof(unsigned long) == 4 )
        return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result;
      else
        return ImageTypeToPixelIDValue< itk::VectorImage<uint64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::LONGLONG:
      return ImageTypeToPixelIDValue< itk::VectorImage<int64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::ULONGLONG:
      return ImageTypeToPixelIDValue< itk::VectorImage<uint64_t, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::FLOAT:
      return ImageTypeToPixelIDValue< itk::VectorImage<float, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::DOUBLE:
      return ImageTypeToPixelIDValue< itk::VectorImage<double, UnusedDimension> >::Result;
      break;
    case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
    default:
      assert( false ); // should never get here unless we forgot a type
      sitkExceptionMacro( "Logic error!" );
    }
}

}
}
<|endoftext|>