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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkMorphologicalWatershedImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "itkSimpleFilterWatcher.h"
#include <itkIntensityWindowingImageFilter.h>
#include <itkMinimumMaximumImageCalculator.h>
#include "itkMorphologicalWatershedImageFilter.h"
#include "itkLabelOverlayImageFilter.h"

int itkMorphologicalWatershedImageFilterTest(int argc, char * argv[])
{
  if( argc < 6 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " InputImage OutputImage MarkWatershedLine FullyConnected Level [OvelayOutput [Alpha]]" << std::endl;
    return EXIT_FAILURE;
    }
  const int dim = 2;

  typedef unsigned char PType;
  typedef itk::Image< PType, dim > IType;

  typedef itk::ImageFileReader< IType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  typedef itk::MorphologicalWatershedImageFilter< IType, IType > FilterType;
  FilterType::Pointer filter = FilterType::New();
  filter->SetInput( reader->GetOutput() );

  // test default values
  if ( filter->GetMarkWatershedLine( ) != true )
    {
    std::cerr << "Wrong default MarkWatershedLine." << std::endl;
    return EXIT_FAILURE;
    }
  if ( filter->GetFullyConnected( ) != false )
    {
    std::cerr << "Wrong default FullyConnected." << std::endl;
    return EXIT_FAILURE;
    }
  if ( filter->GetLevel( ) != 0 )
    {
    std::cerr << "Wrong default Level." << std::endl;
    return EXIT_FAILURE;
    }

  filter->SetMarkWatershedLine( atoi( argv[3] ) );
  if ( filter->GetMarkWatershedLine( ) != (bool)atoi(argv[3]) )
    {
    std::cerr << "Set/Get MarkWatershedLine problem." << std::endl;
    return EXIT_FAILURE;
    }
  filter->SetFullyConnected( atoi( argv[4] ) );
  if ( filter->GetFullyConnected( ) != (bool)atoi(argv[4]) )
    {
    std::cerr << "Set/Get FullyConnected problem." << std::endl;
    return EXIT_FAILURE;
    }
  filter->SetLevel( atoi( argv[5] ) );
  if ( filter->GetLevel( ) != atoi(argv[5]) )
    {
    std::cerr << "Set/Get Level problem." << std::endl;
    return EXIT_FAILURE;
    }

  itk::SimpleFilterWatcher watcher(filter, "filter");

  try
    {
    filter->Update();
    }
  catch ( itk::ExceptionObject & excp )
    {
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  // rescale the output to have a better display
  typedef itk::MinimumMaximumImageCalculator< IType > MaxCalculatorType;
  MaxCalculatorType::Pointer max = MaxCalculatorType::New();
  max->SetImage( filter->GetOutput() );
  max->Compute();

  typedef itk::IntensityWindowingImageFilter< IType, IType > RescaleType;
  RescaleType::Pointer rescale = RescaleType::New();
  rescale->SetInput( filter->GetOutput() );
  rescale->SetWindowMinimum( itk::NumericTraits< PType >::Zero );
  rescale->SetWindowMaximum( max->GetMaximum() );
  rescale->SetOutputMaximum( itk::NumericTraits< PType >::max() );
  rescale->SetOutputMinimum( itk::NumericTraits< PType >::Zero );

  typedef itk::ImageFileWriter< IType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( rescale->GetOutput() );
  writer->SetFileName( argv[2] );

  try
    {
    writer->Update();
    }
  catch ( itk::ExceptionObject & excp )
    {
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  if( argc > 6 )
    {
    typedef itk::RGBPixel<unsigned char>   RGBPixelType;
    typedef itk::Image<RGBPixelType, dim>    RGBImageType;

    typedef itk::LabelOverlayImageFilter<IType, IType, RGBImageType> OverlayType;
    OverlayType::Pointer overlay = OverlayType::New();
    overlay->SetInput( reader->GetOutput() );
    overlay->SetLabelImage( filter->GetOutput() );

    typedef itk::ImageFileWriter< RGBImageType > RGBWriterType;
    RGBWriterType::Pointer rgbwriter = RGBWriterType::New();
    rgbwriter->SetInput( overlay->GetOutput() );
    rgbwriter->SetFileName( argv[6] );

    if( argc > 7 )
      {
      overlay->SetOpacity( atof( argv[7] ) );
      }

    try
      {
      rgbwriter->Update();
      }
    catch ( itk::ExceptionObject & excp )
      {
      std::cerr << excp << std::endl;
      return EXIT_FAILURE;
      }

    }

  return EXIT_SUCCESS;

}
<commit_msg>STYLE: Fixing typdef alignment issues, and replacing typdef with more        explicit names.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkMorphologicalWatershedImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

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

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "itkSimpleFilterWatcher.h"
#include <itkIntensityWindowingImageFilter.h>
#include <itkMinimumMaximumImageCalculator.h>
#include "itkMorphologicalWatershedImageFilter.h"
#include "itkLabelOverlayImageFilter.h"

int itkMorphologicalWatershedImageFilterTest(int argc, char * argv[])
{
  if( argc < 6 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " InputImage OutputImage MarkWatershedLine";
    std::cerr << " FullyConnected Level [OvelayOutput [Alpha]]" << std::endl;
    return EXIT_FAILURE;
    }
  const int dim = 2;

  typedef unsigned char PixelType;

  typedef itk::Image< PixelType, dim > ImageType;

  typedef itk::ImageFileReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  typedef itk::MorphologicalWatershedImageFilter<
    ImageType, ImageType > FilterType;

  FilterType::Pointer filter = FilterType::New();
  filter->SetInput( reader->GetOutput() );

  // test default values
  if ( filter->GetMarkWatershedLine( ) != true )
    {
    std::cerr << "Wrong default MarkWatershedLine." << std::endl;
    return EXIT_FAILURE;
    }
  if ( filter->GetFullyConnected( ) != false )
    {
    std::cerr << "Wrong default FullyConnected." << std::endl;
    return EXIT_FAILURE;
    }
  if ( filter->GetLevel( ) != 0 )
    {
    std::cerr << "Wrong default Level." << std::endl;
    return EXIT_FAILURE;
    }

  filter->SetMarkWatershedLine( atoi( argv[3] ) );
  if ( filter->GetMarkWatershedLine( ) != (bool)atoi(argv[3]) )
    {
    std::cerr << "Set/Get MarkWatershedLine problem." << std::endl;
    return EXIT_FAILURE;
    }
  filter->SetFullyConnected( atoi( argv[4] ) );
  if ( filter->GetFullyConnected( ) != (bool)atoi(argv[4]) )
    {
    std::cerr << "Set/Get FullyConnected problem." << std::endl;
    return EXIT_FAILURE;
    }

  filter->SetLevel( atoi( argv[5] ) );

  if ( filter->GetLevel( ) != atoi(argv[5]) )
    {
    std::cerr << "Set/Get Level problem." << std::endl;
    return EXIT_FAILURE;
    }

  itk::SimpleFilterWatcher watcher(filter, "filter");

  try
    {
    filter->Update();
    }
  catch ( itk::ExceptionObject & excp )
    {
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  // rescale the output to have a better display
  typedef itk::MinimumMaximumImageCalculator< ImageType > MaxCalculatorType;
  MaxCalculatorType::Pointer max = MaxCalculatorType::New();
  max->SetImage( filter->GetOutput() );
  max->Compute();

  typedef itk::IntensityWindowingImageFilter<
    ImageType, ImageType > RescaleType;

  RescaleType::Pointer rescale = RescaleType::New();
  rescale->SetInput( filter->GetOutput() );
  rescale->SetWindowMinimum( itk::NumericTraits< PixelType >::Zero );
  rescale->SetWindowMaximum( max->GetMaximum() );
  rescale->SetOutputMaximum( itk::NumericTraits< PixelType >::max() );
  rescale->SetOutputMinimum( itk::NumericTraits< PixelType >::Zero );

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( rescale->GetOutput() );
  writer->SetFileName( argv[2] );

  try
    {
    writer->Update();
    }
  catch ( itk::ExceptionObject & excp )
    {
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  if( argc > 6 )
    {
    typedef itk::RGBPixel< unsigned char >     RGBPixelType;
    typedef itk::Image< RGBPixelType, dim >    RGBImageType;

    typedef itk::LabelOverlayImageFilter<
      ImageType, ImageType, RGBImageType> OverlayType;

    OverlayType::Pointer overlay = OverlayType::New();
    overlay->SetInput( reader->GetOutput() );
    overlay->SetLabelImage( filter->GetOutput() );

    typedef itk::ImageFileWriter< RGBImageType > RGBWriterType;
    RGBWriterType::Pointer rgbwriter = RGBWriterType::New();
    rgbwriter->SetInput( overlay->GetOutput() );
    rgbwriter->SetFileName( argv[6] );

    if( argc > 7 )
      {
      overlay->SetOpacity( atof( argv[7] ) );
      }

    try
      {
      rgbwriter->Update();
      }
    catch ( itk::ExceptionObject & excp )
      {
      std::cerr << excp << std::endl;
      return EXIT_FAILURE;
      }

    }

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, John Haddon. All rights reserved.
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECorePython/RunTimeTypedBinding.h"

#include "Gaffer/CompoundDataPlug.h"

#include "GafferBindings/ValuePlugBinding.h"
#include "GafferBindings/CompoundDataPlugBinding.h"

using namespace boost::python;
using namespace GafferBindings;
using namespace Gaffer;

static std::string maskedMemberPlugRepr( const CompoundDataPlug::MemberPlug *plug, unsigned flagsMask )
{
	// the only reason we have a different __repr__ implementation than Gaffer::Plug is
	// because we can't determine the nested class name from a PyObject.
	std::string result = "Gaffer.CompoundDataPlug.MemberPlug( \"" + plug->getName().string() + "\", ";

	if( plug->direction()!=Plug::In )
	{
		result += "direction = " + PlugSerialiser::directionRepr( plug->direction() ) + ", ";
	}

	const unsigned flags = plug->getFlags() & flagsMask;
	if( flags != Plug::Default )
	{
		result += "flags = " + PlugSerialiser::flagsRepr( flags ) + ", ";
	}

	result += ")";

	return result;
}

static std::string memberPlugRepr( const CompoundDataPlug::MemberPlug *plug )
{
	return maskedMemberPlugRepr( plug, Plug::All );
}

static CompoundDataPlugPtr compoundDataPlugConstructor( const char *name, Plug::Direction direction, unsigned flags, tuple children )
{
	CompoundDataPlugPtr result = new CompoundDataPlug( name, direction, flags );
	size_t s = extract<size_t>( children.attr( "__len__" )() );
	for( size_t i=0; i<s; i++ )
	{
		Gaffer::PlugPtr c = extract<Gaffer::PlugPtr>( children[i] );
		result->addChild( c );
	}
	return result;
}

static Gaffer::CompoundDataPlug::MemberPlugPtr addMemberWrapper( CompoundDataPlug &p, const std::string &name, IECore::DataPtr value, const std::string &plugName, unsigned plugFlags )
{
	return p.addMember( name, value.get(), plugName, plugFlags );
}

static Gaffer::CompoundDataPlug::MemberPlugPtr addMemberWrapper2( CompoundDataPlug &p, const std::string &name, ValuePlug *valuePlug, const std::string &plugName )
{
	return p.addMember( name, valuePlug, plugName );
}

static Gaffer::CompoundDataPlug::MemberPlugPtr addOptionalMemberWrapper( CompoundDataPlug &p, const std::string &name, IECore::DataPtr value, const std::string plugName, unsigned plugFlags, bool enabled )
{
	return p.addOptionalMember( name, value.get(), plugName, plugFlags, enabled );
}

static Gaffer::CompoundDataPlug::MemberPlugPtr addOptionalMemberWrapper2( CompoundDataPlug &p, const std::string &name, ValuePlug *valuePlug, const std::string &plugName, bool enabled )
{
	return p.addOptionalMember( name, valuePlug, plugName, enabled );
}

static tuple memberDataAndNameWrapper( CompoundDataPlug &p, const CompoundDataPlug::MemberPlug *member )
{
	std::string name;
	IECore::DataPtr d = p.memberDataAndName( member, name );
	return boost::python::make_tuple( d, name );
}

static void fillCompoundData( const CompoundDataPlug &p, IECore::CompoundData *d )
{
	p.fillCompoundData( d->writable() );
}

static void fillCompoundObject( const CompoundDataPlug &p, IECore::CompoundObject *o )
{
	p.fillCompoundObject( o->members() );
}

class MemberPlugSerialiser : public ValuePlugSerialiser
{

	public :

		virtual std::string constructor( const Gaffer::GraphComponent *graphComponent, const Serialisation &serialisation ) const
		{
			return maskedMemberPlugRepr( static_cast<const CompoundDataPlug::MemberPlug *>( graphComponent ), Plug::All & ~Plug::ReadOnly );
		}

		virtual bool childNeedsConstruction( const Gaffer::GraphComponent *child ) const
		{
			// if the parent is dynamic then all the children will need construction.
			const Plug *parent = child->parent<Plug>();
			return parent->getFlags( Gaffer::Plug::Dynamic );
		}

};

void GafferBindings::bindCompoundDataPlug()
{

	scope s = PlugClass<CompoundDataPlug>()
		.def( "__init__", make_constructor( compoundDataPlugConstructor, default_call_policies(),
				(
					arg( "name" ) = GraphComponent::defaultName<CompoundDataPlug>(),
					arg( "direction" ) = Gaffer::Plug::In,
					arg( "flags" ) = Gaffer::Plug::Default,
					arg( "children" ) = tuple()
				)
			)
		)
		.def( "addMember", &addMemberWrapper, ( arg_( "name" ), arg_( "defaultValue" ), arg_( "plugName" ) = "member1", arg_( "plugFlags" ) = Plug::Default | Plug::Dynamic ) )
		.def( "addMember", &addMemberWrapper2, ( arg_( "name" ), arg_( "valuePlug" ), arg_( "plugName" ) = "member1" ) )
		.def( "addOptionalMember", &addOptionalMemberWrapper, ( arg_( "name" ), arg_( "defaultValue" ), arg_( "plugName" ) = "member1", arg_( "plugFlags" ) = Plug::Default | Plug::Dynamic, arg_( "enabled" ) = false ) )
		.def( "addOptionalMember", &addOptionalMemberWrapper2, ( arg_( "name" ), arg_( "valuePlug" ), arg_( "plugName" ) = "member1", arg_( "enabled" ) = false ) )
		.def( "addMembers", &CompoundDataPlug::addMembers, ( arg_( "members" ), arg_( "useNameAsPlugName" ) = false ) )
		.def( "memberDataAndName", &memberDataAndNameWrapper )
		.def( "fillCompoundData", &fillCompoundData )
		.def( "fillCompoundObject", &fillCompoundObject )
	;

	PlugClass<CompoundDataPlug::MemberPlug>()
		.def( init<const char *, Plug::Direction, unsigned>(
				(
					boost::python::arg_( "name" )=GraphComponent::defaultName<CompoundDataPlug::MemberPlug>(),
					boost::python::arg_( "direction" )=Plug::In,
					boost::python::arg_( "flags" )=Plug::Default
				)
			)
		)
		.def( "__repr__", memberPlugRepr )
	;

	Serialisation::registerSerialiser( Gaffer::CompoundDataPlug::MemberPlug::staticTypeId(), new MemberPlugSerialiser );

}
<commit_msg>CompoundDataPlug bindings : Move internals to anonymous namespace.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, John Haddon. All rights reserved.
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECorePython/RunTimeTypedBinding.h"

#include "Gaffer/CompoundDataPlug.h"

#include "GafferBindings/ValuePlugBinding.h"
#include "GafferBindings/CompoundDataPlugBinding.h"

using namespace boost::python;
using namespace GafferBindings;
using namespace Gaffer;

namespace
{

std::string maskedMemberPlugRepr( const CompoundDataPlug::MemberPlug *plug, unsigned flagsMask )
{
	// the only reason we have a different __repr__ implementation than Gaffer::Plug is
	// because we can't determine the nested class name from a PyObject.
	std::string result = "Gaffer.CompoundDataPlug.MemberPlug( \"" + plug->getName().string() + "\", ";

	if( plug->direction()!=Plug::In )
	{
		result += "direction = " + PlugSerialiser::directionRepr( plug->direction() ) + ", ";
	}

	const unsigned flags = plug->getFlags() & flagsMask;
	if( flags != Plug::Default )
	{
		result += "flags = " + PlugSerialiser::flagsRepr( flags ) + ", ";
	}

	result += ")";

	return result;
}

std::string memberPlugRepr( const CompoundDataPlug::MemberPlug *plug )
{
	return maskedMemberPlugRepr( plug, Plug::All );
}

CompoundDataPlugPtr compoundDataPlugConstructor( const char *name, Plug::Direction direction, unsigned flags, tuple children )
{
	CompoundDataPlugPtr result = new CompoundDataPlug( name, direction, flags );
	size_t s = extract<size_t>( children.attr( "__len__" )() );
	for( size_t i=0; i<s; i++ )
	{
		Gaffer::PlugPtr c = extract<Gaffer::PlugPtr>( children[i] );
		result->addChild( c );
	}
	return result;
}

Gaffer::CompoundDataPlug::MemberPlugPtr addMemberWrapper( CompoundDataPlug &p, const std::string &name, IECore::DataPtr value, const std::string &plugName, unsigned plugFlags )
{
	return p.addMember( name, value.get(), plugName, plugFlags );
}

Gaffer::CompoundDataPlug::MemberPlugPtr addMemberWrapper2( CompoundDataPlug &p, const std::string &name, ValuePlug *valuePlug, const std::string &plugName )
{
	return p.addMember( name, valuePlug, plugName );
}

Gaffer::CompoundDataPlug::MemberPlugPtr addOptionalMemberWrapper( CompoundDataPlug &p, const std::string &name, IECore::DataPtr value, const std::string plugName, unsigned plugFlags, bool enabled )
{
	return p.addOptionalMember( name, value.get(), plugName, plugFlags, enabled );
}

Gaffer::CompoundDataPlug::MemberPlugPtr addOptionalMemberWrapper2( CompoundDataPlug &p, const std::string &name, ValuePlug *valuePlug, const std::string &plugName, bool enabled )
{
	return p.addOptionalMember( name, valuePlug, plugName, enabled );
}

tuple memberDataAndNameWrapper( CompoundDataPlug &p, const CompoundDataPlug::MemberPlug *member )
{
	std::string name;
	IECore::DataPtr d = p.memberDataAndName( member, name );
	return boost::python::make_tuple( d, name );
}

void fillCompoundData( const CompoundDataPlug &p, IECore::CompoundData *d )
{
	p.fillCompoundData( d->writable() );
}

void fillCompoundObject( const CompoundDataPlug &p, IECore::CompoundObject *o )
{
	p.fillCompoundObject( o->members() );
}

class MemberPlugSerialiser : public ValuePlugSerialiser
{

	public :

		virtual std::string constructor( const Gaffer::GraphComponent *graphComponent, const Serialisation &serialisation ) const
		{
			return maskedMemberPlugRepr( static_cast<const CompoundDataPlug::MemberPlug *>( graphComponent ), Plug::All & ~Plug::ReadOnly );
		}

		virtual bool childNeedsConstruction( const Gaffer::GraphComponent *child ) const
		{
			// if the parent is dynamic then all the children will need construction.
			const Plug *parent = child->parent<Plug>();
			return parent->getFlags( Gaffer::Plug::Dynamic );
		}

};

} // namespace

void GafferBindings::bindCompoundDataPlug()
{

	scope s = PlugClass<CompoundDataPlug>()
		.def( "__init__", make_constructor( compoundDataPlugConstructor, default_call_policies(),
				(
					arg( "name" ) = GraphComponent::defaultName<CompoundDataPlug>(),
					arg( "direction" ) = Gaffer::Plug::In,
					arg( "flags" ) = Gaffer::Plug::Default,
					arg( "children" ) = tuple()
				)
			)
		)
		.def( "addMember", &addMemberWrapper, ( arg_( "name" ), arg_( "defaultValue" ), arg_( "plugName" ) = "member1", arg_( "plugFlags" ) = Plug::Default | Plug::Dynamic ) )
		.def( "addMember", &addMemberWrapper2, ( arg_( "name" ), arg_( "valuePlug" ), arg_( "plugName" ) = "member1" ) )
		.def( "addOptionalMember", &addOptionalMemberWrapper, ( arg_( "name" ), arg_( "defaultValue" ), arg_( "plugName" ) = "member1", arg_( "plugFlags" ) = Plug::Default | Plug::Dynamic, arg_( "enabled" ) = false ) )
		.def( "addOptionalMember", &addOptionalMemberWrapper2, ( arg_( "name" ), arg_( "valuePlug" ), arg_( "plugName" ) = "member1", arg_( "enabled" ) = false ) )
		.def( "addMembers", &CompoundDataPlug::addMembers, ( arg_( "members" ), arg_( "useNameAsPlugName" ) = false ) )
		.def( "memberDataAndName", &memberDataAndNameWrapper )
		.def( "fillCompoundData", &fillCompoundData )
		.def( "fillCompoundObject", &fillCompoundObject )
	;

	PlugClass<CompoundDataPlug::MemberPlug>()
		.def( init<const char *, Plug::Direction, unsigned>(
				(
					boost::python::arg_( "name" )=GraphComponent::defaultName<CompoundDataPlug::MemberPlug>(),
					boost::python::arg_( "direction" )=Plug::In,
					boost::python::arg_( "flags" )=Plug::Default
				)
			)
		)
		.def( "__repr__", memberPlugRepr )
	;

	Serialisation::registerSerialiser( Gaffer::CompoundDataPlug::MemberPlug::staticTypeId(), new MemberPlugSerialiser );

}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2018, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "SceneGadgetBinding.h"

#include "GafferSceneUI/SceneGadget.h"

#include "GafferUIBindings/GadgetBinding.h"

#include "GafferBindings/SignalBinding.h"

using namespace boost::python;
using namespace IECorePython;
using namespace GafferSceneUI;
using namespace GafferBindings;

namespace
{

GafferScene::ScenePlugPtr getScene( SceneGadget &g )
{
	return const_cast<GafferScene::ScenePlug *>( g.getScene() );
}

void setPaused( SceneGadget &g, bool paused )
{
	ScopedGILRelease gilRelease;
	g.setPaused( paused );
}

void waitForCompletion( SceneGadget &g )
{
	ScopedGILRelease gilRelease;
	g.waitForCompletion();
}

struct SceneGadgetSlotCaller
{
	boost::signals::detail::unusable operator()( boost::python::object slot, SceneGadgetPtr g )
	{
		try
		{
			slot( g );
		}
		catch( const error_already_set &e )
		{
			ExceptionAlgo::translatePythonException();
		}
		return boost::signals::detail::unusable();
	}
};

IECore::CompoundObjectPtr getOpenGLOptions( const SceneGadget &g )
{
	return g.getOpenGLOptions()->copy();
}

IECore::StringVectorDataPtr getSelectionMask( const SceneGadget &g )
{
	const IECore::StringVectorData *d = g.getSelectionMask();
	return d ? d->copy() : nullptr;
}

IECore::InternedStringVectorDataPtr objectAt( SceneGadget &g, IECore::LineSegment3f &l )
{
	IECore::InternedStringVectorDataPtr result = new IECore::InternedStringVectorData;
	if( g.objectAt( l, result->writable() ) )
	{
		return result;
	}
	return nullptr;
}

} // namespace

void GafferSceneUIModule::bindSceneGadget()
{

	scope s = GafferUIBindings::GadgetClass<SceneGadget>()
		.def( init<>() )
		.def( "setScene", &SceneGadget::setScene )
		.def( "getScene", &getScene )
		.def( "setContext", &SceneGadget::setContext )
		.def( "getContext", (Gaffer::Context *(SceneGadget::*)())&SceneGadget::getContext, return_value_policy<CastToIntrusivePtr>() )
		.def( "setExpandedPaths", &SceneGadget::setExpandedPaths )
		.def( "getExpandedPaths", &SceneGadget::getExpandedPaths, return_value_policy<copy_const_reference>() )
		.def( "setMinimumExpansionDepth", &SceneGadget::setMinimumExpansionDepth )
		.def( "getMinimumExpansionDepth", &SceneGadget::getMinimumExpansionDepth )
		.def( "getPaused", &SceneGadget::getPaused )
		.def( "setPaused", &setPaused )
		.def( "state", &SceneGadget::state )
		.def( "stateChangedSignal", &SceneGadget::stateChangedSignal, return_internal_reference<1>() )
		.def( "waitForCompletion", &waitForCompletion )
		.def( "setOpenGLOptions", &SceneGadget::setOpenGLOptions )
		.def( "getOpenGLOptions", &getOpenGLOptions )
		.def( "setSelectionMask", &SceneGadget::setSelectionMask )
		.def( "getSelectionMask", &getSelectionMask )
		.def( "objectAt", &objectAt )
		.def( "objectsAt", &SceneGadget::objectsAt )
		.def( "setSelection", &SceneGadget::setSelection )
		.def( "getSelection", &SceneGadget::getSelection, return_value_policy<copy_const_reference>() )
		.def( "selectionBound", &SceneGadget::selectionBound )
	;

	enum_<SceneGadget::State>( "State" )
		.value( "Paused", SceneGadget::Paused )
		.value( "Running", SceneGadget::Running )
		.value( "Complete", SceneGadget::Complete )
	;

	SignalClass<SceneGadget::SceneGadgetSignal, DefaultSignalCaller<SceneGadget::SceneGadgetSignal>, SceneGadgetSlotCaller>( "ImageGadgetSignal" );

}
<commit_msg>SceneGadget binding : Add missing GIL releases<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2018, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "SceneGadgetBinding.h"

#include "GafferSceneUI/SceneGadget.h"

#include "GafferUIBindings/GadgetBinding.h"

#include "GafferBindings/SignalBinding.h"

using namespace boost::python;
using namespace IECorePython;
using namespace Gaffer;
using namespace GafferScene;
using namespace GafferSceneUI;
using namespace GafferBindings;

namespace
{

void setScene( SceneGadget &g, ScenePlug &scene )
{
	ScopedGILRelease gilRelease;
	g.setScene( &scene );
}

GafferScene::ScenePlugPtr getScene( SceneGadget &g )
{
	return const_cast<GafferScene::ScenePlug *>( g.getScene() );
}

void setContext( SceneGadget &g, Context &context )
{
	ScopedGILRelease gilRelease;
	g.setContext( &context );
}

void setExpandedPaths( SceneGadget &g, const IECore::PathMatcher &expandedPaths )
{
	ScopedGILRelease gilRelease;
	g.setExpandedPaths( expandedPaths );
}

void setMinimumExpansionDepth( SceneGadget &g, size_t depth )
{
	ScopedGILRelease gilRelease;
	g.setMinimumExpansionDepth( depth );
}

void setPaused( SceneGadget &g, bool paused )
{
	ScopedGILRelease gilRelease;
	g.setPaused( paused );
}

void waitForCompletion( SceneGadget &g )
{
	ScopedGILRelease gilRelease;
	g.waitForCompletion();
}

struct SceneGadgetSlotCaller
{
	boost::signals::detail::unusable operator()( boost::python::object slot, SceneGadgetPtr g )
	{
		try
		{
			slot( g );
		}
		catch( const error_already_set &e )
		{
			ExceptionAlgo::translatePythonException();
		}
		return boost::signals::detail::unusable();
	}
};

IECore::CompoundObjectPtr getOpenGLOptions( const SceneGadget &g )
{
	return g.getOpenGLOptions()->copy();
}

IECore::StringVectorDataPtr getSelectionMask( const SceneGadget &g )
{
	const IECore::StringVectorData *d = g.getSelectionMask();
	return d ? d->copy() : nullptr;
}

IECore::InternedStringVectorDataPtr objectAt( SceneGadget &g, IECore::LineSegment3f &l )
{
	IECore::InternedStringVectorDataPtr result = new IECore::InternedStringVectorData;
	if( g.objectAt( l, result->writable() ) )
	{
		return result;
	}
	return nullptr;
}

} // namespace

void GafferSceneUIModule::bindSceneGadget()
{

	scope s = GafferUIBindings::GadgetClass<SceneGadget>()
		.def( init<>() )
		.def( "setScene", &setScene )
		.def( "getScene", &getScene )
		.def( "setContext", &setContext )
		.def( "getContext", (Gaffer::Context *(SceneGadget::*)())&SceneGadget::getContext, return_value_policy<CastToIntrusivePtr>() )
		.def( "setExpandedPaths", &setExpandedPaths )
		.def( "getExpandedPaths", &SceneGadget::getExpandedPaths, return_value_policy<copy_const_reference>() )
		.def( "setMinimumExpansionDepth", &setMinimumExpansionDepth )
		.def( "getMinimumExpansionDepth", &SceneGadget::getMinimumExpansionDepth )
		.def( "getPaused", &SceneGadget::getPaused )
		.def( "setPaused", &setPaused )
		.def( "state", &SceneGadget::state )
		.def( "stateChangedSignal", &SceneGadget::stateChangedSignal, return_internal_reference<1>() )
		.def( "waitForCompletion", &waitForCompletion )
		.def( "setOpenGLOptions", &SceneGadget::setOpenGLOptions )
		.def( "getOpenGLOptions", &getOpenGLOptions )
		.def( "setSelectionMask", &SceneGadget::setSelectionMask )
		.def( "getSelectionMask", &getSelectionMask )
		.def( "objectAt", &objectAt )
		.def( "objectsAt", &SceneGadget::objectsAt )
		.def( "setSelection", &SceneGadget::setSelection )
		.def( "getSelection", &SceneGadget::getSelection, return_value_policy<copy_const_reference>() )
		.def( "selectionBound", &SceneGadget::selectionBound )
	;

	enum_<SceneGadget::State>( "State" )
		.value( "Paused", SceneGadget::Paused )
		.value( "Running", SceneGadget::Running )
		.value( "Complete", SceneGadget::Complete )
	;

	SignalClass<SceneGadget::SceneGadgetSignal, DefaultSignalCaller<SceneGadget::SceneGadgetSignal>, SceneGadgetSlotCaller>( "ImageGadgetSignal" );

}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010-2012, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreHoudini/ToHoudiniPointsConverter.h"

using namespace IECore;
using namespace IECoreHoudini;

IE_CORE_DEFINERUNTIMETYPED( ToHoudiniPointsConverter );

ToHoudiniGeometryConverter::Description<ToHoudiniPointsConverter> ToHoudiniPointsConverter::m_description( PointsPrimitiveTypeId );

ToHoudiniPointsConverter::ToHoudiniPointsConverter( const VisibleRenderable *renderable ) :
	ToHoudiniGeometryConverter( renderable, "Converts an IECore::PointsPrimitive to a Houdini GU_Detail." )
{
}

ToHoudiniPointsConverter::~ToHoudiniPointsConverter()
{
}

bool ToHoudiniPointsConverter::doConversion( const VisibleRenderable *renderable, GU_Detail *geo ) const
{
	const PointsPrimitive *points = static_cast<const PointsPrimitive *>( renderable );
	if ( !points )
	{
		return false;
	}

	const IECore::V3fVectorData *positions = points->variableData<V3fVectorData>( "P" );
	if ( !positions )
	{
		// accept "position" so we can convert the results of the PDCParticleReader without having to rename things
		/// \todo: Consider making the ParticleReader create a P if it doesn't exist for Cortex 6.
		positions = points->variableData<V3fVectorData>( "position" );
	}

	GA_Range newPoints = appendPoints( geo, positions );
	if ( !newPoints.isValid() || newPoints.empty() )
	{
		return false;
	}

	transferAttribs( points, geo, newPoints, GA_Range(), PrimitiveVariable::Vertex );

	return true;
}
<commit_msg>fixed bug to do with Uniform interpolation attribs<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010-2012, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreHoudini/ToHoudiniPointsConverter.h"

using namespace IECore;
using namespace IECoreHoudini;

IE_CORE_DEFINERUNTIMETYPED( ToHoudiniPointsConverter );

ToHoudiniGeometryConverter::Description<ToHoudiniPointsConverter> ToHoudiniPointsConverter::m_description( PointsPrimitiveTypeId );

ToHoudiniPointsConverter::ToHoudiniPointsConverter( const VisibleRenderable *renderable ) :
	ToHoudiniGeometryConverter( renderable, "Converts an IECore::PointsPrimitive to a Houdini GU_Detail." )
{
}

ToHoudiniPointsConverter::~ToHoudiniPointsConverter()
{
}

bool ToHoudiniPointsConverter::doConversion( const VisibleRenderable *renderable, GU_Detail *geo ) const
{
	const PointsPrimitive *points = static_cast<const PointsPrimitive *>( renderable );
	if ( !points )
	{
		return false;
	}

	const IECore::V3fVectorData *positions = points->variableData<V3fVectorData>( "P" );
	if ( !positions )
	{
		// accept "position" so we can convert the results of the PDCParticleReader without having to rename things
		/// \todo: Consider making the ParticleReader create a P if it doesn't exist for Cortex 6.
		positions = points->variableData<V3fVectorData>( "position" );
	}

	GA_Range newPoints = appendPoints( geo, positions );
	if ( !newPoints.isValid() || newPoints.empty() )
	{
		return false;
	}

	transferAttribs( points, geo, newPoints, GA_Range(), PrimitiveVariable::Vertex, PrimitiveVariable::Vertex );

	return true;
}
<|endoftext|>


<commit_before>/** @file series_expansion.test.cc
 *
 *  The test driver for series expansion library.
 *
 *  @author Dongryeol Lee (dongryel@cc.gatech.edu)
 */

// for BOOST testing
#define BOOST_TEST_MAIN

#include <boost/test/unit_test.hpp>
#include <time.h>
#include "core/metric_kernels/lmetric.h"
#include "core/table/table.h"
#include "core/math/math_lib.h"
#include "mlpack/series_expansion/kernel_aux.h"
#include "mlpack/series_expansion/hypercube_farfield_dev.h"
#include "mlpack/series_expansion/hypercube_local_dev.h"
#include "mlpack/series_expansion/multivariate_farfield_dev.h"
#include "mlpack/series_expansion/multivariate_local_dev.h"

namespace mlpack {
namespace series_expansion {

template <
typename TableType,
         enum mlpack::series_expansion::CartesianExpansionType ExpansionType >
class SeriesExpansionTest {

  private:
    void GenerateRandomDataset_(
      int num_dimensions,
      int num_points,
      TableType *random_dataset) {

      random_dataset->Init(num_dimensions, num_points);

      for(int j = 0; j < num_points; j++) {
        core::table::DensePoint point;
        random_dataset->get(j, &point);
        for(int i = 0; i < num_dimensions; i++) {
          point[i] = core::math::Random(0.1, 1.0);
        }
      }
    }

  public:

    int StressTestMain() {
      for(int i = 0; i < 10; i++) {
        int num_dimensions = core::math::RandInt(3, 5);
        int num_points = core::math::RandInt(30, 100);
        if(StressTest(num_dimensions, num_points) == false) {
          printf("Failed!\n");
          exit(0);
        }
      }
      return 0;
    }

    bool StressTest(int num_dimensions, int num_points) {

      std::cout << "Number of dimensions: " << num_dimensions << "\n";
      std::cout << "Number of points: " << num_points << "\n";

      // Generate a random table.
      int max_order = 6 - num_dimensions;
      TableType random_table;
      GenerateRandomDataset_(
        num_dimensions, num_points, &random_table);

      // Form a Cartesian expansion global object.
      mlpack::series_expansion::GaussianKernelAux kernel_aux;
      double bandwidth = core::math::Random(
                           0.05 * num_dimensions, 0.3 * num_dimensions);
      kernel_aux.Init(bandwidth, max_order, random_table.n_attributes());
      kernel_aux.global().Print();

      // Form a far-field expansion and evaluate.
      mlpack::series_expansion::CartesianFarField<ExpansionType> farfield;
      return true;
    }
};
}
}

BOOST_AUTO_TEST_SUITE(TestSuiteSeriesExpansion)
BOOST_AUTO_TEST_CASE(TestCaseSeriesExpansion) {

  // Tree type: hard-coded for a metric tree.
  typedef core::table::Table <
  core::tree::GenMetricTree<core::tree::AbstractStatistic> > TableType;

  // Call the tests.
  mlpack::series_expansion::SeriesExpansionTest <
  TableType, mlpack::series_expansion::MULTIVARIATE > multivariate_test;
  multivariate_test.StressTestMain();
  mlpack::series_expansion::SeriesExpansionTest <
  TableType, mlpack::series_expansion::HYPERCUBE > hypercube_test;
  hypercube_test.StressTestMain();

  std::cout << "All tests passed!\n";
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Epanechnikov expansion test added.<commit_after>/** @file series_expansion.test.cc
 *
 *  The test driver for series expansion library.
 *
 *  @author Dongryeol Lee (dongryel@cc.gatech.edu)
 */

// for BOOST testing
#define BOOST_TEST_MAIN

#include <boost/test/unit_test.hpp>
#include <time.h>
#include "core/metric_kernels/lmetric.h"
#include "core/table/table.h"
#include "core/math/math_lib.h"
#include "mlpack/series_expansion/kernel_aux.h"
#include "mlpack/series_expansion/hypercube_farfield_dev.h"
#include "mlpack/series_expansion/hypercube_local_dev.h"
#include "mlpack/series_expansion/multivariate_farfield_dev.h"
#include "mlpack/series_expansion/multivariate_local_dev.h"

namespace mlpack {
namespace series_expansion {

template <typename TableType, typename KernelAuxType >
class SeriesExpansionTest {

  private:
    void GenerateRandomDataset_(
      int num_dimensions,
      int num_points,
      TableType *random_dataset) {

      random_dataset->Init(num_dimensions, num_points);

      for(int j = 0; j < num_points; j++) {
        core::table::DensePoint point;
        random_dataset->get(j, &point);
        for(int i = 0; i < num_dimensions; i++) {
          point[i] = core::math::Random(0.1, 1.0);
        }
      }
    }

  public:

    int StressTestMain() {
      for(int i = 0; i < 10; i++) {
        int num_dimensions = core::math::RandInt(3, 5);
        int num_points = core::math::RandInt(30, 100);
        if(StressTest(num_dimensions, num_points) == false) {
          printf("Failed!\n");
          exit(0);
        }
      }
      return 0;
    }

    bool StressTest(int num_dimensions, int num_points) {

      std::cout << "Number of dimensions: " << num_dimensions << "\n";
      std::cout << "Number of points: " << num_points << "\n";

      // Generate a random table.
      int max_order = 6 - num_dimensions;
      TableType random_table;
      GenerateRandomDataset_(
        num_dimensions, num_points, &random_table);

      // Form a Cartesian expansion global object.
      KernelAuxType kernel_aux;
      double bandwidth = core::math::Random(
                           0.05 * num_dimensions, 0.3 * num_dimensions);
      kernel_aux.Init(bandwidth, max_order, random_table.n_attributes());
      kernel_aux.global().Print();

      // Form a far-field expansion and evaluate.
      mlpack::series_expansion::CartesianFarField <
      KernelAuxType::ExpansionType > farfield;
      return true;
    }
};
}
}

BOOST_AUTO_TEST_SUITE(TestSuiteSeriesExpansion)
BOOST_AUTO_TEST_CASE(TestCaseSeriesExpansion) {

  // Tree type: hard-coded for a metric tree.
  typedef core::table::Table <
  core::tree::GenMetricTree<core::tree::AbstractStatistic> > TableType;

  // Call the tests.
  mlpack::series_expansion::SeriesExpansionTest <
  TableType, mlpack::series_expansion::GaussianKernelAux > gaussian_kernel_test;
  gaussian_kernel_test.StressTestMain();
  std::cout << "Passed the Gaussian kernel $O(D^p)$ test.\n";

  mlpack::series_expansion::SeriesExpansionTest <
  TableType, mlpack::series_expansion::GaussianKernelMultAux >
  gaussian_mult_kernel_test;
  gaussian_mult_kernel_test.StressTestMain();
  std::cout << "Passed the Gaussian kernel $O(p^D)$ test.\n";

  mlpack::series_expansion::SeriesExpansionTest <
  TableType, mlpack::series_expansion::EpanKernelAux > epan_kernel_test;
  epan_kernel_test.StressTestMain();
  std::cout << "Passed the Epanechnikov kernel $O(D^p)$ test.\n";

  std::cout << "All tests passed!\n";
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
 *  caosVM_agent.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Tue Jun 01 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  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.
 *
 */

#include "caosVM.h"
#include "openc2e.h"
#include "Agent.h"
#include "AgentRef.h"
#include "World.h"
#include <iostream>
using std::cerr;

/**
 ELAS (command) elas (integer)
 %status stub

 Sets the elasticity (in other words, bounciness) of the TARG agent.
*/
void caosVM::c_ELAS() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(elas)

	caos_assert(targ);
	targ->elas = elas;
}

/***
 ELAS (integer)
 %status maybe

 Returns the elasticity of the TARG agent.
*/
void caosVM::v_ELAS() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	result.setInt(targ->elas);
}

/**
 MVTO (command) x (float) y (float)
 %status maybe

 Places the TARG agent at the given x/y position in the world (using the upper left hand corner of the agent).
*/
void caosVM::c_MVTO() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)
	caos_assert(targ);
	targ->moveTo(x, y);
}

/**
 MVBY (command) x (float) y (float)
 %status maybe

 Changes the TARG agent's position by the given relative distances.
*/
void caosVM::c_MVBY() {
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)

	caos_assert(targ);
	targ->moveTo(targ->x + x, targ->y + y);
}

/**
 VELX (variable)
 %status maybe

 Returns the current horizontal velocity, in pixels/tick, of the TARG agent.
*/
void caosVM::v_VELX() {
	VM_VERIFY_SIZE(0)
	caos_assert(targ);
	vm->valueStack.push_back(&targ->velx);
}

/**
 VELY (variable)
 %status maybe

 Returns the current vertical velocity, in pixels/tick, of the TARG agent.
*/
void caosVM::v_VELY() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	vm->valueStack.push_back(&targ->vely);
}

/**
 OBST (float) direction (integer)
 %status maybe

 Returns the distance from the TARG agent to the nearest wall that it might collide with in the given direction.
 (except right now it just gives the direction to the nearest wall at world edge - fuzzie)
*/
void caosVM::v_OBST() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(direction) caos_assert(direction >= 0); caos_assert(direction <= 3);

	// TODO: fix 'might collide with' issue
	// note: this code is mostly copied from GRID - fuzzie

	// TODO: this code should calculate distance *from agent*, not *from centre point*, i expect
	// someone check with DS? - fuzzie

	caos_assert(targ);

	float agentx = targ->x + (targ->getWidth() / 2);
	float agenty = targ->y + (targ->getHeight() / 2);
/*	Room *sourceroom = world.map.roomAt(agentx, agenty);
	if (!sourceroom) {
		// (should we REALLY check for it being in the room system, here?)
		//cerr << targ->identify() << " tried using OBST but isn't in the room system!\n";
		result.setInt(-1);
		return;
	}*/

	int distance = 0;

	if ((direction == 0) || (direction == 1)) {
		int movement = (direction == 0 ? -1 : 1);
		if (direction == 0) agentx = targ->x;
		else agentx = targ->x + targ->getWidth();

		int x = agentx;
		Room *r = 0;
		while (true) {
			if (r) {
				if (!r->containsPoint(x, agenty))
					r = world.map.roomAt(x, agenty);
			} else {
				r = world.map.roomAt(x, agenty);
			}
			if (!r)
				break;
			x += movement;
			distance++;
		}
	} else if ((direction == 2) || (direction == 3)) {
		int movement = (direction == 2 ? -1 : 1);
		if (direction == 2) agenty = targ->y;
		else agenty = targ->y + targ->getHeight();

		int y = agenty;
		Room *r = 0;
		while (true) {
			if (r) {
				if (!r->containsPoint(agentx, y))
					r = world.map.roomAt(agentx, y);
			} else {
				r = world.map.roomAt(agentx, y);
			}
			if (!r)
				break;
			y += movement;
			distance++;
		}
	} else cerr << "OBST got an unknown direction!\n";

	result.setInt(distance);
}

