Merge branch 'master' into add-external-faces

Conflicts:
	vtkm/worklet/CMakeLists.txt
	vtkm/worklet/testing/CMakeLists.txt
This commit is contained in:
Robert Maynard 2015-08-27 16:40:36 -04:00
commit 55a11c4551
42 changed files with 2707 additions and 1520 deletions

@ -26,6 +26,10 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "PGI")
set(CMAKE_COMPILER_IS_PGIXX 1)
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
set(CMAKE_COMPILER_IS_ICCXX 1)
endif()
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_CLANGXX)
include(CheckCXXCompilerFlag)
@ -62,5 +66,10 @@ elseif(CMAKE_COMPILER_IS_PGIXX)
#because it is reporting itself as GCC, but it actually doesn't.
#our workaround for this is to manually explicitly disable float128
add_definitions("-DBOOST_MATH_DISABLE_FLOAT128=1")
elseif(CMAKE_COMPILER_IS_ICCXX)
#Intel compiler offers header level suppression in the form of
# #pragma warning(disable : 1478), but for warning 1478 it seems to not
#work. Instead we add it as a definition
add_definitions("-wd1478")
endif()

@ -25,6 +25,7 @@
#include <vtkm/internal/ExportMacros.h>
#include <vtkm/TypeTraits.h>
#include <iostream>
#include <utility>
namespace vtkm {
@ -166,4 +167,13 @@ struct TypeTraits<vtkm::Pair<T,U> >
} // namespace vtkm
/// Helper function for printing out pairs during testing.
///
template<typename T, typename U>
VTKM_EXEC_CONT_EXPORT
std::ostream &operator<<(std::ostream &stream, const vtkm::Pair<T,U> &vec)
{
return stream << "[" << vec.first << "," << vec.second << "]";
}
#endif //vtk_m_Pair_h