/**
 TMVT (integer) x (float) y (float)
 %status maybe

 Returns 1 if the TARG agent could move to (x, y) and still be in room system, or 0 if otherwise.
*/
void caosVM::v_TMVT() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)

	caos_assert(targ);
	// TODO: do this properly
	Room *r1 = world.map.roomAt(x, y);
	Room *r2 = world.map.roomAt(x + (targ->getWidth() / 2), y + (targ->getHeight() / 2));
	result.setInt((r1 && r2) ? 1 : 0);
}

/**
 TMVF (integer) x (float) y (float)
 %status stub

 Returns 1 if the TARG Creature could move foot to (x, y) and still be in room system, or 0 if otherwise.
*/
void caosVM::v_TMVF() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)

	caos_assert(targ);
	result.setInt(1); // TODO: don't hardcode
}

/**
 ACCG (command) accel (float)
 %status maybe

 Sets the TARG agent's free-fall acceleration, in pixels/tick squared.
*/
void caosVM::c_ACCG() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_FLOAT(accel)

	caos_assert(targ);
	targ->accg = accel;
}

/**
 ACCG (float)
 %status maybe

 Returns the TARG agent's free-fall acceleration, in pixels/tick squared.
*/
void caosVM::v_ACCG() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	result.setFloat(targ->accg);
}

/**
 AERO (command) aero (float)
 %status maybe

 Sets the aerodynamics of the TARG agent to the given float value.
*/
void caosVM::c_AERO() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_FLOAT(aero)

	caos_assert(targ);
	targ->aero = aero;
}

/**
 AERO (float)
 %status maybe

 Returns the aerodynamics of the TARG agent.
*/
void caosVM::v_AERO() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	result.setFloat(targ->aero);
}

/**
 RELX (float) first (agent) second (agent)
 %status maybe

 Returns the relative horizontal distance between the centers of the two given agents.
*/
void caosVM::v_RELX() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_AGENT(second)
	VM_PARAM_AGENT(first)

	float one = first->x + (first->getWidth() / 2.0);
	float two = second->x + (second->getWidth() / 2.0);

	result.setFloat(two - one);
}

/**
 RELY (float) first (agent) second (agent)
 %status maybe

 Returns the relative vertical distance between the centers of the two given agents.
*/
void caosVM::v_RELY() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_AGENT(second)
	VM_PARAM_AGENT(first)

	float one = first->y + (first->getHeight() / 2.0);
	float two = second->y + (second->getHeight() / 2.0);

	result.setFloat(two - one);
}

/**
 VELO (command) xvel (float) yvel (float)
 %status maybe

 Sets the horizontal and vertical velocity of the TARG agent, in pixels/tick.
*/
void caosVM::c_VELO() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_FLOAT(vely)
	VM_PARAM_FLOAT(velx)

	caos_assert(targ);
	targ->velx.reset();
	targ->velx.setFloat(velx);
	targ->vely.reset();
	targ->vely.setFloat(vely);
}