@ -31,6 +31,8 @@ VTKM_THIRDPARTY_PRE_INCLUDE
#include <boost/utility/enable_if.hpp>
VTKM_THIRDPARTY_POST_INCLUDE
#include <iostream>
/*!
* \namespace vtkm
* \brief VTKm Toolkit.
@ -1164,4 +1166,18 @@ operator-(const vtkm::Vec<T,Size> &x)
x, vtkm::internal::Negate());
}
/// Helper function for printing out vectors during testing.
///
template<typename T, vtkm::IdComponent Size>
VTKM_CONT_EXPORT
std::ostream &operator<<(std::ostream &stream, const vtkm::Vec<T,Size> &vec)
{
stream << "[";
for (vtkm::IdComponent component = 0; component < Size-1; component++)
{
stream << vec[component] << ",";
}
return stream << vec[Size-1] << "]";
}
#endif //vtk_m_Types_h

@ -162,7 +162,7 @@ public:
virtual void PrintSummary(std::ostream &out) const
{
out << " Coordinate System ";
this->PrintSummary(out);
this->Superclass::PrintSummary(out);
}
};

@ -53,6 +53,8 @@ struct PolymorphicArrayHandleContainerBase
virtual vtkm::IdComponent GetNumberOfComponents() const = 0;
virtual vtkm::Id GetNumberOfValues() const = 0;
virtual void PrintSummary(std::ostream &out) const = 0;
virtual boost::shared_ptr<PolymorphicArrayHandleContainerBase>
NewInstance() const = 0;
};
@ -90,6 +92,11 @@ struct PolymorphicArrayHandleContainer
return this->Array.GetNumberOfValues();
}
virtual void PrintSummary(std::ostream &out) const
{
vtkm::cont::printSummary_ArrayHandle(this->Array, out);
}
virtual boost::shared_ptr<PolymorphicArrayHandleContainerBase>
NewInstance() const
{
@ -277,6 +284,12 @@ public:
return this->ArrayContainer->GetNumberOfValues();
}
VTKM_CONT_EXPORT
virtual void PrintSummary(std::ostream &out) const
{
this->ArrayContainer->PrintSummary(out);
}
private:
boost::shared_ptr<vtkm::cont::detail::PolymorphicArrayHandleContainerBase>
ArrayContainer;

@ -682,10 +682,7 @@ public:
case ASSOC_CELL_SET: out<<"Cells "; break;
case ASSOC_LOGICAL_DIM: out<<"LogicalDim "; break;
}
vtkm::cont::ArrayHandle<vtkm::Float32> vals;
vals = this->Data.CastToArrayHandle(
vtkm::Float32(), VTKM_DEFAULT_STORAGE_TAG());
printSummary_ArrayHandle(vals, out);
this->Data.PrintSummary(out);
//out<<" Order= "<<Order;
out<<"\n";
}

@ -20,7 +20,6 @@
#ifndef vtk_m_cont_arg_TransportTagTopologyIn_h
#define vtk_m_cont_arg_TransportTagTopologyIn_h
#include <vtkm/TopologyElementTag.h>
#include <vtkm/Types.h>
#include <vtkm/cont/CellSet.h>
@ -36,16 +35,19 @@ namespace arg {
/// \c TransportTagTopologyIn is a tag used with the \c Transport class to
/// transport topology objects for input data.
///
template<typename FromTopology,typename ToTopology>
struct TransportTagTopologyIn { };
template<typename ContObjectType, typename Device>
struct Transport<vtkm::cont::arg::TransportTagTopologyIn, ContObjectType, Device>
template<typename FromTopology,
typename ToTopology,
typename ContObjectType, typename Device>
struct Transport<vtkm::cont::arg::TransportTagTopologyIn<FromTopology,ToTopology>, ContObjectType, Device>
{
VTKM_IS_CELL_SET(ContObjectType);
typedef typename ContObjectType
::template ExecutionTypes<
Device,vtkm::TopologyElementTagPoint,vtkm::TopologyElementTagCell>
Device,FromTopology,ToTopology>
::ExecObjectType ExecObjectType;
VTKM_CONT_EXPORT
@ -53,8 +55,8 @@ struct Transport<vtkm::cont::arg::TransportTagTopologyIn, ContObjectType, Device
{
//create CUDA version of connectivity array.
return object.PrepareForInput(Device(),
vtkm::TopologyElementTagPoint(),
vtkm::TopologyElementTagCell());
FromTopology(),
ToTopology());
}
};

@ -30,6 +30,8 @@ void TestDataSet_Explicit()
vtkm::cont::testing::MakeTestDataSet tds;
vtkm::cont::DataSet ds = tds.Make3DExplicitDataSet1();
ds.PrintSummary(std::cout);
VTKM_TEST_ASSERT(ds.GetNumberOfCellSets() == 1,
"Incorrect number of cell sets");

@ -49,6 +49,8 @@ TwoDimRegularTest()
vtkm::cont::DataSet dataSet = testDataSet.Make2DRegularDataSet0();
dataSet.PrintSummary(std::cout);
typedef vtkm::cont::CellSetStructured<2> CellSetType;
CellSetType cellSet = dataSet.GetCellSet(0).CastTo<CellSetType>();
@ -157,6 +159,8 @@ ThreeDimRegularTest()
vtkm::cont::DataSet dataSet = testDataSet.Make3DRegularDataSet0();
dataSet.PrintSummary(std::cout);
typedef vtkm::cont::CellSetStructured<3> CellSetType;
CellSetType cellSet = dataSet.GetCellSet(0).CastTo<CellSetType>();

@ -29,8 +29,6 @@ VTKM_THIRDPARTY_PRE_INCLUDE
#include <boost/static_assert.hpp>
VTKM_THIRDPARTY_POST_INCLUDE
#include <iostream>
namespace vtkm {
namespace internal {

@ -1,33 +1,33 @@
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
TransferToOpenGL.h
)
#-----------------------------------------------------------------------------
add_subdirectory(internal)
#-----------------------------------------------------------------------------
vtkm_declare_headers(${headers})
if(VTKm_ENABLE_OPENGL_TESTS)
add_subdirectory(testing)
endif()
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
TransferToOpenGL.h
)
#-----------------------------------------------------------------------------
add_subdirectory(internal)
#-----------------------------------------------------------------------------
vtkm_declare_headers(${headers})
if(VTKm_ENABLE_OPENGL_TESTS)
add_subdirectory(testing)
endif()

@ -1,73 +1,73 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_TransferToOpenGL_h
#define vtk_m_opengl_TransferToOpenGL_h
#include <vtkm/cont/ArrayHandle.h>
#include <vtkm/opengl/internal/TransferToOpenGL.h>
namespace vtkm{
namespace opengl{
/// \brief Manages transferring an ArrayHandle to opengl .
///
/// \c TransferToOpenGL manages to transfer the contents of an ArrayHandle
/// to OpenGL as efficiently as possible. Will return the type of array buffer
/// that we have bound the handle too. Will be GL_ELEMENT_ARRAY_BUFFER for
/// vtkm::Id, and GL_ARRAY_BUFFER for everything else.
///
/// This function keeps the buffer as the active buffer of the returned type.
///
/// This function will throw exceptions if the transfer wasn't possible
///
template<typename ValueType, class StorageTag, class DeviceAdapterTag>
VTKM_CONT_EXPORT
GLenum TransferToOpenGL(vtkm::cont::ArrayHandle<ValueType,StorageTag> handle,
GLuint& openGLHandle,
DeviceAdapterTag)
{
vtkm::opengl::internal::TransferToOpenGL<ValueType, DeviceAdapterTag> toGL;
toGL.Transfer(handle,openGLHandle);
return toGL.GetType();
}
/// \brief Manages transferring an ArrayHandle to opengl .
///
/// \c TransferToOpenGL manages to transfer the contents of an ArrayHandle
/// to OpenGL as efficiently as possible. Will use the given \p type as how
/// to bind the buffer.
///
/// This function keeps the buffer as the active buffer of the input type.
///
/// This function will throw exceptions if the transfer wasn't possible
///
template<typename ValueType, class StorageTag, class DeviceAdapterTag>
VTKM_CONT_EXPORT
void TransferToOpenGL(vtkm::cont::ArrayHandle<ValueType, StorageTag> handle,
GLuint& openGLHandle,
GLenum type,
DeviceAdapterTag)
{
vtkm::opengl::internal::TransferToOpenGL<ValueType, DeviceAdapterTag> toGL(type);
toGL.Transfer(handle,openGLHandle);
}
}}
#endif //vtk_m_opengl_TransferToOpenGL_h
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_TransferToOpenGL_h
#define vtk_m_opengl_TransferToOpenGL_h
#include <vtkm/cont/ArrayHandle.h>
#include <vtkm/opengl/internal/TransferToOpenGL.h>
namespace vtkm{
namespace opengl{
/// \brief Manages transferring an ArrayHandle to opengl .
///
/// \c TransferToOpenGL manages to transfer the contents of an ArrayHandle
/// to OpenGL as efficiently as possible. Will return the type of array buffer
/// that we have bound the handle too. Will be GL_ELEMENT_ARRAY_BUFFER for
/// vtkm::Id, and GL_ARRAY_BUFFER for everything else.
///
/// This function keeps the buffer as the active buffer of the returned type.
///
/// This function will throw exceptions if the transfer wasn't possible
///
template<typename ValueType, class StorageTag, class DeviceAdapterTag>
VTKM_CONT_EXPORT
GLenum TransferToOpenGL(vtkm::cont::ArrayHandle<ValueType,StorageTag> handle,
GLuint& openGLHandle,
DeviceAdapterTag)
{
vtkm::opengl::internal::TransferToOpenGL<ValueType, DeviceAdapterTag> toGL;
toGL.Transfer(handle,openGLHandle);
return toGL.GetType();
}
/// \brief Manages transferring an ArrayHandle to opengl .
///
/// \c TransferToOpenGL manages to transfer the contents of an ArrayHandle
/// to OpenGL as efficiently as possible. Will use the given \p type as how
/// to bind the buffer.
///
/// This function keeps the buffer as the active buffer of the input type.
///
/// This function will throw exceptions if the transfer wasn't possible
///
template<typename ValueType, class StorageTag, class DeviceAdapterTag>
VTKM_CONT_EXPORT
void TransferToOpenGL(vtkm::cont::ArrayHandle<ValueType, StorageTag> handle,
GLuint& openGLHandle,
GLenum type,
DeviceAdapterTag)
{
vtkm::opengl::internal::TransferToOpenGL<ValueType, DeviceAdapterTag> toGL(type);
toGL.Transfer(handle,openGLHandle);
}
}}
#endif //vtk_m_opengl_TransferToOpenGL_h

@ -1,34 +1,34 @@
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
SetOpenGLDevice.h
)
vtkm_disable_troublesome_thrust_warnings()
#-----------------------------------------------------------------------------
vtkm_declare_headers(CUDA ${headers})
add_subdirectory(internal)
if(VTKm_ENABLE_OPENGL_TESTS)
add_subdirectory(testing)
endif()
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
SetOpenGLDevice.h
)
vtkm_disable_troublesome_thrust_warnings()
#-----------------------------------------------------------------------------
vtkm_declare_headers(CUDA ${headers})
add_subdirectory(internal)
if(VTKm_ENABLE_OPENGL_TESTS)
add_subdirectory(testing)
endif()

@ -1,55 +1,55 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_cuda_opengl_SetOpenGLDevice_h
#define vtk_m_cuda_opengl_SetOpenGLDevice_h
#include <cuda.h>
#include <cuda_gl_interop.h>
#include <vtkm/cont/ErrorExecution.h>
namespace vtkm{
namespace opengl{
namespace cuda{
static void SetCudaGLDevice(int id)
{
//With Cuda 5.0 cudaGLSetGLDevice is deprecated and shouldn't be needed
//anymore. But it seems that macs still require you to call it or we
//segfault
#ifdef __APPLE__
cudaError_t cError = cudaGLSetGLDevice(id);
#else
cudaError_t cError = cudaSetDevice(id);
#endif
if(cError != cudaSuccess)
{
std::string cuda_error_msg("Unable to setup cuda/opengl interop. Error: ");
cuda_error_msg.append(cudaGetErrorString(cError));
throw vtkm::cont::ErrorExecution(cuda_error_msg);
}
}
}
}
} //namespace
#endif //vtk_m_cuda_opengl_SetOpenGLDevice_h
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_cuda_opengl_SetOpenGLDevice_h
#define vtk_m_cuda_opengl_SetOpenGLDevice_h
#include <cuda.h>
#include <cuda_gl_interop.h>
#include <vtkm/cont/ErrorExecution.h>
namespace vtkm{
namespace opengl{
namespace cuda{
static void SetCudaGLDevice(int id)
{
//With Cuda 5.0 cudaGLSetGLDevice is deprecated and shouldn't be needed
//anymore. But it seems that macs still require you to call it or we
//segfault
#ifdef __APPLE__
cudaError_t cError = cudaGLSetGLDevice(id);
#else
cudaError_t cError = cudaSetDevice(id);
#endif
if(cError != cudaSuccess)
{
std::string cuda_error_msg("Unable to setup cuda/opengl interop. Error: ");
cuda_error_msg.append(cudaGetErrorString(cError));
throw vtkm::cont::ErrorExecution(cuda_error_msg);
}
}
}
}
} //namespace
#endif //vtk_m_cuda_opengl_SetOpenGLDevice_h

@ -1,29 +1,29 @@
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
TransferToOpenGL.h
)
vtkm_disable_troublesome_thrust_warnings()
#-----------------------------------------------------------------------------
vtkm_declare_headers(CUDA ${headers})
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
TransferToOpenGL.h
)
vtkm_disable_troublesome_thrust_warnings()
#-----------------------------------------------------------------------------
vtkm_declare_headers(CUDA ${headers})

@ -1,149 +1,149 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtkm_opengl_cuda_internal_TransferToOpenGL_h
#define vtkm_opengl_cuda_internal_TransferToOpenGL_h
#include <vtkm/cont/ErrorExecution.h>
#include <vtkm/cont/ErrorControlOutOfMemory.h>
#include <vtkm/cont/cuda/internal/DeviceAdapterTagCuda.h>
#include <vtkm/cont/cuda/internal/MakeThrustIterator.h>
#include <vtkm/opengl/internal/TransferToOpenGL.h>
#include <thrust/copy.h>
#include <thrust/device_ptr.h>
namespace vtkm {
namespace opengl {
namespace internal {
/// \brief Manages transferring an ArrayHandle to opengl .
///
/// \c TransferToOpenGL manages to transfer the contents of an ArrayHandle
/// to OpenGL as efficiently as possible.
///
template<typename ValueType>
class TransferToOpenGL<ValueType, vtkm::cont::DeviceAdapterTagCuda>
{
typedef vtkm::cont::DeviceAdapterTagCuda DeviceAdapterTag;
public:
VTKM_CONT_EXPORT TransferToOpenGL():
Type( vtkm::opengl::internal::BufferTypePicker( ValueType() ) )
{}
VTKM_CONT_EXPORT explicit TransferToOpenGL(GLenum type):
Type(type)
{}
GLenum GetType() const { return this->Type; }
template< typename StorageTag >
VTKM_CONT_EXPORT
void Transfer (
vtkm::cont::ArrayHandle<ValueType, StorageTag> &handle,
GLuint& openGLHandle ) const
{
//construct a cuda resource handle
cudaGraphicsResource_t cudaResource;
cudaError_t cError;
//make a buffer for the handle if the user has forgotten too
if(!glIsBuffer(openGLHandle))
{
glGenBuffers(1,&openGLHandle);
}
//bind the buffer to the given buffer type
glBindBuffer(this->Type, openGLHandle);
//Allocate the memory and set it as GL_DYNAMIC_DRAW draw
const std::size_t size = sizeof(ValueType)* handle.GetNumberOfValues();
glBufferData(this->Type, size, 0, GL_DYNAMIC_DRAW);
//register the buffer as being used by cuda
cError = cudaGraphicsGLRegisterBuffer(&cudaResource,
openGLHandle,
cudaGraphicsMapFlagsWriteDiscard);
if(cError != cudaSuccess)
{
throw vtkm::cont::ErrorExecution(
"Could not register the OpenGL buffer handle to CUDA.");
}
//map the resource into cuda, so we can copy it
cError =cudaGraphicsMapResources(1,&cudaResource);
if(cError != cudaSuccess)
{
throw vtkm::cont::ErrorControlOutOfMemory(
"Could not allocate enough memory in CUDA for OpenGL interop.");
}
//get the mapped pointer
std::size_t cuda_size;
ValueType* beginPointer=NULL;
cError = cudaGraphicsResourceGetMappedPointer((void **)&beginPointer,
&cuda_size,
cudaResource);
if(cError != cudaSuccess)
{
throw vtkm::cont::ErrorExecution(
"Unable to get pointers to CUDA memory for OpenGL buffer.");
}
//assert that cuda_size is the same size as the buffer we created in OpenGL
VTKM_ASSERT_CONT(cuda_size == size);
//get the device pointers
typedef vtkm::cont::ArrayHandle<ValueType, StorageTag> HandleType;
typedef typename HandleType::template
ExecutionTypes<DeviceAdapterTag>::PortalConst PortalType;
PortalType portal = handle.PrepareForInput(DeviceAdapterTag());
//Copy the data into memory that opengl owns, since we can't
//give memory from cuda to opengl
//Perhaps a direct call to thrust copy should be wrapped in a vtkm
//compatble function
::thrust::copy(vtkm::cont::cuda::internal::IteratorBegin(portal),
vtkm::cont::cuda::internal::IteratorEnd(portal),
thrust::cuda::pointer<ValueType>(beginPointer));
//unmap the resource
cudaGraphicsUnmapResources(1, &cudaResource);
//unregister the buffer
cudaGraphicsUnregisterResource(cudaResource);
}
private:
GLenum Type;
};
}
}
} //namespace vtkm::opengl::cuda::internal
#endif
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtkm_opengl_cuda_internal_TransferToOpenGL_h
#define vtkm_opengl_cuda_internal_TransferToOpenGL_h
#include <vtkm/cont/ErrorExecution.h>
#include <vtkm/cont/ErrorControlOutOfMemory.h>
#include <vtkm/cont/cuda/internal/DeviceAdapterTagCuda.h>
#include <vtkm/cont/cuda/internal/MakeThrustIterator.h>
#include <vtkm/opengl/internal/TransferToOpenGL.h>
#include <thrust/copy.h>
#include <thrust/device_ptr.h>
namespace vtkm {
namespace opengl {
namespace internal {
/// \brief Manages transferring an ArrayHandle to opengl .
///
/// \c TransferToOpenGL manages to transfer the contents of an ArrayHandle
/// to OpenGL as efficiently as possible.
///
template<typename ValueType>
class TransferToOpenGL<ValueType, vtkm::cont::DeviceAdapterTagCuda>
{
typedef vtkm::cont::DeviceAdapterTagCuda DeviceAdapterTag;
public:
VTKM_CONT_EXPORT TransferToOpenGL():
Type( vtkm::opengl::internal::BufferTypePicker( ValueType() ) )
{}
VTKM_CONT_EXPORT explicit TransferToOpenGL(GLenum type):
Type(type)
{}
GLenum GetType() const { return this->Type; }
template< typename StorageTag >
VTKM_CONT_EXPORT
void Transfer (
vtkm::cont::ArrayHandle<ValueType, StorageTag> &handle,
GLuint& openGLHandle ) const
{
//construct a cuda resource handle
cudaGraphicsResource_t cudaResource;
cudaError_t cError;
//make a buffer for the handle if the user has forgotten too
if(!glIsBuffer(openGLHandle))
{
glGenBuffers(1,&openGLHandle);
}
//bind the buffer to the given buffer type
glBindBuffer(this->Type, openGLHandle);
//Allocate the memory and set it as GL_DYNAMIC_DRAW draw
const std::size_t size = sizeof(ValueType)* handle.GetNumberOfValues();
glBufferData(this->Type, size, 0, GL_DYNAMIC_DRAW);
//register the buffer as being used by cuda
cError = cudaGraphicsGLRegisterBuffer(&cudaResource,
openGLHandle,
cudaGraphicsMapFlagsWriteDiscard);
if(cError != cudaSuccess)
{
throw vtkm::cont::ErrorExecution(
"Could not register the OpenGL buffer handle to CUDA.");
}
//map the resource into cuda, so we can copy it
cError =cudaGraphicsMapResources(1,&cudaResource);
if(cError != cudaSuccess)
{
throw vtkm::cont::ErrorControlOutOfMemory(
"Could not allocate enough memory in CUDA for OpenGL interop.");
}
//get the mapped pointer
std::size_t cuda_size;
ValueType* beginPointer=NULL;
cError = cudaGraphicsResourceGetMappedPointer((void **)&beginPointer,
&cuda_size,
cudaResource);
if(cError != cudaSuccess)
{
throw vtkm::cont::ErrorExecution(
"Unable to get pointers to CUDA memory for OpenGL buffer.");
}
//assert that cuda_size is the same size as the buffer we created in OpenGL
VTKM_ASSERT_CONT(cuda_size == size);
//get the device pointers
typedef vtkm::cont::ArrayHandle<ValueType, StorageTag> HandleType;
typedef typename HandleType::template
ExecutionTypes<DeviceAdapterTag>::PortalConst PortalType;
PortalType portal = handle.PrepareForInput(DeviceAdapterTag());
//Copy the data into memory that opengl owns, since we can't
//give memory from cuda to opengl
//Perhaps a direct call to thrust copy should be wrapped in a vtkm
//compatble function
::thrust::copy(vtkm::cont::cuda::internal::IteratorBegin(portal),
vtkm::cont::cuda::internal::IteratorEnd(portal),
thrust::cuda::pointer<ValueType>(beginPointer));
//unmap the resource
cudaGraphicsUnmapResources(1, &cudaResource);
//unregister the buffer
cudaGraphicsUnregisterResource(cudaResource);
}
private:
GLenum Type;
};
}
}
} //namespace vtkm::opengl::cuda::internal
#endif

@ -1,27 +1,27 @@
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(unit_tests
UnitTestTransferToOpenGLCuda.cu
)
vtkm_disable_troublesome_thrust_warnings()
vtkm_unit_tests(CUDA SOURCES ${unit_tests})
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(unit_tests
UnitTestTransferToOpenGLCuda.cu
)
vtkm_disable_troublesome_thrust_warnings()
vtkm_unit_tests(CUDA SOURCES ${unit_tests})

@ -1,36 +1,36 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
//silence boost threading warnings when using cuda
#define BOOST_SP_DISABLE_THREADS
//This sets up testing with the cuda device adapter
#include <vtkm/cont/cuda/DeviceAdapterCuda.h>
#include <vtkm/cont/cuda/internal/testing/Testing.h>
#include <vtkm/opengl/testing/TestingOpenGLInterop.h>
int UnitTestTransferToOpenGLCuda(int, char *[])
{
int result = 1;
result = vtkm::opengl::testing::TestingOpenGLInterop
<vtkm::cont::cuda::DeviceAdapterTagCuda >::Run();
return vtkm::cont::cuda::internal::Testing::CheckCudaBeforeExit(result);
}
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
//silence boost threading warnings when using cuda
#define BOOST_SP_DISABLE_THREADS
//This sets up testing with the cuda device adapter
#include <vtkm/cont/cuda/DeviceAdapterCuda.h>
#include <vtkm/cont/cuda/internal/testing/Testing.h>
#include <vtkm/opengl/testing/TestingOpenGLInterop.h>
int UnitTestTransferToOpenGLCuda(int, char *[])
{
int result = 1;
result = vtkm::opengl::testing::TestingOpenGLInterop
<vtkm::cont::cuda::DeviceAdapterTagCuda >::Run();
return vtkm::cont::cuda::internal::Testing::CheckCudaBeforeExit(result);
}

@ -1,58 +1,58 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_internal_BufferTypePicker_h
#define vtk_m_opengl_internal_BufferTypePicker_h
#include <vtkm/Types.h>
#include <vtkm/opengl/internal/OpenGLHeaders.h>
namespace vtkm {
namespace opengl {
namespace internal {
/// helper function that guesses what OpenGL buffer type is the best default
/// given a primitive type. Currently GL_ELEMENT_ARRAY_BUFFER is used for integer
/// types, and GL_ARRAY_BUFFER is used for everything else
VTKM_CONT_EXPORT GLenum BufferTypePicker( int )
{ return GL_ELEMENT_ARRAY_BUFFER; }
VTKM_CONT_EXPORT GLenum BufferTypePicker( unsigned int )
{ return GL_ELEMENT_ARRAY_BUFFER; }
#if VTKM_SIZE_LONG == 8
VTKM_CONT_EXPORT GLenum BufferTypePicker( vtkm::Int64 )
{ return GL_ELEMENT_ARRAY_BUFFER; }
VTKM_CONT_EXPORT GLenum BufferTypePicker( vtkm::UInt64 )
{ return GL_ELEMENT_ARRAY_BUFFER; }
#endif
template<typename T>
VTKM_CONT_EXPORT GLenum BufferTypePicker( T )
{ return GL_ARRAY_BUFFER; }
}
}
} //namespace vtkm::opengl::internal
#endif //vtk_m_opengl_internal_BufferTypePicker_h
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_internal_BufferTypePicker_h
#define vtk_m_opengl_internal_BufferTypePicker_h
#include <vtkm/Types.h>
#include <vtkm/opengl/internal/OpenGLHeaders.h>
namespace vtkm {
namespace opengl {
namespace internal {
/// helper function that guesses what OpenGL buffer type is the best default
/// given a primitive type. Currently GL_ELEMENT_ARRAY_BUFFER is used for integer
/// types, and GL_ARRAY_BUFFER is used for everything else
VTKM_CONT_EXPORT GLenum BufferTypePicker( int )
{ return GL_ELEMENT_ARRAY_BUFFER; }
VTKM_CONT_EXPORT GLenum BufferTypePicker( unsigned int )
{ return GL_ELEMENT_ARRAY_BUFFER; }
#if VTKM_SIZE_LONG == 8
VTKM_CONT_EXPORT GLenum BufferTypePicker( vtkm::Int64 )
{ return GL_ELEMENT_ARRAY_BUFFER; }
VTKM_CONT_EXPORT GLenum BufferTypePicker( vtkm::UInt64 )
{ return GL_ELEMENT_ARRAY_BUFFER; }
#endif
template<typename T>
VTKM_CONT_EXPORT GLenum BufferTypePicker( T )
{ return GL_ARRAY_BUFFER; }
}
}
} //namespace vtkm::opengl::internal
#endif //vtk_m_opengl_internal_BufferTypePicker_h

@ -1,33 +1,33 @@
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
BufferTypePicker.h
OpenGLHeaders.h
TransferToOpenGL.h
)
#-----------------------------------------------------------------------------
vtkm_declare_headers(${headers})
#we currently don't have to check if we have glut for these tests
if(VTKm_ENABLE_OPENGL_TESTS)
add_subdirectory(testing)
endif()
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
BufferTypePicker.h
OpenGLHeaders.h
TransferToOpenGL.h
)
#-----------------------------------------------------------------------------
vtkm_declare_headers(${headers})
#we currently don't have to check if we have glut for these tests
if(VTKm_ENABLE_OPENGL_TESTS)
add_subdirectory(testing)
endif()

@ -1,41 +1,41 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_internal_OpenGLHeaders_h
#define vtk_m_opengl_internal_OpenGLHeaders_h
#include <vtkm/internal/ExportMacros.h>
#if defined(__APPLE__)
# include <GL/glew.h>
# include <OpenGL/gl.h>
#else
# include <GL/glew.h>
# include <GL/gl.h>
#endif
#ifdef VTKM_CUDA
# include <cuda_runtime.h>
# include <cuda_gl_interop.h>
#endif
#endif //vtk_m_opengl_internal_OpenGLHeaders_h
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_internal_OpenGLHeaders_h
#define vtk_m_opengl_internal_OpenGLHeaders_h
#include <vtkm/internal/ExportMacros.h>
#if defined(__APPLE__)
# include <GL/glew.h>
# include <OpenGL/gl.h>
#else
# include <GL/glew.h>
# include <GL/gl.h>
#endif
#ifdef VTKM_CUDA
# include <cuda_runtime.h>
# include <cuda_gl_interop.h>
#endif
#endif //vtk_m_opengl_internal_OpenGLHeaders_h

@ -1,167 +1,167 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_internal_TransferToOpenGL_h
#define vtk_m_opengl_internal_TransferToOpenGL_h
#include <vtkm/cont/ArrayHandle.h>
#include <vtkm/cont/StorageBasic.h>
#include <vtkm/cont/DeviceAdapterAlgorithm.h>
#include <vtkm/opengl/internal/OpenGLHeaders.h>
#include <vtkm/opengl/internal/BufferTypePicker.h>
namespace vtkm {
namespace opengl {
namespace internal {
namespace detail
{
template<class ValueType, class StorageTag, class DeviceAdapterTag>
VTKM_CONT_EXPORT
void CopyFromHandle(
vtkm::cont::ArrayHandle<ValueType, StorageTag>& handle,
GLenum type,
DeviceAdapterTag)
{
//Generic implementation that will work no matter what. We copy the data
//in the given handle to a temporary handle using the basic storage tag.
//We then ensure the data is available in the control environment by
//synchronizing the control array. Last, we steal the array and pass the
//iterator to the rendering system
const vtkm::Id numberOfValues = handle.GetNumberOfValues();
const std::size_t size =
sizeof(ValueType) * static_cast<std::size_t>(numberOfValues);
//Copy the data from its specialized Storage container to a basic storage
vtkm::cont::ArrayHandle<ValueType, vtkm::cont::StorageTagBasic> tmpHandle;
vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag>::Copy(handle, tmpHandle);
//Synchronize the arrays to ensure the most current data is available in the
//control environment
tmpHandle.SyncControlArray();
//Note that the temporary ArrayHandle is no longer valid after this call
ValueType* temporaryStorage = tmpHandle.Internals->ControlArray.StealArray();
//Detach the current buffer
glBufferData(type, size, 0, GL_DYNAMIC_DRAW);
//Allocate the memory and set it as static draw and copy into opengl
glBufferSubData(type,0,size,temporaryStorage);
delete[] temporaryStorage;
}
template<class ValueType, class DeviceAdapterTag>
VTKM_CONT_EXPORT
void CopyFromHandle(
vtkm::cont::ArrayHandle<ValueType, vtkm::cont::StorageTagBasic>& handle,
GLenum type,
DeviceAdapterTag)
{
//Specialization given that we are use an C allocated array storage tag
//that allows us to directly hook into the data. We pull the data
//back to the control enviornment using PerpareForInput and give an iterator
//from the portal to OpenGL to upload to the rendering system
//This also works because we know that this class isn't used for cuda interop,
//instead we are specialized
const std::size_t size =
sizeof(ValueType) * static_cast<std::size_t>(handle.GetNumberOfValues());
//Detach the current buffer
glBufferData(type, size, 0, GL_DYNAMIC_DRAW);
//Allocate the memory and set it as static draw and copy into opengl
glBufferSubData(type,0,size,
vtkm::cont::ArrayPortalToIteratorBegin(
handle.PrepareForInput(DeviceAdapterTag())
));
}
} //namespace detail
/// \brief Manages transferring an ArrayHandle to opengl .
///
/// \c TransferToOpenGL manages to transfer the contents of an ArrayHandle
/// to OpenGL as efficiently as possible.
///
template<typename ValueType, class DeviceAdapterTag>
class TransferToOpenGL
{
public:
VTKM_CONT_EXPORT TransferToOpenGL():
Type( vtkm::opengl::internal::BufferTypePicker( ValueType() ) )
{}
VTKM_CONT_EXPORT explicit TransferToOpenGL(GLenum type):
Type(type)
{}
VTKM_CONT_EXPORT GLenum GetType() const { return this->Type; }
template< typename StorageTag >
VTKM_CONT_EXPORT
void Transfer (
vtkm::cont::ArrayHandle<ValueType, StorageTag>& handle,
GLuint& openGLHandle ) const
{
//make a buffer for the handle if the user has forgotten too
if(!glIsBuffer(openGLHandle))
{
glGenBuffers(1,&openGLHandle);
}
//bind the buffer to the given buffer type
glBindBuffer(this->Type, openGLHandle);
//transfer the data.
//the primary concern that we have at this point is data locality and
//the type of storage. Our options include using CopyInto and provide a
//temporary location for the values to reside before we give it to openGL
//this works for all storage types.
//
//Second option is to call PrepareForInput and get a PortalConst in the
//exection environment.
//if we are StorageTagBasic this would allow us the ability to grab
//the raw memory value and copy those, which we know are valid and remove
//a unneeded copy.
//
//The end result is that we have CopyFromHandle which does number two
//from StorageTagBasic, and does the CopyInto for everything else
detail::CopyFromHandle(handle, this->Type, DeviceAdapterTag());
}
private:
GLenum Type;
};
}
}
} //namespace vtkm::opengl::internal
//-----------------------------------------------------------------------------
// These includes are intentionally placed here after the declaration of the
// TransferToOpenGL class, so that people get the correct device adapter
/// specializations if they exist.
#if VTKM_DEVICE_ADAPTER == VTKM_DEVICE_ADAPTER_CUDA
#include <vtkm/opengl/cuda/internal/TransferToOpenGL.h>
#endif
#endif //vtk_m_opengl_internal_TransferToOpenGL_h
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_internal_TransferToOpenGL_h
#define vtk_m_opengl_internal_TransferToOpenGL_h
#include <vtkm/cont/ArrayHandle.h>
#include <vtkm/cont/StorageBasic.h>
#include <vtkm/cont/DeviceAdapterAlgorithm.h>
#include <vtkm/opengl/internal/OpenGLHeaders.h>
#include <vtkm/opengl/internal/BufferTypePicker.h>
namespace vtkm {
namespace opengl {
namespace internal {
namespace detail
{
template<class ValueType, class StorageTag, class DeviceAdapterTag>
VTKM_CONT_EXPORT
void CopyFromHandle(
vtkm::cont::ArrayHandle<ValueType, StorageTag>& handle,
GLenum type,
DeviceAdapterTag)
{
//Generic implementation that will work no matter what. We copy the data
//in the given handle to a temporary handle using the basic storage tag.
//We then ensure the data is available in the control environment by
//synchronizing the control array. Last, we steal the array and pass the
//iterator to the rendering system
const vtkm::Id numberOfValues = handle.GetNumberOfValues();
const std::size_t size =
sizeof(ValueType) * static_cast<std::size_t>(numberOfValues);
//Copy the data from its specialized Storage container to a basic storage
vtkm::cont::ArrayHandle<ValueType, vtkm::cont::StorageTagBasic> tmpHandle;
vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag>::Copy(handle, tmpHandle);
//Synchronize the arrays to ensure the most current data is available in the
//control environment
tmpHandle.SyncControlArray();
//Note that the temporary ArrayHandle is no longer valid after this call
ValueType* temporaryStorage = tmpHandle.Internals->ControlArray.StealArray();
//Detach the current buffer
glBufferData(type, size, 0, GL_DYNAMIC_DRAW);
//Allocate the memory and set it as static draw and copy into opengl
glBufferSubData(type,0,size,temporaryStorage);
delete[] temporaryStorage;
}
template<class ValueType, class DeviceAdapterTag>
VTKM_CONT_EXPORT
void CopyFromHandle(
vtkm::cont::ArrayHandle<ValueType, vtkm::cont::StorageTagBasic>& handle,
GLenum type,
DeviceAdapterTag)
{
//Specialization given that we are use an C allocated array storage tag
//that allows us to directly hook into the data. We pull the data
//back to the control enviornment using PerpareForInput and give an iterator
//from the portal to OpenGL to upload to the rendering system
//This also works because we know that this class isn't used for cuda interop,
//instead we are specialized
const std::size_t size =
sizeof(ValueType) * static_cast<std::size_t>(handle.GetNumberOfValues());
//Detach the current buffer
glBufferData(type, size, 0, GL_DYNAMIC_DRAW);
//Allocate the memory and set it as static draw and copy into opengl
glBufferSubData(type,0,size,
vtkm::cont::ArrayPortalToIteratorBegin(
handle.PrepareForInput(DeviceAdapterTag())
));
}
} //namespace detail
/// \brief Manages transferring an ArrayHandle to opengl .
///
/// \c TransferToOpenGL manages to transfer the contents of an ArrayHandle
/// to OpenGL as efficiently as possible.
///
template<typename ValueType, class DeviceAdapterTag>
class TransferToOpenGL
{
public:
VTKM_CONT_EXPORT TransferToOpenGL():
Type( vtkm::opengl::internal::BufferTypePicker( ValueType() ) )
{}
VTKM_CONT_EXPORT explicit TransferToOpenGL(GLenum type):
Type(type)
{}
VTKM_CONT_EXPORT GLenum GetType() const { return this->Type; }
template< typename StorageTag >
VTKM_CONT_EXPORT
void Transfer (
vtkm::cont::ArrayHandle<ValueType, StorageTag>& handle,
GLuint& openGLHandle ) const
{
//make a buffer for the handle if the user has forgotten too
if(!glIsBuffer(openGLHandle))
{
glGenBuffers(1,&openGLHandle);
}
//bind the buffer to the given buffer type
glBindBuffer(this->Type, openGLHandle);
//transfer the data.
//the primary concern that we have at this point is data locality and
//the type of storage. Our options include using CopyInto and provide a
//temporary location for the values to reside before we give it to openGL
//this works for all storage types.
//
//Second option is to call PrepareForInput and get a PortalConst in the
//exection environment.
//if we are StorageTagBasic this would allow us the ability to grab
//the raw memory value and copy those, which we know are valid and remove
//a unneeded copy.
//
//The end result is that we have CopyFromHandle which does number two
//from StorageTagBasic, and does the CopyInto for everything else
detail::CopyFromHandle(handle, this->Type, DeviceAdapterTag());
}
private:
GLenum Type;
};
}
}
} //namespace vtkm::opengl::internal
//-----------------------------------------------------------------------------
// These includes are intentionally placed here after the declaration of the
// TransferToOpenGL class, so that people get the correct device adapter
/// specializations if they exist.
#if VTKM_DEVICE_ADAPTER == VTKM_DEVICE_ADAPTER_CUDA
#include <vtkm/opengl/cuda/internal/TransferToOpenGL.h>
#endif
#endif //vtk_m_opengl_internal_TransferToOpenGL_h

@ -1,26 +1,26 @@
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(unit_tests
UnitTestBufferTypePicker.cxx
UnitTestOpenGLHeaders.cxx
)
vtkm_unit_tests(SOURCES ${unit_tests})
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(unit_tests
UnitTestBufferTypePicker.cxx
UnitTestOpenGLHeaders.cxx
)
vtkm_unit_tests(SOURCES ${unit_tests})

@ -1,56 +1,56 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <vtkm/opengl/internal/BufferTypePicker.h>
#include <vtkm/cont/testing/Testing.h>
namespace
{
void TestBufferTypePicker()
{
//just verify that certain types match
GLenum type;
typedef unsigned int vtkmUint;
typedef vtkm::FloatDefault T;
type = vtkm::opengl::internal::BufferTypePicker(vtkm::Id());
VTKM_TEST_ASSERT(type == GL_ELEMENT_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(int());
VTKM_TEST_ASSERT(type == GL_ELEMENT_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(vtkmUint());
VTKM_TEST_ASSERT(type == GL_ELEMENT_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(vtkm::Vec<T,4>());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(vtkm::Vec<T,3>());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(vtkm::FloatDefault());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(float());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(double());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
}
}
int UnitTestBufferTypePicker(int, char *[])
{
return vtkm::cont::testing::Testing::Run(TestBufferTypePicker);
}
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <vtkm/opengl/internal/BufferTypePicker.h>
#include <vtkm/cont/testing/Testing.h>
namespace
{
void TestBufferTypePicker()
{
//just verify that certain types match
GLenum type;
typedef unsigned int vtkmUint;
typedef vtkm::FloatDefault T;
type = vtkm::opengl::internal::BufferTypePicker(vtkm::Id());
VTKM_TEST_ASSERT(type == GL_ELEMENT_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(int());
VTKM_TEST_ASSERT(type == GL_ELEMENT_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(vtkmUint());
VTKM_TEST_ASSERT(type == GL_ELEMENT_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(vtkm::Vec<T,4>());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(vtkm::Vec<T,3>());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(vtkm::FloatDefault());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(float());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
type = vtkm::opengl::internal::BufferTypePicker(double());
VTKM_TEST_ASSERT(type == GL_ARRAY_BUFFER, "Bad OpenGL Buffer Type");
}
}
int UnitTestBufferTypePicker(int, char *[])
{
return vtkm::cont::testing::Testing::Run(TestBufferTypePicker);
}

@ -1,43 +1,43 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <vtkm/opengl/internal/OpenGLHeaders.h>
#include <vtkm/cont/testing/Testing.h>
namespace {
void TestOpenGLHeaders()
{
#if defined(GL_VERSION_1_3) && (GL_VERSION_1_3 == 1)
//this is pretty simple, we just verify that certain symbols exist
//and the version of openGL is high enough that our interop will work.
GLenum e = GL_ELEMENT_ARRAY_BUFFER;
GLuint u = 1;
u = u * e;
(void) u;
#else
unable_to_find_required_gl_version();
#endif
}
}
int UnitTestOpenGLHeaders(int, char *[])
{
return vtkm::cont::testing::Testing::Run(TestOpenGLHeaders);
}
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <vtkm/opengl/internal/OpenGLHeaders.h>
#include <vtkm/cont/testing/Testing.h>
namespace {
void TestOpenGLHeaders()
{
#if defined(GL_VERSION_1_3) && (GL_VERSION_1_3 == 1)
//this is pretty simple, we just verify that certain symbols exist
//and the version of openGL is high enough that our interop will work.
GLenum e = GL_ELEMENT_ARRAY_BUFFER;
GLuint u = 1;
u = u * e;
(void) u;
#else
unable_to_find_required_gl_version();
#endif
}
}
int UnitTestOpenGLHeaders(int, char *[])
{
return vtkm::cont::testing::Testing::Run(TestOpenGLHeaders);
}

@ -1,33 +1,33 @@
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
TestingOpenGLInterop.h
TestingWindow.h
WindowBase.h
)
vtkm_declare_headers(${headers})
set(unit_tests
UnitTestTransferToOpenGL.cxx
)
vtkm_unit_tests(SOURCES ${unit_tests})
##============================================================================
## Copyright (c) Kitware, Inc.
## All rights reserved.
## See LICENSE.txt for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notice for more information.
##
## Copyright 2014 Sandia Corporation.
## Copyright 2014 UT-Battelle, LLC.
## Copyright 2014 Los Alamos National Security.
##
## Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
## the U.S. Government retains certain rights in this software.
##
## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
## Laboratory (LANL), the U.S. Government retains certain rights in
## this software.
##============================================================================
set(headers
TestingOpenGLInterop.h
TestingWindow.h
WindowBase.h
)
vtkm_declare_headers(${headers})
set(unit_tests
UnitTestTransferToOpenGL.cxx
)
vtkm_unit_tests(SOURCES ${unit_tests})

@ -1,304 +1,304 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_testing_TestingOpenGLInterop_h
#define vtk_m_opengl_testing_TestingOpenGLInterop_h
#include <vtkm/cont/ArrayHandle.h>
#include <vtkm/cont/ArrayHandleConstant.h>
#include <vtkm/worklet/DispatcherMapField.h>
#include <vtkm/worklet/Magnitude.h>
#include <vtkm/opengl/testing/TestingWindow.h>
#include <vtkm/opengl/TransferToOpenGL.h>
#include <vtkm/cont/testing/Testing.h>
// #include <vtkm/cont/testing/TestingGridGenerator.h>
#include <algorithm>
#include <iterator>
#include <vector>
namespace vtkm {
namespace opengl {
namespace testing {
/// This class has a single static member, Run, that tests the templated
/// DeviceAdapter for support for opengl interop.
///
template< class DeviceAdapterTag,
class StorageTag = VTKM_DEFAULT_STORAGE_TAG>
struct TestingOpenGLInterop
{
private:
//fill the array with a collection of values and return it wrapped in
//an vtkm array handle
template<typename T>
static
vtkm::cont::ArrayHandle<T,StorageTag>
FillArray(std::vector<T>& data, std::size_t length)
{
typedef typename std::vector<T>::iterator iterator;
//make sure the data array is exactly the right length
data.clear();
data.resize(length);
vtkm::Id pos = 0;
for(iterator i = data.begin(); i != data.end(); ++i, ++pos)
{ *i=TestValue(pos,T()); }
std::random_shuffle(data.begin(),data.end());
return vtkm::cont::make_ArrayHandle(data);
}
//Transfer the data in a vtkm ArrayHandle to open gl while making sure
//we don't throw any errors
template<typename ArrayHandleType>
static
void SafelyTransferArray(ArrayHandleType array, GLuint& handle)
{
try
{
vtkm::opengl::TransferToOpenGL(array,handle, DeviceAdapterTag());
}
catch (vtkm::cont::ErrorControlOutOfMemory error)
{
std::cout << error.GetMessage() << std::endl;
VTKM_TEST_ASSERT(true==false,
"Got an unexpected Out Of Memory error transferring to openGL");
}
catch (vtkm::cont::ErrorControlBadValue bvError)
{
std::cout << bvError.GetMessage() << std::endl;
VTKM_TEST_ASSERT(true==false,
"Got an unexpected Bad Value error transferring to openGL");
}
}
template<typename ArrayHandleType>
static
void SafelyTransferArray(ArrayHandleType array, GLuint& handle, GLenum type)
{
try
{
vtkm::opengl::TransferToOpenGL(array,handle,type, DeviceAdapterTag());
}
catch (vtkm::cont::ErrorControlOutOfMemory error)
{
std::cout << error.GetMessage() << std::endl;
VTKM_TEST_ASSERT(true==false,
"Got an unexpected Out Of Memory error transferring to openGL");
}
catch (vtkm::cont::ErrorControlBadValue bvError)
{
std::cout << bvError.GetMessage() << std::endl;
VTKM_TEST_ASSERT(true==false,
"Got an unexpected Bad Value error transferring to openGL");
}
}
//bring the data back from openGL and into a std vector. Will bind the
//passed in handle to the default buffer type for the type T
template<typename T>
static
std::vector<T> CopyGLBuffer(GLuint& handle, T t)
{
//get the type we used for this buffer.
GLenum type = vtkm::opengl::internal::BufferTypePicker(t);
//bind the buffer to the guessed buffer type, this way
//we can call CopyGLBuffer no matter what it the active buffer
glBindBuffer(type, handle);
//get the size of the buffer
int bytesInBuffer = 0;
glGetBufferParameteriv(type, GL_BUFFER_SIZE, &bytesInBuffer);
const std::size_t size = ( static_cast<std::size_t>(bytesInBuffer) / sizeof(T) );
//get the buffer contents and place it into a vector
std::vector<T> data;
data.resize(size);
glGetBufferSubData(type,0,bytesInBuffer,&data[0]);
return data;
}
struct TransferFunctor
{
template <typename T>
void operator()(const T t) const
{
const std::size_t Size = 10;
GLuint GLHandle;
//verify that T is able to be transfer to openGL.
//than pull down the results from the array buffer and verify
//that they match the handles contents
std::vector<T> tempData;
vtkm::cont::ArrayHandle<T,StorageTag> temp =
FillArray(tempData,Size);
//verify that the signature that doesn't have type works
SafelyTransferArray(temp,GLHandle);
bool is_buffer;
is_buffer = glIsBuffer(GLHandle);
VTKM_TEST_ASSERT(is_buffer==true,
"OpenGL buffer not filled");
std::vector<T> returnedValues = CopyGLBuffer(GLHandle, t);
//verify the results match what is in the array handle
temp.SyncControlArray();
T* expectedValues = temp.Internals->ControlArray.StealArray();
for(std::size_t i=0; i < Size; ++i)
{
VTKM_TEST_ASSERT(test_equal(*(expectedValues+i),returnedValues[i]),
"Array Handle failed to transfer properly");
}
temp.ReleaseResources();
temp = FillArray(tempData,Size*2);
GLenum type = vtkm::opengl::internal::BufferTypePicker(t);
SafelyTransferArray(temp,GLHandle,type);
is_buffer = glIsBuffer(GLHandle);
VTKM_TEST_ASSERT(is_buffer==true,
"OpenGL buffer not filled");
returnedValues = CopyGLBuffer(GLHandle, t);
//verify the results match what is in the array handle
temp.SyncControlArray();
expectedValues = temp.Internals->ControlArray.StealArray();
for(std::size_t i=0; i < Size*2; ++i)
{
VTKM_TEST_ASSERT(test_equal(*(expectedValues+i),returnedValues[i]),
"Array Handle failed to transfer properly");
}
//verify this work for a constant value array handle
T constantValue = TestValue(2,T()); //verified by die roll
vtkm::cont::ArrayHandleConstant<T> constant(constantValue,
static_cast<vtkm::Id>(Size) );
SafelyTransferArray(constant,GLHandle);
is_buffer = glIsBuffer(GLHandle);
VTKM_TEST_ASSERT(is_buffer==true,
"OpenGL buffer not filled");
returnedValues = CopyGLBuffer(GLHandle, constantValue);
for(std::size_t i=0; i < Size; ++i)
{
VTKM_TEST_ASSERT(test_equal(returnedValues[i],constantValue),
"Constant value array failed to transfer properly");
}
}
};
// struct TransferGridFunctor
// {
// GLuint CoordGLHandle;
// GLuint MagnitudeGLHandle;
// template <typename GridType>
// void operator()(const GridType)
// {
// //verify we are able to be transfer both coordinates and indices to openGL.
// //than pull down the results from the array buffer and verify
// //that they match the handles contents
// vtkm::cont::testing::TestGrid<GridType,
// StorageTag,
// DeviceAdapterTag> grid(64);
// vtkm::cont::ArrayHandle<vtkm::FloatDefault,
// StorageTag,
// DeviceAdapterTag> magnitudeHandle;
// vtkm::cont::DispatcherMapField< vtkm::worklet::Magnitude,
// DeviceAdapterTag> dispatcher;
// dispatcher.Invoke(grid->GetPointCoordinates(), magnitudeHandle);
// //transfer to openGL 3 handles and catch any errors
// //
// SafelyTransferArray(grid->GetPointCoordinates(),this->CoordGLHandle);
// SafelyTransferArray(magnitudeHandle,this->MagnitudeGLHandle);
// //verify all 3 handles are actually handles
// bool is_buffer = glIsBuffer(this->CoordGLHandle);
// VTKM_TEST_ASSERT(is_buffer==true,
// "Coordinates OpenGL buffer not filled");
// is_buffer = glIsBuffer(this->MagnitudeGLHandle);
// VTKM_TEST_ASSERT(is_buffer==true,
// "Magnitude OpenGL buffer not filled");
// //now that everything is openGL we have one task left.
// //transfer everything back to the host and compare it to the
// //computed values.
// std::vector<vtkm::Vec<vtkm::FloatDefault,3>> GLReturnedCoords = CopyGLBuffer(
// this->CoordGLHandle, vtkm::Vec<vtkm::FloatDefault,3>());
// std::vector<vtkm::FloatDefault> GLReturneMags = CopyGLBuffer(
// this->MagnitudeGLHandle,vtkm::FloatDefault());
// for (vtkm::Id pointIndex = 0;
// pointIndex < grid->GetNumberOfPoints();
// pointIndex++)
// {
// vtkm::Vec<vtkm::FloatDefault,3> pointCoordinateExpected = grid.GetPointCoordinates(
// pointIndex);
// vtkm::Vec<vtkm::FloatDefault,3> pointCoordinatesReturned = GLReturnedCoords[pointIndex];
// VTKM_TEST_ASSERT(test_equal(pointCoordinateExpected,
// pointCoordinatesReturned),
// "Got bad coordinate from OpenGL buffer.");
// vtkm::FloatDefault magnitudeValue = GLReturneMags[pointIndex];
// vtkm::FloatDefault magnitudeExpected =
// sqrt(vtkm::dot(pointCoordinateExpected, pointCoordinateExpected));
// VTKM_TEST_ASSERT(test_equal(magnitudeValue, magnitudeExpected),
// "Got bad magnitude from OpenGL buffer.");
// }
// }
// };
public:
VTKM_CONT_EXPORT static int Run()
{
//create a valid openGL context that we can test transfer of data
vtkm::opengl::testing::TestingWindow window;
window.Init("Testing Window", 300, 300);
//verify that we can transfer basic arrays and constant value arrays to opengl
vtkm::testing::Testing::TryAllTypes(TransferFunctor());
//verify that openGL interop works with all grid types in that we can
//transfer coordinates / verts and properties to openGL
// vtkm::cont::testing::GridTesting::TryAllGridTypes(
// TransferGridFunctor(),
// vtkm::testing::Testing::CellCheckAlwaysTrue(),
// StorageTag(),
// DeviceAdapterTag() );
return 0;
}
};
} } }
#endif //vtk_m_opengl_testing_TestingOpenGLInterop_h
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_testing_TestingOpenGLInterop_h
#define vtk_m_opengl_testing_TestingOpenGLInterop_h
#include <vtkm/cont/ArrayHandle.h>
#include <vtkm/cont/ArrayHandleConstant.h>
#include <vtkm/worklet/DispatcherMapField.h>
#include <vtkm/worklet/Magnitude.h>
#include <vtkm/opengl/testing/TestingWindow.h>
#include <vtkm/opengl/TransferToOpenGL.h>
#include <vtkm/cont/testing/Testing.h>
// #include <vtkm/cont/testing/TestingGridGenerator.h>
#include <algorithm>
#include <iterator>
#include <vector>
namespace vtkm {
namespace opengl {
namespace testing {
/// This class has a single static member, Run, that tests the templated
/// DeviceAdapter for support for opengl interop.
///
template< class DeviceAdapterTag,
class StorageTag = VTKM_DEFAULT_STORAGE_TAG>
struct TestingOpenGLInterop
{
private:
//fill the array with a collection of values and return it wrapped in
//an vtkm array handle
template<typename T>
static
vtkm::cont::ArrayHandle<T,StorageTag>
FillArray(std::vector<T>& data, std::size_t length)
{
typedef typename std::vector<T>::iterator iterator;
//make sure the data array is exactly the right length
data.clear();
data.resize(length);
vtkm::Id pos = 0;
for(iterator i = data.begin(); i != data.end(); ++i, ++pos)
{ *i=TestValue(pos,T()); }
std::random_shuffle(data.begin(),data.end());
return vtkm::cont::make_ArrayHandle(data);
}
//Transfer the data in a vtkm ArrayHandle to open gl while making sure
//we don't throw any errors
template<typename ArrayHandleType>
static
void SafelyTransferArray(ArrayHandleType array, GLuint& handle)
{
try
{
vtkm::opengl::TransferToOpenGL(array,handle, DeviceAdapterTag());
}
catch (vtkm::cont::ErrorControlOutOfMemory error)
{
std::cout << error.GetMessage() << std::endl;
VTKM_TEST_ASSERT(true==false,
"Got an unexpected Out Of Memory error transferring to openGL");
}
catch (vtkm::cont::ErrorControlBadValue bvError)
{
std::cout << bvError.GetMessage() << std::endl;
VTKM_TEST_ASSERT(true==false,
"Got an unexpected Bad Value error transferring to openGL");
}
}
template<typename ArrayHandleType>
static
void SafelyTransferArray(ArrayHandleType array, GLuint& handle, GLenum type)
{
try
{
vtkm::opengl::TransferToOpenGL(array,handle,type, DeviceAdapterTag());
}
catch (vtkm::cont::ErrorControlOutOfMemory error)
{
std::cout << error.GetMessage() << std::endl;
VTKM_TEST_ASSERT(true==false,
"Got an unexpected Out Of Memory error transferring to openGL");
}
catch (vtkm::cont::ErrorControlBadValue bvError)
{
std::cout << bvError.GetMessage() << std::endl;
VTKM_TEST_ASSERT(true==false,
"Got an unexpected Bad Value error transferring to openGL");
}
}
//bring the data back from openGL and into a std vector. Will bind the
//passed in handle to the default buffer type for the type T
template<typename T>
static
std::vector<T> CopyGLBuffer(GLuint& handle, T t)
{
//get the type we used for this buffer.
GLenum type = vtkm::opengl::internal::BufferTypePicker(t);
//bind the buffer to the guessed buffer type, this way
//we can call CopyGLBuffer no matter what it the active buffer
glBindBuffer(type, handle);
//get the size of the buffer
int bytesInBuffer = 0;
glGetBufferParameteriv(type, GL_BUFFER_SIZE, &bytesInBuffer);
const std::size_t size = ( static_cast<std::size_t>(bytesInBuffer) / sizeof(T) );
//get the buffer contents and place it into a vector
std::vector<T> data;
data.resize(size);
glGetBufferSubData(type,0,bytesInBuffer,&data[0]);
return data;
}
struct TransferFunctor
{
template <typename T>
void operator()(const T t) const
{
const std::size_t Size = 10;
GLuint GLHandle;
//verify that T is able to be transfer to openGL.
//than pull down the results from the array buffer and verify
//that they match the handles contents
std::vector<T> tempData;
vtkm::cont::ArrayHandle<T,StorageTag> temp =
FillArray(tempData,Size);
//verify that the signature that doesn't have type works
SafelyTransferArray(temp,GLHandle);
bool is_buffer;
is_buffer = glIsBuffer(GLHandle);
VTKM_TEST_ASSERT(is_buffer==true,
"OpenGL buffer not filled");
std::vector<T> returnedValues = CopyGLBuffer(GLHandle, t);
//verify the results match what is in the array handle
temp.SyncControlArray();
T* expectedValues = temp.Internals->ControlArray.StealArray();
for(std::size_t i=0; i < Size; ++i)
{
VTKM_TEST_ASSERT(test_equal(*(expectedValues+i),returnedValues[i]),
"Array Handle failed to transfer properly");
}
temp.ReleaseResources();
temp = FillArray(tempData,Size*2);
GLenum type = vtkm::opengl::internal::BufferTypePicker(t);
SafelyTransferArray(temp,GLHandle,type);
is_buffer = glIsBuffer(GLHandle);
VTKM_TEST_ASSERT(is_buffer==true,
"OpenGL buffer not filled");
returnedValues = CopyGLBuffer(GLHandle, t);
//verify the results match what is in the array handle
temp.SyncControlArray();
expectedValues = temp.Internals->ControlArray.StealArray();
for(std::size_t i=0; i < Size*2; ++i)
{
VTKM_TEST_ASSERT(test_equal(*(expectedValues+i),returnedValues[i]),
"Array Handle failed to transfer properly");
}
//verify this work for a constant value array handle
T constantValue = TestValue(2,T()); //verified by die roll
vtkm::cont::ArrayHandleConstant<T> constant(constantValue,
static_cast<vtkm::Id>(Size) );
SafelyTransferArray(constant,GLHandle);
is_buffer = glIsBuffer(GLHandle);
VTKM_TEST_ASSERT(is_buffer==true,
"OpenGL buffer not filled");
returnedValues = CopyGLBuffer(GLHandle, constantValue);
for(std::size_t i=0; i < Size; ++i)
{
VTKM_TEST_ASSERT(test_equal(returnedValues[i],constantValue),
"Constant value array failed to transfer properly");
}
}
};
// struct TransferGridFunctor
// {
// GLuint CoordGLHandle;
// GLuint MagnitudeGLHandle;
// template <typename GridType>
// void operator()(const GridType)
// {
// //verify we are able to be transfer both coordinates and indices to openGL.
// //than pull down the results from the array buffer and verify
// //that they match the handles contents
// vtkm::cont::testing::TestGrid<GridType,
// StorageTag,
// DeviceAdapterTag> grid(64);
// vtkm::cont::ArrayHandle<vtkm::FloatDefault,
// StorageTag,
// DeviceAdapterTag> magnitudeHandle;
// vtkm::cont::DispatcherMapField< vtkm::worklet::Magnitude,
// DeviceAdapterTag> dispatcher;
// dispatcher.Invoke(grid->GetPointCoordinates(), magnitudeHandle);
// //transfer to openGL 3 handles and catch any errors
// //
// SafelyTransferArray(grid->GetPointCoordinates(),this->CoordGLHandle);
// SafelyTransferArray(magnitudeHandle,this->MagnitudeGLHandle);
// //verify all 3 handles are actually handles
// bool is_buffer = glIsBuffer(this->CoordGLHandle);
// VTKM_TEST_ASSERT(is_buffer==true,
// "Coordinates OpenGL buffer not filled");
// is_buffer = glIsBuffer(this->MagnitudeGLHandle);
// VTKM_TEST_ASSERT(is_buffer==true,
// "Magnitude OpenGL buffer not filled");
// //now that everything is openGL we have one task left.
// //transfer everything back to the host and compare it to the
// //computed values.
// std::vector<vtkm::Vec<vtkm::FloatDefault,3>> GLReturnedCoords = CopyGLBuffer(
// this->CoordGLHandle, vtkm::Vec<vtkm::FloatDefault,3>());
// std::vector<vtkm::FloatDefault> GLReturneMags = CopyGLBuffer(
// this->MagnitudeGLHandle,vtkm::FloatDefault());
// for (vtkm::Id pointIndex = 0;
// pointIndex < grid->GetNumberOfPoints();
// pointIndex++)
// {
// vtkm::Vec<vtkm::FloatDefault,3> pointCoordinateExpected = grid.GetPointCoordinates(
// pointIndex);
// vtkm::Vec<vtkm::FloatDefault,3> pointCoordinatesReturned = GLReturnedCoords[pointIndex];
// VTKM_TEST_ASSERT(test_equal(pointCoordinateExpected,
// pointCoordinatesReturned),
// "Got bad coordinate from OpenGL buffer.");
// vtkm::FloatDefault magnitudeValue = GLReturneMags[pointIndex];
// vtkm::FloatDefault magnitudeExpected =
// sqrt(vtkm::dot(pointCoordinateExpected, pointCoordinateExpected));
// VTKM_TEST_ASSERT(test_equal(magnitudeValue, magnitudeExpected),
// "Got bad magnitude from OpenGL buffer.");
// }
// }
// };
public:
VTKM_CONT_EXPORT static int Run()
{
//create a valid openGL context that we can test transfer of data
vtkm::opengl::testing::TestingWindow window;
window.Init("Testing Window", 300, 300);
//verify that we can transfer basic arrays and constant value arrays to opengl
vtkm::testing::Testing::TryAllTypes(TransferFunctor());
//verify that openGL interop works with all grid types in that we can
//transfer coordinates / verts and properties to openGL
// vtkm::cont::testing::GridTesting::TryAllGridTypes(
// TransferGridFunctor(),
// vtkm::testing::Testing::CellCheckAlwaysTrue(),
// StorageTag(),
// DeviceAdapterTag() );
return 0;
}
};
} } }
#endif //vtk_m_opengl_testing_TestingOpenGLInterop_h

@ -1,82 +1,82 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_testing_TestingWindow_h
#define vtk_m_opengl_testing_TestingWindow_h
#include <vtkm/internal/ExportMacros.h>
#include <vtkm/opengl/testing/WindowBase.h>
namespace vtkm{
namespace opengl{
namespace testing{
/// \brief Basic Render Window that only makes sure opengl has a valid context
///
/// Bare-bones class that fulfullis the requirements of WindowBase but
/// has no ability to interact with opengl other than to close down the window
///
///
class TestingWindow : public vtkm::opengl::testing::WindowBase<TestingWindow>
{
public:
VTKM_CONT_EXPORT TestingWindow(){};
//called after opengl is inited
VTKM_CONT_EXPORT void PostInit()
{}
VTKM_CONT_EXPORT void Display()
{}
VTKM_CONT_EXPORT void Idle()
{}
VTKM_CONT_EXPORT void ChangeSize(int vtkmNotUsed(w), int vtkmNotUsed(h) )
{}
VTKM_CONT_EXPORT void Key(unsigned char key,
int vtkmNotUsed(x), int vtkmNotUsed(y) )
{
if(key == 27) //escape pressed
{
exit(0);
}
}
VTKM_CONT_EXPORT void SpecialKey(int vtkmNotUsed(key),
int vtkmNotUsed(x), int vtkmNotUsed(y) )
{}
VTKM_CONT_EXPORT void Mouse(int vtkmNotUsed(button), int vtkmNotUsed(state),
int vtkmNotUsed(x), int vtkmNotUsed(y) )
{}
VTKM_CONT_EXPORT void MouseMove(int vtkmNotUsed(x), int vtkmNotUsed(y) )
{}
VTKM_CONT_EXPORT void PassiveMouseMove(int vtkmNotUsed(x), int vtkmNotUsed(y) )
{}
};
}
}
}
#endif //vtk_m_opengl_testing_TestingWindow_h
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_opengl_testing_TestingWindow_h
#define vtk_m_opengl_testing_TestingWindow_h
#include <vtkm/internal/ExportMacros.h>
#include <vtkm/opengl/testing/WindowBase.h>
namespace vtkm{
namespace opengl{
namespace testing{
/// \brief Basic Render Window that only makes sure opengl has a valid context
///
/// Bare-bones class that fulfullis the requirements of WindowBase but
/// has no ability to interact with opengl other than to close down the window
///
///
class TestingWindow : public vtkm::opengl::testing::WindowBase<TestingWindow>
{
public:
VTKM_CONT_EXPORT TestingWindow(){};
//called after opengl is inited
VTKM_CONT_EXPORT void PostInit()
{}
VTKM_CONT_EXPORT void Display()
{}
VTKM_CONT_EXPORT void Idle()
{}
VTKM_CONT_EXPORT void ChangeSize(int vtkmNotUsed(w), int vtkmNotUsed(h) )
{}
VTKM_CONT_EXPORT void Key(unsigned char key,
int vtkmNotUsed(x), int vtkmNotUsed(y) )
{
if(key == 27) //escape pressed
{
exit(0);
}
}
VTKM_CONT_EXPORT void SpecialKey(int vtkmNotUsed(key),
int vtkmNotUsed(x), int vtkmNotUsed(y) )
{}
VTKM_CONT_EXPORT void Mouse(int vtkmNotUsed(button), int vtkmNotUsed(state),
int vtkmNotUsed(x), int vtkmNotUsed(y) )
{}
VTKM_CONT_EXPORT void MouseMove(int vtkmNotUsed(x), int vtkmNotUsed(y) )
{}
VTKM_CONT_EXPORT void PassiveMouseMove(int vtkmNotUsed(x), int vtkmNotUsed(y) )
{}
};
}
}
}
#endif //vtk_m_opengl_testing_TestingWindow_h

@ -1,30 +1,30 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
//This sets up testing with the default device adapter and array container
#include <vtkm/cont/DeviceAdapterSerial.h>
#include <vtkm/opengl/testing/TestingOpenGLInterop.h>
int UnitTestTransferToOpenGL(int, char *[])
{
return vtkm::opengl::testing::TestingOpenGLInterop<
vtkm::cont::DeviceAdapterTagSerial >::Run();
}
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
//This sets up testing with the default device adapter and array container
#include <vtkm/cont/DeviceAdapterSerial.h>
#include <vtkm/opengl/testing/TestingOpenGLInterop.h>
int UnitTestTransferToOpenGL(int, char *[])
{
return vtkm::opengl::testing::TestingOpenGLInterop<
vtkm::cont::DeviceAdapterTagSerial >::Run();
}

@ -1,160 +1,171 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtkm_m_opengl_testing_WindowBase_h
#define vtkm_m_opengl_testing_WindowBase_h
//constructs a valid openGL context so that we can verify
//that vtkm to open gl bindings work
#include <string>
// OpenGL Graphics includes
//glew needs to go before glut
#include <vtkm/opengl/internal/OpenGLHeaders.h>
#if defined (__APPLE__)
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif
#include <vtkm/cont/ErrorControlBadValue.h>
#ifdef VTKM_CUDA
# include <vtkm/cont/cuda/ChooseCudaDevice.h>
# include <vtkm/opengl/cuda/SetOpenGLDevice.h>
#endif
#include <iostream>
namespace vtkm{
namespace opengl{
namespace testing{
namespace internal
{
template <typename T>
struct GLUTStaticCallbackHolder
{ static T* StaticGLUTResource; };
template <typename T>
T* GLUTStaticCallbackHolder<T>::StaticGLUTResource;
}
/// \brief Basic GLUT Wrapper class
///
/// This class gives the ability to wrap the glut function callbacks into
/// a single class so that you can use c++ objects. The only downside
/// is that you can only have a single window created
///
template< class Derived >
class WindowBase : private internal::GLUTStaticCallbackHolder<Derived>
{
public:
void Init(std::string title, int width, int height,
int argc, char** argv)
{
//set our selves as the static instance to call
WindowBase<Derived>::StaticGLUTResource = static_cast<Derived*>(this);
glutInit(&argc,argv);
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowPosition(0,0);
glutInitWindowSize(width,height);
glutCreateWindow(title.c_str());
// glewExperimental = GL_TRUE;
glewInit();
if(!glewIsSupported("GL_VERSION_2_1"))
{
std::cerr << glGetString(GL_RENDERER) << std::endl;
std::cerr << glGetString(GL_VERSION) << std::endl;
throw vtkm::cont::ErrorControlBadValue(
"Unable to create an OpenGL 2.1 Context");
}
#ifdef VTKM_CUDA
int id = vtkm::cuda::cont::FindFastestDeviceId();
vtkm::opengl::cuda::SetCudaGLDevice(id);
#endif
//attach all the glut call backs
glutDisplayFunc( WindowBase<Derived>::GLUTDisplayCallback );
glutIdleFunc( WindowBase<Derived>::GLUTIdleCallback );
glutReshapeFunc( WindowBase<Derived>::GLUTChangeSizeCallback );
glutKeyboardFunc( WindowBase<Derived>::GLUTKeyCallback );
glutSpecialFunc( WindowBase<Derived>::GLUTSpecialKeyCallback );
glutMouseFunc( WindowBase<Derived>::GLUTMouseCallback );
glutMotionFunc( WindowBase<Derived>::GLUTMouseMoveCallback );
glutPassiveMotionFunc( WindowBase<Derived>::GLUTPassiveMouseMoveCallback );
//call any custom init code you want to have
WindowBase<Derived>::StaticGLUTResource->PostInit();
}
void Init(std::string title, int width, int height)
{
int argc=0;
char** argv = 0;
Init(title,width,height,argc,argv);
}
//Init must be called before you call Start so that we have a valid
//opengl context
void Start()
{
glutMainLoop();
}
static void GLUTDisplayCallback()
{ WindowBase<Derived>::StaticGLUTResource->Display(); }
static void GLUTIdleCallback()
{ WindowBase<Derived>::StaticGLUTResource->Idle(); }
static void GLUTChangeSizeCallback(int width, int height)
{ WindowBase<Derived>::StaticGLUTResource->ChangeSize(width,height); }
static void GLUTKeyCallback(unsigned char key, int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->Key(key,x,y); }
static void GLUTSpecialKeyCallback(int key, int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->SpecialKey(key,x,y); }
static void GLUTMouseCallback(int button, int state ,int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->Mouse(button,state,x,y); }
static void GLUTMouseMoveCallback(int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->MouseMove(x,y); }
static void GLUTPassiveMouseMoveCallback(int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->PassiveMouseMove(x,y); }
};
}
}
}
#endif //vtkm_m_opengl_testing_WindowBase_h
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtkm_m_opengl_testing_WindowBase_h
#define vtkm_m_opengl_testing_WindowBase_h
//constructs a valid openGL context so that we can verify
//that vtkm to open gl bindings work
#include <string>
#include <vtkm/internal/Configure.h>
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) && !defined(VTKM_PGI)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
// OpenGL Graphics includes
//glew needs to go before glut
#include <vtkm/opengl/internal/OpenGLHeaders.h>
#if defined (__APPLE__)
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif
#include <vtkm/cont/ErrorControlBadValue.h>
#ifdef VTKM_CUDA
# include <vtkm/cont/cuda/ChooseCudaDevice.h>
# include <vtkm/opengl/cuda/SetOpenGLDevice.h>
#endif
#include <iostream>
namespace vtkm{
namespace opengl{
namespace testing{
namespace internal
{
template <typename T>
struct GLUTStaticCallbackHolder
{ static T* StaticGLUTResource; };
template <typename T>
T* GLUTStaticCallbackHolder<T>::StaticGLUTResource;
}
/// \brief Basic GLUT Wrapper class
///
/// This class gives the ability to wrap the glut function callbacks into
/// a single class so that you can use c++ objects. The only downside
/// is that you can only have a single window created
///
template< class Derived >
class WindowBase : private internal::GLUTStaticCallbackHolder<Derived>
{
public:
void Init(std::string title, int width, int height,
int argc, char** argv)
{
//set our selves as the static instance to call
WindowBase<Derived>::StaticGLUTResource = static_cast<Derived*>(this);
glutInit(&argc,argv);
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowPosition(0,0);
glutInitWindowSize(width,height);
glutCreateWindow(title.c_str());
// glewExperimental = GL_TRUE;
glewInit();
if(!glewIsSupported("GL_VERSION_2_1"))
{
std::cerr << glGetString(GL_RENDERER) << std::endl;
std::cerr << glGetString(GL_VERSION) << std::endl;
throw vtkm::cont::ErrorControlBadValue(
"Unable to create an OpenGL 2.1 Context");
}
#ifdef VTKM_CUDA
int id = vtkm::cuda::cont::FindFastestDeviceId();
vtkm::opengl::cuda::SetCudaGLDevice(id);
#endif
//attach all the glut call backs
glutDisplayFunc( WindowBase<Derived>::GLUTDisplayCallback );
glutIdleFunc( WindowBase<Derived>::GLUTIdleCallback );
glutReshapeFunc( WindowBase<Derived>::GLUTChangeSizeCallback );
glutKeyboardFunc( WindowBase<Derived>::GLUTKeyCallback );
glutSpecialFunc( WindowBase<Derived>::GLUTSpecialKeyCallback );
glutMouseFunc( WindowBase<Derived>::GLUTMouseCallback );
glutMotionFunc( WindowBase<Derived>::GLUTMouseMoveCallback );
glutPassiveMotionFunc( WindowBase<Derived>::GLUTPassiveMouseMoveCallback );
//call any custom init code you want to have
WindowBase<Derived>::StaticGLUTResource->PostInit();
}
void Init(std::string title, int width, int height)
{
int argc=0;
char** argv = 0;
Init(title,width,height,argc,argv);
}
//Init must be called before you call Start so that we have a valid
//opengl context
void Start()
{
glutMainLoop();
}
static void GLUTDisplayCallback()
{ WindowBase<Derived>::StaticGLUTResource->Display(); }
static void GLUTIdleCallback()
{ WindowBase<Derived>::StaticGLUTResource->Idle(); }
static void GLUTChangeSizeCallback(int width, int height)
{ WindowBase<Derived>::StaticGLUTResource->ChangeSize(width,height); }
static void GLUTKeyCallback(unsigned char key, int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->Key(key,x,y); }
static void GLUTSpecialKeyCallback(int key, int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->SpecialKey(key,x,y); }
static void GLUTMouseCallback(int button, int state ,int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->Mouse(button,state,x,y); }
static void GLUTMouseMoveCallback(int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->MouseMove(x,y); }
static void GLUTPassiveMouseMoveCallback(int x, int y)
{ WindowBase<Derived>::StaticGLUTResource->PassiveMouseMove(x,y); }
};
}
}
}
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) && !defined(VTKM_PGI)
# pragma GCC diagnostic pop
#endif
#endif //vtkm_m_opengl_testing_WindowBase_h

@ -346,29 +346,6 @@ bool test_equal(const vtkm::Pair<T1,T2> &pair1,
&& test_equal(pair1.second, pair2.second, tolerance);
}
/// Helper function for printing out vectors during testing.
///
template<typename T, vtkm::IdComponent Size>
VTKM_CONT_EXPORT
std::ostream &operator<<(std::ostream &stream, const vtkm::Vec<T,Size> &vec)
{
stream << "[";
for (vtkm::IdComponent component = 0; component < Size-1; component++)
{
stream << vec[component] << ",";
}
return stream << vec[Size-1] << "]";
}
/// Helper function for printing out pairs during testing.
///
template<typename T, typename U>
VTKM_EXEC_CONT_EXPORT
std::ostream &operator<<(std::ostream &stream, const vtkm::Pair<T,U> &vec)
{
return stream << "[" << vec.first << "," << vec.second << "]";
}
template<typename T>
VTKM_EXEC_CONT_EXPORT

@ -25,6 +25,7 @@ set(headers
WorkletMapTopology.h
AverageByKey.h
CellAverage.h
Clip.h
ExternalFaces.h
PointElevation.h
VertexClustering.h

@ -27,7 +27,8 @@ namespace vtkm {
namespace worklet {
//simple functor that returns the average point value.
class CellAverage : public vtkm::worklet::WorkletMapTopology
class CellAverage :
public vtkm::worklet::WorkletMapTopologyPointToCell
{
public:
typedef void ControlSignature(FieldInFrom<Scalar> inPoints,

663
vtkm/worklet/Clip.h Normal file

@ -0,0 +1,663 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtkm_m_worklet_Clip_h
#define vtkm_m_worklet_Clip_h
#include <vtkm/worklet/DispatcherMapTopology.h>
#include <vtkm/worklet/WorkletMapTopology.h>
#include <vtkm/worklet/internal/ClipTables.h>
#include <vtkm/cont/CellSetExplicit.h>
#include <vtkm/cont/DeviceAdapterAlgorithm.h>
#include <vtkm/cont/DynamicArrayHandle.h>
#include <vtkm/cont/DynamicCellSet.h>
#include <vtkm/exec/ExecutionWholeArray.h>
#include <vtkm/exec/FunctorBase.h>
#define COMBINE_LOWERBOUND_AMEND 0
namespace vtkm {
namespace worklet {
namespace internal {
// TODO: The following code is meant to be temporary until similar functionality is
// implemented elsewhere.
// The current DeviceAdapterAlgorithm::Copy resizes the destination array, and
// therefore, is not usable for our purpose here.
template <typename T, typename StorageIn, typename StorageOut, typename DeviceAdapter>
class CopyArray : public vtkm::exec::FunctorBase
{
public:
typedef typename vtkm::cont::ArrayHandle<T, StorageIn>
::template ExecutionTypes<DeviceAdapter>::PortalConst SourcePortalType;
typedef typename vtkm::cont::ArrayHandle<T, StorageOut>
::template ExecutionTypes<DeviceAdapter>::Portal DestPortalType;
VTKM_CONT_EXPORT
CopyArray(SourcePortalType input, DestPortalType output)
: Input(input), Output(output)
{
}
VTKM_EXEC_EXPORT
void operator()(vtkm::Id idx) const
{
this->Output.Set(idx, this->Input.Get(idx));
}
private:
SourcePortalType Input;
DestPortalType Output;
};
template <typename T, typename StorageIn, typename StorageOut, typename DeviceAdapter>
VTKM_CONT_EXPORT
void ResizeArrayHandle(const vtkm::cont::ArrayHandle<T, StorageIn> &input,
vtkm::Id size,
vtkm::cont::ArrayHandle<T, StorageOut> &output,
DeviceAdapter)
{
typedef vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter> Algorithm;
output.Allocate(size);
CopyArray<T, StorageIn, StorageOut, DeviceAdapter>
copyArray(input.PrepareForInput(DeviceAdapter()),
output.PrepareForInPlace(DeviceAdapter()));
Algorithm::Schedule(copyArray, input.GetNumberOfValues());
}
template<typename T>
VTKM_EXEC_EXPORT
void swap(T &v1, T &v2)
{
T temp = v1;
v1 = v2;
v2 = temp;
}
template <typename DeviceAdapter>
class ExecutionConnectivityExplicit : vtkm::exec::ExecutionObjectBase
{
private:
typedef typename vtkm::cont::ArrayHandle<vtkm::Id>
::template ExecutionTypes<DeviceAdapter>::Portal IdPortal;
public:
VTKM_CONT_EXPORT
ExecutionConnectivityExplicit()
: Shapes(), NumIndices(), Connectivity(), IndexOffsets()
{
}
VTKM_CONT_EXPORT
ExecutionConnectivityExplicit(const IdPortal &shapes,
const IdPortal &numIndices,
const IdPortal &connectivity,
const IdPortal &indexOffsets)
: Shapes(shapes),
NumIndices(numIndices),
Connectivity(connectivity),
IndexOffsets(indexOffsets)
{
}
VTKM_EXEC_EXPORT
void SetCellShape(vtkm::Id cellIndex, vtkm::Id shape)
{
this->Shapes.Set(cellIndex, shape);
}
VTKM_EXEC_EXPORT
void SetNumberOfIndices(vtkm::Id cellIndex, vtkm::Id numIndices)
{
this->NumIndices.Set(cellIndex, numIndices);
}
VTKM_EXEC_EXPORT
void SetIndexOffset(vtkm::Id cellIndex, vtkm::Id indexOffset)
{
this->IndexOffsets.Set(cellIndex, indexOffset);
}
VTKM_EXEC_EXPORT
void SetConnectivity(vtkm::Id connectivityIndex, vtkm::Id pointIndex)
{
this->Connectivity.Set(connectivityIndex, pointIndex);
}
private:
IdPortal Shapes;
IdPortal NumIndices;
IdPortal Connectivity;
IdPortal IndexOffsets;
};
} // namespace internal
struct ClipStats
{
vtkm::Id NumberOfCells;
vtkm::Id NumberOfIndices;
vtkm::Id NumberOfNewPoints;
VTKM_EXEC_CONT_EXPORT
ClipStats operator+(const ClipStats &cs) const
{
ClipStats sum;
sum.NumberOfCells = this->NumberOfCells + cs.NumberOfCells;
sum.NumberOfIndices = this->NumberOfIndices + cs.NumberOfIndices;
sum.NumberOfNewPoints = this->NumberOfNewPoints + cs.NumberOfNewPoints;
return sum;
}
};
struct EdgeInterpolation
{
vtkm::Id Vertex1, Vertex2;
vtkm::Float64 Weight;
struct LessThanOp
{
VTKM_EXEC_EXPORT
bool operator()(const EdgeInterpolation &v1, const EdgeInterpolation &v2) const
{
return (v1.Vertex1 < v2.Vertex1) ||
(v1.Vertex1 == v2.Vertex1 && v1.Vertex2 < v2.Vertex2);
}
};
struct EqualToOp
{
VTKM_EXEC_EXPORT
bool operator()(const EdgeInterpolation &v1, const EdgeInterpolation &v2) const
{
return v1.Vertex1 == v2.Vertex1 && v1.Vertex2 == v2.Vertex2;
}
};
};
VTKM_EXEC_CONT_EXPORT
std::ostream& operator<<(std::ostream &out, const ClipStats &val)
{
return out << std::endl << "{ Cells: " << val.NumberOfCells
<< ", Indices: " << val.NumberOfIndices
<< ", NewPoints: " << val.NumberOfNewPoints << " }";
}
VTKM_EXEC_CONT_EXPORT
std::ostream& operator<<(std::ostream &out, const EdgeInterpolation &val)
{
return out << std::endl << "{ Vertex1: " << val.Vertex1
<< ", Vertex2: " << val.Vertex2
<< ", Weight: " << val.Weight << " }";
}
template<typename DeviceAdapter>
class Clip
{
private:
typedef internal::ClipTables::DevicePortal<DeviceAdapter> ClipTablesPortal;
typedef typename vtkm::cont::ArrayHandle<vtkm::Id>
::template ExecutionTypes<DeviceAdapter>::Portal IdPortal;
typedef typename vtkm::cont::ArrayHandle<vtkm::Id>
::template ExecutionTypes<DeviceAdapter>::PortalConst IdPortalConst;
typedef typename vtkm::cont::ArrayHandle<EdgeInterpolation>
::template ExecutionTypes<DeviceAdapter>::Portal EdgeInterpolationPortal;
typedef typename vtkm::cont::ArrayHandle<EdgeInterpolation>
::template ExecutionTypes<DeviceAdapter>::PortalConst
EdgeInterpolationPortalConst;
typedef vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter> Algorithm;
public:
struct TypeClipStats : vtkm::ListTagBase<ClipStats> { };
class ComputeStats : public vtkm::worklet::WorkletMapTopologyPointToCell
{
public:
typedef void ControlSignature(TopologyIn topology,
FieldInFrom<Scalar> scalars,
FieldOut<IdType> clipTableIdxs,
FieldOut<TypeClipStats> stats);
typedef void ExecutionSignature(_2, CellShape, FromCount, _3, _4);
VTKM_CONT_EXPORT
ComputeStats(vtkm::Float64 value, const ClipTablesPortal &clipTables)
: Value(value), ClipTables(clipTables)
{
}
template<typename ScalarsVecType>
VTKM_EXEC_EXPORT
void operator()(const ScalarsVecType &scalars,
vtkm::Id shape, vtkm::Id count,
vtkm::Id& clipTableIdx, ClipStats& stats) const
{
const vtkm::Id mask[] = { 1, 2, 4, 8, 16, 32, 64, 128 };
vtkm::Id caseId = 0;
for (vtkm::IdComponent i = 0; i < count; ++i)
{
caseId |= (static_cast<vtkm::Float64>(scalars[i]) > this->Value) ?
mask[i] : 0;
}
vtkm::Id idx = this->ClipTables.GetCaseIndex(shape, caseId);
clipTableIdx = idx;
vtkm::Id numberOfCells = this->ClipTables.ValueAt(idx++);
vtkm::Id numberOfIndices = 0;
vtkm::Id numberOfNewPoints = 0;
for (vtkm::Id cell = 0; cell < numberOfCells; ++cell)
{
++idx; // skip shape-id
vtkm::Id npts = this->ClipTables.ValueAt(idx++);
numberOfIndices += npts;
while (npts--)
{
// value < 100 means a new point needs to be generated by clipping an edge
numberOfNewPoints += (this->ClipTables.ValueAt(idx++) < 100) ? 1 : 0;
}
}
stats.NumberOfCells = numberOfCells;
stats.NumberOfIndices = numberOfIndices;
stats.NumberOfNewPoints = numberOfNewPoints;
}
private:
vtkm::Float64 Value;
ClipTablesPortal ClipTables;
};
class GenerateCellSet : public vtkm::worklet::WorkletMapTopologyPointToCell
{
public:
typedef void ControlSignature(TopologyIn topology,
FieldInFrom<Scalar> scalars,
FieldInTo<IdType> clipTableIdxs,
FieldInTo<TypeClipStats> cellSetIdxs,
ExecObject connectivityExplicit,
ExecObject interpolation,
ExecObject newPointsConnectivityReverseMap);
typedef void ExecutionSignature(CellShape, _2, FromIndices, _3, _4, _5, _6, _7);
VTKM_CONT_EXPORT
GenerateCellSet(vtkm::Float64 value, const ClipTablesPortal clipTables)
: Value(value), ClipTables(clipTables)
{
}
template<typename ScalarsVecType, typename IndicesVecType, typename Storage>
VTKM_EXEC_EXPORT
void operator()(
vtkm::Id shape,
const ScalarsVecType &scalars,
const IndicesVecType &indices,
vtkm::Id clipTableIdx,
ClipStats cellSetIndices,
internal::ExecutionConnectivityExplicit<DeviceAdapter> connectivityExplicit,
vtkm::exec::ExecutionWholeArray<EdgeInterpolation, Storage, DeviceAdapter>
interpolation,
vtkm::exec::ExecutionWholeArray<vtkm::Id, Storage, DeviceAdapter>
newPointsConnectivityReverseMap) const
{
vtkm::Id idx = clipTableIdx;
// index of first cell
vtkm::Id cellIdx = cellSetIndices.NumberOfCells;
// index of first cell in connectivity array
vtkm::Id connectivityIdx = cellSetIndices.NumberOfIndices;
// index of new points generated by first cell
vtkm::Id newPtsIdx = cellSetIndices.NumberOfNewPoints;
vtkm::Id numberOfCells = this->ClipTables.ValueAt(idx++);
for (vtkm::Id cell = 0; cell < numberOfCells; ++cell, ++cellIdx)
{
connectivityExplicit.SetCellShape(cellIdx, this->ClipTables.ValueAt(idx++));
vtkm::Id numPoints = this->ClipTables.ValueAt(idx++);
connectivityExplicit.SetNumberOfIndices(cellIdx, numPoints);
connectivityExplicit.SetIndexOffset(cellIdx, connectivityIdx);
for (vtkm::Id pt = 0; pt < numPoints; ++pt, ++idx)
{
vtkm::IdComponent entry =
static_cast<vtkm::IdComponent>(this->ClipTables.ValueAt(idx));
if (entry >= 100) // existing point
{
connectivityExplicit.SetConnectivity(connectivityIdx++,
indices[entry - 100]);
}
else // edge, new point to be generated by cutting the egde
{
vtkm::Vec<vtkm::IdComponent, 2> edge =
this->ClipTables.GetEdge(shape, entry);
EdgeInterpolation ei;
ei.Vertex1 = indices[edge[0]];
ei.Vertex2 = indices[edge[1]];
if (ei.Vertex1 > ei.Vertex2)
{
internal::swap(ei.Vertex1, ei.Vertex2);
internal::swap(edge[0], edge[1]);
}
ei.Weight = (static_cast<vtkm::Float64>(scalars[edge[0]]) - this->Value) /
static_cast<vtkm::Float64>(scalars[edge[0]] - scalars[edge[1]]);
interpolation.Set(newPtsIdx , ei);
newPointsConnectivityReverseMap.Set(newPtsIdx, connectivityIdx++);
++newPtsIdx;
}
}
}
}
private:
vtkm::Float64 Value;
ClipTablesPortal ClipTables;
};
// TODO: Profile and choose the better performing implementation
#if defined(COMBINE_LOWERBOUND_AMEND)
class AmendConnectivity : public vtkm::exec::FunctorBase
{
public:
VTKM_CONT_EXPORT
AmendConnectivity(EdgeInterpolationPortalConst newPoints,
EdgeInterpolationPortalConst uniqueNewPoints,
IdPortalConst newPointsConnectivityReverseMap,
vtkm::Id newPointsOffset,
IdPortal connectivity)
: NewPoints(newPoints),
UniqueNewPoints(uniqueNewPoints),
NewPointsConnectivityReverseMap(newPointsConnectivityReverseMap),
NewPointsOffset(newPointsOffset),
Connectivity(connectivity)
{
}
VTKM_EXEC_EXPORT
void operator()(vtkm::Id idx) const
{
EdgeInterpolation current = this->NewPoints.Get(idx);
typename EdgeInterpolation::LessThanOp lt;
// find point index by looking up in the unique points array (binary search)
vtkm::Id count = UniqueNewPoints.GetNumberOfValues();
vtkm::Id first = 0;
while (count > 0)
{
vtkm::Id step = count/2;
vtkm::Id mid = first + step;
if (lt(this->UniqueNewPoints.Get(mid), current))
{
first = ++mid;
count = step - 1;
}
else
{
count = step;
}
}
this->Connectivity.Set(this->NewPointsConnectivityReverseMap.Get(idx),
this->NewPointsOffset + first);
}
private:
EdgeInterpolationPortalConst NewPoints;
EdgeInterpolationPortalConst UniqueNewPoints;
IdPortalConst NewPointsConnectivityReverseMap;
vtkm::Id NewPointsOffset;
IdPortal Connectivity;
};
#else
class AmendConnectivity : public vtkm::exec::FunctorBase
{
public:
VTKM_CONT_EXPORT
AmendConnectivity(IdPortalConst newPointsConnectivityReverseMap,
IdPortalConst connectivityValues,
vtkm::Id newPointsOffset,
IdPortal connectivity)
: NewPointsConnectivityReverseMap(newPointsConnectivityReverseMap),
ConnectivityValues(connectivityValues),
NewPointsStartIndex(newPointsOffset),
Connectivity(connectivity)
{
}
VTKM_EXEC_EXPORT
void operator()(vtkm::Id idx) const
{
this->Connectivity.Set(this->NewPointsConnectivityReverseMap.Get(idx),
this->ConnectivityValues.Get(idx) + this->NewPointsOffset);
}
private:
IdPortalConst NewPointsConnectivityReverseMap;
IdPortalConst ConnectivityValues;
vtkm::Id NewPointsOffset;
IdPortal Connectivity;
};
#endif
class InterpolateField
{
public:
template <typename T>
class Kernel : public vtkm::exec::FunctorBase
{
public:
typedef typename vtkm::cont::ArrayHandle<T>
::template ExecutionTypes<DeviceAdapter>::Portal FieldPortal;
VTKM_CONT_EXPORT
Kernel(EdgeInterpolationPortalConst interpolation,
vtkm::Id newPointsOffset,
FieldPortal field)
: Interpolation(interpolation), NewPointsOffset(newPointsOffset), Field(field)
{
}
VTKM_EXEC_EXPORT
void operator()(vtkm::Id idx) const
{
EdgeInterpolation ei = this->Interpolation.Get(idx);
T v1 = Field.Get(ei.Vertex1);
T v2 = Field.Get(ei.Vertex2);
typename VecTraits<T>::ComponentType w =
static_cast<typename VecTraits<T>::ComponentType>(ei.Weight);
Field.Set(this->NewPointsOffset + idx, (w * (v2 - v1)) + v1);
}
private:
EdgeInterpolationPortalConst Interpolation;
vtkm::Id NewPointsOffset;
FieldPortal Field;
};
template <typename T, typename Storage>
VTKM_CONT_EXPORT
void operator()(const vtkm::cont::ArrayHandle<T, Storage> &field) const
{
vtkm::Id count = this->InterpolationArray.GetNumberOfValues();
vtkm::cont::ArrayHandle<T, VTKM_DEFAULT_STORAGE_TAG> result;
internal::ResizeArrayHandle(field, field.GetNumberOfValues() + count,
result, DeviceAdapter());
Kernel<T> kernel(
this->InterpolationArray.PrepareForInput(DeviceAdapter()),
this->NewPointsOffset,
result.PrepareForInPlace(DeviceAdapter()));
Algorithm::Schedule(kernel, count);
*(this->Output) = vtkm::cont::DynamicArrayHandle(result);
}
VTKM_CONT_EXPORT
InterpolateField(
vtkm::cont::ArrayHandle<EdgeInterpolation> interpolationArray,
vtkm::Id newPointsOffset,
vtkm::cont::DynamicArrayHandle *output)
: InterpolationArray(interpolationArray),
NewPointsOffset(newPointsOffset),
Output(output)
{
}
private:
vtkm::cont::ArrayHandle<EdgeInterpolation> InterpolationArray;
vtkm::Id NewPointsOffset;
vtkm::cont::DynamicArrayHandle *Output;
};
Clip()
: ClipTablesInstance(), NewPointsInterpolation(), NewPointsOffset()
{
}
vtkm::cont::CellSetExplicit<> Run(const vtkm::cont::DynamicCellSet &cellSet,
const vtkm::cont::DynamicArrayHandle &scalars,
vtkm::Float64 value)
{
DeviceAdapter device;
ClipTablesPortal clipTablesDevicePortal =
this->ClipTablesInstance.GetDevicePortal(device);
// Step 1. compute counts for the elements of the cell set data structure
vtkm::cont::ArrayHandle<vtkm::Id> clipTableIdxs;
vtkm::cont::ArrayHandle<ClipStats> stats;
ComputeStats computeStats(value, clipTablesDevicePortal);
DispatcherMapTopology<ComputeStats>(computeStats).Invoke(cellSet, scalars,
clipTableIdxs, stats);
// compute offsets for each invocation
vtkm::cont::ArrayHandle<ClipStats> cellSetIndices;
ClipStats total = Algorithm::ScanExclusive(stats, cellSetIndices);
// Step 2. generate the output cell set
vtkm::cont::ArrayHandle<vtkm::Id> shapes;
vtkm::cont::ArrayHandle<vtkm::Id> numIndices;
vtkm::cont::ArrayHandle<vtkm::Id> connectivity;
vtkm::cont::ArrayHandle<vtkm::Id> cellToConnectivityMap;
internal::ExecutionConnectivityExplicit<DeviceAdapter> outConnectivity(
shapes.PrepareForOutput(total.NumberOfCells, device),
numIndices.PrepareForOutput(total.NumberOfCells, device),
connectivity.PrepareForOutput(total.NumberOfIndices, device),
cellToConnectivityMap.PrepareForOutput(total.NumberOfCells, device));
vtkm::cont::ArrayHandle<EdgeInterpolation> newPoints;
// reverse map from the new points to connectivity array
vtkm::cont::ArrayHandle<vtkm::Id> newPointsConnectivityReverseMap;
GenerateCellSet generateCellSet(value, clipTablesDevicePortal);
DispatcherMapTopology<GenerateCellSet>(generateCellSet).Invoke(cellSet, scalars,
clipTableIdxs, cellSetIndices, outConnectivity,
vtkm::exec::ExecutionWholeArray<
EdgeInterpolation,
VTKM_DEFAULT_STORAGE_TAG,
DeviceAdapter>(newPoints, total.NumberOfNewPoints),
vtkm::exec::ExecutionWholeArray<
vtkm::Id,
VTKM_DEFAULT_STORAGE_TAG,
DeviceAdapter>(newPointsConnectivityReverseMap, total.NumberOfNewPoints));
// Step 3. remove duplicates from the list of new points
vtkm::cont::ArrayHandle<vtkm::worklet::EdgeInterpolation> uniqueNewPoints;
Algorithm::SortByKey(newPoints, newPointsConnectivityReverseMap,
EdgeInterpolation::LessThanOp());
Algorithm::Copy(newPoints, uniqueNewPoints);
Algorithm::Unique(uniqueNewPoints, EdgeInterpolation::EqualToOp());
this->NewPointsInterpolation = uniqueNewPoints;
this->NewPointsOffset = scalars.GetNumberOfValues();
// Step 4. update the connectivity array with indexes to the new, unique points
#if defined(COMBINE_LOWERBOUND_AMEND)
AmendConnectivity computeNewPointsConnectivity(
newPoints.PrepareForInput(device),
uniqueNewPoints.PrepareForInput(device),
newPointsConnectivityReverseMap.PrepareForInput(device),
this->NewPointsOffset,
connectivity.PrepareForInPlace(device));
Algorithm::Schedule(computeNewPointsConnectivity, total.NumberOfNewPoints);
#else
vtkm::cont::ArrayHandle<vtkm::Id> newPointsIndices;
Algorithm::LowerBounds(uniqueNewPoints, newPointsInfo, newPointsIndices,
EdgeInterpolation::LessThanOp());
Algorithm::Schedule(
AmendConnectivity(newPointsConnectivityMap.PrepareForInput(device),
newPointsIndices.PrepareForInput(device),
this->NewPointsOffset,
connectivity.PrepareForInPlace(device)),
total.NumberOfNewPoints);
#endif
vtkm::cont::CellSetExplicit<> output;
output.Fill(shapes, numIndices, connectivity);
return output;
}
template <typename DynamicArrayHandleType>
vtkm::cont::DynamicArrayHandle ProcessField(
const DynamicArrayHandleType &fieldData) const
{
vtkm::cont::DynamicArrayHandle output;
fieldData.CastAndCall(InterpolateField(this->NewPointsInterpolation,
this->NewPointsOffset,
&output));
return output;
}
private:
internal::ClipTables ClipTablesInstance;
vtkm::cont::ArrayHandle<EdgeInterpolation> NewPointsInterpolation;
vtkm::Id NewPointsOffset;
};
}
} // namespace vtkm::worklet
#endif // vtkm_m_worklet_Clip_h

@ -36,13 +36,13 @@ class DispatcherMapTopology :
public vtkm::worklet::internal::DispatcherBase<
DispatcherMapTopology<WorkletType,Device>,
WorkletType,
vtkm::worklet::WorkletMapTopology,
vtkm::worklet::template WorkletMapTopology<typename WorkletType::FromTopologyType, typename WorkletType::ToTopologyType>,
Device>
{
typedef vtkm::worklet::internal::DispatcherBase<
DispatcherMapTopology<WorkletType,Device>,
WorkletType,
vtkm::worklet::WorkletMapTopology,
vtkm::worklet::template WorkletMapTopology<typename WorkletType::FromTopologyType, typename WorkletType::ToTopologyType>,
Device> Superclass;
public:
@ -85,7 +85,7 @@ public:
// scheduling and call BadicInvoke.
this->BasicInvoke(invocation,
inputDomain.GetSchedulingRange(
vtkm::TopologyElementTagCell()));
typename WorkletType::ToTopologyType()));
}
};

@ -23,6 +23,7 @@
#include <vtkm/worklet/internal/WorkletBase.h>
#include <vtkm/TypeListTag.h>
#include <vtkm/TopologyElementTag.h>
#include <vtkm/cont/arg/ControlSignatureTagBase.h>
#include <vtkm/cont/arg/TransportTagArrayIn.h>
@ -48,15 +49,16 @@ namespace worklet {
/// inputs and outputs are on the same domain. That is, all the arrays are the
/// same size.
///
/// TODO: Although the nomenclature of this class suggests it handles general
/// topological links, it really only handles point to cell operations for
/// now. This worklet needs to be templated to handle generic from/to topology
/// links. I also suggest having convenience subclasses for common (supported?)
/// TODO: I also suggest having convenience subclasses for common (supported?)
/// link directions.
///
template<typename FromTopology, typename ToTopology>
class WorkletMapTopology : public vtkm::worklet::internal::WorkletBase
{
public:
typedef FromTopology FromTopologyType;
typedef ToTopology ToTopologyType;
/// \brief A control signature tag for input fields.
///
/// This tag takes a template argument that is a type list tag that limits
@ -85,7 +87,7 @@ public:
///
struct TopologyIn : vtkm::cont::arg::ControlSignatureTagBase {
typedef vtkm::cont::arg::TypeCheckTagTopology TypeCheckTag;
typedef vtkm::cont::arg::TransportTagTopologyIn TransportTag;
typedef vtkm::cont::arg::TransportTagTopologyIn<FromTopology,ToTopology> TransportTag;
typedef vtkm::exec::arg::FetchTagTopologyIn FetchTag;
};
@ -138,6 +140,13 @@ public:
struct FromIndices : vtkm::exec::arg::FromIndices { };
};
/// Convenience base class for worklets that map from Points to Cells.
///
class WorkletMapTopologyPointToCell
: public WorkletMapTopology<vtkm::TopologyElementTagPoint,
vtkm::TopologyElementTagCell>
{ };
}
} // namespace vtkm::worklet

@ -21,6 +21,7 @@
set(headers
DispatcherBase.h
WorkletBase.h
ClipTables.h
)
vtkm_declare_headers(${headers})

@ -0,0 +1,248 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2015 Sandia Corporation.
// Copyright 2015 UT-Battelle, LLC.
// Copyright 2015 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_ClipTables_h
#define vtk_m_ClipTables_h
#include <vtkm/CellType.h>
#include <vtkm/Types.h>
#include <vtkm/cont/ArrayHandle.h>
namespace vtkm {
namespace worklet {
namespace internal {
// table format:
// ncells, {{celltype, nverts, {edge/verts(>=100), ...}}, ...}, -1 padding
// values < 100 represent edges where the corresponding vertex lies
// values >= 100 reresent existing vertices of the input cell (vertex = value - 100)
static vtkm::Id ClipTablesData[] = {
// VTKM_VERTEX
0, -1, -1, -1, // 0
1, 1, 1, 100, // 1
// VTKM_LINE
0, -1, -1, -1, -1, // 0
1, 3, 2, 100, 1, // 1
1, 3, 2, 0, 101, // 2
1, 3, 2, 100, 101, // 3
// VTKM_TRIANGLE
0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0
1, 5, 3, 0, 2, 100, 0, -1, -1, -1, -1, // 1
1, 5, 3, 1, 0, 101, 0, -1, -1, -1, -1, // 2
2, 5, 3, 1, 2, 100, 5, 3, 1, 100, 101, // 3
1, 5, 3, 2, 1, 102, 0, -1, -1, -1, -1, // 4
2, 5, 3, 0, 1, 102, 5, 3, 102, 100, 0, // 5
2, 5, 3, 0, 101, 2, 5, 3, 2, 101, 102, // 6
1, 5, 3, 100, 101, 102, 0, -1, -1, -1, -1, // 7
// VTKM_PIXEL
0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0
1, 5, 3, 100, 0, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 1
1, 5, 3, 101, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 2
1, 8, 4, 100, 101, 1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 3
1, 5, 3, 102, 3, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 4
1, 8, 4, 100, 0, 2, 102, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 5
3, 5, 3, 101, 1, 0, 5, 3, 102, 3, 2, 8, 4, 0, 1, 2, 3, // 6
3, 5, 3, 100, 101, 1, 5, 3, 100, 1, 2, 5, 3, 100, 2, 102, -1, // 7
1, 5, 3, 103, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 8
3, 5, 3, 100, 0, 3, 5, 3, 103, 2, 1, 8, 4, 0, 1, 2, 3, // 9
1, 8, 4, 101, 103, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10
3, 5, 3, 100, 101, 3, 5, 3, 101, 2, 3, 5, 3, 101, 103, 2, -1, // 11
1, 8, 4, 103, 102, 3, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 12
3, 5, 3, 100, 0, 102, 5, 3, 0, 1, 102, 5, 3, 1, 103, 102, -1, // 13
3, 5, 3, 0, 101, 103, 5, 3, 0, 103, 3, 5, 3, 103, 102, 3, -1, // 14
1, 8, 4, 100, 101, 103, 102, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 15
// VTKM_QUAD
0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0
1, 5, 3, 100, 0, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 1
1, 5, 3, 101, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 2
1, 9, 4, 100, 101, 1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 3
1, 5, 3, 102, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 4
3, 5, 3, 100, 0, 3, 5, 3, 102, 2, 1, 9, 4, 0, 1, 2, 3, // 5
1, 9, 4, 101, 102, 2, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 6
3, 5, 3, 100, 101, 3, 5, 3, 101, 2, 3, 5, 3, 101, 102, 2, -1, // 7
1, 5, 3, 103, 3, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 8
1, 9, 4, 100, 0, 2, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 9
3, 5, 3, 101, 1, 0, 5, 3, 103, 3, 2, 9, 4, 0, 1, 2, 3, // 10
3, 5, 3, 100, 101, 1, 5, 3, 100, 1, 2, 5, 3, 100, 2, 103, -1, // 11
1, 9, 4, 102, 103, 3, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 12
3, 5, 3, 100, 0, 103, 5, 3, 0, 1, 103, 5, 3, 1, 102, 103, -1, // 13
3, 5, 3, 0, 101, 102, 5, 3, 0, 102, 3, 5, 3, 102, 103, 3, -1, // 14
1, 9, 4, 100, 101, 102, 103, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 15
// VTKM_TETRA
0, -1, -1, -1, -1, -1, -1, -1, -1, // 0
1, 10, 4, 0, 3, 2, 100, -1, -1, // 1
1, 10, 4, 0, 1, 4, 101, -1, -1, // 2
1, 13, 6, 101, 1, 4, 100, 2, 3, // 3
1, 10, 4, 1, 2, 5, 102, -1, -1, // 4
1, 13, 6, 102, 5, 1, 100, 3, 0, // 5
1, 13, 6, 102, 2, 5, 101, 0, 4, // 6
1, 13, 6, 3, 4, 5, 100, 101, 102, // 7
1, 10, 4, 3, 4, 5, 103, -1, -1, // 8
1, 13, 6, 103, 4, 5, 100, 0, 2, // 9
1, 13, 6, 103, 5, 3, 101, 1, 0, // 10
1, 13, 6, 100, 101, 103, 2, 1, 5, // 11
1, 13, 6, 2, 102, 1, 3, 103, 4, // 12
1, 13, 6, 0, 1, 4, 100, 102, 103, // 13
1, 13, 6, 0, 3, 2, 101, 103, 102, // 14
1, 10, 4, 100, 101, 102, 103, -1, -1 // 15
};
static vtkm::IdComponent CellEdges[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 3, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 2, 3, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 2, 2, 0, 0, 3, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
enum {
CLIP_TABLES_SIZE = sizeof(ClipTablesData)/sizeof(vtkm::Id),
EDGE_TABLES_SIZE = sizeof(CellEdges)/sizeof(vtkm::IdComponent)
};
static vtkm::Id ShapeToTableWidthMap[VTKM_NUMBER_OF_CELL_TYPES] = {
-1, // VTKM_EMPTY_CELL
4, // VTKM_VERTEX
-1, // VTKM_POLY_VERTEX
5, // VTKM_LINE
-1, // VTKM_POLY_LINE
11, // VTKM_TRIANGLE
-1, // VTKM_TRIANGLE_STRIP
-1, // VTKM_POLYGON
17, // VTKM_PIXEL
17, // VTKM_QUAD
9, // VTKM_TETRA
-1, // VTKM_VOXEL
-1, // VTKM_HEXAHEDRON
-1, // VTKM_WEDGE
-1 // VTKM_PYRAMID
};
static vtkm::Id ShapeToTableIndexMap[VTKM_NUMBER_OF_CELL_TYPES] = {
-1, // VTKM_EMPTY_CELL
0, // VTKM_VERTEX
-1, // VTKM_POLY_VERTEX
8, // VTKM_LINE
-1, // VTKM_POLY_LINE
28, // VTKM_TRIANGLE
-1, // VTKM_TRIANGLE_STRIP
-1, // VTKM_POLYGON
116, // VTKM_PIXEL
388, // VTKM_QUAD
660, // VTKM_TETRA
-1, // VTKM_VOXEL
-1, // VTKM_HEXAHEDRON
-1, // VTKM_WEDGE
-1 // VTKM_PYRAMID
};
class ClipTables
{
private:
typedef vtkm::cont::ArrayHandle<vtkm::Id> IdArrayHandle;
typedef vtkm::cont::ArrayHandle<vtkm::IdComponent> IdComponentArrayHandle;
public:
template<typename DeviceAdapter>
class DevicePortal
{
public:
VTKM_EXEC_EXPORT
vtkm::Id GetCaseIndex(vtkm::Id shape, vtkm::Id caseId) const
{
return this->ShapeToTableIndexMapPortal.Get(shape) +
(this->ShapeToTableWidthMapPortal.Get(shape) * caseId);
}
VTKM_EXEC_EXPORT
vtkm::Id ValueAt(vtkm::Id idx) const
{
return this->ClipTablesPortal.Get(idx);
}
VTKM_EXEC_EXPORT
vtkm::Vec<vtkm::IdComponent, 2> GetEdge(vtkm::Id shape, vtkm::Id edgeId) const
{
vtkm::Id index = (shape * 24) + (edgeId * 2);
return vtkm::make_Vec(this->EdgeTablesPortal.Get(index),
this->EdgeTablesPortal.Get(index + 1));
}
private:
typedef typename IdArrayHandle::ExecutionTypes<DeviceAdapter>::PortalConst
IdPortalConst;
typedef typename IdComponentArrayHandle::ExecutionTypes<DeviceAdapter>::
PortalConst IdComponentPortalConst;
IdPortalConst ClipTablesPortal;
IdPortalConst ShapeToTableWidthMapPortal;
IdPortalConst ShapeToTableIndexMapPortal;
IdComponentPortalConst EdgeTablesPortal;
friend class ClipTables;
};
ClipTables()
: ClipTablesArray(vtkm::cont::make_ArrayHandle(ClipTablesData, CLIP_TABLES_SIZE)),
ShapeToTableWidthMapArray(vtkm::cont::make_ArrayHandle(
ShapeToTableWidthMap, VTKM_NUMBER_OF_CELL_TYPES)),
ShapeToTableIndexMapArray(vtkm::cont::make_ArrayHandle(
ShapeToTableIndexMap, VTKM_NUMBER_OF_CELL_TYPES)),
EdgeTablesArray(vtkm::cont::make_ArrayHandle(CellEdges, EDGE_TABLES_SIZE))
{
}
template<typename DeviceAdapter>
DevicePortal<DeviceAdapter> GetDevicePortal(DeviceAdapter)
{
DevicePortal<DeviceAdapter> portal;
portal.ClipTablesPortal = this->ClipTablesArray.PrepareForInput(DeviceAdapter());
portal.ShapeToTableWidthMapPortal =
this->ShapeToTableWidthMapArray.PrepareForInput(DeviceAdapter());
portal.ShapeToTableIndexMapPortal =
this->ShapeToTableIndexMapArray.PrepareForInput(DeviceAdapter());
portal.EdgeTablesPortal = this->EdgeTablesArray.PrepareForInput(DeviceAdapter());
return portal;
}
private:
IdArrayHandle ClipTablesArray;
IdArrayHandle ShapeToTableWidthMapArray;
IdArrayHandle ShapeToTableIndexMapArray;
IdComponentArrayHandle EdgeTablesArray;
};
}
}
} // namespace vtkm::worklet::internal
#endif // vtk_m_ClipTables_h

@ -20,6 +20,7 @@
set(unit_tests
UnitTestCellAverage.cxx
UnitTestClipping.cxx
UnitTestExternalFaces.cxx
UnitTestPointElevation.cxx
UnitTestWorkletMapField.cxx

@ -0,0 +1,220 @@
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 Sandia Corporation.
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <vtkm/worklet/Clip.h>
#include <vtkm/cont/CellSet.h>
#include <vtkm/cont/CellSetExplicit.h>
#include <vtkm/cont/CoordinateSystem.h>
#include <vtkm/cont/DataSet.h>
#include <vtkm/cont/DeviceAdapterAlgorithm.h>
#include <vtkm/cont/Field.h>
#include <vtkm/cont/testing/Testing.h>
#include <vector>
typedef vtkm::Vec<vtkm::Float32, 3> Coord3D;
typedef vtkm::Vec<vtkm::Float32, 2> Coord2D;
const vtkm::Float32 clipValue = 0.5;
template<typename T, typename Storage>
bool TestArrayHandle(const vtkm::cont::ArrayHandle<T, Storage> &ah, const T *expected,
vtkm::Id size)
{
if (size != ah.GetNumberOfValues())
{
return false;
}
for (vtkm::Id i = 0; i < size; ++i)
{
if (ah.GetPortalConstControl().Get(i) != expected[i])
{
return false;
}
}
return true;
}
vtkm::cont::DataSet MakeTestDatasetExplicit()
{
static const vtkm::Id numVerts = 4;
static const vtkm::Id numCells = 2;
static const Coord3D coords[numVerts] = {
Coord3D(0.0f, 0.0f, 0.0f),
Coord3D(1.0f, 0.0f, 0.0f),
Coord3D(1.0f, 1.0f, 0.0f),
Coord3D(0.0f, 1.0f, 0.0f),
};
static vtkm::Float32 values[] = { 1.0, 2.0, 1.0, 0.0 };
static vtkm::Id shapes[] = { vtkm::VTKM_TRIANGLE, vtkm::VTKM_TRIANGLE };
static vtkm::Id numInds[] = { 3, 3 };
static vtkm::Id connectivity[] = { 0, 1, 3, 3, 1, 2 };
vtkm::cont::DataSet ds;
ds.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", 1, coords, numVerts));
ds.AddField(vtkm::cont::Field("scalars", 1, vtkm::cont::Field::ASSOC_POINTS, values,
numVerts));
std::vector<vtkm::Id> shapesVec(shapes, shapes + numCells);
std::vector<vtkm::Id> numIndsVec(numInds, numInds + numCells);
std::vector<vtkm::Id> connectivityVec(connectivity, connectivity + (numCells * 3));
vtkm::cont::CellSetExplicit<> cs("cells", 3);
cs.FillViaCopy(shapesVec, numIndsVec, connectivityVec);
ds.AddCellSet(cs);
return ds;
}
vtkm::cont::DataSet MakeTestDatasetStructured()
{
static const vtkm::Vec<vtkm::Float32, 3> origin(0.0f, 0.0f, 0.0f);
static const vtkm::Vec<vtkm::Float32, 3> spacing(1.0f, 1.0f, 1.0f);
static const vtkm::Id xdim = 3, ydim = 3;
static const vtkm::Id3 dim(xdim, ydim, 1);
static const vtkm::Id numVerts = xdim * ydim;
vtkm::Float32 scalars[numVerts];
for (vtkm::Id i = 0; i < numVerts; ++i)
{
scalars[i] = 1.0f;
}
scalars[4] = 0.0f;
vtkm::cont::DataSet ds;
ds.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", 1, dim, origin, spacing));
ds.AddField(vtkm::cont::Field("scalars", 1, vtkm::cont::Field::ASSOC_POINTS,
scalars, numVerts));
vtkm::cont::CellSetStructured<2> cs("cells");
cs.SetPointDimensions(vtkm::make_Vec(dim[0], dim[1]));
ds.AddCellSet(cs);
return ds;
}
template <typename DeviceAdapter>
void TestClippingExplicit()
{
vtkm::cont::DataSet ds = MakeTestDatasetExplicit();
vtkm::worklet::Clip<DeviceAdapter> clip;
vtkm::cont::CellSetExplicit<> outputCellSet =
clip.Run(ds.GetCellSet(0), ds.GetField("scalars").GetData(), clipValue);
vtkm::cont::DynamicArrayHandle coords =
clip.ProcessField(ds.GetCoordinateSystem("coordinates").GetData());
vtkm::cont::DynamicArrayHandle scalars =
clip.ProcessField(ds.GetField("scalars").GetData());
vtkm::Id connectivitySize = 12;
vtkm::Id fieldSize = 7;
vtkm::Id expectedConnectivity[] = { 5, 4, 0, 5, 0, 1, 5, 1, 6, 6, 1, 2 };
Coord3D expectedCoords[] = {
Coord3D(0.00f, 0.00f, 0.0f), Coord3D(1.00f, 0.00f, 0.0f),
Coord3D(1.00f, 1.00f, 0.0f), Coord3D(0.00f, 1.00f, 0.0f),
Coord3D(0.00f, 0.50f, 0.0f), Coord3D(0.25f, 0.75f, 0.0f),
Coord3D(0.50f, 1.00f, 0.0f),
};
vtkm::Float32 expectedScalars[] = { 1, 2, 1, 0, 0.5, 0.5, 0.5 };
VTKM_TEST_ASSERT(
TestArrayHandle(outputCellSet.GetConnectivityArray(), expectedConnectivity,
connectivitySize),
"Got incorrect conectivity");
VTKM_TEST_ASSERT(
TestArrayHandle(coords.CastToArrayHandle(Coord3D(),
VTKM_DEFAULT_STORAGE_TAG()), expectedCoords, fieldSize),
"Got incorrect coordinates");
VTKM_TEST_ASSERT(
TestArrayHandle(scalars.CastToArrayHandle(vtkm::Float32(),
VTKM_DEFAULT_STORAGE_TAG()), expectedScalars, fieldSize),
"Got incorrect scalars");
}
template <typename DeviceAdapter>
void TestClippingStrucutred()
{
vtkm::cont::DataSet ds = MakeTestDatasetStructured();
vtkm::worklet::Clip<DeviceAdapter> clip;
vtkm::cont::CellSetExplicit<> outputCellSet =
clip.Run(ds.GetCellSet(0), ds.GetField("scalars").GetData(), clipValue);
vtkm::cont::DynamicArrayHandle coords =
clip.ProcessField(ds.GetCoordinateSystem("coordinates").GetData());
vtkm::cont::DynamicArrayHandle scalars =
clip.ProcessField(ds.GetField("scalars").GetData());
vtkm::Id connectivitySize = 36;
vtkm::Id fieldSize = 13;
vtkm::Id expectedConnectivity[] = {
0, 1, 9, 0, 9, 10, 0, 10, 3, 1, 2, 9, 2, 11, 9, 2, 5, 11,
3, 10, 6, 10, 12, 6, 12, 7, 6, 11, 5, 8, 11, 8, 12, 8, 7, 12 };
Coord3D expectedCoords[] = {
Coord3D(0.0f, 0.0f, 0.0f), Coord3D(1.0f, 0.0f, 0.0f), Coord3D(2.0f, 0.0f, 0.0f),
Coord3D(0.0f, 1.0f, 0.0f), Coord3D(1.0f, 1.0f, 0.0f), Coord3D(2.0f, 1.0f, 0.0f),
Coord3D(0.0f, 2.0f, 0.0f), Coord3D(1.0f, 2.0f, 0.0f), Coord3D(2.0f, 2.0f, 0.0f),
Coord3D(1.0f, 0.5f, 0.0f), Coord3D(0.5f, 1.0f, 0.0f), Coord3D(1.5f, 1.0f, 0.0f),
Coord3D(1.0f, 1.5f, 0.0f),
};
vtkm::Float32 expectedScalars[] = { 1, 1, 1, 1, 0, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5 };
VTKM_TEST_ASSERT(
TestArrayHandle(outputCellSet.GetConnectivityArray(), expectedConnectivity,
connectivitySize),
"Got incorrect conectivity");
VTKM_TEST_ASSERT(
TestArrayHandle(coords.CastToArrayHandle(Coord3D(),
VTKM_DEFAULT_STORAGE_TAG()), expectedCoords, fieldSize),
"Got incorrect coordinates");
VTKM_TEST_ASSERT(
TestArrayHandle(scalars.CastToArrayHandle(vtkm::Float32(),
VTKM_DEFAULT_STORAGE_TAG()), expectedScalars, fieldSize),
"Got incorrect scalars");
}
template <typename DeviceAdapter>
void TestClipping()
{
std::cout << "Testing explicit dataset:" << std::endl;
TestClippingExplicit<DeviceAdapter>();
std::cout << "Testing structured dataset:" << std::endl;
TestClippingStrucutred<DeviceAdapter>();
}
int UnitTestClipping(int, char *[])
{
return vtkm::cont::testing::Testing::Run(
TestClipping<VTKM_DEFAULT_DEVICE_ADAPTER_TAG>);
}

@ -30,7 +30,8 @@
namespace test_explicit {
class MaxPointOrCellValue : public vtkm::worklet::WorkletMapTopology
class MaxPointOrCellValue :
public vtkm::worklet::WorkletMapTopologyPointToCell
{
public:
typedef void ControlSignature(FieldInTo<Scalar> inCells,
@ -65,7 +66,8 @@ public:
}
};
class AveragePointToCellValue : public vtkm::worklet::WorkletMapTopology
class AveragePointToCellValue :
public vtkm::worklet::WorkletMapTopologyPointToCell
{
public:
typedef void ControlSignature(FieldInFrom<Scalar> inPoints,
@ -122,7 +124,7 @@ TestMaxPointOrCell()
//Run a worklet to populate a cell centered field.
//Here, we're filling it with test values.
vtkm::cont::Field f("outcellvar",
1,
0,
vtkm::cont::Field::ASSOC_CELL_SET,
std::string("cells"),
vtkm::Float32());
@ -163,7 +165,7 @@ TestAvgPointToCell()
//Run a worklet to populate a cell centered field.
//Here, we're filling it with test values.
vtkm::cont::Field f("outcellvar",
1,
0,
vtkm::cont::Field::ASSOC_CELL_SET,
std::string("cells"),
vtkm::Float32());

@ -30,7 +30,8 @@
namespace test_regular {
class MaxPointOrCellValue : public vtkm::worklet::WorkletMapTopology
class MaxPointOrCellValue :
public vtkm::worklet::WorkletMapTopologyPointToCell
{
public:
typedef void ControlSignature(FieldInTo<Scalar> inCells,
@ -65,7 +66,8 @@ public:
}
};
class AveragePointToCellValue : public vtkm::worklet::WorkletMapTopology
class AveragePointToCellValue :
public vtkm::worklet::WorkletMapTopologyPointToCell
{
public:
typedef void ControlSignature(FieldInFrom<Scalar> inPoints,