/**
 MVSF (command) x (float) y (float)
 %status stub

 Move the target agent to an area inside the room system at about (x, y).
 This allows 'safe' moves.
*/
void caosVM::c_MVSF() {
	// TODO
	c_MVTO();
}

/**
 FRIC (float)
 %status maybe

 Returns the TARG agent's coefficient of friction as a percentage.
*/
void caosVM::v_FRIC() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	result.setFloat(targ->friction);
}

/**
 FRIC (command) friction (integer)
 %status maybe

 Sets the TARG agent's coefficient of friction, or the percentage of motion that will be lost as it slides on a
 surface.
*/
void caosVM::c_FRIC() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(friction) caos_assert(friction >= 0); caos_assert(friction <= 100);

	caos_assert(targ);
	targ->friction = friction;
}

/**
 FALL (integer)
 %status stub

 Returns 1 if the TARG agent is moving due to gravity, or 0 if otherwise.
*/
void caosVM::v_FALL() {
	VM_VERIFY_SIZE(0)
	caos_assert(targ);

	// XXX: this probably isn't quite correct, but it's close enough for now.
	if (targ->falling)
		result.setInt(1);
	else
		result.setInt(0);
}

/**
 MOVS (integer)
 %status stub

 Returns an integer representing the motion status of the TARG agent.  0 is autonomous, 1 is moving by mouse, 2 is
 floating, 3 is inside a vehicle, and 4 is being carried.
*/
void caosVM::v_MOVS() {
	caos_assert(targ);

	result.setInt(0); // TODO
}

/**
 FLTO (command) x (float) y (float)
 %status maybe

 Sets the TARG agent to float its top-left corner (x, y) away from the top-left corner of the FREL agent.
*/
void caosVM::c_FLTO() {
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)

	caos_assert(targ)
	targ->floatTo(x, y);
}

/**
 FREL (command) agent (agent)
 %status maybe

 Sets the agent the TARG agent floats relative to. You must set the 'floatable' attribute for this to work.
 The default is NULL, which means the target agent floats relative to the main camera.
*/
void caosVM::c_FREL() {
	VM_PARAM_AGENT(agent)

	caos_assert(targ)
	targ->floatTo(agent);
}

/**
 FLTX (float)
 %status maybe

 Returns the x value of the TARG agent's floating vector.
*/
void caosVM::v_FLTX() {
	caos_assert(targ);

	if (targ->floatingagent)
		result.setFloat(targ->floatingagent->x - targ->x);
	else
		result.setFloat(world.camera.getX() - targ->x);
}

/**
 FLTY (float)
 %status maybe

 Returns the y value of the TARG agent's floating vector.
*/
void caosVM::v_FLTY() {
	caos_assert(targ);

	if (targ->floatingagent)
		result.setFloat(targ->floatingagent->x - targ->x);
	else
		result.setFloat(world.camera.getX() - targ->x);
}

/* vim: set noet: */
<commit_msg>add hacky MVSF implementation (only works for simplest case)<commit_after>/*
 *  caosVM_agent.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Tue Jun 01 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  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.
 *
 */

#include "caosVM.h"
#include "openc2e.h"
#include "Agent.h"
#include "AgentRef.h"
#include "World.h"
#include <iostream>
using std::cerr;

/**
 ELAS (command) elas (integer)
 %status stub

 Sets the elasticity (in other words, bounciness) of the TARG agent.
*/
void caosVM::c_ELAS() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(elas)

	caos_assert(targ);
	targ->elas = elas;
}

/***
 ELAS (integer)
 %status maybe

 Returns the elasticity of the TARG agent.
*/
void caosVM::v_ELAS() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	result.setInt(targ->elas);
}

/**
 MVTO (command) x (float) y (float)
 %status maybe

 Places the TARG agent at the given x/y position in the world (using the upper left hand corner of the agent).
*/
void caosVM::c_MVTO() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)
	caos_assert(targ);
	targ->moveTo(x, y);
}

/**
 MVBY (command) x (float) y (float)
 %status maybe

 Changes the TARG agent's position by the given relative distances.
*/
void caosVM::c_MVBY() {
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)

	caos_assert(targ);
	targ->moveTo(targ->x + x, targ->y + y);
}

/**
 VELX (variable)
 %status maybe

 Returns the current horizontal velocity, in pixels/tick, of the TARG agent.
*/
void caosVM::v_VELX() {
	VM_VERIFY_SIZE(0)
	caos_assert(targ);
	vm->valueStack.push_back(&targ->velx);
}

/**
 VELY (variable)
 %status maybe

 Returns the current vertical velocity, in pixels/tick, of the TARG agent.
*/
void caosVM::v_VELY() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	vm->valueStack.push_back(&targ->vely);
}

/**
 OBST (float) direction (integer)
 %status maybe

 Returns the distance from the TARG agent to the nearest wall that it might collide with in the given direction.
 (except right now it just gives the direction to the nearest wall at world edge - fuzzie)
*/
void caosVM::v_OBST() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(direction) caos_assert(direction >= 0); caos_assert(direction <= 3);

	// TODO: fix 'might collide with' issue
	// note: this code is mostly copied from GRID - fuzzie

	// TODO: this code should calculate distance *from agent*, not *from centre point*, i expect
	// someone check with DS? - fuzzie

	caos_assert(targ);

	float agentx = targ->x + (targ->getWidth() / 2);
	float agenty = targ->y + (targ->getHeight() / 2);
/*	Room *sourceroom = world.map.roomAt(agentx, agenty);
	if (!sourceroom) {
		// (should we REALLY check for it being in the room system, here?)
		//cerr << targ->identify() << " tried using OBST but isn't in the room system!\n";
		result.setInt(-1);
		return;
	}*/

	int distance = 0;

	if ((direction == 0) || (direction == 1)) {
		int movement = (direction == 0 ? -1 : 1);
		if (direction == 0) agentx = targ->x;
		else agentx = targ->x + targ->getWidth();

		int x = agentx;
		Room *r = 0;
		while (true) {
			if (r) {
				if (!r->containsPoint(x, agenty))
					r = world.map.roomAt(x, agenty);
			} else {
				r = world.map.roomAt(x, agenty);
			}
			if (!r)
				break;
			x += movement;
			distance++;
		}
	} else if ((direction == 2) || (direction == 3)) {
		int movement = (direction == 2 ? -1 : 1);
		if (direction == 2) agenty = targ->y;
		else agenty = targ->y + targ->getHeight();

		int y = agenty;
		Room *r = 0;
		while (true) {
			if (r) {
				if (!r->containsPoint(agentx, y))
					r = world.map.roomAt(agentx, y);
			} else {
				r = world.map.roomAt(agentx, y);
			}
			if (!r)
				break;
			y += movement;
			distance++;
		}
	} else cerr << "OBST got an unknown direction!\n";

	result.setInt(distance);
}

/**
 TMVT (integer) x (float) y (float)
 %status maybe

 Returns 1 if the TARG agent could move to (x, y) and still be in room system, or 0 if otherwise.
*/
void caosVM::v_TMVT() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)

	caos_assert(targ);
	// TODO: do this properly
	Room *r1 = world.map.roomAt(x, y);
	Room *r2 = world.map.roomAt(x + (targ->getWidth() / 2), y + (targ->getHeight() / 2));
	result.setInt((r1 && r2) ? 1 : 0);
}

/**
 TMVF (integer) x (float) y (float)
 %status stub

 Returns 1 if the TARG Creature could move foot to (x, y) and still be in room system, or 0 if otherwise.
*/
void caosVM::v_TMVF() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)

	caos_assert(targ);
	result.setInt(1); // TODO: don't hardcode
}

/**
 ACCG (command) accel (float)
 %status maybe

 Sets the TARG agent's free-fall acceleration, in pixels/tick squared.
*/
void caosVM::c_ACCG() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_FLOAT(accel)

	caos_assert(targ);
	targ->accg = accel;
}

/**
 ACCG (float)
 %status maybe

 Returns the TARG agent's free-fall acceleration, in pixels/tick squared.
*/
void caosVM::v_ACCG() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	result.setFloat(targ->accg);
}

/**
 AERO (command) aero (float)
 %status maybe

 Sets the aerodynamics of the TARG agent to the given float value.
*/
void caosVM::c_AERO() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_FLOAT(aero)

	caos_assert(targ);
	targ->aero = aero;
}

/**
 AERO (float)
 %status maybe

 Returns the aerodynamics of the TARG agent.
*/
void caosVM::v_AERO() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	result.setFloat(targ->aero);
}

/**
 RELX (float) first (agent) second (agent)
 %status maybe

 Returns the relative horizontal distance between the centers of the two given agents.
*/
void caosVM::v_RELX() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_AGENT(second)
	VM_PARAM_AGENT(first)

	float one = first->x + (first->getWidth() / 2.0);
	float two = second->x + (second->getWidth() / 2.0);

	result.setFloat(two - one);
}

/**
 RELY (float) first (agent) second (agent)
 %status maybe

 Returns the relative vertical distance between the centers of the two given agents.
*/
void caosVM::v_RELY() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_AGENT(second)
	VM_PARAM_AGENT(first)

	float one = first->y + (first->getHeight() / 2.0);
	float two = second->y + (second->getHeight() / 2.0);

	result.setFloat(two - one);
}

/**
 VELO (command) xvel (float) yvel (float)
 %status maybe

 Sets the horizontal and vertical velocity of the TARG agent, in pixels/tick.
*/
void caosVM::c_VELO() {
	VM_VERIFY_SIZE(2)
	VM_PARAM_FLOAT(vely)
	VM_PARAM_FLOAT(velx)

	caos_assert(targ);
	targ->velx.reset();
	targ->velx.setFloat(velx);
	targ->vely.reset();
	targ->vely.setFloat(vely);
}

/**
 MVSF (command) x (float) y (float)
 %status maybe

 Move the target agent to an area inside the room system at about (x, y).
 This allows 'safe' moves.
*/
void caosVM::c_MVSF() {
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)
	caos_assert(targ);

	// TODO: this is a silly hack, to cater for simplest case (where we just need to nudge the agent up a bit)
	unsigned int tries = 0;
	while (tries < 150) {
		Room *r1 = world.map.roomAt(x + (targ->getWidth() / 2), y - tries);
		Room *r2 = world.map.roomAt(x + (targ->getWidth() / 2), y + targ->getHeight() - tries);
		if (r1 && r2) {
			// if they're in the same room, we're fine, otherwise, make sure they're at least connected
			// (hacky, but who cares, given the whole thing is a hack)
			if (r1 == r2 || r1->doors.find(r2) != r1->doors.end()) {
				targ->moveTo(x, y - tries);
				return;
			}
		}
		tries++;
	}
	caos_assert(false); // boom, we failed to move somewhere safe
}

/**
 FRIC (float)
 %status maybe

 Returns the TARG agent's coefficient of friction as a percentage.
*/
void caosVM::v_FRIC() {
	VM_VERIFY_SIZE(0)

	caos_assert(targ);
	result.setFloat(targ->friction);
}

/**
 FRIC (command) friction (integer)
 %status maybe

 Sets the TARG agent's coefficient of friction, or the percentage of motion that will be lost as it slides on a
 surface.
*/
void caosVM::c_FRIC() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(friction) caos_assert(friction >= 0); caos_assert(friction <= 100);

	caos_assert(targ);
	targ->friction = friction;
}

/**
 FALL (integer)
 %status stub

 Returns 1 if the TARG agent is moving due to gravity, or 0 if otherwise.
*/
void caosVM::v_FALL() {
	VM_VERIFY_SIZE(0)
	caos_assert(targ);

	// XXX: this probably isn't quite correct, but it's close enough for now.
	if (targ->falling)
		result.setInt(1);
	else
		result.setInt(0);
}

/**
 MOVS (integer)
 %status stub

 Returns an integer representing the motion status of the TARG agent.  0 is autonomous, 1 is moving by mouse, 2 is
 floating, 3 is inside a vehicle, and 4 is being carried.
*/
void caosVM::v_MOVS() {
	caos_assert(targ);

	result.setInt(0); // TODO
}

/**
 FLTO (command) x (float) y (float)
 %status maybe

 Sets the TARG agent to float its top-left corner (x, y) away from the top-left corner of the FREL agent.
*/
void caosVM::c_FLTO() {
	VM_PARAM_FLOAT(y)
	VM_PARAM_FLOAT(x)

	caos_assert(targ)
	targ->floatTo(x, y);
}

/**
 FREL (command) agent (agent)
 %status maybe

 Sets the agent the TARG agent floats relative to. You must set the 'floatable' attribute for this to work.
 The default is NULL, which means the target agent floats relative to the main camera.
*/
void caosVM::c_FREL() {
	VM_PARAM_AGENT(agent)

	caos_assert(targ)
	targ->floatTo(agent);
}

/**
 FLTX (float)
 %status maybe

 Returns the x value of the TARG agent's floating vector.
*/
void caosVM::v_FLTX() {
	caos_assert(targ);

	if (targ->floatingagent)
		result.setFloat(targ->floatingagent->x - targ->x);
	else
		result.setFloat(world.camera.getX() - targ->x);
}

/**
 FLTY (float)
 %status maybe

 Returns the y value of the TARG agent's floating vector.
*/
void caosVM::v_FLTY() {
	caos_assert(targ);

	if (targ->floatingagent)
		result.setFloat(targ->floatingagent->x - targ->x);
	else
		result.setFloat(world.camera.getX() - targ->x);
}

/* vim: set noet: */
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "google/fhir/stu3/util.h"

#include <iterator>
#include <string>

#include "google/protobuf/descriptor.pb.h"
#include "google/protobuf/reflection.h"
#include "absl/strings/str_cat.h"
#include "google/fhir/status/status.h"
#include "google/fhir/status/statusor.h"
#include "google/fhir/systems/systems.h"
#include "proto/stu3/annotations.pb.h"
#include "proto/stu3/datatypes.pb.h"
#include "proto/stu3/resources.pb.h"
#include "tensorflow/core/lib/core/errors.h"

namespace google {
namespace fhir {
namespace stu3 {

using ::google::fhir::stu3::proto::ContainedResource;
using ::google::protobuf::Message;

using std::string;
StatusOr<string> ExtractCodeBySystem(
    const stu3::proto::CodeableConcept& codeable_concept,
    absl::string_view system_value) {
  for (int i = 0; i < codeable_concept.coding_size(); i++) {
    auto coding = codeable_concept.coding(i);
    if (coding.has_system() && coding.has_code() &&
        coding.system().value() == system_value) {
      return coding.code().value();
    }
  }

  return ::tensorflow::errors::NotFound(
      "Cannot find a value for the corresponding system code.");
}

StatusOr<string> ExtractIcdCode(
    const stu3::proto::CodeableConcept& codeable_concept,
    const std::vector<string>& schemes) {
  bool found_response = false;
  StatusOr<string> result;
  for (int i = 0; i < schemes.size(); i++) {
    StatusOr<string> s = ExtractCodeBySystem(codeable_concept, schemes[i]);

    if (s.status().code() == ::tensorflow::errors::Code::ALREADY_EXISTS) {
      // Multiple codes, so we can return an error already.
      return s;
    } else if (s.ok()) {
      if (found_response) {
        // We found _another_ code. That shouldn't have happened.
        return ::tensorflow::errors::AlreadyExists("Found more than one code");
      } else {
        result = s;
        found_response = true;
      }
    }
  }
  if (found_response) {
    return result;
  } else {
    return ::tensorflow::errors::NotFound(
        "No ICD code with the provided schemes in concept.");
  }
}

Status SetContainedResource(const Message& resource,
                            ContainedResource* contained) {
  const google::protobuf::OneofDescriptor* resource_oneof =
      ContainedResource::descriptor()->FindOneofByName("oneof_resource");
  const google::protobuf::FieldDescriptor* resource_field = nullptr;
  for (int i = 0; i < resource_oneof->field_count(); i++) {
    const google::protobuf::FieldDescriptor* field = resource_oneof->field(i);
    if (field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
      return ::tensorflow::errors::InvalidArgument(
          absl::StrCat("Field ", field->full_name(), "is not a message"));
    }
    if (field->message_type()->name() == resource.GetDescriptor()->name()) {
      resource_field = field;
    }
  }
  if (resource_field == nullptr) {
    return ::tensorflow::errors::InvalidArgument(
        absl::StrCat("Resource type ", resource.GetDescriptor()->name(),
                     " not found in fhir::Bundle::Entry::resource"));
  }
  const google::protobuf::Reflection* ref = contained->GetReflection();
  ref->MutableMessage(contained, resource_field)->CopyFrom(resource);
  return Status::OK();
}

StatusOr<ContainedResource> WrapContainedResource(const Message& resource) {
  ContainedResource contained_resource;
  TF_RETURN_IF_ERROR(SetContainedResource(resource, &contained_resource));
  return contained_resource;
}

}  // namespace stu3
}  // namespace fhir
}  // namespace google
<commit_msg>Fix the build warning: comparison between signed and unsigned integer expressions.<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "google/fhir/stu3/util.h"

#include <iterator>
#include <string>

#include "google/protobuf/descriptor.pb.h"
#include "google/protobuf/reflection.h"
#include "absl/strings/str_cat.h"
#include "google/fhir/status/status.h"
#include "google/fhir/status/statusor.h"
#include "google/fhir/systems/systems.h"
#include "proto/stu3/annotations.pb.h"
#include "proto/stu3/datatypes.pb.h"
#include "proto/stu3/resources.pb.h"
#include "tensorflow/core/lib/core/errors.h"

namespace google {
namespace fhir {
namespace stu3 {

using ::google::fhir::stu3::proto::ContainedResource;
using ::google::protobuf::Message;

using std::string;
StatusOr<string> ExtractCodeBySystem(
    const stu3::proto::CodeableConcept& codeable_concept,
    absl::string_view system_value) {
  for (int i = 0; i < codeable_concept.coding_size(); i++) {
    auto coding = codeable_concept.coding(i);
    if (coding.has_system() && coding.has_code() &&
        coding.system().value() == system_value) {
      return coding.code().value();
    }
  }

  return ::tensorflow::errors::NotFound(
      "Cannot find a value for the corresponding system code.");
}

StatusOr<string> ExtractIcdCode(
    const stu3::proto::CodeableConcept& codeable_concept,
    const std::vector<string>& schemes) {
  bool found_response = false;
  StatusOr<string> result;
  for (size_t i = 0; i < schemes.size(); i++) {
    StatusOr<string> s = ExtractCodeBySystem(codeable_concept, schemes[i]);

    if (s.status().code() == ::tensorflow::errors::Code::ALREADY_EXISTS) {
      // Multiple codes, so we can return an error already.
      return s;
    } else if (s.ok()) {
      if (found_response) {
        // We found _another_ code. That shouldn't have happened.
        return ::tensorflow::errors::AlreadyExists("Found more than one code");
      } else {
        result = s;
        found_response = true;
      }
    }
  }
  if (found_response) {
    return result;
  } else {
    return ::tensorflow::errors::NotFound(
        "No ICD code with the provided schemes in concept.");
  }
}

Status SetContainedResource(const Message& resource,
                            ContainedResource* contained) {
  const google::protobuf::OneofDescriptor* resource_oneof =
      ContainedResource::descriptor()->FindOneofByName("oneof_resource");
  const google::protobuf::FieldDescriptor* resource_field = nullptr;
  for (int i = 0; i < resource_oneof->field_count(); i++) {
    const google::protobuf::FieldDescriptor* field = resource_oneof->field(i);
    if (field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
      return ::tensorflow::errors::InvalidArgument(
          absl::StrCat("Field ", field->full_name(), "is not a message"));
    }
    if (field->message_type()->name() == resource.GetDescriptor()->name()) {
      resource_field = field;
    }
  }
  if (resource_field == nullptr) {
    return ::tensorflow::errors::InvalidArgument(
        absl::StrCat("Resource type ", resource.GetDescriptor()->name(),
                     " not found in fhir::Bundle::Entry::resource"));
  }
  const google::protobuf::Reflection* ref = contained->GetReflection();
  ref->MutableMessage(contained, resource_field)->CopyFrom(resource);
  return Status::OK();
}

StatusOr<ContainedResource> WrapContainedResource(const Message& resource) {
  ContainedResource contained_resource;
  TF_RETURN_IF_ERROR(SetContainedResource(resource, &contained_resource));
  return contained_resource;
}

}  // namespace stu3
}  // namespace fhir
}  // namespace google
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <optional>

// constexpr T* optional<T>::operator->();

#ifdef _LIBCPP_DEBUG
#define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0))
#endif

#include <experimental/optional>
#include <type_traits>
#include <cassert>

#if _LIBCPP_STD_VER > 11

using std::experimental::optional;

struct X
{
    constexpr int test() {return 3;}
};

#endif  // _LIBCPP_STD_VER > 11

int main()
{
#if _LIBCPP_STD_VER > 11
    {
        constexpr optional<X> opt(X{});
        static_assert(opt->test() == 3, "");
    }
#ifdef _LIBCPP_DEBUG
    {
        optional<X> opt;
        assert(opt->test() == 3);
        assert(false);
    }
#endif  // _LIBCPP_DEBUG
#endif  // _LIBCPP_STD_VER > 11
}
<commit_msg>Appease the c++14 buildbots<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <optional>

// constexpr T* optional<T>::operator->();

#ifdef _LIBCPP_DEBUG
#define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0))
#endif

#include <experimental/optional>
#include <type_traits>
#include <cassert>

#if _LIBCPP_STD_VER > 11

using std::experimental::optional;

struct X
{
#if _LIBCPP_STD_VER > 14
    constexpr int test() const {return 3;}
#else
    constexpr int test() {return 3;}
#endif
};

#endif  // _LIBCPP_STD_VER > 11

int main()
{
#if _LIBCPP_STD_VER > 11
    {
        constexpr optional<X> opt(X{});
        static_assert(opt->test() == 3, "");
    }
#ifdef _LIBCPP_DEBUG
    {
        optional<X> opt;
        assert(opt->test() == 3);
        assert(false);
    }
#endif  // _LIBCPP_DEBUG
#endif  // _LIBCPP_STD_VER > 11
}
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2020 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using namespace repo::manipulator::modelconvertor;

TEST(RepoModelImport, ImportModel)
{
	// EXPECT_TRUE(true);
	// EXPECT_EQ(0, 0);
	// ASSERT_TRUE(true);
}<commit_msg>ISSUE #391 Updating the unit test to generate scene<commit_after>/**
*  Copyright (C) 2020 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <gtest/gtest.h>

#include <repo\manipulator\modelconvertor\import\repo_model_import_3drepo.h>
#include <repo\lib\repo_log.h>

using namespace repo::manipulator::modelconvertor;

TEST(RepoModelImport, ImportModel)
{
	ModelImportConfig config;

	auto modelConvertor = std::shared_ptr<AbstractModelImport>(new RepoModelImport(config));

	uint8_t errCode = 0;

	std::string filePath = R"(C:\Users\haroo\Desktop\BIMTextureFiles\cube_bim2.bim)";

	modelConvertor->importModel(filePath, errCode);

	repoInfo << "Error code from importModel(): " << errCode <<std::endl;

	auto repoScene = modelConvertor->generateRepoScene(errCode);

	repoInfo << "Error code from generateRepoScene(): " << errCode << std::endl;

	EXPECT_EQ(0,errCode);
}<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS smarttags (1.36.130); FILE MERGED 2006/12/21 10:43:03 jakob_lechner 1.36.130.1: #i72705#: support for smarttags<commit_after><|endoftext|>


<commit_before>#if defined(__MINGW32__) || defined(_MSC_VER)
#include <stdio.h>
// MSAN isn't supported for any Windows variant
int main(int argc, char **argv) {
    printf("Skipping test on Windows\n");
    return 0;
}
#else
#include "HalideRuntime.h"
#include "HalideBuffer.h"

#include <iostream>
#include <limits>
#include <type_traits>
#include <vector>

#include "msan.h"

using namespace std;
using namespace Halide::Runtime;

// Just copies in -> out.
extern "C" int msan_extern_stage(halide_buffer_t *in, halide_buffer_t *out) {
    if (in->host == nullptr) {
        in->dim[0].extent = 4;
        in->dim[1].extent = 4;
        in->dim[2].extent = 3;
        in->dim[0].min = 0;
        in->dim[1].min = 0;
        in->dim[2].min = 0;
        return 0;
    }
    if (!out->host) {
        fprintf(stderr, "msan_extern_stage failure\n");
        return -1;
    }
    if (in->type != out->type) {
        return -1;
    }
    Buffer<int32_t>(*out).copy_from(Buffer<int32_t>(*in));
    out->set_host_dirty();
    return 0;
}

extern "C" void halide_error(void *user_context, const char *msg) {
    fprintf(stderr, "Saw error: %s\n", msg);
    // Do not exit.
}

// Must provide a stub for this since we aren't compiling with LLVM MSAN
// enabled, and the default implementation of halide_msan_annotate_memory_is_initialized()
// expects this to be present
extern "C" void AnnotateMemoryIsInitialized(const char *file, int line,
                                            const void *mem, size_t size) {
    fprintf(stderr, "Impossible\n");
    exit(-1);
}

enum {
  expect_bounds_inference_buffer,
  expect_intermediate_buffer,
  expect_intermediate_shape,
  expect_output_buffer,
  expect_output_shape,
  expect_intermediate_contents,
  expect_output_contents,
} annotate_stage = expect_bounds_inference_buffer;
const void* output_base = nullptr;
const void* output_previous = nullptr;
int bounds_inference_count = 0;
bool expect_error = false;

void reset_state(const void* base) {
    annotate_stage = expect_bounds_inference_buffer;
    output_base = base;
    output_previous = nullptr;
    bounds_inference_count = 0;
    expect_error = false;
}

extern "C" void halide_msan_annotate_memory_is_initialized(void *user_context, const void *ptr, uint64_t len) {
    printf("%d:%p:%08x\n", (int)annotate_stage, ptr, (unsigned int) len);
    if (annotate_stage == expect_bounds_inference_buffer) {
        if (output_previous != nullptr || len != sizeof(halide_buffer_t)) {
            fprintf(stderr, "Failure: Expected sizeof(halide_buffer_t), saw %d\n", (unsigned int) len);
            exit(-1);
        }
        bounds_inference_count += 1;
        if (bounds_inference_count == 4) {
            annotate_stage = expect_intermediate_buffer;
        }
    } else if (annotate_stage == expect_intermediate_buffer) {
        if (expect_error) {
            if (len != 87) {
                fprintf(stderr, "Failure: Expected error message of len=87, saw %d bytes\n", (unsigned int) len);
                exit(-1);
            }
            return;  // stay in this state
        }
        if (output_previous != nullptr || len != sizeof(halide_buffer_t)) {
            fprintf(stderr, "Failure: Expected sizeof(halide_buffer_t), saw %d\n", (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_intermediate_shape;
    } else if (annotate_stage == expect_intermediate_shape) {
        if (output_previous != nullptr || len != sizeof(halide_dimension_t) * 3) {
            fprintf(stderr, "Failure: Expected sizeof(halide_dimension_t) * 3, saw %d\n", (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_output_buffer;
    } else if (annotate_stage == expect_output_buffer) {
        if (output_previous != nullptr || len != sizeof(halide_buffer_t)) {
            fprintf(stderr, "Failure: Expected sizeof(halide_buffer_t), saw %d\n", (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_output_shape;
    } else if (annotate_stage == expect_output_shape) {
        if (output_previous != nullptr || len != sizeof(halide_dimension_t) * 3) {
            fprintf(stderr, "Failure: Expected sizeof(halide_dimension_t) * 3, saw %d\n", (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_intermediate_contents;
    } else if (annotate_stage == expect_intermediate_contents) {
        if (output_previous != nullptr || len != 4 * 4 * 3 * 4) {
            fprintf(stderr, "Failure: Expected %d, saw %d\n", 4 * 4 * 3 * 4, (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_output_contents;
    } else if (annotate_stage == expect_output_contents) {
        if (output_previous == nullptr) {
            if (ptr != output_base) {
                fprintf(stderr, "Failure: Expected base p %p but saw %p\n", output_base, ptr);
                exit(-1);
            }
            if (ptr <= output_previous) {
                fprintf(stderr, "Failure: Expected monotonic increase but saw %p -> %p\n", output_previous, ptr);
                exit(-1);
            }
            output_previous = ptr;
        }
    } else {
        fprintf(stderr, "Failure: bad enum\n");
        exit(-1);
    }
}

template<typename T>
void verify(const T &image) {
    image.for_each_element([&](int x, int y, int c) {
        int expected = 3;
        for (int i = 0; i < 4; ++i) {
            expected += (int32_t)(i + y + c);
        }
        int actual = image(x, y, c);
        if (actual != expected) {
            fprintf(stderr, "Failure @ %d %d %d: expected %d, got %d\n", x, y, c, expected, actual);
            exit(-1);
        }
    });
}

//-----------------------------------------------------------------------------

int main()
{
    printf("Testing interleaved...\n");
    {
        auto out = Buffer<int32_t>::make_interleaved(4, 4, 3);
        reset_state(out.data());
        if (msan(out) != 0) {
            fprintf(stderr, "Failure!\n");
            exit(-1);
        }
        verify(out);
        if (output_previous == nullptr) {
            fprintf(stderr, "Failure: Expected to see annotations.\n");
            exit(-1);
        }
    }

    printf("Testing sparse chunky...\n");
    {
        const int kPad = 1;
        halide_dimension_t shape[3] = {
            { 0, 4, 3 },
            { 0, 4, (4 * 3) + kPad },
            { 0, 3, 1 },
        };
        std::vector<int32_t> data(((4 * 3) + kPad) * 4);
        auto out = Buffer<int32_t>(data.data(), 3, shape);
        reset_state(out.data());
        if (msan(out) != 0) {
            fprintf(stderr, "Failure!\n");
            exit(-1);
        }
        if (output_previous == nullptr) {
            fprintf(stderr, "Failure: Expected to see annotations.\n");
            exit(-1);
        }
    }

    printf("Testing planar...\n");
    {
        auto out = Buffer<int32_t>(4, 4, 3);
        reset_state(out.data());
        if (msan(out) != 0) {
            fprintf(stderr, "Failure!\n");
            exit(-1);
        }
        if (output_previous == nullptr) {
            fprintf(stderr, "Failure: Expected to see annotations.\n");
            exit(-1);
        }
    }

    printf("Testing sparse planar...\n");
    {
        const int kPad = 1;
        halide_dimension_t shape[3] = {
            { 0, 4, 1 },
            { 0, 4, 4 + kPad },
            { 0, 3, (4 + kPad) * 4 },
        };
        std::vector<int32_t> data((4 + kPad) * 4 * 3);
        auto out = Buffer<int32_t>(data.data(), 3, shape);
        reset_state(out.data());
        if (msan(out) != 0) {
            fprintf(stderr, "Failure!\n");
            exit(-1);
        }
        if (output_previous == nullptr) {
            fprintf(stderr, "Failure: Expected to see annotations.\n");
            exit(-1);
        }
    }
    // Buffers should not be marked as "initialized" if the filter fails with an error.
    printf("Testing error case...\n");
    {
        auto out = Buffer<int32_t>(1, 1, 1);
        reset_state(out.data());
        expect_error = true;
        if (msan(out) == 0) {
            fprintf(stderr, "Failure (expected failure but did not)!\n");
            exit(-1);
        }
        if (output_previous != nullptr) {
            fprintf(stderr, "Failure: Expected NOT to see annotations.\n");
            exit(-1);
        }
    }

    printf("Success!\n");
    return 0;
}

#endif
<commit_msg>use #ifdef _WIN32 for Windows check<commit_after>#ifdef _WIN32
#include <stdio.h>
// MSAN isn't supported for any Windows variant
int main(int argc, char **argv) {
    printf("Skipping test on Windows\n");
    return 0;
}
#else
#include "HalideRuntime.h"
#include "HalideBuffer.h"

#include <iostream>
#include <limits>
#include <type_traits>
#include <vector>

#include "msan.h"

using namespace std;
using namespace Halide::Runtime;

// Just copies in -> out.
extern "C" int msan_extern_stage(halide_buffer_t *in, halide_buffer_t *out) {
    if (in->host == nullptr) {
        in->dim[0].extent = 4;
        in->dim[1].extent = 4;
        in->dim[2].extent = 3;
        in->dim[0].min = 0;
        in->dim[1].min = 0;
        in->dim[2].min = 0;
        return 0;
    }
    if (!out->host) {
        fprintf(stderr, "msan_extern_stage failure\n");
        return -1;
    }
    if (in->type != out->type) {
        return -1;
    }
    Buffer<int32_t>(*out).copy_from(Buffer<int32_t>(*in));
    out->set_host_dirty();
    return 0;
}

extern "C" void halide_error(void *user_context, const char *msg) {
    fprintf(stderr, "Saw error: %s\n", msg);
    // Do not exit.
}

// Must provide a stub for this since we aren't compiling with LLVM MSAN
// enabled, and the default implementation of halide_msan_annotate_memory_is_initialized()
// expects this to be present
extern "C" void AnnotateMemoryIsInitialized(const char *file, int line,
                                            const void *mem, size_t size) {
    fprintf(stderr, "Impossible\n");
    exit(-1);
}

enum {
  expect_bounds_inference_buffer,
  expect_intermediate_buffer,
  expect_intermediate_shape,
  expect_output_buffer,
  expect_output_shape,
  expect_intermediate_contents,
  expect_output_contents,
} annotate_stage = expect_bounds_inference_buffer;
const void* output_base = nullptr;
const void* output_previous = nullptr;
int bounds_inference_count = 0;
bool expect_error = false;

void reset_state(const void* base) {
    annotate_stage = expect_bounds_inference_buffer;
    output_base = base;
    output_previous = nullptr;
    bounds_inference_count = 0;
    expect_error = false;
}

extern "C" void halide_msan_annotate_memory_is_initialized(void *user_context, const void *ptr, uint64_t len) {
    printf("%d:%p:%08x\n", (int)annotate_stage, ptr, (unsigned int) len);
    if (annotate_stage == expect_bounds_inference_buffer) {
        if (output_previous != nullptr || len != sizeof(halide_buffer_t)) {
            fprintf(stderr, "Failure: Expected sizeof(halide_buffer_t), saw %d\n", (unsigned int) len);
            exit(-1);
        }
        bounds_inference_count += 1;
        if (bounds_inference_count == 4) {
            annotate_stage = expect_intermediate_buffer;
        }
    } else if (annotate_stage == expect_intermediate_buffer) {
        if (expect_error) {
            if (len != 87) {
                fprintf(stderr, "Failure: Expected error message of len=87, saw %d bytes\n", (unsigned int) len);
                exit(-1);
            }
            return;  // stay in this state
        }
        if (output_previous != nullptr || len != sizeof(halide_buffer_t)) {
            fprintf(stderr, "Failure: Expected sizeof(halide_buffer_t), saw %d\n", (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_intermediate_shape;
    } else if (annotate_stage == expect_intermediate_shape) {
        if (output_previous != nullptr || len != sizeof(halide_dimension_t) * 3) {
            fprintf(stderr, "Failure: Expected sizeof(halide_dimension_t) * 3, saw %d\n", (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_output_buffer;
    } else if (annotate_stage == expect_output_buffer) {
        if (output_previous != nullptr || len != sizeof(halide_buffer_t)) {
            fprintf(stderr, "Failure: Expected sizeof(halide_buffer_t), saw %d\n", (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_output_shape;
    } else if (annotate_stage == expect_output_shape) {
        if (output_previous != nullptr || len != sizeof(halide_dimension_t) * 3) {
            fprintf(stderr, "Failure: Expected sizeof(halide_dimension_t) * 3, saw %d\n", (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_intermediate_contents;
    } else if (annotate_stage == expect_intermediate_contents) {
        if (output_previous != nullptr || len != 4 * 4 * 3 * 4) {
            fprintf(stderr, "Failure: Expected %d, saw %d\n", 4 * 4 * 3 * 4, (unsigned int) len);
            exit(-1);
        }
        annotate_stage = expect_output_contents;
    } else if (annotate_stage == expect_output_contents) {
        if (output_previous == nullptr) {
            if (ptr != output_base) {
                fprintf(stderr, "Failure: Expected base p %p but saw %p\n", output_base, ptr);
                exit(-1);
            }
            if (ptr <= output_previous) {
                fprintf(stderr, "Failure: Expected monotonic increase but saw %p -> %p\n", output_previous, ptr);
                exit(-1);
            }
            output_previous = ptr;
        }
    } else {
        fprintf(stderr, "Failure: bad enum\n");
        exit(-1);
    }
}

template<typename T>
void verify(const T &image) {
    image.for_each_element([&](int x, int y, int c) {
        int expected = 3;
        for (int i = 0; i < 4; ++i) {
            expected += (int32_t)(i + y + c);
        }
        int actual = image(x, y, c);
        if (actual != expected) {
            fprintf(stderr, "Failure @ %d %d %d: expected %d, got %d\n", x, y, c, expected, actual);
            exit(-1);
        }
    });
}

//-----------------------------------------------------------------------------

int main()
{
    printf("Testing interleaved...\n");
    {
        auto out = Buffer<int32_t>::make_interleaved(4, 4, 3);
        reset_state(out.data());
        if (msan(out) != 0) {
            fprintf(stderr, "Failure!\n");
            exit(-1);
        }
        verify(out);
        if (output_previous == nullptr) {
            fprintf(stderr, "Failure: Expected to see annotations.\n");
            exit(-1);
        }
    }

    printf("Testing sparse chunky...\n");
    {
        const int kPad = 1;
        halide_dimension_t shape[3] = {
            { 0, 4, 3 },
            { 0, 4, (4 * 3) + kPad },
            { 0, 3, 1 },
        };
        std::vector<int32_t> data(((4 * 3) + kPad) * 4);
        auto out = Buffer<int32_t>(data.data(), 3, shape);
        reset_state(out.data());
        if (msan(out) != 0) {
            fprintf(stderr, "Failure!\n");
            exit(-1);
        }
        if (output_previous == nullptr) {
            fprintf(stderr, "Failure: Expected to see annotations.\n");
            exit(-1);
        }
    }

    printf("Testing planar...\n");
    {
        auto out = Buffer<int32_t>(4, 4, 3);
        reset_state(out.data());
        if (msan(out) != 0) {
            fprintf(stderr, "Failure!\n");
            exit(-1);
        }
        if (output_previous == nullptr) {
            fprintf(stderr, "Failure: Expected to see annotations.\n");
            exit(-1);
        }
    }

    printf("Testing sparse planar...\n");
    {
        const int kPad = 1;
        halide_dimension_t shape[3] = {
            { 0, 4, 1 },
            { 0, 4, 4 + kPad },
            { 0, 3, (4 + kPad) * 4 },
        };
        std::vector<int32_t> data((4 + kPad) * 4 * 3);
        auto out = Buffer<int32_t>(data.data(), 3, shape);
        reset_state(out.data());
        if (msan(out) != 0) {
            fprintf(stderr, "Failure!\n");
            exit(-1);
        }
        if (output_previous == nullptr) {
            fprintf(stderr, "Failure: Expected to see annotations.\n");
            exit(-1);
        }
    }
    // Buffers should not be marked as "initialized" if the filter fails with an error.
    printf("Testing error case...\n");
    {
        auto out = Buffer<int32_t>(1, 1, 1);
        reset_state(out.data());
        expect_error = true;
        if (msan(out) == 0) {
            fprintf(stderr, "Failure (expected failure but did not)!\n");
            exit(-1);
        }
        if (output_previous != nullptr) {
            fprintf(stderr, "Failure: Expected NOT to see annotations.\n");
            exit(-1);
        }
    }

    printf("Success!\n");
    return 0;
}

#endif
<|endoftext|>