clang-format: apply to the entire tree

This commit is contained in:
Kitware Robot 2017-05-18 10:29:41 -04:00 committed by Ben Boeckel
parent 9e56a5d881
commit 4ade5f5770
706 changed files with 48160 additions and 58744 deletions

@ -25,25 +25,33 @@
int main() int main()
{ {
int count = 0; int count = 0;
if (cudaSuccess != cudaGetDeviceCount(&count)) return 1; if (cudaSuccess != cudaGetDeviceCount(&count))
if (count == 0) return 1; return 1;
if (count == 0)
return 1;
int prev_arch = 0; int prev_arch = 0;
for (int device = 0; device < count; ++device) for (int device = 0; device < count; ++device)
{ {
cudaDeviceProp prop; cudaDeviceProp prop;
if (cudaSuccess == cudaGetDeviceProperties(&prop, device)) if (cudaSuccess == cudaGetDeviceProperties(&prop, device))
{ {
int arch = (prop.major * 10) + prop.minor; int arch = (prop.major * 10) + prop.minor;
int compute_level = arch; int compute_level = arch;
//arch 21 has no equivalent compute level. //arch 21 has no equivalent compute level.
if(compute_level == 21) { compute_level = 20; } if (compute_level == 21)
{
compute_level = 20;
}
//handle multiple cards of the same architecture //handle multiple cards of the same architecture
if(arch == prev_arch) { continue; } if (arch == prev_arch)
{
continue;
}
prev_arch = arch; prev_arch = arch;
printf(" --generate-code=arch=compute_%d,code=sm_%d", compute_level, arch); printf(" --generate-code=arch=compute_%d,code=sm_%d", compute_level, arch);
}
} }
}
return 0; return 0;
} }

@ -34,29 +34,24 @@
typedef vtkm::Vec<vtkm::Float32, 3> FloatVec3; typedef vtkm::Vec<vtkm::Float32, 3> FloatVec3;
int main(int argc, char* argv[])
int main(int argc, char *argv[])
{ {
if (argc < 4) if (argc < 4)
{ {
std::cout << "Usage: " << std::endl std::cout << "Usage: " << std::endl
<< "$ " << argv[0] << "$ " << argv[0] << " <input_vtk_file> [fieldName] <isoval> <output_vtk_file>"
<< " <input_vtk_file> [fieldName] <isoval> <output_vtk_file>"
<< std::endl; << std::endl;
return 1; return 1;
} }
typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter;
std::cout << "Device Adapter Name: " std::cout << "Device Adapter Name: " << vtkm::cont::DeviceAdapterTraits<DeviceAdapter>::GetName()
<< vtkm::cont::DeviceAdapterTraits<DeviceAdapter>::GetName()
<< std::endl; << std::endl;
vtkm::io::reader::VTKDataSetReader reader(argv[1]); vtkm::io::reader::VTKDataSetReader reader(argv[1]);
vtkm::cont::DataSet input = reader.ReadDataSet(); vtkm::cont::DataSet input = reader.ReadDataSet();
vtkm::cont::Field scalarField = (argc == 5) ? vtkm::cont::Field scalarField = (argc == 5) ? input.GetField(argv[2]) : input.GetField(0);
input.GetField(argv[2]) :
input.GetField(0);
vtkm::Float32 clipValue = std::stof(argv[argc - 2]); vtkm::Float32 clipValue = std::stof(argv[argc - 2]);
vtkm::worklet::Clip clip; vtkm::worklet::Clip clip;
@ -64,10 +59,8 @@ int main(int argc, char *argv[])
vtkm::cont::Timer<DeviceAdapter> total; vtkm::cont::Timer<DeviceAdapter> total;
vtkm::cont::Timer<DeviceAdapter> timer; vtkm::cont::Timer<DeviceAdapter> timer;
vtkm::cont::CellSetExplicit<> outputCellSet = vtkm::cont::CellSetExplicit<> outputCellSet =
clip.Run(input.GetCellSet(0), clip.Run(input.GetCellSet(0), scalarField.GetData().ResetTypeList(vtkm::TypeListTagScalarAll()),
scalarField.GetData().ResetTypeList(vtkm::TypeListTagScalarAll()), clipValue, DeviceAdapter());
clipValue,
DeviceAdapter());
vtkm::Float64 clipTime = timer.GetElapsedTime(); vtkm::Float64 clipTime = timer.GetElapsedTime();
vtkm::cont::DataSet output; vtkm::cont::DataSet output;
@ -75,7 +68,7 @@ int main(int argc, char *argv[])
timer.Reset(); timer.Reset();
vtkm::cont::DynamicArrayHandle coords = vtkm::cont::DynamicArrayHandle coords =
clip.ProcessField(input.GetCoordinateSystem(0), DeviceAdapter()); clip.ProcessField(input.GetCoordinateSystem(0), DeviceAdapter());
vtkm::Float64 processCoordinatesTime = timer.GetElapsedTime(); vtkm::Float64 processCoordinatesTime = timer.GetElapsedTime();
output.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", coords)); output.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", coords));
@ -88,10 +81,8 @@ int main(int argc, char *argv[])
continue; // clip only supports point fields for now. continue; // clip only supports point fields for now.
} }
vtkm::cont::DynamicArrayHandle data = vtkm::cont::DynamicArrayHandle data =
clip.ProcessField(inField.GetData().ResetTypeList(vtkm::TypeListTagAll()), clip.ProcessField(inField.GetData().ResetTypeList(vtkm::TypeListTagAll()), DeviceAdapter());
DeviceAdapter()); output.AddField(vtkm::cont::Field(inField.GetName(), vtkm::cont::Field::ASSOC_POINTS, data));
output.AddField(vtkm::cont::Field(inField.GetName(),
vtkm::cont::Field::ASSOC_POINTS, data));
} }
vtkm::Float64 processScalarsTime = timer.GetElapsedTime(); vtkm::Float64 processScalarsTime = timer.GetElapsedTime();

@ -20,48 +20,48 @@
// Copyright (c) 2016, Los Alamos National Security, LLC // Copyright (c) 2016, Los Alamos National Security, LLC
// All rights reserved. // All rights reserved.
// //
// Copyright 2016. Los Alamos National Security, LLC. // Copyright 2016. Los Alamos National Security, LLC.
// This software was produced under U.S. Government contract DE-AC52-06NA25396 // This software was produced under U.S. Government contract DE-AC52-06NA25396
// for Los Alamos National Laboratory (LANL), which is operated by // for Los Alamos National Laboratory (LANL), which is operated by
// Los Alamos National Security, LLC for the U.S. Department of Energy. // Los Alamos National Security, LLC for the U.S. Department of Energy.
// The U.S. Government has rights to use, reproduce, and distribute this // The U.S. Government has rights to use, reproduce, and distribute this
// software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC // software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC
// MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE // MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE
// USE OF THIS SOFTWARE. If software is modified to produce derivative works, // USE OF THIS SOFTWARE. If software is modified to produce derivative works,
// such modified software should be clearly marked, so as not to confuse it // such modified software should be clearly marked, so as not to confuse it
// with the version available from LANL. // with the version available from LANL.
// //
// Additionally, redistribution and use in source and binary forms, with or // Additionally, redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following conditions // without modification, are permitted provided that the following conditions
// are met: // are met:
// //
// 1. Redistributions of source code must retain the above copyright notice, // 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer. // this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, // 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation // this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution. // and/or other materials provided with the distribution.
// 3. Neither the name of Los Alamos National Security, LLC, Los Alamos // 3. Neither the name of Los Alamos National Security, LLC, Los Alamos
// National Laboratory, LANL, the U.S. Government, nor the names of its // National Laboratory, LANL, the U.S. Government, nor the names of its
// contributors may be used to endorse or promote products derived from // contributors may be used to endorse or promote products derived from
// this software without specific prior written permission. // this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC AND // THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC AND
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LOS ALAMOS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LOS ALAMOS
// NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//============================================================================ //============================================================================
// This code is based on the algorithm presented in the paper: // This code is based on the algorithm presented in the paper:
// “Parallel Peak Pruning for Scalable SMP Contour Tree Computation.” // “Parallel Peak Pruning for Scalable SMP Contour Tree Computation.”
// Hamish Carr, Gunther Weber, Christopher Sewell, and James Ahrens. // Hamish Carr, Gunther Weber, Christopher Sewell, and James Ahrens.
// Proceedings of the IEEE Symposium on Large Data Analysis and Visualization // Proceedings of the IEEE Symposium on Large Data Analysis and Visualization
// (LDAV), October 2016, Baltimore, Maryland. // (LDAV), October 2016, Baltimore, Maryland.
#ifndef VTKM_DEVICE_ADAPTER #ifndef VTKM_DEVICE_ADAPTER
@ -81,7 +81,8 @@ int main(int argc, char* argv[])
{ {
std::cout << "ContourTreeMesh2D Example" << std::endl; std::cout << "ContourTreeMesh2D Example" << std::endl;
if (argc != 2) { if (argc != 2)
{
std::cout << "Parameter is fileName" << std::endl; std::cout << "Parameter is fileName" << std::endl;
std::cout << "File is expected to be ASCII with xdim ydim integers " << std::endl; std::cout << "File is expected to be ASCII with xdim ydim integers " << std::endl;
std::cout << "followed by vector data last dimension varying fastest" << std::endl; std::cout << "followed by vector data last dimension varying fastest" << std::endl;
@ -90,7 +91,8 @@ int main(int argc, char* argv[])
// open input file // open input file
std::ifstream inFile(argv[1]); std::ifstream inFile(argv[1]);
if (inFile.bad()) return 0; if (inFile.bad())
return 0;
// read size of mesh // read size of mesh
vtkm::Id2 vdims; vtkm::Id2 vdims;
@ -120,8 +122,8 @@ int main(int argc, char* argv[])
vtkm::filter::ContourTreeMesh2D filter; vtkm::filter::ContourTreeMesh2D filter;
result = filter.Execute(inDataSet, std::string("values")); result = filter.Execute(inDataSet, std::string("values"));
vtkm::cont::Field resultField = result.GetField(); vtkm::cont::Field resultField = result.GetField();
vtkm::cont::ArrayHandle<vtkm::Pair<vtkm::Id, vtkm::Id> > saddlePeak; vtkm::cont::ArrayHandle<vtkm::Pair<vtkm::Id, vtkm::Id>> saddlePeak;
resultField.GetData().CopyTo(saddlePeak); resultField.GetData().CopyTo(saddlePeak);
return 0; return 0;

@ -20,48 +20,48 @@
// Copyright (c) 2016, Los Alamos National Security, LLC // Copyright (c) 2016, Los Alamos National Security, LLC
// All rights reserved. // All rights reserved.
// //
// Copyright 2016. Los Alamos National Security, LLC. // Copyright 2016. Los Alamos National Security, LLC.
// This software was produced under U.S. Government contract DE-AC52-06NA25396 // This software was produced under U.S. Government contract DE-AC52-06NA25396
// for Los Alamos National Laboratory (LANL), which is operated by // for Los Alamos National Laboratory (LANL), which is operated by
// Los Alamos National Security, LLC for the U.S. Department of Energy. // Los Alamos National Security, LLC for the U.S. Department of Energy.
// The U.S. Government has rights to use, reproduce, and distribute this // The U.S. Government has rights to use, reproduce, and distribute this
// software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC // software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC
// MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE // MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE
// USE OF THIS SOFTWARE. If software is modified to produce derivative works, // USE OF THIS SOFTWARE. If software is modified to produce derivative works,
// such modified software should be clearly marked, so as not to confuse it // such modified software should be clearly marked, so as not to confuse it
// with the version available from LANL. // with the version available from LANL.
// //
// Additionally, redistribution and use in source and binary forms, with or // Additionally, redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following conditions // without modification, are permitted provided that the following conditions
// are met: // are met:
// //
// 1. Redistributions of source code must retain the above copyright notice, // 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer. // this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, // 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation // this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution. // and/or other materials provided with the distribution.
// 3. Neither the name of Los Alamos National Security, LLC, Los Alamos // 3. Neither the name of Los Alamos National Security, LLC, Los Alamos
// National Laboratory, LANL, the U.S. Government, nor the names of its // National Laboratory, LANL, the U.S. Government, nor the names of its
// contributors may be used to endorse or promote products derived from // contributors may be used to endorse or promote products derived from
// this software without specific prior written permission. // this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC AND // THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC AND
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LOS ALAMOS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LOS ALAMOS
// NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//============================================================================ //============================================================================
// This code is based on the algorithm presented in the paper: // This code is based on the algorithm presented in the paper:
// “Parallel Peak Pruning for Scalable SMP Contour Tree Computation.” // “Parallel Peak Pruning for Scalable SMP Contour Tree Computation.”
// Hamish Carr, Gunther Weber, Christopher Sewell, and James Ahrens. // Hamish Carr, Gunther Weber, Christopher Sewell, and James Ahrens.
// Proceedings of the IEEE Symposium on Large Data Analysis and Visualization // Proceedings of the IEEE Symposium on Large Data Analysis and Visualization
// (LDAV), October 2016, Baltimore, Maryland. // (LDAV), October 2016, Baltimore, Maryland.
#ifndef VTKM_DEVICE_ADAPTER #ifndef VTKM_DEVICE_ADAPTER
@ -81,7 +81,8 @@ int main(int argc, char* argv[])
{ {
std::cout << "ContourTreeMesh3D Example" << std::endl; std::cout << "ContourTreeMesh3D Example" << std::endl;
if (argc != 2) { if (argc != 2)
{
std::cout << "Parameter is fileName" << std::endl; std::cout << "Parameter is fileName" << std::endl;
std::cout << "File is expected to be ASCII with xdim ydim zdim integers " << std::endl; std::cout << "File is expected to be ASCII with xdim ydim zdim integers " << std::endl;
std::cout << "followed by vector data last dimension varying fastest" << std::endl; std::cout << "followed by vector data last dimension varying fastest" << std::endl;
@ -90,15 +91,15 @@ int main(int argc, char* argv[])
// open input file // open input file
std::ifstream inFile(argv[1]); std::ifstream inFile(argv[1]);
if (inFile.bad()) return 0; if (inFile.bad())
return 0;
// read size of mesh // read size of mesh
vtkm::Id3 vdims; vtkm::Id3 vdims;
inFile >> vdims[0]; inFile >> vdims[0];
inFile >> vdims[1]; inFile >> vdims[1];
inFile >> vdims[2]; inFile >> vdims[2];
std::size_t nVertices = std::size_t nVertices = static_cast<std::size_t>(vdims[0] * vdims[1] * vdims[2]);
static_cast<std::size_t>(vdims[0] * vdims[1] * vdims[2]);
// read data // read data
std::vector<vtkm::Float32> values(nVertices); std::vector<vtkm::Float32> values(nVertices);
@ -122,8 +123,8 @@ int main(int argc, char* argv[])
vtkm::filter::ContourTreeMesh3D filter; vtkm::filter::ContourTreeMesh3D filter;
result = filter.Execute(inDataSet, std::string("values")); result = filter.Execute(inDataSet, std::string("values"));
vtkm::cont::Field resultField = result.GetField(); vtkm::cont::Field resultField = result.GetField();
vtkm::cont::ArrayHandle<vtkm::Pair<vtkm::Id, vtkm::Id> > saddlePeak; vtkm::cont::ArrayHandle<vtkm::Pair<vtkm::Id, vtkm::Id>> saddlePeak;
resultField.GetData().CopyTo(saddlePeak); resultField.GetData().CopyTo(saddlePeak);
return 0; return 0;

@ -34,17 +34,11 @@
#include <iostream> #include <iostream>
void makeScene(const vtkm::cont::DataSet &inputData, void makeScene(const vtkm::cont::DataSet& inputData, const vtkm::rendering::ColorTable& colorTable,
const vtkm::rendering::ColorTable &colorTable, const std::string& fieldName, vtkm::rendering::Scene& scene)
const std::string &fieldName,
vtkm::rendering::Scene &scene)
{ {
scene.AddActor(vtkm::rendering::Actor(inputData.GetCellSet(), scene.AddActor(vtkm::rendering::Actor(inputData.GetCellSet(), inputData.GetCoordinateSystem(),
inputData.GetCoordinateSystem(), inputData.GetField(fieldName), colorTable));
inputData.GetField(fieldName),
colorTable));
} }
// This example reads an input vtk file specified on the command-line (or generates a default // This example reads an input vtk file specified on the command-line (or generates a default
@ -78,7 +72,7 @@ int main(int argc, char* argv[])
fieldName = "SCALARS:pointvar"; fieldName = "SCALARS:pointvar";
} }
typedef vtkm::rendering::MapperRayTracer Mapper; typedef vtkm::rendering::MapperRayTracer Mapper;
typedef vtkm::rendering::CanvasRayTracer Canvas; typedef vtkm::rendering::CanvasRayTracer Canvas;
// Set up a camera for rendering the input data // Set up a camera for rendering the input data
@ -91,7 +85,7 @@ int main(int argc, char* argv[])
camera.ResetToBounds(coordsBounds); camera.ResetToBounds(coordsBounds);
vtkm::Vec<vtkm::Float32,3> totalExtent; vtkm::Vec<vtkm::Float32, 3> totalExtent;
totalExtent[0] = vtkm::Float32(coordsBounds.X.Max - coordsBounds.X.Min); totalExtent[0] = vtkm::Float32(coordsBounds.X.Max - coordsBounds.X.Min);
totalExtent[1] = vtkm::Float32(coordsBounds.Y.Max - coordsBounds.Y.Min); totalExtent[1] = vtkm::Float32(coordsBounds.Y.Max - coordsBounds.Y.Min);
totalExtent[2] = vtkm::Float32(coordsBounds.Z.Max - coordsBounds.Z.Min); totalExtent[2] = vtkm::Float32(coordsBounds.Z.Max - coordsBounds.Z.Min);
@ -107,15 +101,11 @@ int main(int argc, char* argv[])
// Create a scene for rendering the input data // Create a scene for rendering the input data
vtkm::rendering::Scene scene; vtkm::rendering::Scene scene;
vtkm::rendering::Color bg(0.2f, 0.2f, 0.2f, 1.0f); vtkm::rendering::Color bg(0.2f, 0.2f, 0.2f, 1.0f);
Canvas canvas(512,512); Canvas canvas(512, 512);
makeScene(inputData, colorTable, fieldName, scene); makeScene(inputData, colorTable, fieldName, scene);
// Create a view and use it to render the input data using OS Mesa // Create a view and use it to render the input data using OS Mesa
vtkm::rendering::View3D view(scene, vtkm::rendering::View3D view(scene, mapper, canvas, camera, bg);
mapper,
canvas,
camera,
bg);
view.Initialize(); view.Initialize();
view.Paint(); view.Paint();
view.SaveAs("demo_input.pnm"); view.SaveAs("demo_input.pnm");
@ -125,8 +115,7 @@ int main(int argc, char* argv[])
filter.SetGenerateNormals(false); filter.SetGenerateNormals(false);
filter.SetMergeDuplicatePoints(false); filter.SetMergeDuplicatePoints(false);
filter.SetIsoValue(0, isovalue); filter.SetIsoValue(0, isovalue);
vtkm::filter::ResultDataSet result = filter.Execute( inputData, vtkm::filter::ResultDataSet result = filter.Execute(inputData, inputData.GetField(fieldName));
inputData.GetField(fieldName) );
filter.MapFieldOntoOutput(result, inputData.GetField(fieldName)); filter.MapFieldOntoOutput(result, inputData.GetField(fieldName));
vtkm::cont::DataSet& outputData = result.GetDataSet(); vtkm::cont::DataSet& outputData = result.GetDataSet();
// Render a separate image with the output isosurface // Render a separate image with the output isosurface
@ -134,12 +123,7 @@ int main(int argc, char* argv[])
vtkm::rendering::Scene scene2; vtkm::rendering::Scene scene2;
makeScene(outputData, colorTable, fieldName, scene2); makeScene(outputData, colorTable, fieldName, scene2);
vtkm::rendering::View3D view2(scene2, mapper, canvas, camera, bg);
vtkm::rendering::View3D view2(scene2,
mapper,
canvas,
camera,
bg);
view2.Initialize(); view2.Initialize();
view2.Paint(); view2.Paint();
view2.SaveAs("demo_output.pnm"); view2.SaveAs("demo_output.pnm");

@ -31,18 +31,13 @@
struct ExampleFieldWorklet : public vtkm::worklet::WorkletMapField struct ExampleFieldWorklet : public vtkm::worklet::WorkletMapField
{ {
typedef void ControlSignature( FieldIn<>, FieldIn<>, FieldIn<>, typedef void ControlSignature(FieldIn<>, FieldIn<>, FieldIn<>, FieldOut<>, FieldOut<>,
FieldOut<>, FieldOut<>, FieldOut<> ); FieldOut<>);
typedef void ExecutionSignature( _1, _2, _3, _4, _5, _6 ); typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6);
template<typename T, typename U, typename V> template <typename T, typename U, typename V>
VTKM_EXEC VTKM_EXEC void operator()(const vtkm::Vec<T, 3>& vec, const U& scalar1, const V& scalar2,
void operator()( const vtkm::Vec< T, 3 > & vec, vtkm::Vec<T, 3>& out_vec, U& out_scalar1, V& out_scalar2) const
const U & scalar1,
const V& scalar2,
vtkm::Vec<T, 3>& out_vec,
U& out_scalar1,
V& out_scalar2 ) const
{ {
out_vec = vec * scalar1; out_vec = vec * scalar1;
out_scalar1 = static_cast<U>(scalar1 + scalar2); out_scalar1 = static_cast<U>(scalar1 + scalar2);
@ -50,46 +45,35 @@ struct ExampleFieldWorklet : public vtkm::worklet::WorkletMapField
std::cout << "hello world" << std::endl; std::cout << "hello world" << std::endl;
} }
template<typename T, typename U, typename V, typename W, typename X, typename Y> template <typename T, typename U, typename V, typename W, typename X, typename Y>
VTKM_EXEC VTKM_EXEC void operator()(const T&, const U&, const V&, W&, X&, Y&) const
void operator()( const T &,
const U &,
const V&,
W&,
X&,
Y& ) const
{ {
//no-op //no-op
} }
}; };
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
(void)argc; (void)argc;
(void)argv; (void)argv;
std::vector< vtkm::Vec<vtkm::Float32, 3> > inputVec(10); std::vector<vtkm::Vec<vtkm::Float32, 3>> inputVec(10);
std::vector< vtkm::Int32 > inputScalar1(10); std::vector<vtkm::Int32> inputScalar1(10);
std::vector< vtkm::Float64 > inputScalar2(10); std::vector<vtkm::Float64> inputScalar2(10);
vtkm::cont::ArrayHandle< vtkm::Vec<vtkm::Float32, 3> > handleV = vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3>> handleV =
vtkm::cont::make_ArrayHandle(inputVec); vtkm::cont::make_ArrayHandle(inputVec);
vtkm::cont::ArrayHandle< vtkm::Int32 > handleS1 = vtkm::cont::ArrayHandle<vtkm::Int32> handleS1 = vtkm::cont::make_ArrayHandle(inputScalar1);
vtkm::cont::make_ArrayHandle(inputScalar1);
vtkm::cont::ArrayHandle< vtkm::Float64 > handleS2 = vtkm::cont::ArrayHandle<vtkm::Float64> handleS2 = vtkm::cont::make_ArrayHandle(inputScalar2);
vtkm::cont::make_ArrayHandle(inputScalar2);
vtkm::cont::ArrayHandle< vtkm::Vec<vtkm::Float32, 3> > handleOV; vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3>> handleOV;
vtkm::cont::ArrayHandle< vtkm::Int32 > handleOS1; vtkm::cont::ArrayHandle<vtkm::Int32> handleOS1;
vtkm::cont::ArrayHandle< vtkm::Float64 > handleOS2; vtkm::cont::ArrayHandle<vtkm::Float64> handleOS2;
vtkm::cont::DynamicArrayHandle out1(handleOV), out2(handleOS1), out3(handleOS2); vtkm::cont::DynamicArrayHandle out1(handleOV), out2(handleOS1), out3(handleOS2);
vtkm::worklet::DispatcherMapField<ExampleFieldWorklet> dispatcher; vtkm::worklet::DispatcherMapField<ExampleFieldWorklet> dispatcher;
dispatcher.Invoke(handleV, handleS1, handleS2, out1, out2, out3); dispatcher.Invoke(handleV, handleS1, handleS2, out1, out2, out3);
} }

@ -35,25 +35,25 @@
//Suppress warnings about glut being deprecated on OSX //Suppress warnings about glut being deprecated on OSX
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic push #pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif #endif
//OpenGL Graphics includes //OpenGL Graphics includes
//glew needs to go before glut //glew needs to go before glut
//that is why this is after the TransferToOpenGL include //that is why this is after the TransferToOpenGL include
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
#include "LoadShaders.h" #include "LoadShaders.h"
template< typename DeviceAdapter, typename T > template <typename DeviceAdapter, typename T>
struct HelloVTKMInterop struct HelloVTKMInterop
{ {
vtkm::Vec< vtkm::Int32, 2 > Dims; vtkm::Vec<vtkm::Int32, 2> Dims;
GLuint ProgramId; GLuint ProgramId;
GLuint VAOId; GLuint VAOId;
@ -63,71 +63,69 @@ struct HelloVTKMInterop
vtkm::cont::Timer<DeviceAdapter> Timer; vtkm::cont::Timer<DeviceAdapter> Timer;
std::vector< vtkm::Vec< T, 3 > > InputData; std::vector<vtkm::Vec<T, 3>> InputData;
vtkm::cont::ArrayHandle< vtkm::Vec< T, 3 > > InHandle; vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>> InHandle;
vtkm::cont::ArrayHandle< vtkm::Vec< T, 3 > > OutCoords; vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>> OutCoords;
vtkm::cont::ArrayHandle< vtkm::Vec< vtkm::UInt8, 4 > > OutColors; vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::UInt8, 4>> OutColors;
HelloVTKMInterop(vtkm::Int32 width, vtkm::Int32 height): HelloVTKMInterop(vtkm::Int32 width, vtkm::Int32 height)
Dims(256,256), : Dims(256, 256)
ProgramId(), , ProgramId()
VAOId(), , VAOId()
VBOState(), , VBOState()
ColorState(), , ColorState()
Timer(), , Timer()
InputData(), , InputData()
InHandle(), , InHandle()
OutCoords(), , OutCoords()
OutColors() , OutColors()
{ {
int dim = 256; int dim = 256;
this->InputData.reserve( static_cast<std::size_t>(dim*dim) ); this->InputData.reserve(static_cast<std::size_t>(dim * dim));
for (int i = 0; i < dim; ++i ) for (int i = 0; i < dim; ++i)
{ {
for (int j = 0; j < dim; ++j ) for (int j = 0; j < dim; ++j)
{ {
this->InputData.push_back(vtkm::Vec<T,3>(2.f*static_cast<T>(i/dim)-1.f, this->InputData.push_back(vtkm::Vec<T, 3>(2.f * static_cast<T>(i / dim) - 1.f, 0.f,
0.f, 2.f * static_cast<T>(j / dim) - 1.f));
2.f*static_cast<T>(j/dim)-1.f));
} }
} }
this->Dims = vtkm::Vec< vtkm::Int32, 2 >( dim, dim ); this->Dims = vtkm::Vec<vtkm::Int32, 2>(dim, dim);
this->InHandle = vtkm::cont::make_ArrayHandle(this->InputData); this->InHandle = vtkm::cont::make_ArrayHandle(this->InputData);
glGenVertexArrays( 1, &this->VAOId ); glGenVertexArrays(1, &this->VAOId);
glBindVertexArray( this->VAOId ); glBindVertexArray(this->VAOId);
this->ProgramId = LoadShaders(); this->ProgramId = LoadShaders();
glUseProgram( this->ProgramId ); glUseProgram(this->ProgramId);
glClearColor( .08f, .08f, .08f, 0.f ); glClearColor(.08f, .08f, .08f, 0.f);
glViewport(0, 0, width, height ); glViewport(0, 0, width, height);
} }
void render() void render()
{ {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
vtkm::Int32 arraySize = this->Dims[0]*this->Dims[1]; vtkm::Int32 arraySize = this->Dims[0] * this->Dims[1];
//precomputed based on 1027x768 render window size //precomputed based on 1027x768 render window size
vtkm::Float32 mvp[16] = {-1.79259f, 0.f, 0.f, 0.f, vtkm::Float32 mvp[16] = { -1.79259f, 0.f, 0.f, 0.f, 0.f, 1.26755f,
0.f, 1.26755f, -0.721392f, -0.707107f, -0.721392f, -0.707107f, 0.f, 1.26755f, 0.721392f, 0.707107f,
0.f, 1.26755f, 0.721392f, 0.707107f, 0.f, 0.f, 1.24076f, 1.41421f };
0.f, 0.f, 1.24076f, 1.41421f};
GLint unifLoc = glGetUniformLocation( this->ProgramId, "MVP"); GLint unifLoc = glGetUniformLocation(this->ProgramId, "MVP");
glUniformMatrix4fv( unifLoc, 1, GL_FALSE, mvp ); glUniformMatrix4fv(unifLoc, 1, GL_FALSE, mvp);
glEnableVertexAttribArray(0); glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, *this->VBOState.GetHandle()); glBindBuffer(GL_ARRAY_BUFFER, *this->VBOState.GetHandle());
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 ); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, *this->ColorState.GetHandle()); glBindBuffer(GL_ARRAY_BUFFER, *this->ColorState.GetHandle());
glColorPointer(4, GL_UNSIGNED_BYTE, 0, 0 ); glColorPointer(4, GL_UNSIGNED_BYTE, 0, 0);
glDrawArrays( GL_POINTS, 0, arraySize ); glDrawArrays(GL_POINTS, 0, arraySize);
glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_COLOR_ARRAY);
glDisableVertexAttribArray(0); glDisableVertexAttribArray(0);
@ -136,51 +134,53 @@ struct HelloVTKMInterop
struct GenerateSurfaceWorklet : public vtkm::worklet::WorkletMapField struct GenerateSurfaceWorklet : public vtkm::worklet::WorkletMapField
{ {
vtkm::Float32 t; vtkm::Float32 t;
GenerateSurfaceWorklet(vtkm::Float32 st) : t(st) {} GenerateSurfaceWorklet(vtkm::Float32 st)
: t(st)
{
}
typedef void ControlSignature( FieldIn<>, FieldOut<>, FieldOut<> ); typedef void ControlSignature(FieldIn<>, FieldOut<>, FieldOut<>);
typedef void ExecutionSignature( _1, _2, _3 ); typedef void ExecutionSignature(_1, _2, _3);
VTKM_EXEC VTKM_EXEC
void operator()( const vtkm::Vec< T, 3 > & input, void operator()(const vtkm::Vec<T, 3>& input, vtkm::Vec<T, 3>& output,
vtkm::Vec<T, 3> & output, vtkm::Vec<vtkm::UInt8, 4>& color) const
vtkm::Vec<vtkm::UInt8, 4>& color ) const
{ {
output[0] = input[0]; output[0] = input[0];
output[1] = 0.25f * vtkm::Sin( input[0] * 10.f + t ) * vtkm::Cos( input[2] * 10.f + t ); output[1] = 0.25f * vtkm::Sin(input[0] * 10.f + t) * vtkm::Cos(input[2] * 10.f + t);
output[2] = input[2]; output[2] = input[2];
color[0] = 0; color[0] = 0;
color[1] = static_cast<vtkm::UInt8>(160 + 96*vtkm::Sin(input[0]*10.f+t)); color[1] = static_cast<vtkm::UInt8>(160 + 96 * vtkm::Sin(input[0] * 10.f + t));
color[2] = static_cast<vtkm::UInt8>(160 + 96*vtkm::Cos(input[2]*5.f+t)); color[2] = static_cast<vtkm::UInt8>(160 + 96 * vtkm::Cos(input[2] * 5.f + t));
color[3] = 255; color[3] = 255;
} }
}; };
void renderFrame( ) void renderFrame()
{ {
typedef vtkm::worklet::DispatcherMapField<GenerateSurfaceWorklet> DispatcherType; typedef vtkm::worklet::DispatcherMapField<GenerateSurfaceWorklet> DispatcherType;
vtkm::Float32 t = static_cast<vtkm::Float32>(this->Timer.GetElapsedTime()); vtkm::Float32 t = static_cast<vtkm::Float32>(this->Timer.GetElapsedTime());
GenerateSurfaceWorklet worklet( t ); GenerateSurfaceWorklet worklet(t);
DispatcherType(worklet).Invoke( this->InHandle, this->OutCoords, this->OutColors ); DispatcherType(worklet).Invoke(this->InHandle, this->OutCoords, this->OutColors);
vtkm::interop::TransferToOpenGL( this->OutCoords, this->VBOState, DeviceAdapter() ); vtkm::interop::TransferToOpenGL(this->OutCoords, this->VBOState, DeviceAdapter());
vtkm::interop::TransferToOpenGL( this->OutColors, this->ColorState, DeviceAdapter() ); vtkm::interop::TransferToOpenGL(this->OutColors, this->ColorState, DeviceAdapter());
this->render(); this->render();
if(t > 10) if (t > 10)
{ {
//after 10seconds quit the demo //after 10seconds quit the demo
exit(0); exit(0);
} }
} }
}; };
//global static so that glut callback can access it //global static so that glut callback can access it
typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter;
HelloVTKMInterop< DeviceAdapter, vtkm::Float32 >* helloWorld = nullptr; HelloVTKMInterop<DeviceAdapter, vtkm::Float32>* helloWorld = nullptr;
// Render the output using simple OpenGL // Render the output using simple OpenGL
void run() void run()
@ -197,26 +197,26 @@ void idle()
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
typedef vtkm::cont::DeviceAdapterTraits<DeviceAdapter> DeviceAdapterTraits; typedef vtkm::cont::DeviceAdapterTraits<DeviceAdapter> DeviceAdapterTraits;
std::cout << "Running Hello World example on device adapter: " std::cout << "Running Hello World example on device adapter: " << DeviceAdapterTraits::GetName()
<< DeviceAdapterTraits::GetName() << std::endl; << std::endl;
glewExperimental = GL_TRUE; glewExperimental = GL_TRUE;
glutInit(&argc, argv); glutInit(&argc, argv);
const vtkm::UInt32 width = 1024; const vtkm::UInt32 width = 1024;
const vtkm::UInt32 height = 768; const vtkm::UInt32 height = 768;
glutInitWindowSize ( width, height ); glutInitWindowSize(width, height);
glutInitDisplayMode ( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("VTK-m Hello World OpenGL Interop"); glutCreateWindow("VTK-m Hello World OpenGL Interop");
GLenum err = glewInit(); GLenum err = glewInit();
if (GLEW_OK != err) if (GLEW_OK != err)
{ {
std::cout << "glewInit failed\n"; std::cout << "glewInit failed\n";
} }
HelloVTKMInterop< DeviceAdapter, vtkm::Float32 > hw(width,height); HelloVTKMInterop<DeviceAdapter, vtkm::Float32> hw(width, height);
helloWorld = &hw; helloWorld = &hw;
glutDisplayFunc(run); glutDisplayFunc(run);
@ -225,5 +225,5 @@ int main(int argc, char** argv)
} }
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

@ -21,113 +21,109 @@
#ifndef LOAD_SHADERS #ifndef LOAD_SHADERS
#define LOAD_SHADERS #define LOAD_SHADERS
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
namespace shaders namespace shaders
{ {
static std::string const& make_fragment_shader_code() static std::string const& make_fragment_shader_code()
{ {
static std::string const data = static std::string const data = "#version 120\n"
"#version 120\n" "void main(void)"
"void main(void)" "{"
"{" " gl_FragColor = gl_Color;"
" gl_FragColor = gl_Color;" "}";
"}";
return data; return data;
} }
static std::string const& make_vertex_shader_code() static std::string const& make_vertex_shader_code()
{ {
static std::string const data = static std::string const data = "#version 120\n"
"#version 120\n" "attribute vec3 posAttr;"
"attribute vec3 posAttr;" "uniform mat4 MVP;"
"uniform mat4 MVP;" "void main()"
"void main()" "{"
"{" " vec4 pos = vec4( posAttr, 1.0 );"
" vec4 pos = vec4( posAttr, 1.0 );" " gl_FrontColor = gl_Color;"
" gl_FrontColor = gl_Color;" " gl_Position = MVP * pos;"
" gl_Position = MVP * pos;" "}";
"}";
return data; return data;
} }
} }
inline GLuint LoadShaders() inline GLuint LoadShaders()
{ {
// Create the shaders // Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Get the Vertex Shader code // Get the Vertex Shader code
std::string VertexShaderCode = shaders::make_vertex_shader_code(); std::string VertexShaderCode = shaders::make_vertex_shader_code();
// Get the Fragment Shader code // Get the Fragment Shader code
std::string FragmentShaderCode = shaders::make_fragment_shader_code(); std::string FragmentShaderCode = shaders::make_fragment_shader_code();
GLint Result = GL_FALSE; GLint Result = GL_FALSE;
int InfoLogLength; int InfoLogLength;
// Compile Vertex Shader // Compile Vertex Shader
std::cout << "Compiling vertex shader" << std::endl; std::cout << "Compiling vertex shader" << std::endl;
char const * VertexSourcePointer = VertexShaderCode.c_str(); char const* VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer, nullptr); glShaderSource(VertexShaderID, 1, &VertexSourcePointer, nullptr);
glCompileShader(VertexShaderID); glCompileShader(VertexShaderID);
// Check Vertex Shader // Check Vertex Shader
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
std::vector<char> VertexShaderErrorMessage( static_cast<std::size_t>(InfoLogLength) ); std::vector<char> VertexShaderErrorMessage(static_cast<std::size_t>(InfoLogLength));
if(VertexShaderErrorMessage.size() > 0) if (VertexShaderErrorMessage.size() > 0)
{ {
glGetShaderInfoLog(VertexShaderID, InfoLogLength, nullptr, &VertexShaderErrorMessage[0]); glGetShaderInfoLog(VertexShaderID, InfoLogLength, nullptr, &VertexShaderErrorMessage[0]);
std::cout << &VertexShaderErrorMessage[0] << std::endl; std::cout << &VertexShaderErrorMessage[0] << std::endl;
} }
// Compile Fragment Shader // Compile Fragment Shader
std::cout << "Compiling fragment shader" << std::endl; std::cout << "Compiling fragment shader" << std::endl;
char const * FragmentSourcePointer = FragmentShaderCode.c_str(); char const* FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, nullptr); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, nullptr);
glCompileShader(FragmentShaderID); glCompileShader(FragmentShaderID);
// Check Fragment Shader // Check Fragment Shader
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
std::vector<char> FragmentShaderErrorMessage( static_cast<std::size_t>(InfoLogLength) ); std::vector<char> FragmentShaderErrorMessage(static_cast<std::size_t>(InfoLogLength));
if(FragmentShaderErrorMessage.size() > 0) if (FragmentShaderErrorMessage.size() > 0)
{ {
glGetShaderInfoLog(FragmentShaderID, InfoLogLength, nullptr, &FragmentShaderErrorMessage[0]); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, nullptr, &FragmentShaderErrorMessage[0]);
std::cout << &FragmentShaderErrorMessage[0] << std::endl; std::cout << &FragmentShaderErrorMessage[0] << std::endl;
} }
// Link the program // Link the program
std::cout << "Linking program" << std::endl; std::cout << "Linking program" << std::endl;
GLuint ProgramID = glCreateProgram(); GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID); glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID); glLinkProgram(ProgramID);
// Check the program // Check the program
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
std::vector<char> ProgramErrorMessage( static_cast<std::size_t>(InfoLogLength) ); std::vector<char> ProgramErrorMessage(static_cast<std::size_t>(InfoLogLength));
if(ProgramErrorMessage.size() > 0) if (ProgramErrorMessage.size() > 0)
{ {
glGetProgramInfoLog(ProgramID, InfoLogLength, nullptr, &ProgramErrorMessage[0]); glGetProgramInfoLog(ProgramID, InfoLogLength, nullptr, &ProgramErrorMessage[0]);
std::cout << &ProgramErrorMessage[0] << std::endl; std::cout << &ProgramErrorMessage[0] << std::endl;
} }
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
glDeleteShader(VertexShaderID); return ProgramID;
glDeleteShader(FragmentShaderID);
return ProgramID;
} }
#endif #endif

@ -34,14 +34,14 @@
//Suppress warnings about glut being deprecated on OSX //Suppress warnings about glut being deprecated on OSX
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic push #pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif #endif
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
#include "quaternion.h" #include "quaternion.h"
@ -49,13 +49,14 @@
#include <vector> #include <vector>
static vtkm::Id3 dims(256, 256, 256); static vtkm::Id3 dims(256, 256, 256);
static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32,3> > verticesArray, normalsArray; static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3>> verticesArray, normalsArray;
static vtkm::cont::ArrayHandle<vtkm::Float32> scalarsArray; static vtkm::cont::ArrayHandle<vtkm::Float32> scalarsArray;
static Quaternion qrot; static Quaternion qrot;
static int lastx, lasty; static int lastx, lasty;
static int mouse_state = 1; static int mouse_state = 1;
namespace { namespace
{
// Define the tangle field for the input data // Define the tangle field for the input data
class TangleField : public vtkm::worklet::WorkletMapField class TangleField : public vtkm::worklet::WorkletMapField
@ -70,29 +71,40 @@ public:
const vtkm::Id cellsPerLayer; const vtkm::Id cellsPerLayer;
VTKM_CONT VTKM_CONT
TangleField(const vtkm::Id3 dims, const vtkm::Float32 mins[3], const vtkm::Float32 maxs[3]) : xdim(dims[0]), ydim(dims[1]), zdim(dims[2]), TangleField(const vtkm::Id3 dims, const vtkm::Float32 mins[3], const vtkm::Float32 maxs[3])
xmin(mins[0]), ymin(mins[1]), zmin(mins[2]), xmax(maxs[0]), ymax(maxs[1]), zmax(maxs[2]), cellsPerLayer((xdim) * (ydim)) { }; : xdim(dims[0])
, ydim(dims[1])
, zdim(dims[2])
, xmin(mins[0])
, ymin(mins[1])
, zmin(mins[2])
, xmax(maxs[0])
, ymax(maxs[1])
, zmax(maxs[2])
, cellsPerLayer((xdim) * (ydim)){};
VTKM_EXEC VTKM_EXEC
void operator()(const vtkm::Id &vertexId, vtkm::Float32 &v) const void operator()(const vtkm::Id& vertexId, vtkm::Float32& v) const
{ {
const vtkm::Id x = vertexId % (xdim); const vtkm::Id x = vertexId % (xdim);
const vtkm::Id y = (vertexId / (xdim)) % (ydim); const vtkm::Id y = (vertexId / (xdim)) % (ydim);
const vtkm::Id z = vertexId / cellsPerLayer; const vtkm::Id z = vertexId / cellsPerLayer;
const vtkm::Float32 fx = static_cast<vtkm::Float32>(x) / static_cast<vtkm::Float32>(xdim-1); const vtkm::Float32 fx = static_cast<vtkm::Float32>(x) / static_cast<vtkm::Float32>(xdim - 1);
const vtkm::Float32 fy = static_cast<vtkm::Float32>(y) / static_cast<vtkm::Float32>(xdim-1); const vtkm::Float32 fy = static_cast<vtkm::Float32>(y) / static_cast<vtkm::Float32>(xdim - 1);
const vtkm::Float32 fz = static_cast<vtkm::Float32>(z) / static_cast<vtkm::Float32>(xdim-1); const vtkm::Float32 fz = static_cast<vtkm::Float32>(z) / static_cast<vtkm::Float32>(xdim - 1);
const vtkm::Float32 xx = 3.0f*(xmin+(xmax-xmin)*(fx)); const vtkm::Float32 xx = 3.0f * (xmin + (xmax - xmin) * (fx));
const vtkm::Float32 yy = 3.0f*(ymin+(ymax-ymin)*(fy)); const vtkm::Float32 yy = 3.0f * (ymin + (ymax - ymin) * (fy));
const vtkm::Float32 zz = 3.0f*(zmin+(zmax-zmin)*(fz)); const vtkm::Float32 zz = 3.0f * (zmin + (zmax - zmin) * (fz));
v = (xx*xx*xx*xx - 5.0f*xx*xx + yy*yy*yy*yy - 5.0f*yy*yy + zz*zz*zz*zz - 5.0f*zz*zz + 11.8f) * 0.2f + 0.5f; v = (xx * xx * xx * xx - 5.0f * xx * xx + yy * yy * yy * yy - 5.0f * yy * yy +
zz * zz * zz * zz - 5.0f * zz * zz + 11.8f) *
0.2f +
0.5f;
} }
}; };
// Construct an input data set using the tangle field worklet // Construct an input data set using the tangle field worklet
vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims) vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims)
{ {
@ -100,24 +112,23 @@ vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims)
const vtkm::Id3 vdims(dims[0] + 1, dims[1] + 1, dims[2] + 1); const vtkm::Id3 vdims(dims[0] + 1, dims[1] + 1, dims[2] + 1);
vtkm::Float32 mins[3] = {-1.0f, -1.0f, -1.0f}; vtkm::Float32 mins[3] = { -1.0f, -1.0f, -1.0f };
vtkm::Float32 maxs[3] = {1.0f, 1.0f, 1.0f}; vtkm::Float32 maxs[3] = { 1.0f, 1.0f, 1.0f };
vtkm::cont::ArrayHandle<vtkm::Float32> fieldArray; vtkm::cont::ArrayHandle<vtkm::Float32> fieldArray;
vtkm::cont::ArrayHandleCounting<vtkm::Id> vertexCountImplicitArray(0, 1, vdims[0]*vdims[1]*vdims[2]); vtkm::cont::ArrayHandleCounting<vtkm::Id> vertexCountImplicitArray(0, 1, vdims[0] * vdims[1] *
vtkm::worklet::DispatcherMapField<TangleField> tangleFieldDispatcher(TangleField(vdims, mins, maxs)); vdims[2]);
vtkm::worklet::DispatcherMapField<TangleField> tangleFieldDispatcher(
TangleField(vdims, mins, maxs));
tangleFieldDispatcher.Invoke(vertexCountImplicitArray, fieldArray); tangleFieldDispatcher.Invoke(vertexCountImplicitArray, fieldArray);
vtkm::Vec<vtkm::FloatDefault,3> origin(0.0f, 0.0f, 0.0f); vtkm::Vec<vtkm::FloatDefault, 3> origin(0.0f, 0.0f, 0.0f);
vtkm::Vec<vtkm::FloatDefault,3> spacing( vtkm::Vec<vtkm::FloatDefault, 3> spacing(1.0f / static_cast<vtkm::FloatDefault>(dims[0]),
1.0f/static_cast<vtkm::FloatDefault>(dims[0]), 1.0f / static_cast<vtkm::FloatDefault>(dims[2]),
1.0f/static_cast<vtkm::FloatDefault>(dims[2]), 1.0f / static_cast<vtkm::FloatDefault>(dims[1]));
1.0f/static_cast<vtkm::FloatDefault>(dims[1]));
vtkm::cont::ArrayHandleUniformPointCoordinates vtkm::cont::ArrayHandleUniformPointCoordinates coordinates(vdims, origin, spacing);
coordinates(vdims, origin, spacing); dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", coordinates));
dataSet.AddCoordinateSystem(
vtkm::cont::CoordinateSystem("coordinates", coordinates));
dataSet.AddField(vtkm::cont::Field("nodevar", vtkm::cont::Field::ASSOC_POINTS, fieldArray)); dataSet.AddField(vtkm::cont::Field("nodevar", vtkm::cont::Field::ASSOC_POINTS, fieldArray));
@ -128,10 +139,8 @@ vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims)
return dataSet; return dataSet;
} }
} }
// Initialize the OpenGL state // Initialize the OpenGL state
void initializeGL() void initializeGL()
{ {
@ -157,7 +166,6 @@ void initializeGL()
glEnable(GL_COLOR_MATERIAL); glEnable(GL_COLOR_MATERIAL);
} }
// Render the output using simple OpenGL // Render the output using simple OpenGL
void displayCall() void displayCall()
{ {
@ -166,7 +174,7 @@ void displayCall()
glMatrixMode(GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glLoadIdentity(); glLoadIdentity();
gluPerspective( 45.0f, 1.0f, 1.0f, 20.0f); gluPerspective(45.0f, 1.0f, 1.0f, 20.0f);
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); glLoadIdentity();
@ -181,7 +189,7 @@ void displayCall()
glColor3f(0.1f, 0.1f, 0.6f); glColor3f(0.1f, 0.1f, 0.6f);
glBegin(GL_TRIANGLES); glBegin(GL_TRIANGLES);
for (vtkm::IdComponent i=0; i<verticesArray.GetNumberOfValues(); i++) for (vtkm::IdComponent i = 0; i < verticesArray.GetNumberOfValues(); i++)
{ {
vtkm::Vec<vtkm::Float32, 3> curNormal = normalsArray.GetPortalConstControl().Get(i); vtkm::Vec<vtkm::Float32, 3> curNormal = normalsArray.GetPortalConstControl().Get(i);
vtkm::Vec<vtkm::Float32, 3> curVertex = verticesArray.GetPortalConstControl().Get(i); vtkm::Vec<vtkm::Float32, 3> curVertex = verticesArray.GetPortalConstControl().Get(i);
@ -194,7 +202,6 @@ void displayCall()
glutSwapBuffers(); glutSwapBuffers();
} }
// Allow rotations of the view // Allow rotations of the view
void mouseMove(int x, int y) void mouseMove(int x, int y)
{ {
@ -205,11 +212,11 @@ void mouseMove(int x, int y)
{ {
vtkm::Float32 pideg = static_cast<vtkm::Float32>(vtkm::Pi_2()); vtkm::Float32 pideg = static_cast<vtkm::Float32>(vtkm::Pi_2());
Quaternion newRotX; Quaternion newRotX;
newRotX.setEulerAngles(-0.2f*dx*pideg/180.0f, 0.0f, 0.0f); newRotX.setEulerAngles(-0.2f * dx * pideg / 180.0f, 0.0f, 0.0f);
qrot.mul(newRotX); qrot.mul(newRotX);
Quaternion newRotY; Quaternion newRotY;
newRotY.setEulerAngles(0.0f, 0.0f, -0.2f*dy*pideg/180.0f); newRotY.setEulerAngles(0.0f, 0.0f, -0.2f * dy * pideg / 180.0f);
qrot.mul(newRotY); qrot.mul(newRotY);
} }
lastx = x; lastx = x;
@ -218,15 +225,18 @@ void mouseMove(int x, int y)
glutPostRedisplay(); glutPostRedisplay();
} }
// Respond to mouse button // Respond to mouse button
void mouseCall(int button, int state, int x, int y) void mouseCall(int button, int state, int x, int y)
{ {
if (button == 0) mouse_state = state; if (button == 0)
if ((button == 0) && (state == 0)) { lastx = x; lasty = y; } mouse_state = state;
if ((button == 0) && (state == 0))
{
lastx = x;
lasty = y;
}
} }
// Compute and render an isosurface for a uniform grid example // Compute and render an isosurface for a uniform grid example
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
@ -236,21 +246,20 @@ int main(int argc, char* argv[])
filter.SetGenerateNormals(true); filter.SetGenerateNormals(true);
filter.SetMergeDuplicatePoints(false); filter.SetMergeDuplicatePoints(false);
filter.SetIsoValue(0, 0.5); filter.SetIsoValue(0, 0.5);
vtkm::filter::ResultDataSet result = vtkm::filter::ResultDataSet result = filter.Execute(dataSet, dataSet.GetField("nodevar"));
filter.Execute( dataSet, dataSet.GetField("nodevar") );
filter.MapFieldOntoOutput(result, dataSet.GetField("nodevar")); filter.MapFieldOntoOutput(result, dataSet.GetField("nodevar"));
//need to extract vertices, normals, and scalars //need to extract vertices, normals, and scalars
vtkm::cont::DataSet& outputData = result.GetDataSet(); vtkm::cont::DataSet& outputData = result.GetDataSet();
typedef vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3>> VertType;
typedef vtkm::cont::ArrayHandle< vtkm::Vec<vtkm::Float32,3> > VertType;
vtkm::cont::CoordinateSystem coords = outputData.GetCoordinateSystem(); vtkm::cont::CoordinateSystem coords = outputData.GetCoordinateSystem();
verticesArray = coords.GetData().Cast<VertType>(); verticesArray = coords.GetData().Cast<VertType>();
normalsArray = outputData.GetField("normals").GetData().Cast<VertType>(); normalsArray = outputData.GetField("normals").GetData().Cast<VertType>();
scalarsArray = outputData.GetField("nodevar").GetData().Cast< vtkm::cont::ArrayHandle<vtkm::Float32> >(); scalarsArray =
outputData.GetField("nodevar").GetData().Cast<vtkm::cont::ArrayHandle<vtkm::Float32>>();
std::cout << "Number of output vertices: " << verticesArray.GetNumberOfValues() << std::endl; std::cout << "Number of output vertices: " << verticesArray.GetNumberOfValues() << std::endl;
@ -282,5 +291,5 @@ int main(int argc, char* argv[])
} }
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

@ -36,55 +36,84 @@
class Quaternion class Quaternion
{ {
public: public:
Quaternion() { x = y = z = 0.0; w = 1.0; } Quaternion()
Quaternion(double ax, double ay, double az, double aw) : x(ax), y(ay), z(az), w(aw) {}; {
void set(double ax, double ay, double az, double aw) { x = ax; y = ay; z = az; w = aw; } x = y = z = 0.0;
void normalize() w = 1.0;
{ }
float norm = static_cast<float>(sqrt(x*x + y*y + z*z + w*w)); Quaternion(double ax, double ay, double az, double aw)
if (norm > 0.00001) { x /= norm; y /= norm; z /= norm; w /= norm; } : x(ax)
} , y(ay)
void mul(Quaternion q) , z(az)
{ , w(aw){};
double tx, ty, tz, tw; void set(double ax, double ay, double az, double aw)
tx = w*q.x + x*q.w + y*q.z - z*q.y; {
ty = w*q.y + y*q.w + z*q.x - x*q.z; x = ax;
tz = w*q.z + z*q.w + x*q.y - y*q.x; y = ay;
tw = w*q.w - x*q.x - y*q.y - z*q.z; z = az;
w = aw;
}
void normalize()
{
float norm = static_cast<float>(sqrt(x * x + y * y + z * z + w * w));
if (norm > 0.00001)
{
x /= norm;
y /= norm;
z /= norm;
w /= norm;
}
}
void mul(Quaternion q)
{
double tx, ty, tz, tw;
tx = w * q.x + x * q.w + y * q.z - z * q.y;
ty = w * q.y + y * q.w + z * q.x - x * q.z;
tz = w * q.z + z * q.w + x * q.y - y * q.x;
tw = w * q.w - x * q.x - y * q.y - z * q.z;
x = tx; y = ty; z = tz; w = tw; x = tx;
} y = ty;
void setEulerAngles(float pitch, float yaw, float roll) z = tz;
{ w = tw;
w = cos(pitch/2.0)*cos(yaw/2.0)*cos(roll/2.0) - sin(pitch/2.0)*sin(yaw/2.0)*sin(roll/2.0); }
x = sin(pitch/2.0)*sin(yaw/2.0)*cos(roll/2.0) + cos(pitch/2.0)*cos(yaw/2.0)*sin(roll/2.0); void setEulerAngles(float pitch, float yaw, float roll)
y = sin(pitch/2.0)*cos(yaw/2.0)*cos(roll/2.0) + cos(pitch/2.0)*sin(yaw/2.0)*sin(roll/2.0); {
z = cos(pitch/2.0)*sin(yaw/2.0)*cos(roll/2.0) - sin(pitch/2.0)*cos(yaw/2.0)*sin(roll/2.0); w = cos(pitch / 2.0) * cos(yaw / 2.0) * cos(roll / 2.0) -
sin(pitch / 2.0) * sin(yaw / 2.0) * sin(roll / 2.0);
x = sin(pitch / 2.0) * sin(yaw / 2.0) * cos(roll / 2.0) +
cos(pitch / 2.0) * cos(yaw / 2.0) * sin(roll / 2.0);
y = sin(pitch / 2.0) * cos(yaw / 2.0) * cos(roll / 2.0) +
cos(pitch / 2.0) * sin(yaw / 2.0) * sin(roll / 2.0);
z = cos(pitch / 2.0) * sin(yaw / 2.0) * cos(roll / 2.0) -
sin(pitch / 2.0) * cos(yaw / 2.0) * sin(roll / 2.0);
normalize(); normalize();
} }
void getRotMat(float* m) const void getRotMat(float* m) const
{ {
for (int i=0; i<16; i++) {m[i] = 0.0;} for (int i = 0; i < 16; i++)
{
m[i] = 0.0;
}
m[0] = static_cast<float>(1.0 - 2.0*y*y - 2.0*z*z); m[0] = static_cast<float>(1.0 - 2.0 * y * y - 2.0 * z * z);
m[1] = static_cast<float>(2.0*x*y - 2.0*z*w); m[1] = static_cast<float>(2.0 * x * y - 2.0 * z * w);
m[2] = static_cast<float>(2.0*x*z + 2.0*y*w); m[2] = static_cast<float>(2.0 * x * z + 2.0 * y * w);
m[4] = static_cast<float>(2.0*x*y + 2.0*z*w); m[4] = static_cast<float>(2.0 * x * y + 2.0 * z * w);
m[5] = static_cast<float>(1.0 - 2.0*x*x - 2.0*z*z); m[5] = static_cast<float>(1.0 - 2.0 * x * x - 2.0 * z * z);
m[6] = static_cast<float>(2.0*y*z - 2.0*x*w); m[6] = static_cast<float>(2.0 * y * z - 2.0 * x * w);
m[8] = static_cast<float>(2.0*x*z - 2.0*y*w); m[8] = static_cast<float>(2.0 * x * z - 2.0 * y * w);
m[9] = static_cast<float>(2.0*y*z + 2.0*x*w); m[9] = static_cast<float>(2.0 * y * z + 2.0 * x * w);
m[10] = static_cast<float>(1.0 - 2.0*x*x - 2.0*y*y); m[10] = static_cast<float>(1.0 - 2.0 * x * x - 2.0 * y * y);
m[15] = 1.0; m[15] = 1.0;
} }
double x,y,z,w; double x, y, z, w;
}; };
#endif /* QUATERNION_H_ */ #endif /* QUATERNION_H_ */

@ -31,25 +31,26 @@
#include <vtkm/cont/serial/DeviceAdapterSerial.h> #include <vtkm/cont/serial/DeviceAdapterSerial.h>
#include <vtkm/cont/tbb/DeviceAdapterTBB.h> #include <vtkm/cont/tbb/DeviceAdapterTBB.h>
typedef vtkm::Vec< vtkm::Float32, 3 > FloatVec3; typedef vtkm::Vec<vtkm::Float32, 3> FloatVec3;
typedef vtkm::Vec< vtkm::UInt8, 4 > Uint8Vec4; typedef vtkm::Vec<vtkm::UInt8, 4> Uint8Vec4;
struct GenerateSurfaceWorklet : public vtkm::worklet::WorkletMapField struct GenerateSurfaceWorklet : public vtkm::worklet::WorkletMapField
{ {
vtkm::Float32 t; vtkm::Float32 t;
GenerateSurfaceWorklet(vtkm::Float32 st) : t(st) {} GenerateSurfaceWorklet(vtkm::Float32 st)
: t(st)
{
}
typedef void ControlSignature( FieldIn<>, FieldOut<>, FieldOut<> ); typedef void ControlSignature(FieldIn<>, FieldOut<>, FieldOut<>);
typedef void ExecutionSignature( _1, _2, _3 ); typedef void ExecutionSignature(_1, _2, _3);
template<typename T> template <typename T>
VTKM_EXEC VTKM_EXEC void operator()(const vtkm::Vec<T, 3>& input, vtkm::Vec<T, 3>& output,
void operator()( const vtkm::Vec< T, 3 > & input, vtkm::Vec<vtkm::UInt8, 4>& color) const
vtkm::Vec<T, 3> & output,
vtkm::Vec<vtkm::UInt8, 4>& color ) const
{ {
output[0] = input[0]; output[0] = input[0];
output[1] = 0.25f * vtkm::Sin( input[0] * 10.f + t ) * vtkm::Cos( input[2] * 10.f + t ); output[1] = 0.25f * vtkm::Sin(input[0] * 10.f + t) * vtkm::Cos(input[2] * 10.f + t);
output[2] = input[2]; output[2] = input[2];
color[0] = 0; color[0] = 0;
@ -61,65 +62,58 @@ struct GenerateSurfaceWorklet : public vtkm::worklet::WorkletMapField
struct RunGenerateSurfaceWorklet struct RunGenerateSurfaceWorklet
{ {
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
bool operator()(DeviceAdapterTag ) const bool operator()(DeviceAdapterTag) const
{ {
//At this point we know we have runtime support //At this point we know we have runtime support
typedef vtkm::cont::DeviceAdapterTraits<DeviceAdapterTag> DeviceTraits; typedef vtkm::cont::DeviceAdapterTraits<DeviceAdapterTag> DeviceTraits;
typedef vtkm::worklet::DispatcherMapField<GenerateSurfaceWorklet, typedef vtkm::worklet::DispatcherMapField<GenerateSurfaceWorklet, DeviceAdapterTag>
DeviceAdapterTag> DispatcherType; DispatcherType;
std::cout << "Running a worklet on device adapter: " std::cout << "Running a worklet on device adapter: " << DeviceTraits::GetName() << std::endl;
<< DeviceTraits::GetName() << std::endl;
GenerateSurfaceWorklet worklet( 0.05f ); GenerateSurfaceWorklet worklet(0.05f);
DispatcherType(worklet).Invoke( this->In, DispatcherType(worklet).Invoke(this->In, this->Out, this->Color);
this->Out,
this->Color);
return true; return true;
} }
vtkm::cont::ArrayHandle< FloatVec3 > In; vtkm::cont::ArrayHandle<FloatVec3> In;
vtkm::cont::ArrayHandle< FloatVec3 > Out; vtkm::cont::ArrayHandle<FloatVec3> Out;
vtkm::cont::ArrayHandle< Uint8Vec4 > Color; vtkm::cont::ArrayHandle<Uint8Vec4> Color;
}; };
template <typename T>
template<typename T> std::vector<vtkm::Vec<T, 3>> make_testData(int size)
std::vector< vtkm::Vec<T, 3> > make_testData(int size)
{ {
std::vector< vtkm::Vec< T, 3 > > data; std::vector<vtkm::Vec<T, 3>> data;
data.reserve( static_cast<std::size_t>(size*size) ); data.reserve(static_cast<std::size_t>(size * size));
for (int i = 0; i < size; ++i ) for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{ {
for (int j = 0; j < size; ++j ) data.push_back(vtkm::Vec<T, 3>(2.f * static_cast<T>(i / size) - 1.f, 0.f,
{ 2.f * static_cast<T>(j / size) - 1.f));
data.push_back( vtkm::Vec<T,3>(2.f*static_cast<T>(i/size)-1.f,
0.f,
2.f*static_cast<T>(j/size)-1.f));
}
} }
}
return data; return data;
} }
//This is the list of devices to compile in support for. The order of the //This is the list of devices to compile in support for. The order of the
//devices determines the runtime preference. //devices determines the runtime preference.
struct DevicesToTry struct DevicesToTry
: vtkm::ListTagBase< : vtkm::ListTagBase<vtkm::cont::DeviceAdapterTagCuda, vtkm::cont::DeviceAdapterTagTBB,
vtkm::cont::DeviceAdapterTagCuda, vtkm::cont::DeviceAdapterTagSerial>
vtkm::cont::DeviceAdapterTagTBB, {
vtkm::cont::DeviceAdapterTagSerial> { }; };
int main(int, char**) int main(int, char**)
{ {
std::vector< FloatVec3 > data = make_testData<vtkm::Float32>(1024); std::vector<FloatVec3> data = make_testData<vtkm::Float32>(1024);
//make array handles for the data //make array handles for the data
// TryExecutes takes a functor and a list of devices. It then tries to run // TryExecutes takes a functor and a list of devices. It then tries to run
// the functor for each device (in the order given in the list) until the // the functor for each device (in the order given in the list) until the
// execution succeeds. This allows you to compile in support for multiple // execution succeeds. This allows you to compile in support for multiple
@ -136,7 +130,4 @@ int main(int, char**)
RunGenerateSurfaceWorklet task; RunGenerateSurfaceWorklet task;
task.In = vtkm::cont::make_ArrayHandle(data); task.In = vtkm::cont::make_ArrayHandle(data);
vtkm::cont::TryExecute(task, DevicesToTry()); vtkm::cont::TryExecute(task, DevicesToTry());
} }

@ -30,16 +30,16 @@
//Suppress warnings about glut being deprecated on OSX //Suppress warnings about glut being deprecated on OSX
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic push #pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif #endif
#include <vtkm/rendering/internal/OpenGLHeaders.h> //Required for compile.... #include <vtkm/rendering/internal/OpenGLHeaders.h> //Required for compile....
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
#include <vtkm/rendering/CanvasGL.h> #include <vtkm/rendering/CanvasGL.h>
@ -47,113 +47,109 @@
#include <vtkm/rendering/MapperGL.h> #include <vtkm/rendering/MapperGL.h>
#include <vtkm/rendering/View3D.h> #include <vtkm/rendering/View3D.h>
vtkm::rendering::View3D *view = nullptr; vtkm::rendering::View3D* view = nullptr;
const vtkm::Int32 W = 512, H = 512; const vtkm::Int32 W = 512, H = 512;
int buttonStates[3] = {GLUT_UP, GLUT_UP, GLUT_UP}; int buttonStates[3] = { GLUT_UP, GLUT_UP, GLUT_UP };
bool shiftKey = false; bool shiftKey = false;
int lastx=-1, lasty=-1; int lastx = -1, lasty = -1;
void void reshape(int, int)
reshape(int, int)
{ {
//Don't allow resizing window. //Don't allow resizing window.
glutReshapeWindow(W,H); glutReshapeWindow(W, H);
} }
// Render the output using simple OpenGL // Render the output using simple OpenGL
void displayCall() void displayCall()
{ {
view->Paint(); view->Paint();
glutSwapBuffers(); glutSwapBuffers();
} }
// Allow rotations of the camera // Allow rotations of the camera
void mouseMove(int x, int y) void mouseMove(int x, int y)
{ {
const vtkm::Id width = view->GetCanvas().GetWidth(); const vtkm::Id width = view->GetCanvas().GetWidth();
const vtkm::Id height = view->GetCanvas().GetHeight(); const vtkm::Id height = view->GetCanvas().GetHeight();
//Map to XY //Map to XY
y = static_cast<int>(height-y); y = static_cast<int>(height - y);
if (lastx != -1 && lasty != -1) if (lastx != -1 && lasty != -1)
{
vtkm::Float32 x1 = vtkm::Float32(lastx * 2) / vtkm::Float32(width) - 1.0f;
vtkm::Float32 y1 = vtkm::Float32(lasty * 2) / vtkm::Float32(height) - 1.0f;
vtkm::Float32 x2 = vtkm::Float32(x * 2) / vtkm::Float32(width) - 1.0f;
vtkm::Float32 y2 = vtkm::Float32(y * 2) / vtkm::Float32(height) - 1.0f;
if (buttonStates[0] == GLUT_DOWN)
{ {
vtkm::Float32 x1 = vtkm::Float32(lastx*2)/vtkm::Float32(width) - 1.0f; if (shiftKey)
vtkm::Float32 y1 = vtkm::Float32(lasty*2)/vtkm::Float32(height) - 1.0f; view->GetCamera().Pan(x2 - x1, y2 - y1);
vtkm::Float32 x2 = vtkm::Float32(x*2)/vtkm::Float32(width) - 1.0f; else
vtkm::Float32 y2 = vtkm::Float32(y*2)/vtkm::Float32(height) - 1.0f; view->GetCamera().TrackballRotate(x1, y1, x2, y2);
if (buttonStates[0] == GLUT_DOWN)
{
if (shiftKey)
view->GetCamera().Pan(x2-x1, y2-y1);
else
view->GetCamera().TrackballRotate(x1,y1, x2,y2);
}
else if (buttonStates[1] == GLUT_DOWN)
view->GetCamera().Zoom(y2-y1);
} }
else if (buttonStates[1] == GLUT_DOWN)
view->GetCamera().Zoom(y2 - y1);
}
lastx = x; lastx = x;
lasty = y; lasty = y;
glutPostRedisplay(); glutPostRedisplay();
} }
// Respond to mouse button // Respond to mouse button
void mouseCall(int button, int state, int vtkmNotUsed(x), int vtkmNotUsed(y)) void mouseCall(int button, int state, int vtkmNotUsed(x), int vtkmNotUsed(y))
{ {
int modifiers = glutGetModifiers(); int modifiers = glutGetModifiers();
shiftKey = modifiers & GLUT_ACTIVE_SHIFT; shiftKey = modifiers & GLUT_ACTIVE_SHIFT;
buttonStates[button] = state; buttonStates[button] = state;
//std::cout<<"Buttons: "<<buttonStates[0]<<" "<<buttonStates[1]<<" "<<buttonStates[2]<<" SHIFT= "<<shiftKey<<std::endl; //std::cout<<"Buttons: "<<buttonStates[0]<<" "<<buttonStates[1]<<" "<<buttonStates[2]<<" SHIFT= "<<shiftKey<<std::endl;
//mouse down, reset. //mouse down, reset.
if (buttonStates[button] == GLUT_DOWN) if (buttonStates[button] == GLUT_DOWN)
{ {
lastx = -1; lastx = -1;
lasty = -1; lasty = -1;
} }
} }
// Compute and render an isosurface for a uniform grid example // Compute and render an isosurface for a uniform grid example
int int main(int argc, char* argv[])
main(int argc, char* argv[])
{ {
vtkm::cont::testing::MakeTestDataSet maker; vtkm::cont::testing::MakeTestDataSet maker;
vtkm::cont::DataSet ds = maker.Make3DUniformDataSet0(); vtkm::cont::DataSet ds = maker.Make3DUniformDataSet0();
lastx = lasty = -1; lastx = lasty = -1;
glutInit(&argc, argv); glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(W,H); glutInitWindowSize(W, H);
glutCreateWindow("VTK-m Rendering"); glutCreateWindow("VTK-m Rendering");
glutDisplayFunc(displayCall); glutDisplayFunc(displayCall);
glutMotionFunc(mouseMove); glutMotionFunc(mouseMove);
glutMouseFunc(mouseCall); glutMouseFunc(mouseCall);
glutReshapeFunc(reshape); glutReshapeFunc(reshape);
vtkm::rendering::Color bg(0.2f, 0.2f, 0.2f, 1.0f); vtkm::rendering::Color bg(0.2f, 0.2f, 0.2f, 1.0f);
vtkm::rendering::CanvasGL canvas; vtkm::rendering::CanvasGL canvas;
vtkm::rendering::MapperGL mapper; vtkm::rendering::MapperGL mapper;
vtkm::rendering::Scene scene; vtkm::rendering::Scene scene;
scene.AddActor(vtkm::rendering::Actor(ds.GetCellSet(), scene.AddActor(vtkm::rendering::Actor(ds.GetCellSet(), ds.GetCoordinateSystem(),
ds.GetCoordinateSystem(), ds.GetField("pointvar"),
ds.GetField("pointvar"), vtkm::rendering::ColorTable("thermal")));
vtkm::rendering::ColorTable("thermal")));
//Create vtkm rendering stuff. //Create vtkm rendering stuff.
view = new vtkm::rendering::View3D(scene, mapper, canvas, bg); view = new vtkm::rendering::View3D(scene, mapper, canvas, bg);
view->Initialize(); view->Initialize();
glutMainLoop(); glutMainLoop();
return 0; return 0;
} }
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

79
examples/streamline/StreamLineUniformGrid.cxx Executable file → Normal file

@ -36,14 +36,14 @@
//Suppress warnings about glut being deprecated on OSX //Suppress warnings about glut being deprecated on OSX
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic push #pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif #endif
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
#include "../isosurface/quaternion.h" #include "../isosurface/quaternion.h"
@ -51,7 +51,7 @@
typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter;
// Output data set shared with opengl // Output data set shared with opengl
static vtkm::worklet::StreamLineFilterUniformGrid<vtkm::Float32, DeviceAdapter> *streamLineFilter; static vtkm::worklet::StreamLineFilterUniformGrid<vtkm::Float32, DeviceAdapter>* streamLineFilter;
static vtkm::cont::DataSet outDataSet; static vtkm::cont::DataSet outDataSet;
// Input parameters // Input parameters
@ -61,7 +61,7 @@ const vtkm::Float32 tStep = 0.5f;
const vtkm::Id direction = vtkm::worklet::internal::BOTH; const vtkm::Id direction = vtkm::worklet::internal::BOTH;
// Point location of vertices from a CastAndCall but needs a static cast eventually // Point location of vertices from a CastAndCall but needs a static cast eventually
static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3> > vertexArray; static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3>> vertexArray;
// OpenGL display variables // OpenGL display variables
Quaternion qrot; Quaternion qrot;
@ -76,16 +76,14 @@ int mouse_state = 1;
struct GetVertexArray struct GetVertexArray
{ {
template <typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT void operator()(ArrayHandleType array) const
void operator()(ArrayHandleType array) const
{ {
this->GetVertexPortal(array.GetPortalConstControl()); this->GetVertexPortal(array.GetPortalConstControl());
} }
private: private:
template <typename PortalType> template <typename PortalType>
VTKM_CONT VTKM_CONT void GetVertexPortal(const PortalType& portal) const
void GetVertexPortal(const PortalType &portal) const
{ {
for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++) for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++)
{ {
@ -131,7 +129,7 @@ void displayCall()
glMatrixMode(GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glLoadIdentity(); glLoadIdentity();
gluPerspective( 60.0f, 1.0f, 1.0f, 100.0f); gluPerspective(60.0f, 1.0f, 1.0f, 100.0f);
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); glLoadIdentity();
@ -147,8 +145,8 @@ void displayCall()
// Get the cell set, coordinate system and coordinate data // Get the cell set, coordinate system and coordinate data
vtkm::cont::CellSetExplicit<> cellSet; vtkm::cont::CellSetExplicit<> cellSet;
outDataSet.GetCellSet(0).CopyTo(cellSet); outDataSet.GetCellSet(0).CopyTo(cellSet);
const vtkm::cont::DynamicArrayHandleCoordinateSystem &coordArray = const vtkm::cont::DynamicArrayHandleCoordinateSystem& coordArray =
outDataSet.GetCoordinateSystem().GetData(); outDataSet.GetCoordinateSystem().GetData();
vtkm::Id numberOfCells = cellSet.GetNumberOfCells(); vtkm::Id numberOfCells = cellSet.GetNumberOfCells();
vtkm::Id numberOfPoints = coordArray.GetNumberOfValues(); vtkm::Id numberOfPoints = coordArray.GetNumberOfValues();
@ -169,7 +167,7 @@ void displayCall()
glBegin(GL_LINE_STRIP); glBegin(GL_LINE_STRIP);
for (vtkm::IdComponent i = 0; i < numIndices; i++) for (vtkm::IdComponent i = 0; i < numIndices; i++)
{ {
vtkm::Vec<vtkm::Float32,3> pt = vertexArray.GetPortalConstControl().Get(polylineIndices[i]); vtkm::Vec<vtkm::Float32, 3> pt = vertexArray.GetPortalConstControl().Get(polylineIndices[i]);
glVertex3f(pt[0], pt[1], pt[2]); glVertex3f(pt[0], pt[1], pt[2]);
} }
glEnd(); glEnd();
@ -201,19 +199,23 @@ void mouseMove(int x, int y)
glutPostRedisplay(); glutPostRedisplay();
} }
// Respond to mouse button // Respond to mouse button
void mouseCall(int button, int state, int x, int y) void mouseCall(int button, int state, int x, int y)
{ {
if (button == 0) mouse_state = state; if (button == 0)
if ((button == 0) && (state == 0)) { lastx = x; lasty = y; } mouse_state = state;
if ((button == 0) && (state == 0))
{
lastx = x;
lasty = y;
}
} }
namespace { namespace
{
template <typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, 3> Normalize(vtkm::Vec<T, 3> v)
vtkm::Vec<T,3> Normalize(vtkm::Vec<T,3> v)
{ {
T magnitude = static_cast<T>(sqrt(vtkm::dot(v, v))); T magnitude = static_cast<T>(sqrt(vtkm::dot(v, v)));
T zero = static_cast<T>(0.0); T zero = static_cast<T>(0.0);
@ -223,50 +225,50 @@ vtkm::Vec<T,3> Normalize(vtkm::Vec<T,3> v)
else else
return one / magnitude * v; return one / magnitude * v;
} }
} }
// Run streamlines on a uniform grid of vector data // Run streamlines on a uniform grid of vector data
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
std::cout << "StreamLineUniformGrid Example" << std::endl; std::cout << "StreamLineUniformGrid Example" << std::endl;
std::cout << "Parameters are fileName [numSeeds maxSteps timeStep direction]" << std::endl << std::endl; std::cout << "Parameters are fileName [numSeeds maxSteps timeStep direction]" << std::endl
<< std::endl;
std::cout << "Direction is FORWARD=0 BACKWARD=1 BOTH=2" << std::endl << std::endl; std::cout << "Direction is FORWARD=0 BACKWARD=1 BOTH=2" << std::endl << std::endl;
std::cout << "File is expected to be binary with xdim ydim zdim as 32 bit integers " << std::endl; std::cout << "File is expected to be binary with xdim ydim zdim as 32 bit integers " << std::endl;
std::cout << "followed by vector data per dimension point as 32 bit float" << std::endl; std::cout << "followed by vector data per dimension point as 32 bit float" << std::endl;
// Read in the vector data for testing // Read in the vector data for testing
FILE * pFile = fopen(argv[1], "rb"); FILE* pFile = fopen(argv[1], "rb");
if (pFile == nullptr) perror ("Error opening file"); if (pFile == nullptr)
perror("Error opening file");
size_t ret_code = 0; size_t ret_code = 0;
// Size of the dataset // Size of the dataset
int dims[3]; int dims[3];
ret_code = fread(dims, sizeof(int), 3, pFile); ret_code = fread(dims, sizeof(int), 3, pFile);
if(ret_code != 3) if (ret_code != 3)
{ {
perror("Error reading size of data"); perror("Error reading size of data");
fclose(pFile); fclose(pFile);
return 0; return 0;
} }
const vtkm::Id3 vdims(dims[0], dims[1], dims[2]); const vtkm::Id3 vdims(dims[0], dims[1], dims[2]);
// Read vector data at each point of the uniform grid and store // Read vector data at each point of the uniform grid and store
vtkm::Id nElements = vdims[0] * vdims[1] * vdims[2] * 3; vtkm::Id nElements = vdims[0] * vdims[1] * vdims[2] * 3;
float* data = new float[static_cast<std::size_t>(nElements)]; float* data = new float[static_cast<std::size_t>(nElements)];
ret_code = fread(data, sizeof(float), static_cast<std::size_t>(nElements), pFile); ret_code = fread(data, sizeof(float), static_cast<std::size_t>(nElements), pFile);
if( ret_code != static_cast<size_t>(nElements) ) if (ret_code != static_cast<size_t>(nElements))
{ {
perror("Error reading vector data"); perror("Error reading vector data");
fclose(pFile); fclose(pFile);
return 0; return 0;
} }
//We are done with the file now, so release the file descriptor //We are done with the file now, so release the file descriptor
fclose(pFile); fclose(pFile);
std::vector<vtkm::Vec<vtkm::Float32, 3> > field; std::vector<vtkm::Vec<vtkm::Float32, 3>> field;
for (vtkm::Id i = 0; i < nElements; i++) for (vtkm::Id i = 0; i < nElements; i++)
{ {
vtkm::Float32 x = data[i]; vtkm::Float32 x = data[i];
@ -275,7 +277,7 @@ int main(int argc, char* argv[])
vtkm::Vec<vtkm::Float32, 3> vecData(x, y, z); vtkm::Vec<vtkm::Float32, 3> vecData(x, y, z);
field.push_back(Normalize(vecData)); field.push_back(Normalize(vecData));
} }
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3> > fieldArray; vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3>> fieldArray;
fieldArray = vtkm::cont::make_ArrayHandle(field); fieldArray = vtkm::cont::make_ArrayHandle(field);
// Construct the input dataset (uniform) to hold the input and set vector data // Construct the input dataset (uniform) to hold the input and set vector data
@ -290,12 +292,7 @@ int main(int argc, char* argv[])
// Create and run the filter // Create and run the filter
streamLineFilter = new vtkm::worklet::StreamLineFilterUniformGrid<vtkm::Float32, DeviceAdapter>(); streamLineFilter = new vtkm::worklet::StreamLineFilterUniformGrid<vtkm::Float32, DeviceAdapter>();
outDataSet = streamLineFilter->Run(inDataSet, outDataSet = streamLineFilter->Run(inDataSet, direction, nSeeds, nSteps, tStep);
direction,
nSeeds,
nSteps,
tStep);
// Render the output dataset of polylines // Render the output dataset of polylines
lastx = lasty = 0; lastx = lasty = 0;
@ -320,5 +317,5 @@ int main(int argc, char* argv[])
} }
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

@ -32,27 +32,28 @@
//Suppress warnings about glut being deprecated on OSX //Suppress warnings about glut being deprecated on OSX
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic push #pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif #endif
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
#include "../isosurface/quaternion.h" #include "../isosurface/quaternion.h"
typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter;
namespace { namespace
{
// Takes input uniform grid and outputs unstructured grid of tets // Takes input uniform grid and outputs unstructured grid of tets
static vtkm::cont::DataSet outDataSet; static vtkm::cont::DataSet outDataSet;
// Point location of vertices from a CastAndCall but needs a static cast eventually // Point location of vertices from a CastAndCall but needs a static cast eventually
static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float64, 3> > vertexArray; static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float64, 3>> vertexArray;
// OpenGL display variables // OpenGL display variables
Quaternion qrot; Quaternion qrot;
@ -69,24 +70,24 @@ vtkm::cont::DataSet MakeTetrahedralizeExplicitDataSet()
vtkm::cont::DataSetBuilderExplicitIterative builder; vtkm::cont::DataSetBuilderExplicitIterative builder;
builder.Begin(); builder.Begin();
builder.AddPoint( 0, 0, 0); builder.AddPoint(0, 0, 0);
builder.AddPoint( 1, 0, 0); builder.AddPoint(1, 0, 0);
builder.AddPoint( 2, 0, 0); builder.AddPoint(2, 0, 0);
builder.AddPoint( 3, 0, 0); builder.AddPoint(3, 0, 0);
builder.AddPoint( 0, 1, 0); builder.AddPoint(0, 1, 0);
builder.AddPoint( 1, 1, 0); builder.AddPoint(1, 1, 0);
builder.AddPoint( 2, 1, 0); builder.AddPoint(2, 1, 0);
builder.AddPoint( 2.5, 1.0, 0.0); builder.AddPoint(2.5, 1.0, 0.0);
builder.AddPoint( 0, 2, 0); builder.AddPoint(0, 2, 0);
builder.AddPoint( 1, 2, 0); builder.AddPoint(1, 2, 0);
builder.AddPoint( 0.5, 0.5, 1.0); builder.AddPoint(0.5, 0.5, 1.0);
builder.AddPoint( 1, 0, 1); builder.AddPoint(1, 0, 1);
builder.AddPoint( 2, 0, 1); builder.AddPoint(2, 0, 1);
builder.AddPoint( 3, 0, 1); builder.AddPoint(3, 0, 1);
builder.AddPoint( 1, 1, 1); builder.AddPoint(1, 1, 1);
builder.AddPoint( 2, 1, 1); builder.AddPoint(2, 1, 1);
builder.AddPoint( 2.5, 1.0, 1.0); builder.AddPoint(2.5, 1.0, 1.0);
builder.AddPoint( 0.5, 1.5, 1.0); builder.AddPoint(0.5, 1.5, 1.0);
builder.AddCell(vtkm::CELL_SHAPE_TETRA); builder.AddCell(vtkm::CELL_SHAPE_TETRA);
builder.AddCellPoint(0); builder.AddCellPoint(0);
@ -130,16 +131,14 @@ vtkm::cont::DataSet MakeTetrahedralizeExplicitDataSet()
struct GetVertexArray struct GetVertexArray
{ {
template <typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT void operator()(ArrayHandleType array) const
void operator()(ArrayHandleType array) const
{ {
this->GetVertexPortal(array.GetPortalConstControl()); this->GetVertexPortal(array.GetPortalConstControl());
} }
private: private:
template <typename PortalType> template <typename PortalType>
VTKM_CONT VTKM_CONT void GetVertexPortal(const PortalType& portal) const
void GetVertexPortal(const PortalType &portal) const
{ {
for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++) for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++)
{ {
@ -175,7 +174,6 @@ void initializeGL()
glEnable(GL_COLOR_MATERIAL); glEnable(GL_COLOR_MATERIAL);
} }
// //
// Render the output using simple OpenGL // Render the output using simple OpenGL
// //
@ -186,7 +184,7 @@ void displayCall()
glMatrixMode(GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glLoadIdentity(); glLoadIdentity();
gluPerspective( 45.0f, 1.0f, 1.0f, 40.0f); gluPerspective(45.0f, 1.0f, 1.0f, 40.0f);
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); glLoadIdentity();
@ -209,15 +207,14 @@ void displayCall()
vtkm::cont::CastAndCall(outDataSet.GetCoordinateSystem(), GetVertexArray()); vtkm::cont::CastAndCall(outDataSet.GetCoordinateSystem(), GetVertexArray());
// Draw the five tetrahedra belonging to each hexadron // Draw the five tetrahedra belonging to each hexadron
vtkm::Float32 color[5][3] = { vtkm::Float32 color[5][3] = { { 1.0f, 0.0f, 0.0f },
{1.0f, 0.0f, 0.0f}, { 0.0f, 1.0f, 0.0f },
{0.0f, 1.0f, 0.0f}, { 0.0f, 0.0f, 1.0f },
{0.0f, 0.0f, 1.0f}, { 1.0f, 0.0f, 1.0f },
{1.0f, 0.0f, 1.0f}, { 1.0f, 1.0f, 0.0f } };
{1.0f, 1.0f, 0.0f}
};
for (vtkm::Id tetra = 0; tetra < numberOfCells; tetra++) { for (vtkm::Id tetra = 0; tetra < numberOfCells; tetra++)
{
vtkm::Id indx = tetra % 5; vtkm::Id indx = tetra % 5;
glColor3f(color[indx][0], color[indx][1], color[indx][2]); glColor3f(color[indx][0], color[indx][1], color[indx][2]);
@ -226,13 +223,13 @@ void displayCall()
cellSet.GetIndices(tetra, tetIndices); cellSet.GetIndices(tetra, tetIndices);
// Get the vertex points for this tetrahedron // Get the vertex points for this tetrahedron
vtkm::Vec<vtkm::Float64,3> pt0 = vertexArray.GetPortalConstControl().Get(tetIndices[0]); vtkm::Vec<vtkm::Float64, 3> pt0 = vertexArray.GetPortalConstControl().Get(tetIndices[0]);
vtkm::Vec<vtkm::Float64,3> pt1 = vertexArray.GetPortalConstControl().Get(tetIndices[1]); vtkm::Vec<vtkm::Float64, 3> pt1 = vertexArray.GetPortalConstControl().Get(tetIndices[1]);
vtkm::Vec<vtkm::Float64,3> pt2 = vertexArray.GetPortalConstControl().Get(tetIndices[2]); vtkm::Vec<vtkm::Float64, 3> pt2 = vertexArray.GetPortalConstControl().Get(tetIndices[2]);
vtkm::Vec<vtkm::Float64,3> pt3 = vertexArray.GetPortalConstControl().Get(tetIndices[3]); vtkm::Vec<vtkm::Float64, 3> pt3 = vertexArray.GetPortalConstControl().Get(tetIndices[3]);
// Draw the tetrahedron filled with alternating colors // Draw the tetrahedron filled with alternating colors
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBegin(GL_TRIANGLE_STRIP); glBegin(GL_TRIANGLE_STRIP);
glVertex3d(pt0[0], pt0[1], pt0[2]); glVertex3d(pt0[0], pt0[1], pt0[2]);
glVertex3d(pt1[0], pt1[1], pt1[2]); glVertex3d(pt1[0], pt1[1], pt1[2]);
@ -244,7 +241,7 @@ void displayCall()
// Draw the tetrahedron wireframe // Draw the tetrahedron wireframe
glColor3f(1.0f, 1.0f, 1.0f); glColor3f(1.0f, 1.0f, 1.0f);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_TRIANGLE_STRIP); glBegin(GL_TRIANGLE_STRIP);
glVertex3d(pt0[0], pt0[1], pt0[2]); glVertex3d(pt0[0], pt0[1], pt0[2]);
glVertex3d(pt1[0], pt1[1], pt1[2]); glVertex3d(pt1[0], pt1[1], pt1[2]);
@ -258,7 +255,6 @@ void displayCall()
glutSwapBuffers(); glutSwapBuffers();
} }
// Allow rotations of the view // Allow rotations of the view
void mouseMove(int x, int y) void mouseMove(int x, int y)
{ {
@ -282,15 +278,18 @@ void mouseMove(int x, int y)
glutPostRedisplay(); glutPostRedisplay();
} }
// Respond to mouse button // Respond to mouse button
void mouseCall(int button, int state, int x, int y) void mouseCall(int button, int state, int x, int y)
{ {
if (button == 0) mouse_state = state; if (button == 0)
if ((button == 0) && (state == 0)) { lastx = x; lasty = y; } mouse_state = state;
if ((button == 0) && (state == 0))
{
lastx = x;
lasty = y;
}
} }
// Tetrahedralize and render uniform grid example // Tetrahedralize and render uniform grid example
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
@ -329,5 +328,5 @@ int main(int argc, char* argv[])
} }
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

@ -31,14 +31,14 @@
//Suppress warnings about glut being deprecated on OSX //Suppress warnings about glut being deprecated on OSX
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic push #pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif #endif
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
#include "../isosurface/quaternion.h" #include "../isosurface/quaternion.h"
@ -46,14 +46,14 @@
typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter;
// Default size of the example // Default size of the example
static vtkm::Id3 dims(4,4,4); static vtkm::Id3 dims(4, 4, 4);
static vtkm::Id cellsToDisplay = 64; static vtkm::Id cellsToDisplay = 64;
// Takes input uniform grid and outputs unstructured grid of tets // Takes input uniform grid and outputs unstructured grid of tets
static vtkm::cont::DataSet tetDataSet; static vtkm::cont::DataSet tetDataSet;
// Point location of vertices from a CastAndCall but needs a static cast eventually // Point location of vertices from a CastAndCall but needs a static cast eventually
static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float64, 3> > vertexArray; static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float64, 3>> vertexArray;
// OpenGL display variables // OpenGL display variables
static Quaternion qrot; static Quaternion qrot;
@ -71,14 +71,12 @@ vtkm::cont::DataSet MakeTetrahedralizeTestDataSet(vtkm::Id3 dim)
const vtkm::Id3 vdims(dim[0] + 1, dim[1] + 1, dim[2] + 1); const vtkm::Id3 vdims(dim[0] + 1, dim[1] + 1, dim[2] + 1);
const vtkm::Vec<vtkm::Float32, 3> origin = vtkm::make_Vec(0.0f, 0.0f, 0.0f); const vtkm::Vec<vtkm::Float32, 3> origin = vtkm::make_Vec(0.0f, 0.0f, 0.0f);
const vtkm::Vec<vtkm::Float32, 3> spacing = vtkm::make_Vec( const vtkm::Vec<vtkm::Float32, 3> spacing = vtkm::make_Vec(
1.0f/static_cast<vtkm::Float32>(dim[0]), 1.0f / static_cast<vtkm::Float32>(dim[0]), 1.0f / static_cast<vtkm::Float32>(dim[1]),
1.0f/static_cast<vtkm::Float32>(dim[1]), 1.0f / static_cast<vtkm::Float32>(dim[2]));
1.0f/static_cast<vtkm::Float32>(dim[2]));
// Generate coordinate system // Generate coordinate system
vtkm::cont::ArrayHandleUniformPointCoordinates coordinates(vdims, origin, spacing); vtkm::cont::ArrayHandleUniformPointCoordinates coordinates(vdims, origin, spacing);
dataSet.AddCoordinateSystem( dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", coordinates));
vtkm::cont::CoordinateSystem("coordinates", coordinates));
// Generate cell set // Generate cell set
vtkm::cont::CellSetStructured<3> cellSet("cells"); vtkm::cont::CellSetStructured<3> cellSet("cells");
@ -96,16 +94,14 @@ vtkm::cont::DataSet MakeTetrahedralizeTestDataSet(vtkm::Id3 dim)
struct GetVertexArray struct GetVertexArray
{ {
template <typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT void operator()(ArrayHandleType array) const
void operator()(ArrayHandleType array) const
{ {
this->GetVertexPortal(array.GetPortalConstControl()); this->GetVertexPortal(array.GetPortalConstControl());
} }
private: private:
template <typename PortalType> template <typename PortalType>
VTKM_CONT VTKM_CONT void GetVertexPortal(const PortalType& portal) const
void GetVertexPortal(const PortalType &portal) const
{ {
for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++) for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++)
{ {
@ -141,7 +137,6 @@ void initializeGL()
glEnable(GL_COLOR_MATERIAL); glEnable(GL_COLOR_MATERIAL);
} }
// //
// Render the output using simple OpenGL // Render the output using simple OpenGL
// //
@ -152,7 +147,7 @@ void displayCall()
glMatrixMode(GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glLoadIdentity(); glLoadIdentity();
gluPerspective( 45.0f, 1.0f, 1.0f, 20.0f); gluPerspective(45.0f, 1.0f, 1.0f, 20.0f);
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); glLoadIdentity();
@ -176,14 +171,11 @@ void displayCall()
// Draw the five tetrahedra belonging to each hexadron // Draw the five tetrahedra belonging to each hexadron
vtkm::Id tetra = 0; vtkm::Id tetra = 0;
vtkm::Float32 color[5][3] = vtkm::Float32 color[5][3] = { { 1.0f, 0.0f, 0.0f },
{ { 0.0f, 1.0f, 0.0f },
{1.0f, 0.0f, 0.0f}, { 0.0f, 0.0f, 1.0f },
{0.0f, 1.0f, 0.0f}, { 1.0f, 0.0f, 1.0f },
{0.0f, 0.0f, 1.0f}, { 1.0f, 1.0f, 0.0f } };
{1.0f, 0.0f, 1.0f},
{1.0f, 1.0f, 0.0f}
};
for (vtkm::Id hex = 0; hex < cellsToDisplay; hex++) for (vtkm::Id hex = 0; hex < cellsToDisplay; hex++)
{ {
@ -197,13 +189,13 @@ void displayCall()
cellSet.GetIndices(tetra, tetIndices); cellSet.GetIndices(tetra, tetIndices);
// Get the vertex points for this tetrahedron // Get the vertex points for this tetrahedron
vtkm::Vec<vtkm::Float64,3> pt0 = vertexArray.GetPortalConstControl().Get(tetIndices[0]); vtkm::Vec<vtkm::Float64, 3> pt0 = vertexArray.GetPortalConstControl().Get(tetIndices[0]);
vtkm::Vec<vtkm::Float64,3> pt1 = vertexArray.GetPortalConstControl().Get(tetIndices[1]); vtkm::Vec<vtkm::Float64, 3> pt1 = vertexArray.GetPortalConstControl().Get(tetIndices[1]);
vtkm::Vec<vtkm::Float64,3> pt2 = vertexArray.GetPortalConstControl().Get(tetIndices[2]); vtkm::Vec<vtkm::Float64, 3> pt2 = vertexArray.GetPortalConstControl().Get(tetIndices[2]);
vtkm::Vec<vtkm::Float64,3> pt3 = vertexArray.GetPortalConstControl().Get(tetIndices[3]); vtkm::Vec<vtkm::Float64, 3> pt3 = vertexArray.GetPortalConstControl().Get(tetIndices[3]);
// Draw the tetrahedron filled with alternating colors // Draw the tetrahedron filled with alternating colors
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBegin(GL_TRIANGLE_STRIP); glBegin(GL_TRIANGLE_STRIP);
glVertex3d(pt0[0], pt0[1], pt0[2]); glVertex3d(pt0[0], pt0[1], pt0[2]);
glVertex3d(pt1[0], pt1[1], pt1[2]); glVertex3d(pt1[0], pt1[1], pt1[2]);
@ -215,7 +207,7 @@ void displayCall()
// Draw the tetrahedron wireframe // Draw the tetrahedron wireframe
glColor3f(1.0f, 1.0f, 1.0f); glColor3f(1.0f, 1.0f, 1.0f);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_TRIANGLE_STRIP); glBegin(GL_TRIANGLE_STRIP);
glVertex3d(pt0[0], pt0[1], pt0[2]); glVertex3d(pt0[0], pt0[1], pt0[2]);
glVertex3d(pt1[0], pt1[1], pt1[2]); glVertex3d(pt1[0], pt1[1], pt1[2]);
@ -233,7 +225,6 @@ void displayCall()
glutSwapBuffers(); glutSwapBuffers();
} }
// Allow rotations of the view // Allow rotations of the view
void mouseMove(int x, int y) void mouseMove(int x, int y)
{ {
@ -257,15 +248,18 @@ void mouseMove(int x, int y)
glutPostRedisplay(); glutPostRedisplay();
} }
// Respond to mouse button // Respond to mouse button
void mouseCall(int button, int state, int x, int y) void mouseCall(int button, int state, int x, int y)
{ {
if (button == 0) mouse_state = state; if (button == 0)
if ((button == 0) && (state == 0)) { lastx = x; lasty = y; } mouse_state = state;
if ((button == 0) && (state == 0))
{
lastx = x;
lasty = y;
}
} }
// Tetrahedralize and render uniform grid example // Tetrahedralize and render uniform grid example
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
@ -280,7 +274,8 @@ int main(int argc, char* argv[])
dims[2] = atoi(argv[3]); dims[2] = atoi(argv[3]);
cellsToDisplay = dims[0] * dims[1] * dims[2]; cellsToDisplay = dims[0] * dims[1] * dims[2];
} }
if (argc == 5) { if (argc == 5)
{
cellsToDisplay = atoi(argv[4]); cellsToDisplay = atoi(argv[4]);
} }
@ -314,5 +309,5 @@ int main(int argc, char* argv[])
} }
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

@ -31,26 +31,27 @@
//Suppress warnings about glut being deprecated on OSX //Suppress warnings about glut being deprecated on OSX
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic push #pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif #endif
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter;
namespace { namespace
{
// Takes input uniform grid and outputs unstructured grid of triangles // Takes input uniform grid and outputs unstructured grid of triangles
static vtkm::cont::DataSet outDataSet; static vtkm::cont::DataSet outDataSet;
static vtkm::Id numberOfInPoints; static vtkm::Id numberOfInPoints;
// Point location of vertices from a CastAndCall but needs a static cast eventually // Point location of vertices from a CastAndCall but needs a static cast eventually
static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float64, 3> > vertexArray; static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float64, 3>> vertexArray;
} // anonymous namespace } // anonymous namespace
@ -132,16 +133,14 @@ vtkm::cont::DataSet MakeTriangulateExplicitDataSet()
struct GetVertexArray struct GetVertexArray
{ {
template <typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT void operator()(ArrayHandleType array) const
void operator()(ArrayHandleType array) const
{ {
this->GetVertexPortal(array.GetPortalConstControl()); this->GetVertexPortal(array.GetPortalConstControl());
} }
private: private:
template <typename PortalType> template <typename PortalType>
VTKM_CONT VTKM_CONT void GetVertexPortal(const PortalType& portal) const
void GetVertexPortal(const PortalType &portal) const
{ {
for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++) for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++)
{ {
@ -161,7 +160,6 @@ void initializeGL()
glOrtho(-0.5f, 3.5f, -0.5f, 4.5f, -1.0f, 1.0f); glOrtho(-0.5f, 3.5f, -0.5f, 4.5f, -1.0f, 1.0f);
} }
// //
// Render the output using simple OpenGL // Render the output using simple OpenGL
// //
@ -182,13 +180,11 @@ void displayCall()
// Draw the two triangles belonging to each quad // Draw the two triangles belonging to each quad
vtkm::Float32 color[4][3] = { vtkm::Float32 color[4][3] = {
{1.0f, 0.0f, 0.0f}, { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 0.0f }
{0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 1.0f},
{1.0f, 1.0f, 0.0f}
}; };
for (vtkm::Id triangle = 0; triangle < numberOfCells; triangle++) { for (vtkm::Id triangle = 0; triangle < numberOfCells; triangle++)
{
vtkm::Id indx = triangle % 4; vtkm::Id indx = triangle % 4;
glColor3f(color[indx][0], color[indx][1], color[indx][2]); glColor3f(color[indx][0], color[indx][1], color[indx][2]);
@ -197,16 +193,16 @@ void displayCall()
cellSet.GetIndices(triangle, triIndices); cellSet.GetIndices(triangle, triIndices);
// Get the vertex points for this triangle // Get the vertex points for this triangle
vtkm::Vec<vtkm::Float64,3> pt0 = vertexArray.GetPortalConstControl().Get(triIndices[0]); vtkm::Vec<vtkm::Float64, 3> pt0 = vertexArray.GetPortalConstControl().Get(triIndices[0]);
vtkm::Vec<vtkm::Float64,3> pt1 = vertexArray.GetPortalConstControl().Get(triIndices[1]); vtkm::Vec<vtkm::Float64, 3> pt1 = vertexArray.GetPortalConstControl().Get(triIndices[1]);
vtkm::Vec<vtkm::Float64,3> pt2 = vertexArray.GetPortalConstControl().Get(triIndices[2]); vtkm::Vec<vtkm::Float64, 3> pt2 = vertexArray.GetPortalConstControl().Get(triIndices[2]);
// Draw the triangle filled with alternating colors // Draw the triangle filled with alternating colors
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBegin(GL_TRIANGLES); glBegin(GL_TRIANGLES);
glVertex3d(pt0[0], pt0[1], pt0[2]); glVertex3d(pt0[0], pt0[1], pt0[2]);
glVertex3d(pt1[0], pt1[1], pt1[2]); glVertex3d(pt1[0], pt1[1], pt1[2]);
glVertex3d(pt2[0], pt2[1], pt2[2]); glVertex3d(pt2[0], pt2[1], pt2[2]);
glEnd(); glEnd();
} }
glFlush(); glFlush();
@ -248,5 +244,5 @@ int main(int argc, char* argv[])
} }
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

@ -31,27 +31,27 @@
//Suppress warnings about glut being deprecated on OSX //Suppress warnings about glut being deprecated on OSX
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic push #pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif #endif
#if defined (__APPLE__) #if defined(__APPLE__)
# include <GLUT/glut.h> #include <GLUT/glut.h>
#else #else
# include <GL/glut.h> #include <GL/glut.h>
#endif #endif
typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter;
// Default size of the example // Default size of the example
static vtkm::Id2 dims(4,4); static vtkm::Id2 dims(4, 4);
static vtkm::Id cellsToDisplay = 16; static vtkm::Id cellsToDisplay = 16;
// Takes input uniform grid and outputs unstructured grid of triangles // Takes input uniform grid and outputs unstructured grid of triangles
static vtkm::cont::DataSet triDataSet; static vtkm::cont::DataSet triDataSet;
// Point location of vertices from a CastAndCall but needs a static cast eventually // Point location of vertices from a CastAndCall but needs a static cast eventually
static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float64, 3> > vertexArray; static vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float64, 3>> vertexArray;
// //
// Construct an input data set with uniform grid of indicated dimensions, origin and spacing // Construct an input data set with uniform grid of indicated dimensions, origin and spacing
@ -64,14 +64,11 @@ vtkm::cont::DataSet MakeTriangulateTestDataSet(vtkm::Id2 dim)
const vtkm::Id3 vdims(dim[0] + 1, dim[1] + 1, 1); const vtkm::Id3 vdims(dim[0] + 1, dim[1] + 1, 1);
const vtkm::Vec<vtkm::Float32, 3> origin = vtkm::make_Vec(0.0f, 0.0f, 0.0f); const vtkm::Vec<vtkm::Float32, 3> origin = vtkm::make_Vec(0.0f, 0.0f, 0.0f);
const vtkm::Vec<vtkm::Float32, 3> spacing = vtkm::make_Vec( const vtkm::Vec<vtkm::Float32, 3> spacing = vtkm::make_Vec(
1.0f/static_cast<vtkm::Float32>(dim[0]), 1.0f / static_cast<vtkm::Float32>(dim[0]), 1.0f / static_cast<vtkm::Float32>(dim[1]), 0.0f);
1.0f/static_cast<vtkm::Float32>(dim[1]),
0.0f);
// Generate coordinate system // Generate coordinate system
vtkm::cont::ArrayHandleUniformPointCoordinates coordinates(vdims, origin, spacing); vtkm::cont::ArrayHandleUniformPointCoordinates coordinates(vdims, origin, spacing);
dataSet.AddCoordinateSystem( dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", coordinates));
vtkm::cont::CoordinateSystem("coordinates", coordinates));
// Generate cell set // Generate cell set
vtkm::cont::CellSetStructured<2> cellSet("cells"); vtkm::cont::CellSetStructured<2> cellSet("cells");
@ -89,16 +86,14 @@ vtkm::cont::DataSet MakeTriangulateTestDataSet(vtkm::Id2 dim)
struct GetVertexArray struct GetVertexArray
{ {
template <typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT void operator()(ArrayHandleType array) const
void operator()(ArrayHandleType array) const
{ {
this->GetVertexPortal(array.GetPortalConstControl()); this->GetVertexPortal(array.GetPortalConstControl());
} }
private: private:
template <typename PortalType> template <typename PortalType>
VTKM_CONT VTKM_CONT void GetVertexPortal(const PortalType& portal) const
void GetVertexPortal(const PortalType &portal) const
{ {
for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++) for (vtkm::Id index = 0; index < portal.GetNumberOfValues(); index++)
{ {
@ -118,7 +113,6 @@ void initializeGL()
glOrtho(-0.5f, 1.5f, -0.5f, 1.5f, -1.0f, 1.0f); glOrtho(-0.5f, 1.5f, -0.5f, 1.5f, -1.0f, 1.0f);
} }
// //
// Render the output using simple OpenGL // Render the output using simple OpenGL
// //
@ -138,12 +132,8 @@ void displayCall()
// Draw the two triangles belonging to each quad // Draw the two triangles belonging to each quad
vtkm::Id triangle = 0; vtkm::Id triangle = 0;
vtkm::Float32 color[4][3] = vtkm::Float32 color[4][3] = {
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 0.0f }
{1.0f, 0.0f, 0.0f},
{0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 1.0f},
{1.0f, 1.0f, 0.0f}
}; };
for (vtkm::Id quad = 0; quad < cellsToDisplay; quad++) for (vtkm::Id quad = 0; quad < cellsToDisplay; quad++)
@ -158,16 +148,16 @@ void displayCall()
cellSet.GetIndices(triangle, triIndices); cellSet.GetIndices(triangle, triIndices);
// Get the vertex points for this triangle // Get the vertex points for this triangle
vtkm::Vec<vtkm::Float64,3> pt0 = vertexArray.GetPortalConstControl().Get(triIndices[0]); vtkm::Vec<vtkm::Float64, 3> pt0 = vertexArray.GetPortalConstControl().Get(triIndices[0]);
vtkm::Vec<vtkm::Float64,3> pt1 = vertexArray.GetPortalConstControl().Get(triIndices[1]); vtkm::Vec<vtkm::Float64, 3> pt1 = vertexArray.GetPortalConstControl().Get(triIndices[1]);
vtkm::Vec<vtkm::Float64,3> pt2 = vertexArray.GetPortalConstControl().Get(triIndices[2]); vtkm::Vec<vtkm::Float64, 3> pt2 = vertexArray.GetPortalConstControl().Get(triIndices[2]);
// Draw the triangle filled with alternating colors // Draw the triangle filled with alternating colors
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBegin(GL_TRIANGLES); glBegin(GL_TRIANGLES);
glVertex3d(pt0[0], pt0[1], pt0[2]); glVertex3d(pt0[0], pt0[1], pt0[2]);
glVertex3d(pt1[0], pt1[1], pt1[2]); glVertex3d(pt1[0], pt1[1], pt1[2]);
glVertex3d(pt2[0], pt2[1], pt2[2]); glVertex3d(pt2[0], pt2[1], pt2[2]);
glEnd(); glEnd();
triangle++; triangle++;
@ -222,5 +212,5 @@ int main(int argc, char* argv[])
} }
#if (defined(VTKM_GCC) || defined(VTKM_CLANG)) #if (defined(VTKM_GCC) || defined(VTKM_CLANG))
# pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif

@ -31,8 +31,8 @@
#include <vtkm/cont/DataSet.h> #include <vtkm/cont/DataSet.h>
#include <vtkm/cont/Timer.h> #include <vtkm/cont/Timer.h>
namespace
namespace { {
// Define the tangle field for the input data // Define the tangle field for the input data
class TangleField : public vtkm::worklet::WorkletMapField class TangleField : public vtkm::worklet::WorkletMapField
@ -47,29 +47,40 @@ public:
const vtkm::Id cellsPerLayer; const vtkm::Id cellsPerLayer;
VTKM_CONT VTKM_CONT
TangleField(const vtkm::Id3 dims, const vtkm::Float32 mins[3], const vtkm::Float32 maxs[3]) : xdim(dims[0]), ydim(dims[1]), zdim(dims[2]), TangleField(const vtkm::Id3 dims, const vtkm::Float32 mins[3], const vtkm::Float32 maxs[3])
xmin(mins[0]), ymin(mins[1]), zmin(mins[2]), xmax(maxs[0]), ymax(maxs[1]), zmax(maxs[2]), cellsPerLayer((xdim) * (ydim)) { }; : xdim(dims[0])
, ydim(dims[1])
, zdim(dims[2])
, xmin(mins[0])
, ymin(mins[1])
, zmin(mins[2])
, xmax(maxs[0])
, ymax(maxs[1])
, zmax(maxs[2])
, cellsPerLayer((xdim) * (ydim)){};
VTKM_EXEC VTKM_EXEC
void operator()(const vtkm::Id &vertexId, vtkm::Float32 &v) const void operator()(const vtkm::Id& vertexId, vtkm::Float32& v) const
{ {
const vtkm::Id x = vertexId % (xdim); const vtkm::Id x = vertexId % (xdim);
const vtkm::Id y = (vertexId / (xdim)) % (ydim); const vtkm::Id y = (vertexId / (xdim)) % (ydim);
const vtkm::Id z = vertexId / cellsPerLayer; const vtkm::Id z = vertexId / cellsPerLayer;
const vtkm::Float32 fx = static_cast<vtkm::Float32>(x) / static_cast<vtkm::Float32>(xdim-1); const vtkm::Float32 fx = static_cast<vtkm::Float32>(x) / static_cast<vtkm::Float32>(xdim - 1);
const vtkm::Float32 fy = static_cast<vtkm::Float32>(y) / static_cast<vtkm::Float32>(xdim-1); const vtkm::Float32 fy = static_cast<vtkm::Float32>(y) / static_cast<vtkm::Float32>(xdim - 1);
const vtkm::Float32 fz = static_cast<vtkm::Float32>(z) / static_cast<vtkm::Float32>(xdim-1); const vtkm::Float32 fz = static_cast<vtkm::Float32>(z) / static_cast<vtkm::Float32>(xdim - 1);
const vtkm::Float32 xx = 3.0f*(xmin+(xmax-xmin)*(fx)); const vtkm::Float32 xx = 3.0f * (xmin + (xmax - xmin) * (fx));
const vtkm::Float32 yy = 3.0f*(ymin+(ymax-ymin)*(fy)); const vtkm::Float32 yy = 3.0f * (ymin + (ymax - ymin) * (fy));
const vtkm::Float32 zz = 3.0f*(zmin+(zmax-zmin)*(fz)); const vtkm::Float32 zz = 3.0f * (zmin + (zmax - zmin) * (fz));
v = (xx*xx*xx*xx - 5.0f*xx*xx + yy*yy*yy*yy - 5.0f*yy*yy + zz*zz*zz*zz - 5.0f*zz*zz + 11.8f) * 0.2f + 0.5f; v = (xx * xx * xx * xx - 5.0f * xx * xx + yy * yy * yy * yy - 5.0f * yy * yy +
zz * zz * zz * zz - 5.0f * zz * zz + 11.8f) *
0.2f +
0.5f;
} }
}; };
// Construct an input data set using the tangle field worklet // Construct an input data set using the tangle field worklet
vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims) vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims)
{ {
@ -77,24 +88,23 @@ vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims)
const vtkm::Id3 vdims(dims[0] + 1, dims[1] + 1, dims[2] + 1); const vtkm::Id3 vdims(dims[0] + 1, dims[1] + 1, dims[2] + 1);
vtkm::Float32 mins[3] = {-1.0f, -1.0f, -1.0f}; vtkm::Float32 mins[3] = { -1.0f, -1.0f, -1.0f };
vtkm::Float32 maxs[3] = {1.0f, 1.0f, 1.0f}; vtkm::Float32 maxs[3] = { 1.0f, 1.0f, 1.0f };
vtkm::cont::ArrayHandle<vtkm::Float32> fieldArray; vtkm::cont::ArrayHandle<vtkm::Float32> fieldArray;
vtkm::cont::ArrayHandleCounting<vtkm::Id> vertexCountImplicitArray(0, 1, vdims[0]*vdims[1]*vdims[2]); vtkm::cont::ArrayHandleCounting<vtkm::Id> vertexCountImplicitArray(0, 1, vdims[0] * vdims[1] *
vtkm::worklet::DispatcherMapField<TangleField> tangleFieldDispatcher(TangleField(vdims, mins, maxs)); vdims[2]);
vtkm::worklet::DispatcherMapField<TangleField> tangleFieldDispatcher(
TangleField(vdims, mins, maxs));
tangleFieldDispatcher.Invoke(vertexCountImplicitArray, fieldArray); tangleFieldDispatcher.Invoke(vertexCountImplicitArray, fieldArray);
vtkm::Vec<vtkm::FloatDefault,3> origin(0.0f, 0.0f, 0.0f); vtkm::Vec<vtkm::FloatDefault, 3> origin(0.0f, 0.0f, 0.0f);
vtkm::Vec<vtkm::FloatDefault,3> spacing( vtkm::Vec<vtkm::FloatDefault, 3> spacing(1.0f / static_cast<vtkm::FloatDefault>(dims[0]),
1.0f/static_cast<vtkm::FloatDefault>(dims[0]), 1.0f / static_cast<vtkm::FloatDefault>(dims[2]),
1.0f/static_cast<vtkm::FloatDefault>(dims[2]), 1.0f / static_cast<vtkm::FloatDefault>(dims[1]));
1.0f/static_cast<vtkm::FloatDefault>(dims[1]));
vtkm::cont::ArrayHandleUniformPointCoordinates vtkm::cont::ArrayHandleUniformPointCoordinates coordinates(vdims, origin, spacing);
coordinates(vdims, origin, spacing); dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", coordinates));
dataSet.AddCoordinateSystem(
vtkm::cont::CoordinateSystem("coordinates", coordinates));
dataSet.AddField(vtkm::cont::Field("nodevar", vtkm::cont::Field::ASSOC_POINTS, fieldArray)); dataSet.AddField(vtkm::cont::Field("nodevar", vtkm::cont::Field::ASSOC_POINTS, fieldArray));
@ -105,10 +115,8 @@ vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims)
return dataSet; return dataSet;
} }
} }
namespace vtkm namespace vtkm
{ {
namespace worklet namespace worklet
@ -120,26 +128,26 @@ public:
typedef _2 ExecutionSignature(_1, WorkIndex); typedef _2 ExecutionSignature(_1, WorkIndex);
VTKM_EXEC VTKM_EXEC
vtkm::Float32 operator()(vtkm::Int64 x, vtkm::Id& index) const { vtkm::Float32 operator()(vtkm::Int64 x, vtkm::Id& index) const { return (vtkm::Sin(1.0 * x)); }
return (vtkm::Sin(1.0*x));
}
}; };
} }
} }
// Run a simple worklet, and compute an isosurface // Run a simple worklet, and compute an isosurface
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
vtkm::Int64 N = 1024*1024*1024; vtkm::Int64 N = 1024 * 1024 * 1024;
if (argc > 1) N = N*atoi(argv[1]); if (argc > 1)
else N = N*4; N = N * atoi(argv[1]);
else
N = N * 4;
std::cout << "Testing streaming worklet with size " << N << std::endl; std::cout << "Testing streaming worklet with size " << N << std::endl;
vtkm::cont::ArrayHandle<vtkm::Int64> input; vtkm::cont::ArrayHandle<vtkm::Int64> input;
vtkm::cont::ArrayHandle<vtkm::Float32> output; vtkm::cont::ArrayHandle<vtkm::Float32> output;
std::vector<vtkm::Int64> data(N); std::vector<vtkm::Int64> data(N);
for (vtkm::Int64 i=0; i<N; i++) data[i] = i; for (vtkm::Int64 i = 0; i < N; i++)
data[i] = i;
input = vtkm::cont::make_ArrayHandle(data); input = vtkm::cont::make_ArrayHandle(data);
typedef vtkm::cont::DeviceAdapterAlgorithm<VTKM_DEFAULT_DEVICE_ADAPTER_TAG> DeviceAlgorithms; typedef vtkm::cont::DeviceAdapterAlgorithm<VTKM_DEFAULT_DEVICE_ADAPTER_TAG> DeviceAlgorithms;
@ -148,30 +156,29 @@ int main(int argc, char* argv[])
#ifdef VTKM_USE_UNIFIED_MEMORY #ifdef VTKM_USE_UNIFIED_MEMORY
std::cout << "Testing with unified memory" << std::endl; std::cout << "Testing with unified memory" << std::endl;
vtkm::worklet::DispatcherMapField<vtkm::worklet::SineWorklet> vtkm::worklet::DispatcherMapField<vtkm::worklet::SineWorklet> dispatcher(sineWorklet);
dispatcher(sineWorklet);
vtkm::cont::Timer<> timer; vtkm::cont::Timer<> timer;
dispatcher.Invoke(input, output); dispatcher.Invoke(input, output);
std::cout << output.GetPortalConstControl().Get(output.GetNumberOfValues()-1) << std::endl; std::cout << output.GetPortalConstControl().Get(output.GetNumberOfValues() - 1) << std::endl;
vtkm::Float64 elapsedTime = timer.GetElapsedTime(); vtkm::Float64 elapsedTime = timer.GetElapsedTime();
std::cout << "Time: " << elapsedTime << std::endl; std::cout << "Time: " << elapsedTime << std::endl;
#else #else
vtkm::worklet::DispatcherStreamingMapField<vtkm::worklet::SineWorklet> vtkm::worklet::DispatcherStreamingMapField<vtkm::worklet::SineWorklet> dispatcher(sineWorklet);
dispatcher(sineWorklet); vtkm::Id NBlocks = N / (1024 * 1024 * 1024);
vtkm::Id NBlocks = N/(1024*1024*1024);
NBlocks *= 2; NBlocks *= 2;
dispatcher.SetNumberOfBlocks(NBlocks); dispatcher.SetNumberOfBlocks(NBlocks);
std::cout << "Testing with streaming (without unified memory) with " << NBlocks << " blocks" << std::endl; std::cout << "Testing with streaming (without unified memory) with " << NBlocks << " blocks"
<< std::endl;
vtkm::cont::Timer<> timer; vtkm::cont::Timer<> timer;
dispatcher.Invoke(input, output); dispatcher.Invoke(input, output);
std::cout << output.GetPortalConstControl().Get(output.GetNumberOfValues()-1) << std::endl; std::cout << output.GetPortalConstControl().Get(output.GetNumberOfValues() - 1) << std::endl;
vtkm::Float64 elapsedTime = timer.GetElapsedTime(); vtkm::Float64 elapsedTime = timer.GetElapsedTime();
std::cout << "Time: " << elapsedTime << std::endl; std::cout << "Time: " << elapsedTime << std::endl;
@ -179,32 +186,33 @@ int main(int argc, char* argv[])
#endif #endif
int dim = 128; int dim = 128;
if (argc > 2) dim = atoi(argv[2]); if (argc > 2)
dim = atoi(argv[2]);
std::cout << "Testing Marching Cubes with size " << dim << "x" << dim << "x" << dim << std::endl; std::cout << "Testing Marching Cubes with size " << dim << "x" << dim << "x" << dim << std::endl;
vtkm::Id3 dims(dim, dim, dim); vtkm::Id3 dims(dim, dim, dim);
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32,3> > verticesArray, normalsArray; vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3>> verticesArray, normalsArray;
vtkm::cont::ArrayHandle<vtkm::Float32> scalarsArray; vtkm::cont::ArrayHandle<vtkm::Float32> scalarsArray;
vtkm::cont::DataSet dataSet = MakeIsosurfaceTestDataSet(dims); vtkm::cont::DataSet dataSet = MakeIsosurfaceTestDataSet(dims);
vtkm::filter::MarchingCubes filter; vtkm::filter::MarchingCubes filter;
filter.SetGenerateNormals(true); filter.SetGenerateNormals(true);
filter.SetMergeDuplicatePoints( false ); filter.SetMergeDuplicatePoints(false);
filter.SetIsoValue( 0.5 ); filter.SetIsoValue(0.5);
vtkm::filter::ResultDataSet result = vtkm::filter::ResultDataSet result = filter.Execute(dataSet, dataSet.GetField("nodevar"));
filter.Execute( dataSet, dataSet.GetField("nodevar") );
filter.MapFieldOntoOutput(result, dataSet.GetField("nodevar")); filter.MapFieldOntoOutput(result, dataSet.GetField("nodevar"));
//need to extract vertices, normals, and scalars //need to extract vertices, normals, and scalars
vtkm::cont::DataSet& outputData = result.GetDataSet(); vtkm::cont::DataSet& outputData = result.GetDataSet();
typedef vtkm::cont::ArrayHandle< vtkm::Vec<vtkm::Float32,3> > VertType; typedef vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 3>> VertType;
vtkm::cont::CoordinateSystem coords = outputData.GetCoordinateSystem(); vtkm::cont::CoordinateSystem coords = outputData.GetCoordinateSystem();
verticesArray = coords.GetData().Cast<VertType>(); verticesArray = coords.GetData().Cast<VertType>();
normalsArray = outputData.GetField("normals").GetData().Cast<VertType>(); normalsArray = outputData.GetField("normals").GetData().Cast<VertType>();
scalarsArray = outputData.GetField("nodevar").GetData().Cast< vtkm::cont::ArrayHandle<vtkm::Float32> >(); scalarsArray =
outputData.GetField("nodevar").GetData().Cast<vtkm::cont::ArrayHandle<vtkm::Float32>>();
std::cout << "Number of output vertices: " << verticesArray.GetNumberOfValues() << std::endl; std::cout << "Number of output vertices: " << verticesArray.GetNumberOfValues() << std::endl;
@ -220,4 +228,3 @@ int main(int argc, char* argv[])
return 0; return 0;
} }

2
vtkm/.gitattributes vendored Normal file

@ -0,0 +1,2 @@
# Generated.
TypeListTag.h -format.clang-format

@ -37,11 +37,9 @@
/// for the possibility that the condition is never evaluated. /// for the possibility that the condition is never evaluated.
/// ///
#if !defined(NDEBUG) #if !defined(NDEBUG)
#define VTKM_ASSERT(condition) \ #define VTKM_ASSERT(condition) assert(condition)
assert(condition)
#else #else
#define VTKM_ASSERT(condition) #define VTKM_ASSERT(condition)
#endif #endif
#endif //vtk_m_Assert_h #endif //vtk_m_Assert_h

@ -20,37 +20,38 @@
#ifndef vtk_m_BaseComponent_h #ifndef vtk_m_BaseComponent_h
#define vtk_m_BaseComponent_h #define vtk_m_BaseComponent_h
#include <vtkm/Matrix.h> #include <vtkm/Matrix.h>
#include <vtkm/TypeTraits.h> #include <vtkm/TypeTraits.h>
#include <vtkm/VecTraits.h> #include <vtkm/VecTraits.h>
namespace vtkm { namespace vtkm
{
namespace detail { namespace detail
{
template<typename VecType, typename DimensionalityTag> template <typename VecType, typename DimensionalityTag>
struct BaseComponentImpl; struct BaseComponentImpl;
template<typename VecType> template <typename VecType>
struct BaseComponentImpl<VecType, vtkm::TypeTraitsVectorTag> struct BaseComponentImpl<VecType, vtkm::TypeTraitsVectorTag>
{ {
private: private:
using ComponentType = typename vtkm::VecTraits<VecType>::ComponentType; using ComponentType = typename vtkm::VecTraits<VecType>::ComponentType;
public: public:
using Type = using Type =
typename BaseComponentImpl< typename BaseComponentImpl<ComponentType,
ComponentType, typename vtkm::TypeTraits<ComponentType>::DimensionalityTag>::Type;
typename vtkm::TypeTraits<ComponentType>::DimensionalityTag
>::Type;
}; };
template<typename VecType> template <typename VecType>
struct BaseComponentImpl<VecType, vtkm::TypeTraitsMatrixTag> struct BaseComponentImpl<VecType, vtkm::TypeTraitsMatrixTag>
: BaseComponentImpl<VecType, vtkm::TypeTraitsVectorTag> : BaseComponentImpl<VecType, vtkm::TypeTraitsVectorTag>
{ }; {
};
template<typename ScalarType> template <typename ScalarType>
struct BaseComponentImpl<ScalarType, vtkm::TypeTraitsScalarTag> struct BaseComponentImpl<ScalarType, vtkm::TypeTraitsScalarTag>
{ {
using Type = ScalarType; using Type = ScalarType;
@ -60,13 +61,12 @@ struct BaseComponentImpl<ScalarType, vtkm::TypeTraitsScalarTag>
// Finds the base component type of a Vec. If you have a Vec of Vecs, it will // Finds the base component type of a Vec. If you have a Vec of Vecs, it will
// descend all Vecs until you get to the scalar type. // descend all Vecs until you get to the scalar type.
template<typename VecType> template <typename VecType>
struct BaseComponent struct BaseComponent
{ {
using Type = using Type =
typename detail::BaseComponentImpl< typename detail::BaseComponentImpl<VecType,
VecType, typename vtkm::TypeTraits<VecType>::DimensionalityTag>::Type;
typename vtkm::TypeTraits<VecType>::DimensionalityTag>::Type;
}; };
} // namespace vtkm } // namespace vtkm

@ -23,7 +23,8 @@
#include <vtkm/Math.h> #include <vtkm/Math.h>
#include <vtkm/internal/ExportMacros.h> #include <vtkm/internal/ExportMacros.h>
namespace vtkm { namespace vtkm
{
// Disable conversion warnings for Sum and Product on GCC only. // Disable conversion warnings for Sum and Product on GCC only.
// GCC creates false positive warnings for signed/unsigned char* operations. // GCC creates false positive warnings for signed/unsigned char* operations.
@ -41,7 +42,7 @@ namespace vtkm {
/// Note: Requires Type \p T implement the + operator. /// Note: Requires Type \p T implement the + operator.
struct Sum struct Sum
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT T operator()(const T& x, const T& y) const VTKM_EXEC_CONT T operator()(const T& x, const T& y) const
{ {
return x + y; return x + y;
@ -53,7 +54,7 @@ struct Sum
/// Note: Requires Type \p T implement the * operator. /// Note: Requires Type \p T implement the * operator.
struct Product struct Product
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT T operator()(const T& x, const T& y) const VTKM_EXEC_CONT T operator()(const T& x, const T& y) const
{ {
return x * y; return x * y;
@ -64,17 +65,16 @@ struct Product
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif // gcc || clang #endif // gcc || clang
/// Binary Predicate that takes two arguments argument \c x, and \c y and /// Binary Predicate that takes two arguments argument \c x, and \c y and
/// returns the \c x if x > y otherwise returns \c y. /// returns the \c x if x > y otherwise returns \c y.
/// Note: Requires Type \p T implement the < operator. /// Note: Requires Type \p T implement the < operator.
//needs to be full length to not clash with vtkm::math function Max. //needs to be full length to not clash with vtkm::math function Max.
struct Maximum struct Maximum
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT T operator()(const T& x, const T& y) const VTKM_EXEC_CONT T operator()(const T& x, const T& y) const
{ {
return x < y ? y: x; return x < y ? y : x;
} }
}; };
@ -84,14 +84,13 @@ struct Maximum
//needs to be full length to not clash with vtkm::math function Min. //needs to be full length to not clash with vtkm::math function Min.
struct Minimum struct Minimum
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT T operator()(const T& x, const T& y) const VTKM_EXEC_CONT T operator()(const T& x, const T& y) const
{ {
return x < y ? x: y; return x < y ? x : y;
} }
}; };
/// Binary Predicate that takes two arguments argument \c x, and \c y and /// Binary Predicate that takes two arguments argument \c x, and \c y and
/// returns a vtkm::Vec<T,2> that represents the minimum and maximum values /// returns a vtkm::Vec<T,2> that represents the minimum and maximum values
/// Note: Requires Type \p T implement the vtkm::Min and vtkm::Max functions. /// Note: Requires Type \p T implement the vtkm::Min and vtkm::Max functions.
@ -99,27 +98,25 @@ template <typename T>
struct MinAndMax struct MinAndMax
{ {
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Vec<T,2> operator()(const T& a, const T& b) const vtkm::Vec<T, 2> operator()(const T& a, const T& b) const
{ {
return vtkm::make_Vec(vtkm::Min(a, b), vtkm::Max(a, b)); return vtkm::make_Vec(vtkm::Min(a, b), vtkm::Max(a, b));
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Vec<T,2> operator()( vtkm::Vec<T, 2> operator()(const vtkm::Vec<T, 2>& a, const vtkm::Vec<T, 2>& b) const
const vtkm::Vec<T,2>& a, const vtkm::Vec<T,2>& b) const
{ {
return vtkm::make_Vec( return vtkm::make_Vec(vtkm::Min(a[0], b[0]), vtkm::Max(a[1], b[1]));
vtkm::Min(a[0], b[0]), vtkm::Max(a[1], b[1]));
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Vec<T,2> operator()(const T& a, const vtkm::Vec<T,2>& b) const vtkm::Vec<T, 2> operator()(const T& a, const vtkm::Vec<T, 2>& b) const
{ {
return vtkm::make_Vec(vtkm::Min(a, b[0]), vtkm::Max(a, b[1])); return vtkm::make_Vec(vtkm::Min(a, b[0]), vtkm::Max(a, b[1]));
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Vec<T,2> operator()(const vtkm::Vec<T,2>& a, const T& b) const vtkm::Vec<T, 2> operator()(const vtkm::Vec<T, 2>& a, const T& b) const
{ {
return vtkm::make_Vec(vtkm::Min(a[0], b), vtkm::Max(a[1], b)); return vtkm::make_Vec(vtkm::Min(a[0], b), vtkm::Max(a[1], b));
} }
@ -130,7 +127,7 @@ struct MinAndMax
/// Note: Requires Type \p T implement the & operator. /// Note: Requires Type \p T implement the & operator.
struct BitwiseAnd struct BitwiseAnd
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT T operator()(const T& x, const T& y) const VTKM_EXEC_CONT T operator()(const T& x, const T& y) const
{ {
return x & y; return x & y;
@ -142,7 +139,7 @@ struct BitwiseAnd
/// Note: Requires Type \p T implement the | operator. /// Note: Requires Type \p T implement the | operator.
struct BitwiseOr struct BitwiseOr
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT T operator()(const T& x, const T& y) const VTKM_EXEC_CONT T operator()(const T& x, const T& y) const
{ {
return x | y; return x | y;
@ -154,14 +151,13 @@ struct BitwiseOr
/// Note: Requires Type \p T implement the ^ operator. /// Note: Requires Type \p T implement the ^ operator.
struct BitwiseXor struct BitwiseXor
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT T operator()(const T& x, const T& y) const VTKM_EXEC_CONT T operator()(const T& x, const T& y) const
{ {
return x ^ y; return x ^ y;
} }
}; };
} // namespace vtkm } // namespace vtkm
#endif //vtk_m_BinaryOperators_h #endif //vtk_m_BinaryOperators_h

@ -22,14 +22,15 @@
#include <vtkm/internal/ExportMacros.h> #include <vtkm/internal/ExportMacros.h>
namespace vtkm { namespace vtkm
{
/// Binary Predicate that takes two arguments argument \c x, and \c y and /// Binary Predicate that takes two arguments argument \c x, and \c y and
/// returns True if and only if \c x is equal to \c y. /// returns True if and only if \c x is equal to \c y.
/// Note: Requires Type \p T implement the == operator. /// Note: Requires Type \p T implement the == operator.
struct Equal struct Equal
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const
{ {
return x == y; return x == y;
@ -41,7 +42,7 @@ struct Equal
/// Note: Requires Type \p T implement the != operator. /// Note: Requires Type \p T implement the != operator.
struct NotEqual struct NotEqual
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const
{ {
return x != y; return x != y;
@ -53,7 +54,7 @@ struct NotEqual
/// Note: Requires Type \p T implement the < operator. /// Note: Requires Type \p T implement the < operator.
struct SortLess struct SortLess
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const
{ {
return x < y; return x < y;
@ -66,7 +67,7 @@ struct SortLess
/// comparison /// comparison
struct SortGreater struct SortGreater
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const
{ {
return y < x; return y < x;
@ -79,7 +80,7 @@ struct SortGreater
/// && operator. /// && operator.
struct LogicalAnd struct LogicalAnd
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const
{ {
return x && y; return x && y;
@ -92,7 +93,7 @@ struct LogicalAnd
/// || operator. /// || operator.
struct LogicalOr struct LogicalOr
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const VTKM_EXEC_CONT bool operator()(const T& x, const T& y) const
{ {
return x || y; return x || y;

@ -23,7 +23,8 @@
#include <vtkm/Range.h> #include <vtkm/Range.h>
namespace vtkm { namespace vtkm
{
/// \brief Represent an axis-aligned 3D bounds in space. /// \brief Represent an axis-aligned 3D bounds in space.
/// ///
@ -42,53 +43,49 @@ struct Bounds
vtkm::Range Z; vtkm::Range Z;
VTKM_EXEC_CONT VTKM_EXEC_CONT
Bounds() { } Bounds() {}
VTKM_EXEC_CONT VTKM_EXEC_CONT
Bounds(const vtkm::Range &xRange, Bounds(const vtkm::Range& xRange, const vtkm::Range& yRange, const vtkm::Range& zRange)
const vtkm::Range &yRange, : X(xRange)
const vtkm::Range &zRange) , Y(yRange)
: X(xRange), Y(yRange), Z(zRange) { } , Z(zRange)
{
}
template<typename T1, template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
typename T2, VTKM_EXEC_CONT Bounds(const T1& minX, const T2& maxX, const T3& minY, const T4& maxY,
typename T3, const T5& minZ, const T6& maxZ)
typename T4, : X(vtkm::Range(minX, maxX))
typename T5, , Y(vtkm::Range(minY, maxY))
typename T6> , Z(vtkm::Range(minZ, maxZ))
VTKM_EXEC_CONT {
Bounds(const T1 &minX, const T2 &maxX, }
const T3 &minY, const T4 &maxY,
const T5 &minZ, const T6 &maxZ)
: X(vtkm::Range(minX, maxX)),
Y(vtkm::Range(minY, maxY)),
Z(vtkm::Range(minZ, maxZ))
{ }
/// Initialize bounds with an array of 6 values in the order xmin, xmax, /// Initialize bounds with an array of 6 values in the order xmin, xmax,
/// ymin, ymax, zmin, zmax. /// ymin, ymax, zmin, zmax.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT explicit Bounds(const T bounds[6])
explicit Bounds(const T bounds[6]) : X(vtkm::Range(bounds[0], bounds[1]))
: X(vtkm::Range(bounds[0], bounds[1])), , Y(vtkm::Range(bounds[2], bounds[3]))
Y(vtkm::Range(bounds[2], bounds[3])), , Z(vtkm::Range(bounds[4], bounds[5]))
Z(vtkm::Range(bounds[4], bounds[5])) {
{ } }
/// Initialize bounds with the minimum corner point and the maximum corner /// Initialize bounds with the minimum corner point and the maximum corner
/// point. /// point.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT Bounds(const vtkm::Vec<T, 3>& minPoint, const vtkm::Vec<T, 3>& maxPoint)
Bounds(const vtkm::Vec<T,3> &minPoint, const vtkm::Vec<T,3> &maxPoint) : X(vtkm::Range(minPoint[0], maxPoint[0]))
: X(vtkm::Range(minPoint[0], maxPoint[0])), , Y(vtkm::Range(minPoint[1], maxPoint[1]))
Y(vtkm::Range(minPoint[1], maxPoint[1])), , Z(vtkm::Range(minPoint[2], maxPoint[2]))
Z(vtkm::Range(minPoint[2], maxPoint[2])) {
{ } }
VTKM_EXEC_CONT VTKM_EXEC_CONT
const vtkm::Bounds &operator=(const vtkm::Bounds &src) const vtkm::Bounds& operator=(const vtkm::Bounds& src)
{ {
this->X = src.X; this->X = src.X;
this->Y = src.Y; this->Y = src.Y;
@ -105,20 +102,15 @@ struct Bounds
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool IsNonEmpty() const bool IsNonEmpty() const
{ {
return (this->X.IsNonEmpty() && return (this->X.IsNonEmpty() && this->Y.IsNonEmpty() && this->Z.IsNonEmpty());
this->Y.IsNonEmpty() &&
this->Z.IsNonEmpty());
} }
/// \b Determines if a point coordinate is within the bounds. /// \b Determines if a point coordinate is within the bounds.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT bool Contains(const vtkm::Vec<T, 3>& point) const
bool Contains(const vtkm::Vec<T,3> &point) const
{ {
return (this->X.Contains(point[0]) && return (this->X.Contains(point[0]) && this->Y.Contains(point[1]) && this->Z.Contains(point[2]));
this->Y.Contains(point[1]) &&
this->Z.Contains(point[2]));
} }
/// \b Returns the center of the range. /// \b Returns the center of the range.
@ -127,11 +119,9 @@ struct Bounds
/// are empty, the results are undefined. /// are empty, the results are undefined.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Vec<vtkm::Float64,3> Center() const vtkm::Vec<vtkm::Float64, 3> Center() const
{ {
return vtkm::Vec<vtkm::Float64,3>(this->X.Center(), return vtkm::Vec<vtkm::Float64, 3>(this->X.Center(), this->Y.Center(), this->Z.Center());
this->Y.Center(),
this->Z.Center());
} }
/// \b Expand bounds to include a point. /// \b Expand bounds to include a point.
@ -140,9 +130,8 @@ struct Bounds
/// given point coordinates. If the bounds already include this point, then /// given point coordinates. If the bounds already include this point, then
/// nothing is done. /// nothing is done.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT void Include(const vtkm::Vec<T, 3>& point)
void Include(const vtkm::Vec<T,3> &point)
{ {
this->X.Include(point[0]); this->X.Include(point[0]);
this->Y.Include(point[1]); this->Y.Include(point[1]);
@ -155,7 +144,7 @@ struct Bounds
/// that of another bounds. Esentially it is the union of the two bounds. /// that of another bounds. Esentially it is the union of the two bounds.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Include(const vtkm::Bounds &bounds) void Include(const vtkm::Bounds& bounds)
{ {
this->X.Include(bounds.X); this->X.Include(bounds.X);
this->Y.Include(bounds.Y); this->Y.Include(bounds.Y);
@ -167,7 +156,7 @@ struct Bounds
/// This is a nondestructive form of \c Include. /// This is a nondestructive form of \c Include.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Bounds Union(const vtkm::Bounds &otherBounds) const vtkm::Bounds Union(const vtkm::Bounds& otherBounds) const
{ {
vtkm::Bounds unionBounds(*this); vtkm::Bounds unionBounds(*this);
unionBounds.Include(otherBounds); unionBounds.Include(otherBounds);
@ -177,25 +166,18 @@ struct Bounds
/// \b Operator for union /// \b Operator for union
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Bounds operator+(const vtkm::Bounds &otherBounds) const vtkm::Bounds operator+(const vtkm::Bounds& otherBounds) const { return this->Union(otherBounds); }
VTKM_EXEC_CONT
bool operator==(const vtkm::Bounds& bounds) const
{ {
return this->Union(otherBounds); return ((this->X == bounds.X) && (this->Y == bounds.Y) && (this->Z == bounds.Z));
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator==(const vtkm::Bounds &bounds) const bool operator!=(const vtkm::Bounds& bounds) const
{ {
return ((this->X == bounds.X) && return ((this->X != bounds.X) || (this->Y != bounds.Y) || (this->Z != bounds.Z));
(this->Y == bounds.Y) &&
(this->Z == bounds.Z));
}
VTKM_EXEC_CONT
bool operator!=(const vtkm::Bounds &bounds) const
{
return ((this->X != bounds.X) ||
(this->Y != bounds.Y) ||
(this->Z != bounds.Z));
} }
}; };
@ -203,12 +185,9 @@ struct Bounds
/// Helper function for printing bounds during testing /// Helper function for printing bounds during testing
/// ///
static inline VTKM_CONT static inline VTKM_CONT std::ostream& operator<<(std::ostream& stream, const vtkm::Bounds& bounds)
std::ostream &operator<<(std::ostream &stream, const vtkm::Bounds &bounds)
{ {
return stream << "{ X:" << bounds.X return stream << "{ X:" << bounds.X << ", Y:" << bounds.Y << ", Z:" << bounds.Z << " }";
<< ", Y:" << bounds.Y
<< ", Z:" << bounds.Z << " }";
} }
#endif //vtk_m_Bounds_h #endif //vtk_m_Bounds_h

@ -23,7 +23,8 @@
#include <vtkm/StaticAssert.h> #include <vtkm/StaticAssert.h>
#include <vtkm/Types.h> #include <vtkm/Types.h>
namespace vtkm { namespace vtkm
{
/// CellShapeId identifies the type of each cell. Currently these are designed /// CellShapeId identifies the type of each cell. Currently these are designed
/// to match up with VTK cell types. /// to match up with VTK cell types.
@ -31,21 +32,21 @@ namespace vtkm {
enum CellShapeIdEnum enum CellShapeIdEnum
{ {
// Linear cells // Linear cells
CELL_SHAPE_EMPTY = 0, CELL_SHAPE_EMPTY = 0,
CELL_SHAPE_VERTEX = 1, CELL_SHAPE_VERTEX = 1,
//CELL_SHAPE_POLY_VERTEX = 2, //CELL_SHAPE_POLY_VERTEX = 2,
CELL_SHAPE_LINE = 3, CELL_SHAPE_LINE = 3,
//CELL_SHAPE_POLY_LINE = 4, //CELL_SHAPE_POLY_LINE = 4,
CELL_SHAPE_TRIANGLE = 5, CELL_SHAPE_TRIANGLE = 5,
//CELL_SHAPE_TRIANGLE_STRIP = 6, //CELL_SHAPE_TRIANGLE_STRIP = 6,
CELL_SHAPE_POLYGON = 7, CELL_SHAPE_POLYGON = 7,
//CELL_SHAPE_PIXEL = 8, //CELL_SHAPE_PIXEL = 8,
CELL_SHAPE_QUAD = 9, CELL_SHAPE_QUAD = 9,
CELL_SHAPE_TETRA = 10, CELL_SHAPE_TETRA = 10,
//CELL_SHAPE_VOXEL = 11, //CELL_SHAPE_VOXEL = 11,
CELL_SHAPE_HEXAHEDRON = 12, CELL_SHAPE_HEXAHEDRON = 12,
CELL_SHAPE_WEDGE = 13, CELL_SHAPE_WEDGE = 13,
CELL_SHAPE_PYRAMID = 14, CELL_SHAPE_PYRAMID = 14,
NUMBER_OF_CELL_SHAPES NUMBER_OF_CELL_SHAPES
}; };
@ -56,13 +57,16 @@ enum CellShapeIdEnum
// There are also many other cell-specific features that code might expect such // There are also many other cell-specific features that code might expect such
// as \c CellTraits and interpolations. // as \c CellTraits and interpolations.
namespace internal { namespace internal
{
/// A class that can be used to determine if a class is a CellShapeTag or not. /// A class that can be used to determine if a class is a CellShapeTag or not.
/// The class will be either std::true_type or std::false_type. /// The class will be either std::true_type or std::false_type.
/// ///
template<typename T> template <typename T>
struct CellShapeTagCheck : std::false_type { }; struct CellShapeTagCheck : std::false_type
{
};
} // namespace internal } // namespace internal
@ -70,15 +74,15 @@ struct CellShapeTagCheck : std::false_type { };
/// concept check to make sure that a template argument is a proper cell shape /// concept check to make sure that a template argument is a proper cell shape
/// tag. /// tag.
/// ///
#define VTKM_IS_CELL_SHAPE_TAG(tag) \ #define VTKM_IS_CELL_SHAPE_TAG(tag) \
VTKM_STATIC_ASSERT_MSG( \ VTKM_STATIC_ASSERT_MSG(::vtkm::internal::CellShapeTagCheck<tag>::value, \
::vtkm::internal::CellShapeTagCheck<tag>::value, \ "Provided type is not a valid VTK-m cell shape tag.")
"Provided type is not a valid VTK-m cell shape tag.")
/// A traits-like class to get an CellShapeId known at compile time to a tag. /// A traits-like class to get an CellShapeId known at compile time to a tag.
/// ///
template<vtkm::IdComponent Id> template <vtkm::IdComponent Id>
struct CellShapeIdToTag { struct CellShapeIdToTag
{
// If you get a compile error for this class about Id not being defined, that // If you get a compile error for this class about Id not being defined, that
// probably means you are using an ID that does not have a defined cell // probably means you are using an ID that does not have a defined cell
// shape. // shape.
@ -86,29 +90,32 @@ struct CellShapeIdToTag {
typedef std::false_type valid; typedef std::false_type valid;
}; };
// Define a tag for each cell shape as well as the support structs to go // Define a tag for each cell shape as well as the support structs to go
// between tags and ids. The following macro is only valid here. // between tags and ids. The following macro is only valid here.
#define VTKM_DEFINE_CELL_TAG(name, idname) \ #define VTKM_DEFINE_CELL_TAG(name, idname) \
struct CellShapeTag ## name { \ struct CellShapeTag##name \
static const vtkm::UInt8 Id = vtkm::idname; \ { \
}; \ static const vtkm::UInt8 Id = vtkm::idname; \
namespace internal { \ }; \
template<> \ namespace internal \
struct CellShapeTagCheck<vtkm::CellShapeTag ## name> : std::true_type { }; \ { \
} \ template <> \
static inline VTKM_EXEC_CONT \ struct CellShapeTagCheck<vtkm::CellShapeTag##name> : std::true_type \
const char *GetCellShapeName(vtkm::CellShapeTag ## name) { \ { \
return #name; \ }; \
} \ } \
template<> \ static inline VTKM_EXEC_CONT const char* GetCellShapeName(vtkm::CellShapeTag##name) \
struct CellShapeIdToTag<vtkm::idname> { \ { \
typedef std::true_type valid; \ return #name; \
typedef vtkm::CellShapeTag ## name Tag; \ } \
template <> \
struct CellShapeIdToTag<vtkm::idname> \
{ \
typedef std::true_type valid; \
typedef vtkm::CellShapeTag##name Tag; \
} }
VTKM_DEFINE_CELL_TAG(Empty, CELL_SHAPE_EMPTY); VTKM_DEFINE_CELL_TAG(Empty, CELL_SHAPE_EMPTY);
VTKM_DEFINE_CELL_TAG(Vertex, CELL_SHAPE_VERTEX); VTKM_DEFINE_CELL_TAG(Vertex, CELL_SHAPE_VERTEX);
//VTKM_DEFINE_CELL_TAG(PolyVertex, CELL_SHAPE_POLY_VERTEX); //VTKM_DEFINE_CELL_TAG(PolyVertex, CELL_SHAPE_POLY_VERTEX);
@ -127,28 +134,29 @@ VTKM_DEFINE_CELL_TAG(Pyramid, CELL_SHAPE_PYRAMID);
#undef VTKM_DEFINE_CELL_TAG #undef VTKM_DEFINE_CELL_TAG
/// A special cell shape tag that holds a cell shape that is not known at /// A special cell shape tag that holds a cell shape that is not known at
/// compile time. Unlike other cell set tags, the Id field is set at runtime /// compile time. Unlike other cell set tags, the Id field is set at runtime
/// so its value cannot be used in template parameters. You need to use /// so its value cannot be used in template parameters. You need to use
/// \c vtkmGenericCellShapeMacro to specialize on the cell type. /// \c vtkmGenericCellShapeMacro to specialize on the cell type.
/// ///
struct CellShapeTagGeneric { struct CellShapeTagGeneric
{
VTKM_EXEC_CONT VTKM_EXEC_CONT
CellShapeTagGeneric(vtkm::UInt8 shape) : Id(shape) { } CellShapeTagGeneric(vtkm::UInt8 shape)
: Id(shape)
{
}
vtkm::UInt8 Id; vtkm::UInt8 Id;
}; };
#define vtkmGenericCellShapeMacroCase(cellShapeId, call) \
#define vtkmGenericCellShapeMacroCase(cellShapeId, call) \ case vtkm::cellShapeId: \
case vtkm::cellShapeId: \ { \
{ \ typedef vtkm::CellShapeIdToTag<vtkm::cellShapeId>::Tag CellShapeTag; \
typedef \ call; \
vtkm::CellShapeIdToTag<vtkm::cellShapeId>::Tag CellShapeTag; \ } \
call; \ break
} \
break
/// \brief A macro used in a \c switch statement to determine cell shape. /// \brief A macro used in a \c switch statement to determine cell shape.
/// ///
@ -180,16 +188,16 @@ struct CellShapeTagGeneric {
/// Note that \c vtkmGenericCellShapeMacro does not have a default case. You /// Note that \c vtkmGenericCellShapeMacro does not have a default case. You
/// should consider adding one that gives a /// should consider adding one that gives a
/// ///
#define vtkmGenericCellShapeMacro(call) \ #define vtkmGenericCellShapeMacro(call) \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_EMPTY, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_EMPTY, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_VERTEX, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_VERTEX, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_LINE, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_LINE, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_TRIANGLE, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_TRIANGLE, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_POLYGON, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_POLYGON, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_QUAD, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_QUAD, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_TETRA, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_TETRA, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_HEXAHEDRON, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_HEXAHEDRON, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_WEDGE, call); \ vtkmGenericCellShapeMacroCase(CELL_SHAPE_WEDGE, call); \
vtkmGenericCellShapeMacroCase(CELL_SHAPE_PYRAMID, call) vtkmGenericCellShapeMacroCase(CELL_SHAPE_PYRAMID, call)
} // namespace vtkm } // namespace vtkm

@ -22,22 +22,29 @@
#include <vtkm/CellShape.h> #include <vtkm/CellShape.h>
namespace vtkm { namespace vtkm
{
/// \c vtkm::CellTraits::TopologyDimensionType is typedef to this with the /// \c vtkm::CellTraits::TopologyDimensionType is typedef to this with the
/// template parameter set to \c TOPOLOGICAL_DIMENSIONS. See \c /// template parameter set to \c TOPOLOGICAL_DIMENSIONS. See \c
/// vtkm::CellTraits for more information. /// vtkm::CellTraits for more information.
/// ///
template<vtkm::IdComponent dimension> template <vtkm::IdComponent dimension>
struct CellTopologicalDimensionsTag { }; struct CellTopologicalDimensionsTag
{
};
/// \brief Tag for cell shapes with a fixed number of points. /// \brief Tag for cell shapes with a fixed number of points.
/// ///
struct CellTraitsTagSizeFixed { }; struct CellTraitsTagSizeFixed
{
};
/// \brief Tag for cell shapes that can have a variable number of points. /// \brief Tag for cell shapes that can have a variable number of points.
/// ///
struct CellTraitsTagSizeVariable { }; struct CellTraitsTagSizeVariable
{
};
/// \brief Information about a cell based on its tag. /// \brief Information about a cell based on its tag.
/// ///
@ -45,7 +52,7 @@ struct CellTraitsTagSizeVariable { };
/// about cells (like the number of vertices in the cell or its /// about cells (like the number of vertices in the cell or its
/// dimensionality). /// dimensionality).
/// ///
template<class CellTag> template <class CellTag>
struct CellTraits struct CellTraits
#ifdef VTKM_DOXYGEN_ONLY #ifdef VTKM_DOXYGEN_ONLY
{ {
@ -59,8 +66,7 @@ struct CellTraits
/// a convenient way to overload a function based on topological dimensions /// a convenient way to overload a function based on topological dimensions
/// (which is usually more efficient than conditionals). /// (which is usually more efficient than conditionals).
/// ///
typedef vtkm::CellTopologicalDimensionsTag<TOPOLOGICAL_DIMENSIONS> typedef vtkm::CellTopologicalDimensionsTag<TOPOLOGICAL_DIMENSIONS> TopologicalDimensionsTag;
TopologicalDimensionsTag;
/// \brief A tag specifying whether the number of points is fixed. /// \brief A tag specifying whether the number of points is fixed.
/// ///
@ -77,31 +83,31 @@ struct CellTraits
/// ///
static const vtkm::IdComponent NUM_POINTS = 3; static const vtkm::IdComponent NUM_POINTS = 3;
}; };
#else // VTKM_DOXYGEN_ONLY #else // VTKM_DOXYGEN_ONLY
; ;
#endif // VTKM_DOXYGEN_ONLY #endif // VTKM_DOXYGEN_ONLY
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Define traits for every cell type. // Define traits for every cell type.
#define VTKM_DEFINE_CELL_TRAITS(name, dimensions, numPoints) \ #define VTKM_DEFINE_CELL_TRAITS(name, dimensions, numPoints) \
template<> \ template <> \
struct CellTraits<vtkm::CellShapeTag ## name> { \ struct CellTraits<vtkm::CellShapeTag##name> \
const static vtkm::IdComponent TOPOLOGICAL_DIMENSIONS = dimensions; \ { \
typedef vtkm::CellTopologicalDimensionsTag<TOPOLOGICAL_DIMENSIONS> \ const static vtkm::IdComponent TOPOLOGICAL_DIMENSIONS = dimensions; \
TopologicalDimensionsTag; \ typedef vtkm::CellTopologicalDimensionsTag<TOPOLOGICAL_DIMENSIONS> TopologicalDimensionsTag; \
typedef vtkm::CellTraitsTagSizeFixed IsSizeFixed; \ typedef vtkm::CellTraitsTagSizeFixed IsSizeFixed; \
static const vtkm::IdComponent NUM_POINTS = numPoints; \ static const vtkm::IdComponent NUM_POINTS = numPoints; \
} }
#define VTKM_DEFINE_CELL_TRAITS_VARIABLE(name, dimensions) \ #define VTKM_DEFINE_CELL_TRAITS_VARIABLE(name, dimensions) \
template<> \ template <> \
struct CellTraits<vtkm::CellShapeTag ## name> { \ struct CellTraits<vtkm::CellShapeTag##name> \
const static vtkm::IdComponent TOPOLOGICAL_DIMENSIONS = dimensions; \ { \
typedef vtkm::CellTopologicalDimensionsTag<TOPOLOGICAL_DIMENSIONS> \ const static vtkm::IdComponent TOPOLOGICAL_DIMENSIONS = dimensions; \
TopologicalDimensionsTag; \ typedef vtkm::CellTopologicalDimensionsTag<TOPOLOGICAL_DIMENSIONS> TopologicalDimensionsTag; \
typedef vtkm::CellTraitsTagSizeVariable IsSizeFixed; \ typedef vtkm::CellTraitsTagSizeVariable IsSizeFixed; \
} }
VTKM_DEFINE_CELL_TRAITS(Empty, 0, 0); VTKM_DEFINE_CELL_TRAITS(Empty, 0, 0);

@ -27,15 +27,16 @@
#include <type_traits> #include <type_traits>
namespace vtkm { namespace vtkm
namespace internal {
template<typename ListTag>
struct ListTagCheck : std::is_base_of<vtkm::detail::ListRoot,ListTag>
{ {
static VTKM_CONSTEXPR bool Valid = std::is_base_of<vtkm::detail::ListRoot,
ListTag>::value; namespace internal
{
template <typename ListTag>
struct ListTagCheck : std::is_base_of<vtkm::detail::ListRoot, ListTag>
{
static VTKM_CONSTEXPR bool Valid = std::is_base_of<vtkm::detail::ListRoot, ListTag>::value;
}; };
} // namespace internal } // namespace internal
@ -45,49 +46,47 @@ struct ListTagCheck : std::is_base_of<vtkm::detail::ListRoot,ListTag>
/// actually a device adapter tag. (You can get weird errors elsewhere in the /// actually a device adapter tag. (You can get weird errors elsewhere in the
/// code when a mistake is made.) /// code when a mistake is made.)
/// ///
#define VTKM_IS_LIST_TAG(tag) \ #define VTKM_IS_LIST_TAG(tag) \
VTKM_STATIC_ASSERT_MSG( \ VTKM_STATIC_ASSERT_MSG((::vtkm::internal::ListTagCheck<tag>::value), \
(::vtkm::internal::ListTagCheck<tag>::value), \ "Provided type is not a valid VTK-m list tag.")
"Provided type is not a valid VTK-m list tag.")
/// A special tag for a list that represents holding all potential values /// A special tag for a list that represents holding all potential values
/// ///
/// Note: Can not be used with ForEach for obvious reasons. /// Note: Can not be used with ForEach for obvious reasons.
struct ListTagUniversal : detail::ListRoot { struct ListTagUniversal : detail::ListRoot
{
using list = vtkm::detail::ListBase<vtkm::detail::UniversalTag>; using list = vtkm::detail::ListBase<vtkm::detail::UniversalTag>;
}; };
/// A special tag for an empty list. /// A special tag for an empty list.
/// ///
struct ListTagEmpty : detail::ListRoot { struct ListTagEmpty : detail::ListRoot
{
using list = vtkm::detail::ListBase<>; using list = vtkm::detail::ListBase<>;
}; };
/// A tag that is a construction of two other tags joined together. This struct /// A tag that is a construction of two other tags joined together. This struct
/// can be subclassed and still behave like a list tag. /// can be subclassed and still behave like a list tag.
template<typename ListTag1, typename ListTag2> template <typename ListTag1, typename ListTag2>
struct ListTagJoin : detail::ListRoot { struct ListTagJoin : detail::ListRoot
using list = typename detail::ListJoin< {
typename ListTag1::list, using list = typename detail::ListJoin<typename ListTag1::list, typename ListTag2::list>::type;
typename ListTag2::list>::type;
}; };
/// A tag that consits of elements that are found in both tags. This struct /// A tag that consits of elements that are found in both tags. This struct
/// can be subclassed and still behave like a list tag. /// can be subclassed and still behave like a list tag.
template<typename ListTag1, typename ListTag2> template <typename ListTag1, typename ListTag2>
struct ListTagIntersect : detail::ListRoot { struct ListTagIntersect : detail::ListRoot
using list = typename detail::ListIntersect< {
typename ListTag1::list, using list =
typename ListTag2::list>::type; typename detail::ListIntersect<typename ListTag1::list, typename ListTag2::list>::type;
}; };
/// For each typename represented by the list tag, call the functor with a /// For each typename represented by the list tag, call the functor with a
/// default instance of that type. /// default instance of that type.
/// ///
template<typename Functor, typename ListTag> template <typename Functor, typename ListTag>
VTKM_CONT VTKM_CONT void ListForEach(Functor& f, ListTag)
void ListForEach(Functor &f, ListTag)
{ {
VTKM_IS_LIST_TAG(ListTag); VTKM_IS_LIST_TAG(ListTag);
detail::ListForEachImpl(f, typename ListTag::list()); detail::ListForEachImpl(f, typename ListTag::list());
@ -96,9 +95,8 @@ void ListForEach(Functor &f, ListTag)
/// For each typename represented by the list tag, call the functor with a /// For each typename represented by the list tag, call the functor with a
/// default instance of that type. /// default instance of that type.
/// ///
template<typename Functor, typename ListTag> template <typename Functor, typename ListTag>
VTKM_CONT VTKM_CONT void ListForEach(const Functor& f, ListTag)
void ListForEach(const Functor &f, ListTag)
{ {
VTKM_IS_LIST_TAG(ListTag); VTKM_IS_LIST_TAG(ListTag);
detail::ListForEachImpl(f, typename ListTag::list()); detail::ListForEachImpl(f, typename ListTag::list());
@ -108,12 +106,11 @@ void ListForEach(const Functor &f, ListTag)
/// There is a static boolean named \c value that is set to true if the type is /// There is a static boolean named \c value that is set to true if the type is
/// contained in the list and false otherwise. /// contained in the list and false otherwise.
/// ///
template<typename ListTag, typename Type> template <typename ListTag, typename Type>
struct ListContains struct ListContains
{ {
VTKM_IS_LIST_TAG(ListTag); VTKM_IS_LIST_TAG(ListTag);
static VTKM_CONSTEXPR bool value = static VTKM_CONSTEXPR bool value = detail::ListContainsImpl<Type, typename ListTag::list>::value;
detail::ListContainsImpl<Type,typename ListTag::list>::value;
}; };
} // namespace vtkm } // namespace vtkm

File diff suppressed because it is too large Load Diff

@ -28,7 +28,8 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
#include <vtkm/VecTraits.h> #include <vtkm/VecTraits.h>
namespace vtkm { namespace vtkm
{
/// \brief Basic Matrix type. /// \brief Basic Matrix type.
/// ///
@ -40,26 +41,29 @@ namespace vtkm {
/// per-thread data structure to hold information like geometric transforms and /// per-thread data structure to hold information like geometric transforms and
/// tensors. /// tensors.
/// ///
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
class Matrix { class Matrix
{
public: public:
typedef T ComponentType; typedef T ComponentType;
static const vtkm::IdComponent NUM_ROWS = NumRow; static const vtkm::IdComponent NUM_ROWS = NumRow;
static const vtkm::IdComponent NUM_COLUMNS = NumCol; static const vtkm::IdComponent NUM_COLUMNS = NumCol;
VTKM_EXEC_CONT VTKM_EXEC_CONT
Matrix() { } Matrix() {}
VTKM_EXEC_CONT VTKM_EXEC_CONT
explicit Matrix(const ComponentType &value) explicit Matrix(const ComponentType& value)
: Components(vtkm::Vec<ComponentType, NUM_COLUMNS>(value)) { } : Components(vtkm::Vec<ComponentType, NUM_COLUMNS>(value))
{
}
/// Brackets are used to reference a matrix like a 2D array (i.e. /// Brackets are used to reference a matrix like a 2D array (i.e.
/// matrix[row][column]). /// matrix[row][column]).
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
const vtkm::Vec<ComponentType, NUM_COLUMNS> & const vtkm::Vec<ComponentType, NUM_COLUMNS>& operator[](vtkm::IdComponent rowIndex) const
operator[](vtkm::IdComponent rowIndex) const { {
VTKM_ASSERT(rowIndex >= 0); VTKM_ASSERT(rowIndex >= 0);
VTKM_ASSERT(rowIndex < NUM_ROWS); VTKM_ASSERT(rowIndex < NUM_ROWS);
return this->Components[rowIndex]; return this->Components[rowIndex];
@ -69,8 +73,8 @@ public:
/// matrix[row][column]. /// matrix[row][column].
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Vec<ComponentType, NUM_COLUMNS> & vtkm::Vec<ComponentType, NUM_COLUMNS>& operator[](vtkm::IdComponent rowIndex)
operator[](vtkm::IdComponent rowIndex) { {
VTKM_ASSERT(rowIndex >= 0); VTKM_ASSERT(rowIndex >= 0);
VTKM_ASSERT(rowIndex < NUM_ROWS); VTKM_ASSERT(rowIndex < NUM_ROWS);
return this->Components[rowIndex]; return this->Components[rowIndex];
@ -80,8 +84,8 @@ public:
/// notation i.e. matrix(row,column). /// notation i.e. matrix(row,column).
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
const ComponentType & const ComponentType& operator()(vtkm::IdComponent rowIndex, vtkm::IdComponent colIndex) const
operator()(vtkm::IdComponent rowIndex, vtkm::IdComponent colIndex) const { {
VTKM_ASSERT(rowIndex >= 0); VTKM_ASSERT(rowIndex >= 0);
VTKM_ASSERT(rowIndex < NUM_ROWS); VTKM_ASSERT(rowIndex < NUM_ROWS);
VTKM_ASSERT(colIndex >= 0); VTKM_ASSERT(colIndex >= 0);
@ -93,8 +97,8 @@ public:
/// notation i.e. matrix(row,column). /// notation i.e. matrix(row,column).
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
ComponentType & ComponentType& operator()(vtkm::IdComponent rowIndex, vtkm::IdComponent colIndex)
operator()(vtkm::IdComponent rowIndex, vtkm::IdComponent colIndex) { {
VTKM_ASSERT(rowIndex >= 0); VTKM_ASSERT(rowIndex >= 0);
VTKM_ASSERT(rowIndex < NUM_ROWS); VTKM_ASSERT(rowIndex < NUM_ROWS);
VTKM_ASSERT(colIndex >= 0); VTKM_ASSERT(colIndex >= 0);
@ -109,10 +113,9 @@ private:
/// Returns a tuple containing the given row (indexed from 0) of the given /// Returns a tuple containing the given row (indexed from 0) of the given
/// matrix. /// matrix.
/// ///
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
VTKM_EXEC_CONT VTKM_EXEC_CONT const vtkm::Vec<T, NumCol>& MatrixGetRow(
const vtkm::Vec<T, NumCol> &MatrixGetRow( const vtkm::Matrix<T, NumRow, NumCol>& matrix, vtkm::IdComponent rowIndex)
const vtkm::Matrix<T,NumRow,NumCol> &matrix, vtkm::IdComponent rowIndex)
{ {
return matrix[rowIndex]; return matrix[rowIndex];
} }
@ -120,10 +123,9 @@ const vtkm::Vec<T, NumCol> &MatrixGetRow(
/// Returns a tuple containing the given column (indexed from 0) of the given /// Returns a tuple containing the given column (indexed from 0) of the given
/// matrix. Might not be as efficient as the \c MatrixGetRow function. /// matrix. Might not be as efficient as the \c MatrixGetRow function.
/// ///
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, NumRow> MatrixGetColumn(const vtkm::Matrix<T, NumRow, NumCol>& matrix,
vtkm::Vec<T, NumRow> MatrixGetColumn( vtkm::IdComponent columnIndex)
const vtkm::Matrix<T,NumRow,NumCol> &matrix, vtkm::IdComponent columnIndex)
{ {
vtkm::Vec<T, NumRow> columnValues; vtkm::Vec<T, NumRow> columnValues;
for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++) for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++)
@ -135,22 +137,19 @@ vtkm::Vec<T, NumRow> MatrixGetColumn(
/// Convenience function for setting a row of a matrix. /// Convenience function for setting a row of a matrix.
/// ///
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
VTKM_EXEC_CONT VTKM_EXEC_CONT void MatrixSetRow(vtkm::Matrix<T, NumRow, NumCol>& matrix,
void MatrixSetRow(vtkm::Matrix<T,NumRow,NumCol> &matrix, vtkm::IdComponent rowIndex, const vtkm::Vec<T, NumCol>& rowValues)
vtkm::IdComponent rowIndex,
const vtkm::Vec<T,NumCol> &rowValues)
{ {
matrix[rowIndex] = rowValues; matrix[rowIndex] = rowValues;
} }
/// Convenience function for setting a column of a matrix. /// Convenience function for setting a column of a matrix.
/// ///
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
VTKM_EXEC_CONT VTKM_EXEC_CONT void MatrixSetColumn(vtkm::Matrix<T, NumRow, NumCol>& matrix,
void MatrixSetColumn(vtkm::Matrix<T,NumRow,NumCol> &matrix, vtkm::IdComponent columnIndex,
vtkm::IdComponent columnIndex, const vtkm::Vec<T, NumRow>& columnValues)
const vtkm::Vec<T,NumRow> &columnValues)
{ {
for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++) for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++)
{ {
@ -160,27 +159,21 @@ void MatrixSetColumn(vtkm::Matrix<T,NumRow,NumCol> &matrix,
/// Standard matrix multiplication. /// Standard matrix multiplication.
/// ///
template<typename T, template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol,
vtkm::IdComponent NumRow, vtkm::IdComponent NumInternal>
vtkm::IdComponent NumCol, VTKM_EXEC_CONT vtkm::Matrix<T, NumRow, NumCol> MatrixMultiply(
vtkm::IdComponent NumInternal> const vtkm::Matrix<T, NumRow, NumInternal>& leftFactor,
VTKM_EXEC_CONT const vtkm::Matrix<T, NumInternal, NumCol>& rightFactor)
vtkm::Matrix<T,NumRow,NumCol> MatrixMultiply(
const vtkm::Matrix<T,NumRow,NumInternal> &leftFactor,
const vtkm::Matrix<T,NumInternal,NumCol> &rightFactor)
{ {
vtkm::Matrix<T,NumRow,NumCol> result; vtkm::Matrix<T, NumRow, NumCol> result;
for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++) for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++)
{ {
for (vtkm::IdComponent colIndex = 0; colIndex < NumCol; colIndex++) for (vtkm::IdComponent colIndex = 0; colIndex < NumCol; colIndex++)
{ {
T sum = T(leftFactor(rowIndex, 0) * rightFactor(0, colIndex)); T sum = T(leftFactor(rowIndex, 0) * rightFactor(0, colIndex));
for (vtkm::IdComponent internalIndex = 1; for (vtkm::IdComponent internalIndex = 1; internalIndex < NumInternal; internalIndex++)
internalIndex < NumInternal;
internalIndex++)
{ {
sum = T(sum + (leftFactor(rowIndex, internalIndex) sum = T(sum + (leftFactor(rowIndex, internalIndex) * rightFactor(internalIndex, colIndex)));
* rightFactor(internalIndex, colIndex)));
} }
result(rowIndex, colIndex) = sum; result(rowIndex, colIndex) = sum;
} }
@ -190,70 +183,60 @@ vtkm::Matrix<T,NumRow,NumCol> MatrixMultiply(
/// Standard matrix-vector multiplication. /// Standard matrix-vector multiplication.
/// ///
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, NumRow> MatrixMultiply(
vtkm::Vec<T,NumRow> MatrixMultiply( const vtkm::Matrix<T, NumRow, NumCol>& leftFactor, const vtkm::Vec<T, NumCol>& rightFactor)
const vtkm::Matrix<T,NumRow,NumCol> &leftFactor,
const vtkm::Vec<T,NumCol> &rightFactor)
{ {
vtkm::Vec<T,NumRow> product; vtkm::Vec<T, NumRow> product;
for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++) for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++)
{ {
product[rowIndex] = product[rowIndex] = vtkm::dot(vtkm::MatrixGetRow(leftFactor, rowIndex), rightFactor);
vtkm::dot(vtkm::MatrixGetRow(leftFactor,rowIndex), rightFactor);
} }
return product; return product;
} }
/// Standard vector-matrix multiplication /// Standard vector-matrix multiplication
/// ///
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, NumCol> MatrixMultiply(
vtkm::Vec<T,NumCol> MatrixMultiply( const vtkm::Vec<T, NumRow>& leftFactor, const vtkm::Matrix<T, NumRow, NumCol>& rightFactor)
const vtkm::Vec<T,NumRow> &leftFactor,
const vtkm::Matrix<T,NumRow,NumCol> &rightFactor)
{ {
vtkm::Vec<T,NumCol> product; vtkm::Vec<T, NumCol> product;
for (vtkm::IdComponent colIndex = 0; colIndex < NumCol; colIndex++) for (vtkm::IdComponent colIndex = 0; colIndex < NumCol; colIndex++)
{ {
product[colIndex] = product[colIndex] = vtkm::dot(leftFactor, vtkm::MatrixGetColumn(rightFactor, colIndex));
vtkm::dot(leftFactor,
vtkm::MatrixGetColumn(rightFactor, colIndex));
} }
return product; return product;
} }
/// Returns the identity matrix. /// Returns the identity matrix.
/// ///
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, Size, Size> MatrixIdentity()
vtkm::Matrix<T,Size,Size> MatrixIdentity()
{ {
vtkm::Matrix<T,Size,Size> result(T(0)); vtkm::Matrix<T, Size, Size> result(T(0));
for (vtkm::IdComponent index = 0; index < Size; index++) for (vtkm::IdComponent index = 0; index < Size; index++)
{ {
result(index,index) = T(1.0); result(index, index) = T(1.0);
} }
return result; return result;
} }
/// Fills the given matrix with the identity matrix. /// Fills the given matrix with the identity matrix.
/// ///
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT void MatrixIdentity(vtkm::Matrix<T, Size, Size>& matrix)
void MatrixIdentity(vtkm::Matrix<T,Size,Size> &matrix)
{ {
matrix = vtkm::MatrixIdentity<T,Size>(); matrix = vtkm::MatrixIdentity<T, Size>();
} }
/// Returns the transpose of the given matrix. /// Returns the transpose of the given matrix.
/// ///
template<typename T, vtkm::IdComponent NumRows, vtkm::IdComponent NumCols> template <typename T, vtkm::IdComponent NumRows, vtkm::IdComponent NumCols>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, NumCols, NumRows> MatrixTranspose(
vtkm::Matrix<T,NumCols,NumRows> MatrixTranspose( const vtkm::Matrix<T, NumRows, NumCols>& matrix)
const vtkm::Matrix<T,NumRows,NumCols> &matrix)
{ {
vtkm::Matrix<T,NumCols,NumRows> result; vtkm::Matrix<T, NumCols, NumRows> result;
for (vtkm::IdComponent index = 0; index < NumRows; index++) for (vtkm::IdComponent index = 0; index < NumRows; index++)
{ {
vtkm::MatrixSetColumn(result, index, vtkm::MatrixGetRow(matrix, index)); vtkm::MatrixSetColumn(result, index, vtkm::MatrixGetRow(matrix, index));
@ -270,22 +253,19 @@ vtkm::Matrix<T,NumCols,NumRows> MatrixTranspose(
return result; return result;
} }
namespace detail { namespace detail
{
// Used with MatrixLUPFactor. // Used with MatrixLUPFactor.
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT void MatrixLUPFactorFindPivot(vtkm::Matrix<T, Size, Size>& A,
void MatrixLUPFactorFindPivot(vtkm::Matrix<T,Size,Size> &A, vtkm::Vec<vtkm::IdComponent, Size>& permutation,
vtkm::Vec<vtkm::IdComponent,Size> &permutation, vtkm::IdComponent topCornerIndex, T& inversionParity,
vtkm::IdComponent topCornerIndex, bool& valid)
T &inversionParity,
bool &valid)
{ {
vtkm::IdComponent maxRowIndex = topCornerIndex; vtkm::IdComponent maxRowIndex = topCornerIndex;
T maxValue = vtkm::Abs(A(maxRowIndex, topCornerIndex)); T maxValue = vtkm::Abs(A(maxRowIndex, topCornerIndex));
for (vtkm::IdComponent rowIndex = topCornerIndex + 1; for (vtkm::IdComponent rowIndex = topCornerIndex + 1; rowIndex < Size; rowIndex++)
rowIndex < Size;
rowIndex++)
{ {
T compareValue = vtkm::Abs(A(rowIndex, topCornerIndex)); T compareValue = vtkm::Abs(A(rowIndex, topCornerIndex));
if (maxValue < compareValue) if (maxValue < compareValue)
@ -295,15 +275,16 @@ void MatrixLUPFactorFindPivot(vtkm::Matrix<T,Size,Size> &A,
} }
} }
if (maxValue < vtkm::Epsilon<T>()) { valid = false; } if (maxValue < vtkm::Epsilon<T>())
{
valid = false;
}
if (maxRowIndex != topCornerIndex) if (maxRowIndex != topCornerIndex)
{ {
// Swap rows in matrix. // Swap rows in matrix.
vtkm::Vec<T,Size> maxRow = vtkm::MatrixGetRow(A, maxRowIndex); vtkm::Vec<T, Size> maxRow = vtkm::MatrixGetRow(A, maxRowIndex);
vtkm::MatrixSetRow(A, vtkm::MatrixSetRow(A, maxRowIndex, vtkm::MatrixGetRow(A, topCornerIndex));
maxRowIndex,
vtkm::MatrixGetRow(A,topCornerIndex));
vtkm::MatrixSetRow(A, topCornerIndex, maxRow); vtkm::MatrixSetRow(A, topCornerIndex, maxRow);
// Record change in permutation matrix. // Record change in permutation matrix.
@ -317,30 +298,22 @@ void MatrixLUPFactorFindPivot(vtkm::Matrix<T,Size,Size> &A,
} }
// Used with MatrixLUPFactor // Used with MatrixLUPFactor
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT void MatrixLUPFactorFindUpperTriangleElements(vtkm::Matrix<T, Size, Size>& A,
void MatrixLUPFactorFindUpperTriangleElements(vtkm::Matrix<T,Size,Size> &A, vtkm::IdComponent topCornerIndex)
vtkm::IdComponent topCornerIndex)
{ {
// Compute values for upper triangle on row topCornerIndex // Compute values for upper triangle on row topCornerIndex
for (vtkm::IdComponent colIndex = topCornerIndex+1; for (vtkm::IdComponent colIndex = topCornerIndex + 1; colIndex < Size; colIndex++)
colIndex < Size;
colIndex++)
{ {
A(topCornerIndex,colIndex) /= A(topCornerIndex,topCornerIndex); A(topCornerIndex, colIndex) /= A(topCornerIndex, topCornerIndex);
} }
// Update the rest of the matrix for calculations on subsequent rows // Update the rest of the matrix for calculations on subsequent rows
for (vtkm::IdComponent rowIndex = topCornerIndex+1; for (vtkm::IdComponent rowIndex = topCornerIndex + 1; rowIndex < Size; rowIndex++)
rowIndex < Size;
rowIndex++)
{ {
for (vtkm::IdComponent colIndex = topCornerIndex+1; for (vtkm::IdComponent colIndex = topCornerIndex + 1; colIndex < Size; colIndex++)
colIndex < Size;
colIndex++)
{ {
A(rowIndex,colIndex) -= A(rowIndex, colIndex) -= A(rowIndex, topCornerIndex) * A(topCornerIndex, colIndex);
A(rowIndex,topCornerIndex)*A(topCornerIndex,colIndex);
} }
} }
} }
@ -375,12 +348,10 @@ void MatrixLUPFactorFindUpperTriangleElements(vtkm::Matrix<T,Size,Size> &A,
/// LUP-factorization. If the LUP-factorization succeeds, valid is set to true. /// LUP-factorization. If the LUP-factorization succeeds, valid is set to true.
/// Otherwise, valid is set to false and the result is indeterminant. /// Otherwise, valid is set to false and the result is indeterminant.
/// ///
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT void MatrixLUPFactor(vtkm::Matrix<T, Size, Size>& A,
void MatrixLUPFactor(vtkm::Matrix<T,Size,Size> &A, vtkm::Vec<vtkm::IdComponent, Size>& permutation,
vtkm::Vec<vtkm::IdComponent,Size> &permutation, T& inversionParity, bool& valid)
T &inversionParity,
bool &valid)
{ {
// Initialize permutation. // Initialize permutation.
for (vtkm::IdComponent index = 0; index < Size; index++) for (vtkm::IdComponent index = 0; index < Size; index++)
@ -401,12 +372,10 @@ void MatrixLUPFactor(vtkm::Matrix<T,Size,Size> &A,
/// system Ax = b. Instead of A, this method takes in the LU and P /// system Ax = b. Instead of A, this method takes in the LU and P
/// matrices calculated by MatrixLUPFactor from A. The x matrix is returned. /// matrices calculated by MatrixLUPFactor from A. The x matrix is returned.
/// ///
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, Size> MatrixLUPSolve(
vtkm::Vec<T,Size> const vtkm::Matrix<T, Size, Size>& LU, const vtkm::Vec<vtkm::IdComponent, Size>& permutation,
MatrixLUPSolve(const vtkm::Matrix<T,Size,Size> &LU, const vtkm::Vec<T, Size>& b)
const vtkm::Vec<vtkm::IdComponent,Size> &permutation,
const vtkm::Vec<T,Size> &b)
{ {
// The LUP-factorization gives us PA = LU or equivalently A = inv(P)LU. // The LUP-factorization gives us PA = LU or equivalently A = inv(P)LU.
// Substituting into Ax = b gives us inv(P)LUx = b or LUx = Pb. // Substituting into Ax = b gives us inv(P)LUx = b or LUx = Pb.
@ -414,28 +383,28 @@ MatrixLUPSolve(const vtkm::Matrix<T,Size,Size> &LU,
// Substituting in the previous two equations yields Ly = Pb. // Substituting in the previous two equations yields Ly = Pb.
// Solving Ly = Pb is easy because L is triangular and P is just a // Solving Ly = Pb is easy because L is triangular and P is just a
// permutation. // permutation.
vtkm::Vec<T,Size> y; vtkm::Vec<T, Size> y;
for (vtkm::IdComponent rowIndex = 0; rowIndex < Size; rowIndex++) for (vtkm::IdComponent rowIndex = 0; rowIndex < Size; rowIndex++)
{ {
y[rowIndex] = b[permutation[rowIndex]]; y[rowIndex] = b[permutation[rowIndex]];
// Recall that L is stored in the lower triangle of LU including diagonal. // Recall that L is stored in the lower triangle of LU including diagonal.
for (vtkm::IdComponent colIndex = 0; colIndex < rowIndex; colIndex++) for (vtkm::IdComponent colIndex = 0; colIndex < rowIndex; colIndex++)
{ {
y[rowIndex] -= LU(rowIndex,colIndex)*y[colIndex]; y[rowIndex] -= LU(rowIndex, colIndex) * y[colIndex];
}
y[rowIndex] /= LU(rowIndex,rowIndex);
} }
y[rowIndex] /= LU(rowIndex, rowIndex);
}
// Now that we have y, we can easily solve Ux = y for x. // Now that we have y, we can easily solve Ux = y for x.
vtkm::Vec<T,Size> x; vtkm::Vec<T, Size> x;
for (vtkm::IdComponent rowIndex = Size-1; rowIndex >= 0; rowIndex--) for (vtkm::IdComponent rowIndex = Size - 1; rowIndex >= 0; rowIndex--)
{ {
// Recall that U is stored in the upper triangle of LU with the diagonal // Recall that U is stored in the upper triangle of LU with the diagonal
// implicitly all 1's. // implicitly all 1's.
x[rowIndex] = y[rowIndex]; x[rowIndex] = y[rowIndex];
for (vtkm::IdComponent colIndex = rowIndex+1; colIndex < Size; colIndex++) for (vtkm::IdComponent colIndex = rowIndex + 1; colIndex < Size; colIndex++)
{ {
x[rowIndex] -= LU(rowIndex,colIndex)*x[colIndex]; x[rowIndex] -= LU(rowIndex, colIndex) * x[colIndex];
} }
} }
@ -447,16 +416,14 @@ MatrixLUPSolve(const vtkm::Matrix<T,Size,Size> &LU,
/// Solve the linear system Ax = b for x. If a single solution is found, valid /// Solve the linear system Ax = b for x. If a single solution is found, valid
/// is set to true, false otherwise. /// is set to true, false otherwise.
/// ///
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, Size> SolveLinearSystem(const vtkm::Matrix<T, Size, Size>& A,
vtkm::Vec<T,Size> SolveLinearSystem(const vtkm::Matrix<T,Size,Size> &A, const vtkm::Vec<T, Size>& b, bool& valid)
const vtkm::Vec<T,Size> &b,
bool &valid)
{ {
// First, we will make an LUP-factorization to help us. // First, we will make an LUP-factorization to help us.
vtkm::Matrix<T,Size,Size> LU = A; vtkm::Matrix<T, Size, Size> LU = A;
vtkm::Vec<vtkm::IdComponent,Size> permutation; vtkm::Vec<vtkm::IdComponent, Size> permutation;
T inversionParity; // Unused. T inversionParity; // Unused.
detail::MatrixLUPFactor(LU, permutation, inversionParity, valid); detail::MatrixLUPFactor(LU, permutation, inversionParity, valid);
// Next, use the decomposition to solve the system. // Next, use the decomposition to solve the system.
@ -466,48 +433,49 @@ vtkm::Vec<T,Size> SolveLinearSystem(const vtkm::Matrix<T,Size,Size> &A,
/// Find and return the inverse of the given matrix. If the matrix is singular, /// Find and return the inverse of the given matrix. If the matrix is singular,
/// the inverse will not be correct and valid will be set to false. /// the inverse will not be correct and valid will be set to false.
/// ///
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, Size, Size> MatrixInverse(const vtkm::Matrix<T, Size, Size>& A,
vtkm::Matrix<T,Size,Size> MatrixInverse(const vtkm::Matrix<T,Size,Size> &A, bool& valid)
bool &valid)
{ {
// First, we will make an LUP-factorization to help us. // First, we will make an LUP-factorization to help us.
vtkm::Matrix<T,Size,Size> LU = A; vtkm::Matrix<T, Size, Size> LU = A;
vtkm::Vec<vtkm::IdComponent,Size> permutation; vtkm::Vec<vtkm::IdComponent, Size> permutation;
T inversionParity; // Unused T inversionParity; // Unused
detail::MatrixLUPFactor(LU, permutation, inversionParity, valid); detail::MatrixLUPFactor(LU, permutation, inversionParity, valid);
// We will use the decomposition to solve AX = I for X where X is // We will use the decomposition to solve AX = I for X where X is
// clearly the inverse of A. Our solve method only works for vectors, // clearly the inverse of A. Our solve method only works for vectors,
// so we solve for one column of invA at a time. // so we solve for one column of invA at a time.
vtkm::Matrix<T,Size,Size> invA; vtkm::Matrix<T, Size, Size> invA;
vtkm::Vec<T,Size> ICol(T(0)); vtkm::Vec<T, Size> ICol(T(0));
for (vtkm::IdComponent colIndex = 0; colIndex < Size; colIndex++) for (vtkm::IdComponent colIndex = 0; colIndex < Size; colIndex++)
{ {
ICol[colIndex] = 1; ICol[colIndex] = 1;
vtkm::Vec<T,Size> invACol = detail::MatrixLUPSolve(LU, permutation, ICol); vtkm::Vec<T, Size> invACol = detail::MatrixLUPSolve(LU, permutation, ICol);
ICol[colIndex] = 0; ICol[colIndex] = 0;
vtkm::MatrixSetColumn(invA, colIndex, invACol); vtkm::MatrixSetColumn(invA, colIndex, invACol);
} }
return invA; return invA;
} }
/// Compute the determinant of a matrix. /// Compute the determinant of a matrix.
/// ///
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
VTKM_EXEC_CONT VTKM_EXEC_CONT T MatrixDeterminant(const vtkm::Matrix<T, Size, Size>& A)
T MatrixDeterminant(const vtkm::Matrix<T,Size,Size> &A)
{ {
// First, we will make an LUP-factorization to help us. // First, we will make an LUP-factorization to help us.
vtkm::Matrix<T,Size,Size> LU = A; vtkm::Matrix<T, Size, Size> LU = A;
vtkm::Vec<vtkm::IdComponent,Size> permutation; vtkm::Vec<vtkm::IdComponent, Size> permutation;
T inversionParity; T inversionParity;
bool valid; bool valid;
detail::MatrixLUPFactor(LU, permutation, inversionParity, valid); detail::MatrixLUPFactor(LU, permutation, inversionParity, valid);
// If the matrix is singular, the factorization is invalid, but in that // If the matrix is singular, the factorization is invalid, but in that
// case we know that the determinant is 0. // case we know that the determinant is 0.
if (!valid) { return 0; } if (!valid)
{
return 0;
}
// The determinant is equal to the product of the diagonal of the L matrix, // The determinant is equal to the product of the diagonal of the L matrix,
// possibly negated depending on the parity of the inversion. The // possibly negated depending on the parity of the inversion. The
@ -515,35 +483,31 @@ T MatrixDeterminant(const vtkm::Matrix<T,Size,Size> &A)
// respectively. This sign determines whether the product should be negated. // respectively. This sign determines whether the product should be negated.
T product = inversionParity; T product = inversionParity;
for (vtkm::IdComponent index = 0; index < Size; index++) for (vtkm::IdComponent index = 0; index < Size; index++)
{ {
product *= LU(index,index); product *= LU(index, index);
} }
return product; return product;
} }
// Specializations for common small determinants. // Specializations for common small determinants.
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT T MatrixDeterminant(const vtkm::Matrix<T, 1, 1>& A)
T MatrixDeterminant(const vtkm::Matrix<T,1,1> &A)
{ {
return A(0,0); return A(0, 0);
} }
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT T MatrixDeterminant(const vtkm::Matrix<T, 2, 2>& A)
T MatrixDeterminant(const vtkm::Matrix<T,2,2> &A)
{ {
return A(0,0)*A(1,1) - A(1,0)*A(0,1); return A(0, 0) * A(1, 1) - A(1, 0) * A(0, 1);
} }
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT T MatrixDeterminant(const vtkm::Matrix<T, 3, 3>& A)
T MatrixDeterminant(const vtkm::Matrix<T,3,3> &A)
{ {
return A(0,0) * A(1,1) * A(2,2) + A(1,0) * A(2,1) * A(0,2) + return A(0, 0) * A(1, 1) * A(2, 2) + A(1, 0) * A(2, 1) * A(0, 2) + A(2, 0) * A(0, 1) * A(1, 2) -
A(2,0) * A(0,1) * A(1,2) - A(0,0) * A(2,1) * A(1,2) - A(0, 0) * A(2, 1) * A(1, 2) - A(1, 0) * A(0, 1) * A(2, 2) - A(2, 0) * A(1, 1) * A(0, 2);
A(1,0) * A(0,1) * A(2,2) - A(2,0) * A(1,1) * A(0,2);
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -552,49 +516,50 @@ T MatrixDeterminant(const vtkm::Matrix<T,3,3> &A)
/// Tag used to identify 2 dimensional types (matrices). A TypeTraits class /// Tag used to identify 2 dimensional types (matrices). A TypeTraits class
/// will typedef this class to DimensionalityTag. /// will typedef this class to DimensionalityTag.
/// ///
struct TypeTraitsMatrixTag {}; struct TypeTraitsMatrixTag
{
};
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
struct TypeTraits<vtkm::Matrix<T, NumRow, NumCol> > { struct TypeTraits<vtkm::Matrix<T, NumRow, NumCol>>
{
typedef typename TypeTraits<T>::NumericTag NumericTag; typedef typename TypeTraits<T>::NumericTag NumericTag;
typedef TypeTraitsMatrixTag DimensionalityTag; typedef TypeTraitsMatrixTag DimensionalityTag;
}; };
/// A matrix has vector traits to implement component-wise operations. /// A matrix has vector traits to implement component-wise operations.
/// ///
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
struct VecTraits<vtkm::Matrix<T, NumRow, NumCol> > { struct VecTraits<vtkm::Matrix<T, NumRow, NumCol>>
{
private: private:
typedef vtkm::Matrix<T, NumRow, NumCol> MatrixType; typedef vtkm::Matrix<T, NumRow, NumCol> MatrixType;
public: public:
typedef T ComponentType; typedef T ComponentType;
static const vtkm::IdComponent NUM_COMPONENTS = NumRow*NumCol; static const vtkm::IdComponent NUM_COMPONENTS = NumRow * NumCol;
typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents; typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents;
typedef vtkm::VecTraitsTagSizeStatic IsSizeStatic; typedef vtkm::VecTraitsTagSizeStatic IsSizeStatic;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const MatrixType &) { static vtkm::IdComponent GetNumberOfComponents(const MatrixType&) { return NUM_COMPONENTS; }
return NUM_COMPONENTS;
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
static const ComponentType &GetComponent(const MatrixType &matrix, static const ComponentType& GetComponent(const MatrixType& matrix, vtkm::IdComponent component)
vtkm::IdComponent component) { {
vtkm::IdComponent colIndex = component % NumCol; vtkm::IdComponent colIndex = component % NumCol;
vtkm::IdComponent rowIndex = component / NumCol; vtkm::IdComponent rowIndex = component / NumCol;
return matrix(rowIndex,colIndex); return matrix(rowIndex, colIndex);
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
static ComponentType &GetComponent(MatrixType &matrix, static ComponentType& GetComponent(MatrixType& matrix, vtkm::IdComponent component)
vtkm::IdComponent component) { {
vtkm::IdComponent colIndex = component % NumCol; vtkm::IdComponent colIndex = component % NumCol;
vtkm::IdComponent rowIndex = component / NumCol; vtkm::IdComponent rowIndex = component / NumCol;
return matrix(rowIndex,colIndex); return matrix(rowIndex, colIndex);
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
static void SetComponent(MatrixType &matrix, static void SetComponent(MatrixType& matrix, vtkm::IdComponent component, T value)
vtkm::IdComponent component,
T value)
{ {
GetComponent(matrix, component) = value; GetComponent(matrix, component) = value;
} }
@ -605,24 +570,23 @@ public:
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// Basic comparison operators. // Basic comparison operators.
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
VTKM_EXEC_CONT VTKM_EXEC_CONT bool operator==(const vtkm::Matrix<T, NumRow, NumCol>& a,
bool operator==(const vtkm::Matrix<T,NumRow,NumCol> &a, const vtkm::Matrix<T, NumRow, NumCol>& b)
const vtkm::Matrix<T,NumRow,NumCol> &b)
{ {
for (vtkm::IdComponent colIndex = 0; colIndex < NumCol; colIndex++) for (vtkm::IdComponent colIndex = 0; colIndex < NumCol; colIndex++)
{ {
for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++) for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++)
{ {
if (a(rowIndex, colIndex) != b(rowIndex, colIndex)) return false; if (a(rowIndex, colIndex) != b(rowIndex, colIndex))
return false;
} }
} }
return true; return true;
} }
template<typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol> template <typename T, vtkm::IdComponent NumRow, vtkm::IdComponent NumCol>
VTKM_EXEC_CONT VTKM_EXEC_CONT bool operator!=(const vtkm::Matrix<T, NumRow, NumCol>& a,
bool operator!=(const vtkm::Matrix<T,NumRow,NumCol> &a, const vtkm::Matrix<T, NumRow, NumCol>& b)
const vtkm::Matrix<T,NumRow,NumCol> &b)
{ {
return !(a == b); return !(a == b);
} }

@ -23,7 +23,8 @@
#include <vtkm/Math.h> #include <vtkm/Math.h>
#include <vtkm/Matrix.h> #include <vtkm/Matrix.h>
namespace vtkm { namespace vtkm
{
/// Uses Newton's method (a.k.a. Newton-Raphson method) to solve a nonlinear /// Uses Newton's method (a.k.a. Newton-Raphson method) to solve a nonlinear
/// system of equations. This function assumes that the number of variables /// system of equations. This function assumes that the number of variables
@ -36,30 +37,22 @@ namespace vtkm {
/// returned. /// returned.
/// ///
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<typename ScalarType, template <typename ScalarType, vtkm::IdComponent Size, typename JacobianFunctor,
vtkm::IdComponent Size, typename FunctionFunctor>
typename JacobianFunctor, VTKM_EXEC_CONT vtkm::Vec<ScalarType, Size> NewtonsMethod(
typename FunctionFunctor> JacobianFunctor jacobianEvaluator, FunctionFunctor functionEvaluator,
VTKM_EXEC_CONT vtkm::Vec<ScalarType, Size> desiredFunctionOutput,
vtkm::Vec<ScalarType,Size> vtkm::Vec<ScalarType, Size> initialGuess = vtkm::Vec<ScalarType, Size>(ScalarType(0)),
NewtonsMethod(JacobianFunctor jacobianEvaluator, ScalarType convergeDifference = ScalarType(1e-3), vtkm::IdComponent maxIterations = 10)
FunctionFunctor functionEvaluator,
vtkm::Vec<ScalarType,Size> desiredFunctionOutput,
vtkm::Vec<ScalarType,Size> initialGuess
= vtkm::Vec<ScalarType,Size>(ScalarType(0)),
ScalarType convergeDifference = ScalarType(1e-3),
vtkm::IdComponent maxIterations = 10)
{ {
typedef vtkm::Vec<ScalarType,Size> VectorType; typedef vtkm::Vec<ScalarType, Size> VectorType;
typedef vtkm::Matrix<ScalarType,Size,Size> MatrixType; typedef vtkm::Matrix<ScalarType, Size, Size> MatrixType;
VectorType x = initialGuess; VectorType x = initialGuess;
bool converged = false; bool converged = false;
for (vtkm::IdComponent iteration = 0; for (vtkm::IdComponent iteration = 0; !converged && (iteration < maxIterations); iteration++)
!converged && (iteration < maxIterations); {
iteration++)
{
// For Newton's method, we solve the linear system // For Newton's method, we solve the linear system
// //
// Jacobian x deltaX = currentFunctionOutput - desiredFunctionOutput // Jacobian x deltaX = currentFunctionOutput - desiredFunctionOutput
@ -72,21 +65,18 @@ NewtonsMethod(JacobianFunctor jacobianEvaluator,
MatrixType jacobian = jacobianEvaluator(x); MatrixType jacobian = jacobianEvaluator(x);
VectorType currentFunctionOutput = functionEvaluator(x); VectorType currentFunctionOutput = functionEvaluator(x);
bool valid; // Ignored. bool valid; // Ignored.
VectorType deltaX = VectorType deltaX =
vtkm::SolveLinearSystem( vtkm::SolveLinearSystem(jacobian, currentFunctionOutput - desiredFunctionOutput, valid);
jacobian,
currentFunctionOutput - desiredFunctionOutput,
valid);
x = x - deltaX; x = x - deltaX;
converged = true; converged = true;
for (vtkm::IdComponent index = 0; index < Size; index++) for (vtkm::IdComponent index = 0; index < Size; index++)
{ {
converged &= (vtkm::Abs(deltaX[index]) < convergeDifference); converged &= (vtkm::Abs(deltaX[index]) < convergeDifference);
}
} }
}
// Not checking whether converged. // Not checking whether converged.
return x; return x;

@ -27,7 +27,8 @@
#include <iostream> #include <iostream>
#include <utility> #include <utility>
namespace vtkm { namespace vtkm
{
/// A \c vtkm::Pair is essentially the same as an STL pair object except that /// A \c vtkm::Pair is essentially the same as an STL pair object except that
/// the methods (constructors and operators) are defined to work in both the /// the methods (constructors and operators) are defined to work in both the
@ -64,37 +65,50 @@ struct Pair
SecondType second; SecondType second;
VTKM_EXEC_CONT VTKM_EXEC_CONT
Pair() : first(), second() { } Pair()
: first()
, second()
{
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
Pair(const FirstType &firstSrc, const SecondType &secondSrc) Pair(const FirstType& firstSrc, const SecondType& secondSrc)
: first(firstSrc), second(secondSrc) { } : first(firstSrc)
, second(secondSrc)
{
}
template <typename U1, typename U2> template <typename U1, typename U2>
VTKM_EXEC_CONT VTKM_EXEC_CONT Pair(const vtkm::Pair<U1, U2>& src)
Pair(const vtkm::Pair<U1,U2> &src) : first(src.first)
: first(src.first), second(src.second) { } , second(src.second)
{
}
template <typename U1, typename U2> template <typename U1, typename U2>
VTKM_EXEC_CONT VTKM_EXEC_CONT Pair(const std::pair<U1, U2>& src)
Pair(const std::pair<U1,U2> &src) : first(src.first)
: first(src.first), second(src.second) { } , second(src.second)
{
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Pair<FirstType,SecondType> & vtkm::Pair<FirstType, SecondType>& operator=(const vtkm::Pair<FirstType, SecondType>& src)
operator=(const vtkm::Pair<FirstType,SecondType> &src) { {
this->first = src.first; this->first = src.first;
this->second = src.second; this->second = src.second;
return *this; return *this;
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator==(const vtkm::Pair<FirstType,SecondType> &other) const { bool operator==(const vtkm::Pair<FirstType, SecondType>& other) const
{
return ((this->first == other.first) && (this->second == other.second)); return ((this->first == other.first) && (this->second == other.second));
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator!=(const vtkm::Pair<FirstType,SecondType> &other) const { bool operator!=(const vtkm::Pair<FirstType, SecondType>& other) const
{
return !(*this == other); return !(*this == other);
} }
@ -102,54 +116,46 @@ struct Pair
/// first are equal. /// first are equal.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator<(const vtkm::Pair<FirstType,SecondType> &other) const { bool operator<(const vtkm::Pair<FirstType, SecondType>& other) const
return ((this->first < other.first) {
|| (!(other.first < this->first) && (this->second < other.second))); return ((this->first < other.first) ||
(!(other.first < this->first) && (this->second < other.second)));
} }
/// Tests ordering on the first object, and then on the second object if the /// Tests ordering on the first object, and then on the second object if the
/// first are equal. /// first are equal.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator>(const vtkm::Pair<FirstType,SecondType> &other) const { bool operator>(const vtkm::Pair<FirstType, SecondType>& other) const { return (other < *this); }
return (other < *this);
}
/// Tests ordering on the first object, and then on the second object if the /// Tests ordering on the first object, and then on the second object if the
/// first are equal. /// first are equal.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator<=(const vtkm::Pair<FirstType,SecondType> &other) const { bool operator<=(const vtkm::Pair<FirstType, SecondType>& other) const { return !(other < *this); }
return !(other < *this);
}
/// Tests ordering on the first object, and then on the second object if the /// Tests ordering on the first object, and then on the second object if the
/// first are equal. /// first are equal.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator>=(const vtkm::Pair<FirstType,SecondType> &other) const { bool operator>=(const vtkm::Pair<FirstType, SecondType>& other) const { return !(*this < other); }
return !(*this < other);
}
}; };
/// Pairwise Add. /// Pairwise Add.
/// This is done by adding the two objects separately. /// This is done by adding the two objects separately.
/// Useful for Reduce operation on a zipped array /// Useful for Reduce operation on a zipped array
template<typename T, typename U> template <typename T, typename U>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Pair<T, U> operator+(const vtkm::Pair<T, U>& a, const vtkm::Pair<T, U>& b)
vtkm::Pair<T, U> operator+(const vtkm::Pair<T, U>& a, const vtkm::Pair<T, U> &b)
{ {
return vtkm::Pair<T,U>(a.first + b.first, a.second + b.second); return vtkm::Pair<T, U>(a.first + b.first, a.second + b.second);
} }
template <typename T1, typename T2> template <typename T1, typename T2>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Pair<T1, T2> make_Pair(const T1& firstSrc, const T2& secondSrc)
vtkm::Pair<T1,T2> make_Pair(const T1 &firstSrc, const T2 &secondSrc)
{ {
return vtkm::Pair<T1,T2>(firstSrc, secondSrc); return vtkm::Pair<T1, T2>(firstSrc, secondSrc);
} }
} // namespace vtkm } // namespace vtkm
#endif //vtk_m_Pair_h #endif //vtk_m_Pair_h

@ -25,7 +25,8 @@
#include <vtkm/Math.h> #include <vtkm/Math.h>
#include <vtkm/Types.h> #include <vtkm/Types.h>
namespace vtkm { namespace vtkm
{
/// \brief Represent a continuous scalar range of values. /// \brief Represent a continuous scalar range of values.
/// ///
@ -42,16 +43,21 @@ struct Range
vtkm::Float64 Max; vtkm::Float64 Max;
VTKM_EXEC_CONT VTKM_EXEC_CONT
Range() : Min(vtkm::Infinity64()), Max(vtkm::NegativeInfinity64()) { } Range()
: Min(vtkm::Infinity64())
, Max(vtkm::NegativeInfinity64())
{
}
template<typename T1, typename T2> template <typename T1, typename T2>
VTKM_EXEC_CONT VTKM_EXEC_CONT Range(const T1& min, const T2& max)
Range(const T1 &min, const T2 &max) : Min(static_cast<vtkm::Float64>(min))
: Min(static_cast<vtkm::Float64>(min)), Max(static_cast<vtkm::Float64>(max)) , Max(static_cast<vtkm::Float64>(max))
{ } {
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
const vtkm::Range &operator=(const vtkm::Range &src) const vtkm::Range& operator=(const vtkm::Range& src)
{ {
this->Min = src.Min; this->Min = src.Min;
this->Max = src.Max; this->Max = src.Max;
@ -68,10 +74,7 @@ struct Range
/// are equal then true is returned. /// are equal then true is returned.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool IsNonEmpty() const bool IsNonEmpty() const { return (this->Min <= this->Max); }
{
return (this->Min <= this->Max);
}
/// \b Determines if a value is within the range. /// \b Determines if a value is within the range.
/// ///
@ -79,9 +82,8 @@ struct Range
/// otherwise. \c Contains treats the min and max as inclusive. That is, if /// otherwise. \c Contains treats the min and max as inclusive. That is, if
/// the value is exactly the min or max, true is returned. /// the value is exactly the min or max, true is returned.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT bool Contains(const T& value) const
bool Contains(const T &value) const
{ {
return ((this->Min <= static_cast<vtkm::Float64>(value)) && return ((this->Min <= static_cast<vtkm::Float64>(value)) &&
(this->Max >= static_cast<vtkm::Float64>(value))); (this->Max >= static_cast<vtkm::Float64>(value)));
@ -115,7 +117,7 @@ struct Range
{ {
if (this->IsNonEmpty()) if (this->IsNonEmpty())
{ {
return 0.5*(this->Max + this->Min); return 0.5 * (this->Max + this->Min);
} }
else else
{ {
@ -129,9 +131,8 @@ struct Range
/// given value. If the range already includes this value, then nothing is /// given value. If the range already includes this value, then nothing is
/// done. /// done.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT void Include(const T& value)
void Include(const T &value)
{ {
this->Min = vtkm::Min(this->Min, static_cast<vtkm::Float64>(value)); this->Min = vtkm::Min(this->Min, static_cast<vtkm::Float64>(value));
this->Max = vtkm::Max(this->Max, static_cast<vtkm::Float64>(value)); this->Max = vtkm::Max(this->Max, static_cast<vtkm::Float64>(value));
@ -143,7 +144,7 @@ struct Range
/// of another range. Esentially it is the union of the two ranges. /// of another range. Esentially it is the union of the two ranges.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Include(const vtkm::Range &range) void Include(const vtkm::Range& range)
{ {
this->Include(range.Min); this->Include(range.Min);
this->Include(range.Max); this->Include(range.Max);
@ -154,7 +155,7 @@ struct Range
/// This is a nondestructive form of \c Include. /// This is a nondestructive form of \c Include.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Range Union(const vtkm::Range &otherRange) const vtkm::Range Union(const vtkm::Range& otherRange) const
{ {
vtkm::Range unionRange(*this); vtkm::Range unionRange(*this);
unionRange.Include(otherRange); unionRange.Include(otherRange);
@ -164,19 +165,16 @@ struct Range
/// \b Operator for union /// \b Operator for union
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Range operator+(const vtkm::Range &otherRange) const vtkm::Range operator+(const vtkm::Range& otherRange) const { return this->Union(otherRange); }
{
return this->Union(otherRange);
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator==(const vtkm::Range &otherRange) const bool operator==(const vtkm::Range& otherRange) const
{ {
return ((this->Min == otherRange.Min) && (this->Max == otherRange.Max)); return ((this->Min == otherRange.Min) && (this->Max == otherRange.Max));
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
bool operator!=(const vtkm::Range &otherRange) const bool operator!=(const vtkm::Range& otherRange) const
{ {
return ((this->Min != otherRange.Min) || (this->Max != otherRange.Max)); return ((this->Min != otherRange.Min) || (this->Max != otherRange.Max));
} }
@ -186,8 +184,7 @@ struct Range
/// Helper function for printing ranges during testing /// Helper function for printing ranges during testing
/// ///
static inline VTKM_CONT static inline VTKM_CONT std::ostream& operator<<(std::ostream& stream, const vtkm::Range& range)
std::ostream &operator<<(std::ostream &stream, const vtkm::Range &range)
{ {
return stream << "[" << range.Min << ".." << range.Max << "]"; return stream << "[" << range.Min << ".." << range.Max << "]";
} }

@ -23,10 +23,8 @@
#include <type_traits> #include <type_traits>
#include <vtkm/internal/Configure.h> #include <vtkm/internal/Configure.h>
#define VTKM_STATIC_ASSERT(condition) \ #define VTKM_STATIC_ASSERT(condition) \
static_assert( (condition), "Failed static assert: " #condition) static_assert((condition), "Failed static assert: " #condition)
#define VTKM_STATIC_ASSERT_MSG(condition, message) \ #define VTKM_STATIC_ASSERT_MSG(condition, message) static_assert((condition), message)
static_assert( (condition), message)
#endif //vtk_m_StaticAssert_h #endif //vtk_m_StaticAssert_h

@ -22,7 +22,8 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
namespace vtkm { namespace vtkm
{
/// \brief A tag used to identify the cell elements in a topology. /// \brief A tag used to identify the cell elements in a topology.
/// ///
@ -30,7 +31,9 @@ namespace vtkm {
/// example, a 3D mesh has points, edges, faces, and cells. Each of these is an /// example, a 3D mesh has points, edges, faces, and cells. Each of these is an
/// example of a topology element and has its own tag. /// example of a topology element and has its own tag.
/// ///
struct TopologyElementTagCell { }; struct TopologyElementTagCell
{
};
/// \brief A tag used to identify the point elements in a topology. /// \brief A tag used to identify the point elements in a topology.
/// ///
@ -38,7 +41,9 @@ struct TopologyElementTagCell { };
/// example, a 3D mesh has points, edges, faces, and cells. Each of these is an /// example, a 3D mesh has points, edges, faces, and cells. Each of these is an
/// example of a topology element and has its own tag. /// example of a topology element and has its own tag.
/// ///
struct TopologyElementTagPoint { }; struct TopologyElementTagPoint
{
};
/// \brief A tag used to identify the edge elements in a topology. /// \brief A tag used to identify the edge elements in a topology.
/// ///
@ -46,7 +51,9 @@ struct TopologyElementTagPoint { };
/// example, a 3D mesh has points, edges, faces, and cells. Each of these is an /// example, a 3D mesh has points, edges, faces, and cells. Each of these is an
/// example of a topology element and has its own tag. /// example of a topology element and has its own tag.
/// ///
struct TopologyElementTagEdge { }; struct TopologyElementTagEdge
{
};
/// \brief A tag used to identify the face elements in a topology. /// \brief A tag used to identify the face elements in a topology.
/// ///
@ -54,10 +61,12 @@ struct TopologyElementTagEdge { };
/// example, a 3D mesh has points, edges, faces, and cells. Each of these is an /// example, a 3D mesh has points, edges, faces, and cells. Each of these is an
/// example of a topology element and has its own tag. /// example of a topology element and has its own tag.
/// ///
struct TopologyElementTagFace { }; struct TopologyElementTagFace
{
};
namespace internal
namespace internal { {
/// Checks to see if the given object is a topology element tag.This check is /// Checks to see if the given object is a topology element tag.This check is
/// compatible with C++11 type_traits. /// compatible with C++11 type_traits.
@ -65,35 +74,34 @@ namespace internal {
/// std::false_type. Both of these have a typedef named value with the /// std::false_type. Both of these have a typedef named value with the
/// respective boolean value. /// respective boolean value.
/// ///
template<typename T> template <typename T>
struct TopologyElementTagCheck : std::false_type struct TopologyElementTagCheck : std::false_type
{ {
}; };
template<> template <>
struct TopologyElementTagCheck<vtkm::TopologyElementTagCell> : std::true_type struct TopologyElementTagCheck<vtkm::TopologyElementTagCell> : std::true_type
{ {
}; };
template<> template <>
struct TopologyElementTagCheck<vtkm::TopologyElementTagPoint> : std::true_type struct TopologyElementTagCheck<vtkm::TopologyElementTagPoint> : std::true_type
{ {
}; };
template<> template <>
struct TopologyElementTagCheck<vtkm::TopologyElementTagEdge> : std::true_type struct TopologyElementTagCheck<vtkm::TopologyElementTagEdge> : std::true_type
{ {
}; };
template<> template <>
struct TopologyElementTagCheck<vtkm::TopologyElementTagFace> : std::true_type struct TopologyElementTagCheck<vtkm::TopologyElementTagFace> : std::true_type
{ {
}; };
#define VTKM_IS_TOPOLOGY_ELEMENT_TAG(type) \
#define VTKM_IS_TOPOLOGY_ELEMENT_TAG(type) \ static_assert(::vtkm::internal::TopologyElementTagCheck<type>::value, \
static_assert( ::vtkm::internal::TopologyElementTagCheck<type>::value, \ "Invalid Topology Element Tag being used")
"Invalid Topology Element Tag being used")
} // namespace internal } // namespace internal

@ -28,7 +28,8 @@
#include <vtkm/Matrix.h> #include <vtkm/Matrix.h>
#include <vtkm/VectorAnalysis.h> #include <vtkm/VectorAnalysis.h>
namespace vtkm { namespace vtkm
{
/// \brief Transform a 3D point by a transformation matrix. /// \brief Transform a 3D point by a transformation matrix.
/// ///
@ -41,16 +42,14 @@ namespace vtkm {
/// (such as translate, scale, and rotate), but not for perspective /// (such as translate, scale, and rotate), but not for perspective
/// transformations. /// transformations.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, 3> Transform3DPoint(const vtkm::Matrix<T, 4, 4>& matrix,
vtkm::Vec<T,3> Transform3DPoint(const vtkm::Matrix<T,4,4> &matrix, const vtkm::Vec<T, 3>& point)
const vtkm::Vec<T,3> &point)
{ {
vtkm::Vec<T,4> homogeneousPoint(point[0], point[1], point[2], T(1)); vtkm::Vec<T, 4> homogeneousPoint(point[0], point[1], point[2], T(1));
return vtkm::Vec<T,3>( return vtkm::Vec<T, 3>(vtkm::dot(vtkm::MatrixGetRow(matrix, 0), homogeneousPoint),
vtkm::dot(vtkm::MatrixGetRow(matrix,0), homogeneousPoint), vtkm::dot(vtkm::MatrixGetRow(matrix, 1), homogeneousPoint),
vtkm::dot(vtkm::MatrixGetRow(matrix,1), homogeneousPoint), vtkm::dot(vtkm::MatrixGetRow(matrix, 2), homogeneousPoint));
vtkm::dot(vtkm::MatrixGetRow(matrix,2), homogeneousPoint));
} }
/// \brief Transform a 3D point by a transformation matrix with perspective. /// \brief Transform a 3D point by a transformation matrix with perspective.
@ -62,17 +61,15 @@ vtkm::Vec<T,3> Transform3DPoint(const vtkm::Matrix<T,4,4> &matrix,
/// transformed homogeneous coordiante. This makes it applicable for perspective /// transformed homogeneous coordiante. This makes it applicable for perspective
/// transformations, but requires some more computations. /// transformations, but requires some more computations.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, 3> Transform3DPointPerspective(const vtkm::Matrix<T, 4, 4>& matrix,
vtkm::Vec<T,3> Transform3DPointPerspective(const vtkm::Matrix<T,4,4> &matrix, const vtkm::Vec<T, 3>& point)
const vtkm::Vec<T,3> &point)
{ {
vtkm::Vec<T,4> homogeneousPoint(point[0], point[1], point[2], T(1)); vtkm::Vec<T, 4> homogeneousPoint(point[0], point[1], point[2], T(1));
T inverseW = 1/vtkm::dot(vtkm::MatrixGetRow(matrix,3), homogeneousPoint); T inverseW = 1 / vtkm::dot(vtkm::MatrixGetRow(matrix, 3), homogeneousPoint);
return vtkm::Vec<T,3>( return vtkm::Vec<T, 3>(vtkm::dot(vtkm::MatrixGetRow(matrix, 0), homogeneousPoint) * inverseW,
vtkm::dot(vtkm::MatrixGetRow(matrix,0), homogeneousPoint)*inverseW, vtkm::dot(vtkm::MatrixGetRow(matrix, 1), homogeneousPoint) * inverseW,
vtkm::dot(vtkm::MatrixGetRow(matrix,1), homogeneousPoint)*inverseW, vtkm::dot(vtkm::MatrixGetRow(matrix, 2), homogeneousPoint) * inverseW);
vtkm::dot(vtkm::MatrixGetRow(matrix,2), homogeneousPoint)*inverseW);
} }
/// \brief Transform a 3D vector by a transformation matrix. /// \brief Transform a 3D vector by a transformation matrix.
@ -81,17 +78,13 @@ vtkm::Vec<T,3> Transform3DPointPerspective(const vtkm::Matrix<T,4,4> &matrix,
/// transformed by the given matrix in homogeneous coordinates. Unlike points, /// transformed by the given matrix in homogeneous coordinates. Unlike points,
/// vectors do not get translated. /// vectors do not get translated.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<T, 3> Transform3DVector(const vtkm::Matrix<T, 4, 4>& matrix,
vtkm::Vec<T,3> Transform3DVector(const vtkm::Matrix<T,4,4> &matrix, const vtkm::Vec<T, 3>& vector)
const vtkm::Vec<T,3> &vector)
{ {
vtkm::Vec<T,4> homogeneousVector(vector[0], vector[1], vector[2], T(0)); vtkm::Vec<T, 4> homogeneousVector(vector[0], vector[1], vector[2], T(0));
homogeneousVector = vtkm::MatrixMultiply(matrix, homogeneousVector); homogeneousVector = vtkm::MatrixMultiply(matrix, homogeneousVector);
return vtkm::Vec<T,3>( return vtkm::Vec<T, 3>(homogeneousVector[0], homogeneousVector[1], homogeneousVector[2]);
homogeneousVector[0],
homogeneousVector[1],
homogeneousVector[2]);
} }
/// \brief Returns a scale matrix. /// \brief Returns a scale matrix.
@ -99,16 +92,15 @@ vtkm::Vec<T,3> Transform3DVector(const vtkm::Matrix<T,4,4> &matrix,
/// Given a scale factor for the x, y, and z directions, returns a /// Given a scale factor for the x, y, and z directions, returns a
/// transformation matrix for those scales. /// transformation matrix for those scales.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DScale(const T& scaleX, const T& scaleY,
vtkm::Matrix<T,4,4> const T& scaleZ)
Transform3DScale(const T &scaleX, const T &scaleY, const T &scaleZ)
{ {
vtkm::Matrix<T,4,4> scaleMatrix(T(0)); vtkm::Matrix<T, 4, 4> scaleMatrix(T(0));
scaleMatrix(0,0) = scaleX; scaleMatrix(0, 0) = scaleX;
scaleMatrix(1,1) = scaleY; scaleMatrix(1, 1) = scaleY;
scaleMatrix(2,2) = scaleZ; scaleMatrix(2, 2) = scaleZ;
scaleMatrix(3,3) = T(1); scaleMatrix(3, 3) = T(1);
return scaleMatrix; return scaleMatrix;
} }
@ -117,9 +109,8 @@ Transform3DScale(const T &scaleX, const T &scaleY, const T &scaleZ)
/// Given a scale factor for the x, y, and z directions (defined in a Vec), /// Given a scale factor for the x, y, and z directions (defined in a Vec),
/// returns a transformation matrix for those scales. /// returns a transformation matrix for those scales.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DScale(const vtkm::Vec<T, 3>& scaleVec)
vtkm::Matrix<T,4,4> Transform3DScale(const vtkm::Vec<T,3> &scaleVec)
{ {
return vtkm::Transform3DScale(scaleVec[0], scaleVec[1], scaleVec[2]); return vtkm::Transform3DScale(scaleVec[0], scaleVec[1], scaleVec[2]);
} }
@ -129,29 +120,26 @@ vtkm::Matrix<T,4,4> Transform3DScale(const vtkm::Vec<T,3> &scaleVec)
/// Given a uniform scale factor, returns a transformation matrix for those /// Given a uniform scale factor, returns a transformation matrix for those
/// scales. /// scales.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DScale(const T& scale)
vtkm::Matrix<T,4,4> Transform3DScale(const T &scale)
{ {
return vtkm::Transform3DScale(scale, scale, scale); return vtkm::Transform3DScale(scale, scale, scale);
} }
/// \brief Returns a translation matrix. /// \brief Returns a translation matrix.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DTranslate(const T& x, const T& y, const T& z)
vtkm::Matrix<T,4,4> Transform3DTranslate(const T &x, const T &y, const T &z)
{ {
vtkm::Matrix<T,4,4> translateMatrix; vtkm::Matrix<T, 4, 4> translateMatrix;
vtkm::MatrixIdentity(translateMatrix); vtkm::MatrixIdentity(translateMatrix);
translateMatrix(0,3) = x; translateMatrix(0, 3) = x;
translateMatrix(1,3) = y; translateMatrix(1, 3) = y;
translateMatrix(2,3) = z; translateMatrix(2, 3) = z;
return translateMatrix; return translateMatrix;
} }
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DTranslate(const vtkm::Vec<T, 3>& v)
vtkm::Matrix<T,4,4> Transform3DTranslate(const vtkm::Vec<T,3> &v)
{ {
return vtkm::Transform3DTranslate(v[0], v[1], v[2]); return vtkm::Transform3DTranslate(v[0], v[1], v[2]);
} }
@ -163,54 +151,51 @@ vtkm::Matrix<T,4,4> Transform3DTranslate(const vtkm::Vec<T,3> &v)
/// follows the right-hand rule, so if the vector points toward the user, the /// follows the right-hand rule, so if the vector points toward the user, the
/// rotation will be counterclockwise. /// rotation will be counterclockwise.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DRotate(T angleDegrees,
vtkm::Matrix<T,4,4> Transform3DRotate(T angleDegrees, const vtkm::Vec<T, 3>& axisOfRotation)
const vtkm::Vec<T,3> &axisOfRotation)
{ {
T angleRadians = static_cast<T>(vtkm::Pi()/180)*angleDegrees; T angleRadians = static_cast<T>(vtkm::Pi() / 180) * angleDegrees;
const vtkm::Vec<T,3> normAxis = vtkm::Normal(axisOfRotation); const vtkm::Vec<T, 3> normAxis = vtkm::Normal(axisOfRotation);
T sinAngle = vtkm::Sin(angleRadians); T sinAngle = vtkm::Sin(angleRadians);
T cosAngle = vtkm::Cos(angleRadians); T cosAngle = vtkm::Cos(angleRadians);
vtkm::Matrix<T,4,4> matrix; vtkm::Matrix<T, 4, 4> matrix;
matrix(0,0) = normAxis[0]*normAxis[0]*(1-cosAngle) + cosAngle; matrix(0, 0) = normAxis[0] * normAxis[0] * (1 - cosAngle) + cosAngle;
matrix(0,1) = normAxis[0]*normAxis[1]*(1-cosAngle) - normAxis[2]*sinAngle; matrix(0, 1) = normAxis[0] * normAxis[1] * (1 - cosAngle) - normAxis[2] * sinAngle;
matrix(0,2) = normAxis[0]*normAxis[2]*(1-cosAngle) + normAxis[1]*sinAngle; matrix(0, 2) = normAxis[0] * normAxis[2] * (1 - cosAngle) + normAxis[1] * sinAngle;
matrix(0,3) = T(0); matrix(0, 3) = T(0);
matrix(1,0) = normAxis[1]*normAxis[0]*(1-cosAngle) + normAxis[2]*sinAngle; matrix(1, 0) = normAxis[1] * normAxis[0] * (1 - cosAngle) + normAxis[2] * sinAngle;
matrix(1,1) = normAxis[1]*normAxis[1]*(1-cosAngle) + cosAngle; matrix(1, 1) = normAxis[1] * normAxis[1] * (1 - cosAngle) + cosAngle;
matrix(1,2) = normAxis[1]*normAxis[2]*(1-cosAngle) - normAxis[0]*sinAngle; matrix(1, 2) = normAxis[1] * normAxis[2] * (1 - cosAngle) - normAxis[0] * sinAngle;
matrix(1,3) = T(0); matrix(1, 3) = T(0);
matrix(2,0) = normAxis[2]*normAxis[0]*(1-cosAngle) - normAxis[1]*sinAngle; matrix(2, 0) = normAxis[2] * normAxis[0] * (1 - cosAngle) - normAxis[1] * sinAngle;
matrix(2,1) = normAxis[2]*normAxis[1]*(1-cosAngle) + normAxis[0]*sinAngle; matrix(2, 1) = normAxis[2] * normAxis[1] * (1 - cosAngle) + normAxis[0] * sinAngle;
matrix(2,2) = normAxis[2]*normAxis[2]*(1-cosAngle) + cosAngle; matrix(2, 2) = normAxis[2] * normAxis[2] * (1 - cosAngle) + cosAngle;
matrix(2,3) = T(0); matrix(2, 3) = T(0);
matrix(3,0) = T(0); matrix(3, 0) = T(0);
matrix(3,1) = T(0); matrix(3, 1) = T(0);
matrix(3,2) = T(0); matrix(3, 2) = T(0);
matrix(3,3) = T(1); matrix(3, 3) = T(1);
return matrix; return matrix;
} }
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DRotate(T angleDegrees, T x, T y, T z)
vtkm::Matrix<T,4,4> Transform3DRotate(T angleDegrees, T x, T y, T z)
{ {
return vtkm::Transform3DRotate(angleDegrees, vtkm::Vec<T,3>(x,y,z)); return vtkm::Transform3DRotate(angleDegrees, vtkm::Vec<T, 3>(x, y, z));
} }
/// \brief Returns a rotation matrix. /// \brief Returns a rotation matrix.
/// ///
/// Returns a transformation matrix that rotates around the x axis. /// Returns a transformation matrix that rotates around the x axis.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DRotateX(T angleDegrees)
vtkm::Matrix<T,4,4> Transform3DRotateX(T angleDegrees)
{ {
return vtkm::Transform3DRotate(angleDegrees, T(1), T(0), T(0)); return vtkm::Transform3DRotate(angleDegrees, T(1), T(0), T(0));
} }
@ -219,9 +204,8 @@ vtkm::Matrix<T,4,4> Transform3DRotateX(T angleDegrees)
/// ///
/// Returns a transformation matrix that rotates around the y axis. /// Returns a transformation matrix that rotates around the y axis.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DRotateY(T angleDegrees)
vtkm::Matrix<T,4,4> Transform3DRotateY(T angleDegrees)
{ {
return vtkm::Transform3DRotate(angleDegrees, T(0), T(1), T(0)); return vtkm::Transform3DRotate(angleDegrees, T(0), T(1), T(0));
} }
@ -230,9 +214,8 @@ vtkm::Matrix<T,4,4> Transform3DRotateY(T angleDegrees)
/// ///
/// Returns a transformation matrix that rotates around the z axis. /// Returns a transformation matrix that rotates around the z axis.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Matrix<T, 4, 4> Transform3DRotateZ(T angleDegrees)
vtkm::Matrix<T,4,4> Transform3DRotateZ(T angleDegrees)
{ {
return vtkm::Transform3DRotate(angleDegrees, T(0), T(0), T(1)); return vtkm::Transform3DRotate(angleDegrees, T(0), T(0), T(1));
} }

@ -22,42 +22,52 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
namespace vtkm { namespace vtkm
{
/// Tag used to identify types that aren't Real, Integer, Scalar or Vector. /// Tag used to identify types that aren't Real, Integer, Scalar or Vector.
/// ///
struct TypeTraitsUnknownTag {}; struct TypeTraitsUnknownTag
{
};
/// Tag used to identify types that store real (floating-point) numbers. A /// Tag used to identify types that store real (floating-point) numbers. A
/// TypeTraits class will typedef this class to NumericTag if it stores real /// TypeTraits class will typedef this class to NumericTag if it stores real
/// numbers (or vectors of real numbers). /// numbers (or vectors of real numbers).
/// ///
struct TypeTraitsRealTag {}; struct TypeTraitsRealTag
{
};
/// Tag used to identify types that store integer numbers. A TypeTraits class /// Tag used to identify types that store integer numbers. A TypeTraits class
/// will typedef this class to NumericTag if it stores integer numbers (or /// will typedef this class to NumericTag if it stores integer numbers (or
/// vectors of integers). /// vectors of integers).
/// ///
struct TypeTraitsIntegerTag {}; struct TypeTraitsIntegerTag
{
};
/// Tag used to identify 0 dimensional types (scalars). Scalars can also be /// Tag used to identify 0 dimensional types (scalars). Scalars can also be
/// treated like vectors when used with VecTraits. A TypeTraits class will /// treated like vectors when used with VecTraits. A TypeTraits class will
/// typedef this class to DimensionalityTag. /// typedef this class to DimensionalityTag.
/// ///
struct TypeTraitsScalarTag {}; struct TypeTraitsScalarTag
{
};
/// Tag used to identify 1 dimensional types (vectors). A TypeTraits class will /// Tag used to identify 1 dimensional types (vectors). A TypeTraits class will
/// typedef this class to DimensionalityTag. /// typedef this class to DimensionalityTag.
/// ///
struct TypeTraitsVectorTag {}; struct TypeTraitsVectorTag
{
};
/// The TypeTraits class provides helpful compile-time information about the /// The TypeTraits class provides helpful compile-time information about the
/// basic types used in VTKm (and a few others for convienience). The majority /// basic types used in VTKm (and a few others for convienience). The majority
/// of TypeTraits contents are typedefs to tags that can be used to easily /// of TypeTraits contents are typedefs to tags that can be used to easily
/// override behavior of called functions. /// override behavior of called functions.
/// ///
template<typename T> template <typename T>
class TypeTraits class TypeTraits
{ {
public: public:
@ -77,27 +87,32 @@ public:
// Const types should have the same traits as their non-const counterparts. // Const types should have the same traits as their non-const counterparts.
// //
template<typename T> template <typename T>
struct TypeTraits<const T> : TypeTraits<T> struct TypeTraits<const T> : TypeTraits<T>
{ }; {
};
#define VTKM_BASIC_REAL_TYPE(T) \ #define VTKM_BASIC_REAL_TYPE(T) \
template<> struct TypeTraits<T> { \ template <> \
typedef TypeTraitsRealTag NumericTag; \ struct TypeTraits<T> \
typedef TypeTraitsScalarTag DimensionalityTag; \ { \
VTKM_EXEC_CONT static T ZeroInitialization() { return T(); } \ typedef TypeTraitsRealTag NumericTag; \
typedef TypeTraitsScalarTag DimensionalityTag; \
VTKM_EXEC_CONT static T ZeroInitialization() { return T(); } \
}; };
#define VTKM_BASIC_INTEGER_TYPE(T) \ #define VTKM_BASIC_INTEGER_TYPE(T) \
template<> struct TypeTraits< T > { \ template <> \
typedef TypeTraitsIntegerTag NumericTag; \ struct TypeTraits<T> \
typedef TypeTraitsScalarTag DimensionalityTag; \ { \
VTKM_EXEC_CONT static T ZeroInitialization() \ typedef TypeTraitsIntegerTag NumericTag; \
{ \ typedef TypeTraitsScalarTag DimensionalityTag; \
typedef T ReturnType; \ VTKM_EXEC_CONT static T ZeroInitialization() \
return ReturnType(); \ { \
} \ typedef T ReturnType; \
}; \ return ReturnType(); \
} \
};
/// Traits for basic C++ types. /// Traits for basic C++ types.
/// ///
@ -117,64 +132,61 @@ VTKM_BASIC_INTEGER_TYPE(unsigned long)
VTKM_BASIC_INTEGER_TYPE(long long) VTKM_BASIC_INTEGER_TYPE(long long)
VTKM_BASIC_INTEGER_TYPE(unsigned long long) VTKM_BASIC_INTEGER_TYPE(unsigned long long)
#undef VTKM_BASIC_REAL_TYPE #undef VTKM_BASIC_REAL_TYPE
#undef VTKM_BASIC_INTEGER_TYPE #undef VTKM_BASIC_INTEGER_TYPE
/// Traits for Vec types. /// Traits for Vec types.
/// ///
template<typename T, vtkm::IdComponent Size> template <typename T, vtkm::IdComponent Size>
struct TypeTraits<vtkm::Vec<T,Size> > struct TypeTraits<vtkm::Vec<T, Size>>
{ {
typedef typename vtkm::TypeTraits<T>::NumericTag NumericTag; typedef typename vtkm::TypeTraits<T>::NumericTag NumericTag;
typedef TypeTraitsVectorTag DimensionalityTag; typedef TypeTraitsVectorTag DimensionalityTag;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::Vec<T,Size> ZeroInitialization() static vtkm::Vec<T, Size> ZeroInitialization()
{ {
return vtkm::Vec<T,Size>(vtkm::TypeTraits<T>::ZeroInitialization()); return vtkm::Vec<T, Size>(vtkm::TypeTraits<T>::ZeroInitialization());
} }
}; };
/// Traits for VecCConst types. /// Traits for VecCConst types.
/// ///
template<typename T> template <typename T>
struct TypeTraits<vtkm::VecCConst<T> > struct TypeTraits<vtkm::VecCConst<T>>
{ {
using NumericTag = typename vtkm::TypeTraits<T>::NumericTag; using NumericTag = typename vtkm::TypeTraits<T>::NumericTag;
using DimensionalityTag = TypeTraitsVectorTag; using DimensionalityTag = TypeTraitsVectorTag;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::VecCConst<T> ZeroInitialization() static vtkm::VecCConst<T> ZeroInitialization() { return vtkm::VecCConst<T>(); }
{ return vtkm::VecCConst<T>(); }
}; };
/// Traits for VecC types. /// Traits for VecC types.
/// ///
template<typename T> template <typename T>
struct TypeTraits<vtkm::VecC<T> > struct TypeTraits<vtkm::VecC<T>>
{ {
using NumericTag = typename vtkm::TypeTraits<T>::NumericTag; using NumericTag = typename vtkm::TypeTraits<T>::NumericTag;
using DimensionalityTag = TypeTraitsVectorTag; using DimensionalityTag = TypeTraitsVectorTag;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::VecC<T> ZeroInitialization() static vtkm::VecC<T> ZeroInitialization() { return vtkm::VecC<T>(); }
{ return vtkm::VecC<T>(); }
}; };
/// \brief Traits for Pair types. /// \brief Traits for Pair types.
/// ///
template<typename T, typename U> template <typename T, typename U>
struct TypeTraits<vtkm::Pair<T,U> > struct TypeTraits<vtkm::Pair<T, U>>
{ {
typedef TypeTraitsUnknownTag NumericTag; typedef TypeTraitsUnknownTag NumericTag;
typedef TypeTraitsScalarTag DimensionalityTag; typedef TypeTraitsScalarTag DimensionalityTag;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::Pair<T,U> ZeroInitialization() static vtkm::Pair<T, U> ZeroInitialization()
{ {
return vtkm::Pair<T,U>(TypeTraits<T>::ZeroInitialization(), return vtkm::Pair<T, U>(TypeTraits<T>::ZeroInitialization(),
TypeTraits<U>::ZeroInitialization()); TypeTraits<U>::ZeroInitialization());
} }
}; };

File diff suppressed because it is too large Load Diff

@ -23,16 +23,17 @@
#include <vtkm/TypeTraits.h> #include <vtkm/TypeTraits.h>
#include <vtkm/internal/ExportMacros.h> #include <vtkm/internal/ExportMacros.h>
namespace vtkm { namespace vtkm
{
/// Predicate that takes a single argument \c x, and returns /// Predicate that takes a single argument \c x, and returns
/// True if it is the identity of the Type \p T. /// True if it is the identity of the Type \p T.
struct IsZeroInitialized struct IsZeroInitialized
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T &x) const VTKM_EXEC_CONT bool operator()(const T& x) const
{ {
return (x == vtkm::TypeTraits<T>::ZeroInitialization() ); return (x == vtkm::TypeTraits<T>::ZeroInitialization());
} }
}; };
@ -40,10 +41,10 @@ struct IsZeroInitialized
/// True if it isn't the identity of the Type \p T. /// True if it isn't the identity of the Type \p T.
struct NotZeroInitialized struct NotZeroInitialized
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T &x) const VTKM_EXEC_CONT bool operator()(const T& x) const
{ {
return (x != vtkm::TypeTraits<T>::ZeroInitialization() ); return (x != vtkm::TypeTraits<T>::ZeroInitialization());
} }
}; };
@ -53,7 +54,7 @@ struct NotZeroInitialized
/// ! operator. /// ! operator.
struct LogicalNot struct LogicalNot
{ {
template<typename T> template <typename T>
VTKM_EXEC_CONT bool operator()(const T& x) const VTKM_EXEC_CONT bool operator()(const T& x) const
{ {
return !x; return !x;

@ -27,39 +27,42 @@
#include <vtkm/internal/ArrayPortalValueReference.h> #include <vtkm/internal/ArrayPortalValueReference.h>
namespace vtkm { namespace vtkm
{
/// \brief A short variable-length array from a window in an ArrayPortal. /// \brief A short variable-length array from a window in an ArrayPortal.
/// ///
/// The \c VecFromPortal class is a Vec-like class that holds an array portal /// The \c VecFromPortal class is a Vec-like class that holds an array portal
/// and exposes a small window of that portal as if it were a \c Vec. /// and exposes a small window of that portal as if it were a \c Vec.
/// ///
template<typename PortalType> template <typename PortalType>
class VecFromPortal class VecFromPortal
{ {
public: public:
using ComponentType = using ComponentType = typename std::remove_const<typename PortalType::ValueType>::type;
typename std::remove_const<typename PortalType::ValueType>::type;
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
VecFromPortal() : NumComponents(0), Offset(0) { } VecFromPortal()
: NumComponents(0)
VTKM_SUPPRESS_EXEC_WARNINGS , Offset(0)
VTKM_EXEC_CONT {
VecFromPortal(const PortalType &portal,
vtkm::IdComponent numComponents = 0,
vtkm::Id offset = 0)
: Portal(portal), NumComponents(numComponents), Offset(offset) { }
VTKM_EXEC_CONT
vtkm::IdComponent GetNumberOfComponents() const {
return this->NumComponents;
} }
template<typename T, vtkm::IdComponent DestSize> VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
void CopyInto(vtkm::Vec<T,DestSize> &dest) const VecFromPortal(const PortalType& portal, vtkm::IdComponent numComponents = 0, vtkm::Id offset = 0)
: Portal(portal)
, NumComponents(numComponents)
, Offset(offset)
{
}
VTKM_EXEC_CONT
vtkm::IdComponent GetNumberOfComponents() const { return this->NumComponents; }
template <typename T, vtkm::IdComponent DestSize>
VTKM_EXEC_CONT void CopyInto(vtkm::Vec<T, DestSize>& dest) const
{ {
vtkm::IdComponent numComponents = vtkm::Min(DestSize, this->NumComponents); vtkm::IdComponent numComponents = vtkm::Min(DestSize, this->NumComponents);
for (vtkm::IdComponent index = 0; index < numComponents; index++) for (vtkm::IdComponent index = 0; index < numComponents; index++)
@ -70,11 +73,10 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::internal::ArrayPortalValueReference<PortalType> vtkm::internal::ArrayPortalValueReference<PortalType> operator[](vtkm::IdComponent index) const
operator[](vtkm::IdComponent index) const
{ {
return vtkm::internal::ArrayPortalValueReference<PortalType>( return vtkm::internal::ArrayPortalValueReference<PortalType>(this->Portal,
this->Portal, index + this->Offset); index + this->Offset);
} }
private: private:
@ -83,8 +85,8 @@ private:
vtkm::Id Offset; vtkm::Id Offset;
}; };
template<typename PortalType> template <typename PortalType>
struct TypeTraits<vtkm::VecFromPortal<PortalType> > struct TypeTraits<vtkm::VecFromPortal<PortalType>>
{ {
private: private:
typedef typename PortalType::ValueType ComponentType; typedef typename PortalType::ValueType ComponentType;
@ -101,8 +103,8 @@ public:
} }
}; };
template<typename PortalType> template <typename PortalType>
struct VecTraits<vtkm::VecFromPortal<PortalType> > struct VecTraits<vtkm::VecFromPortal<PortalType>>
{ {
typedef vtkm::VecFromPortal<PortalType> VecType; typedef vtkm::VecFromPortal<PortalType> VecType;
@ -112,23 +114,21 @@ struct VecTraits<vtkm::VecFromPortal<PortalType> >
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const VecType &vector) { static vtkm::IdComponent GetNumberOfComponents(const VecType& vector)
{
return vector.GetNumberOfComponents(); return vector.GetNumberOfComponents();
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
static ComponentType GetComponent(const VecType &vector, static ComponentType GetComponent(const VecType& vector, vtkm::IdComponent componentIndex)
vtkm::IdComponent componentIndex)
{ {
return vector[componentIndex]; return vector[componentIndex];
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<vtkm::IdComponent destSize> template <vtkm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const VecType& src, vtkm::Vec<ComponentType, destSize>& dest)
static void CopyInto(const VecType &src,
vtkm::Vec<ComponentType,destSize> &dest)
{ {
src.CopyInto(dest); src.CopyInto(dest);
} }

@ -25,7 +25,8 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
#include <vtkm/VecTraits.h> #include <vtkm/VecTraits.h>
namespace vtkm { namespace vtkm
{
/// \brief A short vector from an ArrayPortal and a vector of indices. /// \brief A short vector from an ArrayPortal and a vector of indices.
/// ///
@ -33,36 +34,33 @@ namespace vtkm {
/// portal and a second Vec-like containing indices into the array. Each value /// portal and a second Vec-like containing indices into the array. Each value
/// of this vector is the value from the array with the respective index. /// of this vector is the value from the array with the respective index.
/// ///
template<typename IndexVecType, typename PortalType> template <typename IndexVecType, typename PortalType>
class VecFromPortalPermute class VecFromPortalPermute
{ {
public: public:
using ComponentType = using ComponentType = typename std::remove_const<typename PortalType::ValueType>::type;
typename std::remove_const<typename PortalType::ValueType>::type;
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
VecFromPortalPermute() { } VecFromPortalPermute() {}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
VecFromPortalPermute(const IndexVecType *indices, const PortalType &portal) VecFromPortalPermute(const IndexVecType* indices, const PortalType& portal)
: Indices(indices), Portal(portal) { } : Indices(indices)
, Portal(portal)
VTKM_SUPPRESS_EXEC_WARNINGS {
VTKM_EXEC_CONT
vtkm::IdComponent GetNumberOfComponents() const {
return this->Indices->GetNumberOfComponents();
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<vtkm::IdComponent DestSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT
void CopyInto(vtkm::Vec<ComponentType,DestSize> &dest) const vtkm::IdComponent GetNumberOfComponents() const { return this->Indices->GetNumberOfComponents(); }
VTKM_SUPPRESS_EXEC_WARNINGS
template <vtkm::IdComponent DestSize>
VTKM_EXEC_CONT void CopyInto(vtkm::Vec<ComponentType, DestSize>& dest) const
{ {
vtkm::IdComponent numComponents = vtkm::IdComponent numComponents = vtkm::Min(DestSize, this->GetNumberOfComponents());
vtkm::Min(DestSize, this->GetNumberOfComponents());
for (vtkm::IdComponent index = 0; index < numComponents; index++) for (vtkm::IdComponent index = 0; index < numComponents; index++)
{ {
dest[index] = (*this)[index]; dest[index] = (*this)[index];
@ -77,17 +75,15 @@ public:
} }
private: private:
const IndexVecType *Indices; const IndexVecType* Indices;
PortalType Portal; PortalType Portal;
}; };
template<typename IndexVecType, typename PortalType> template <typename IndexVecType, typename PortalType>
struct TypeTraits< struct TypeTraits<vtkm::VecFromPortalPermute<IndexVecType, PortalType>>
vtkm::VecFromPortalPermute<IndexVecType,PortalType> >
{ {
private: private:
typedef vtkm::VecFromPortalPermute<IndexVecType,PortalType> typedef vtkm::VecFromPortalPermute<IndexVecType, PortalType> VecType;
VecType;
typedef typename PortalType::ValueType ComponentType; typedef typename PortalType::ValueType ComponentType;
public: public:
@ -96,18 +92,13 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
static VecType ZeroInitialization() static VecType ZeroInitialization() { return VecType(); }
{
return VecType();
}
}; };
template<typename IndexVecType, typename PortalType> template <typename IndexVecType, typename PortalType>
struct VecTraits< struct VecTraits<vtkm::VecFromPortalPermute<IndexVecType, PortalType>>
vtkm::VecFromPortalPermute<IndexVecType,PortalType> >
{ {
typedef vtkm::VecFromPortalPermute<IndexVecType,PortalType> typedef vtkm::VecFromPortalPermute<IndexVecType, PortalType> VecType;
VecType;
typedef typename VecType::ComponentType ComponentType; typedef typename VecType::ComponentType ComponentType;
typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents; typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents;
@ -115,23 +106,21 @@ struct VecTraits<
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const VecType &vector) { static vtkm::IdComponent GetNumberOfComponents(const VecType& vector)
{
return vector.GetNumberOfComponents(); return vector.GetNumberOfComponents();
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
static ComponentType GetComponent(const VecType &vector, static ComponentType GetComponent(const VecType& vector, vtkm::IdComponent componentIndex)
vtkm::IdComponent componentIndex)
{ {
return vector[componentIndex]; return vector[componentIndex];
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<vtkm::IdComponent destSize> template <vtkm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const VecType& src, vtkm::Vec<ComponentType, destSize>& dest)
static void CopyInto(const VecType &src,
vtkm::Vec<ComponentType,destSize> &dest)
{ {
src.CopyInto(dest); src.CopyInto(dest);
} }

@ -25,29 +25,31 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
#include <vtkm/VecTraits.h> #include <vtkm/VecTraits.h>
namespace vtkm { namespace vtkm
{
namespace detail { namespace detail
{
/// Specifies the size of VecRectilinearPointCoordinates for the given /// Specifies the size of VecRectilinearPointCoordinates for the given
/// dimension. /// dimension.
/// ///
template<vtkm::IdComponent NumDimensions> template <vtkm::IdComponent NumDimensions>
struct VecRectilinearPointCoordinatesNumComponents; struct VecRectilinearPointCoordinatesNumComponents;
template<> template <>
struct VecRectilinearPointCoordinatesNumComponents<1> struct VecRectilinearPointCoordinatesNumComponents<1>
{ {
static const vtkm::IdComponent NUM_COMPONENTS = 2; static const vtkm::IdComponent NUM_COMPONENTS = 2;
}; };
template<> template <>
struct VecRectilinearPointCoordinatesNumComponents<2> struct VecRectilinearPointCoordinatesNumComponents<2>
{ {
static const vtkm::IdComponent NUM_COMPONENTS = 4; static const vtkm::IdComponent NUM_COMPONENTS = 4;
}; };
template<> template <>
struct VecRectilinearPointCoordinatesNumComponents<3> struct VecRectilinearPointCoordinatesNumComponents<3>
{ {
static const vtkm::IdComponent NUM_COMPONENTS = 8; static const vtkm::IdComponent NUM_COMPONENTS = 8;
@ -55,14 +57,8 @@ struct VecRectilinearPointCoordinatesNumComponents<3>
VTKM_EXEC_CONSTANT VTKM_EXEC_CONSTANT
const vtkm::FloatDefault VecRectilinearPointCoordinatesOffsetTable[8][3] = { const vtkm::FloatDefault VecRectilinearPointCoordinatesOffsetTable[8][3] = {
{ 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 1.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f },
{ 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 1.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { 0.0f, 1.0f, 1.0f }
{ 1.0f, 1.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f },
{ 1.0f, 0.0f, 1.0f },
{ 1.0f, 1.0f, 1.0f },
{ 0.0f, 1.0f, 1.0f }
}; };
} // namespace detail } // namespace detail
@ -74,29 +70,30 @@ const vtkm::FloatDefault VecRectilinearPointCoordinatesOffsetTable[8][3] = {
/// dimensions of the cell, which can be 1 (for a line), 2 (for a pixel), or 3 /// dimensions of the cell, which can be 1 (for a line), 2 (for a pixel), or 3
/// (for a voxel). /// (for a voxel).
/// ///
template<vtkm::IdComponent NumDimensions> template <vtkm::IdComponent NumDimensions>
class VecRectilinearPointCoordinates class VecRectilinearPointCoordinates
{ {
public: public:
typedef vtkm::Vec<vtkm::FloatDefault,3> ComponentType; typedef vtkm::Vec<vtkm::FloatDefault, 3> ComponentType;
static const vtkm::IdComponent NUM_COMPONENTS = static const vtkm::IdComponent NUM_COMPONENTS =
detail::VecRectilinearPointCoordinatesNumComponents<NumDimensions>::NUM_COMPONENTS; detail::VecRectilinearPointCoordinatesNumComponents<NumDimensions>::NUM_COMPONENTS;
VTKM_EXEC_CONT VTKM_EXEC_CONT
VecRectilinearPointCoordinates(ComponentType origin = ComponentType(0,0,0), VecRectilinearPointCoordinates(ComponentType origin = ComponentType(0, 0, 0),
ComponentType spacing = ComponentType(1,1,1)) ComponentType spacing = ComponentType(1, 1, 1))
: Origin(origin), Spacing(spacing) { } : Origin(origin)
, Spacing(spacing)
{
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::IdComponent GetNumberOfComponents() const { return NUM_COMPONENTS; } vtkm::IdComponent GetNumberOfComponents() const { return NUM_COMPONENTS; }
template<vtkm::IdComponent DestSize> template <vtkm::IdComponent DestSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT void CopyInto(vtkm::Vec<ComponentType, DestSize>& dest) const
void CopyInto(vtkm::Vec<ComponentType,DestSize> &dest) const
{ {
vtkm::IdComponent numComponents = vtkm::IdComponent numComponents = vtkm::Min(DestSize, this->GetNumberOfComponents());
vtkm::Min(DestSize, this->GetNumberOfComponents());
for (vtkm::IdComponent index = 0; index < numComponents; index++) for (vtkm::IdComponent index = 0; index < numComponents; index++)
{ {
dest[index] = (*this)[index]; dest[index] = (*this)[index];
@ -106,18 +103,17 @@ public:
VTKM_EXEC_CONT VTKM_EXEC_CONT
ComponentType operator[](vtkm::IdComponent index) const ComponentType operator[](vtkm::IdComponent index) const
{ {
const vtkm::FloatDefault *offset = const vtkm::FloatDefault* offset = detail::VecRectilinearPointCoordinatesOffsetTable[index];
detail::VecRectilinearPointCoordinatesOffsetTable[index]; return ComponentType(this->Origin[0] + offset[0] * this->Spacing[0],
return ComponentType(this->Origin[0] + offset[0]*this->Spacing[0], this->Origin[1] + offset[1] * this->Spacing[1],
this->Origin[1] + offset[1]*this->Spacing[1], this->Origin[2] + offset[2] * this->Spacing[2]);
this->Origin[2] + offset[2]*this->Spacing[2]);
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
const ComponentType &GetOrigin() const { return this->Origin; } const ComponentType& GetOrigin() const { return this->Origin; }
VTKM_EXEC_CONT VTKM_EXEC_CONT
const ComponentType &GetSpacing() const { return this->Spacing; } const ComponentType& GetSpacing() const { return this->Spacing; }
private: private:
// Position of lower left point. // Position of lower left point.
@ -127,49 +123,42 @@ private:
ComponentType Spacing; ComponentType Spacing;
}; };
template<vtkm::IdComponent NumDimensions> template <vtkm::IdComponent NumDimensions>
struct TypeTraits<vtkm::VecRectilinearPointCoordinates<NumDimensions> > struct TypeTraits<vtkm::VecRectilinearPointCoordinates<NumDimensions>>
{ {
typedef vtkm::TypeTraitsRealTag NumericTag; typedef vtkm::TypeTraitsRealTag NumericTag;
typedef TypeTraitsVectorTag DimensionalityTag; typedef TypeTraitsVectorTag DimensionalityTag;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::VecRectilinearPointCoordinates<NumDimensions> static vtkm::VecRectilinearPointCoordinates<NumDimensions> ZeroInitialization()
ZeroInitialization()
{ {
return vtkm::VecRectilinearPointCoordinates<NumDimensions>( return vtkm::VecRectilinearPointCoordinates<NumDimensions>(
vtkm::Vec<vtkm::FloatDefault,3>(0,0,0), vtkm::Vec<vtkm::FloatDefault, 3>(0, 0, 0), vtkm::Vec<vtkm::FloatDefault, 3>(0, 0, 0));
vtkm::Vec<vtkm::FloatDefault,3>(0,0,0));
} }
}; };
template<vtkm::IdComponent NumDimensions> template <vtkm::IdComponent NumDimensions>
struct VecTraits<vtkm::VecRectilinearPointCoordinates<NumDimensions> > struct VecTraits<vtkm::VecRectilinearPointCoordinates<NumDimensions>>
{ {
typedef vtkm::VecRectilinearPointCoordinates<NumDimensions> VecType; typedef vtkm::VecRectilinearPointCoordinates<NumDimensions> VecType;
typedef vtkm::Vec<vtkm::FloatDefault,3> ComponentType; typedef vtkm::Vec<vtkm::FloatDefault, 3> ComponentType;
typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents; typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents;
typedef vtkm::VecTraitsTagSizeStatic IsSizeStatic; typedef vtkm::VecTraitsTagSizeStatic IsSizeStatic;
static const vtkm::IdComponent NUM_COMPONENTS = VecType::NUM_COMPONENTS; static const vtkm::IdComponent NUM_COMPONENTS = VecType::NUM_COMPONENTS;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const VecType &) { static vtkm::IdComponent GetNumberOfComponents(const VecType&) { return NUM_COMPONENTS; }
return NUM_COMPONENTS;
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
static ComponentType GetComponent(const VecType &vector, static ComponentType GetComponent(const VecType& vector, vtkm::IdComponent componentIndex)
vtkm::IdComponent componentIndex)
{ {
return vector[componentIndex]; return vector[componentIndex];
} }
template<vtkm::IdComponent destSize> template <vtkm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const VecType& src, vtkm::Vec<ComponentType, destSize>& dest)
static void CopyInto(const VecType &src,
vtkm::Vec<ComponentType,destSize> &dest)
{ {
src.CopyInto(dest); src.CopyInto(dest);
} }

@ -22,36 +22,46 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
namespace vtkm { namespace vtkm
{
/// A tag for vectors that are "true" vectors (i.e. have more than one /// A tag for vectors that are "true" vectors (i.e. have more than one
/// component). /// component).
/// ///
struct VecTraitsTagMultipleComponents { }; struct VecTraitsTagMultipleComponents
{
};
/// A tag for vectors that are really just scalars (i.e. have only one /// A tag for vectors that are really just scalars (i.e. have only one
/// component) /// component)
/// ///
struct VecTraitsTagSingleComponent { }; struct VecTraitsTagSingleComponent
{
};
/// A tag for vectors where the number of components are known at compile time. /// A tag for vectors where the number of components are known at compile time.
/// ///
struct VecTraitsTagSizeStatic { }; struct VecTraitsTagSizeStatic
{
};
/// A tag for vectors where the number of components are not determined until /// A tag for vectors where the number of components are not determined until
/// run time. /// run time.
/// ///
struct VecTraitsTagSizeVariable { }; struct VecTraitsTagSizeVariable
{
};
namespace internal { namespace internal
{
template<vtkm::IdComponent numComponents> template <vtkm::IdComponent numComponents>
struct VecTraitsMultipleComponentChooser struct VecTraitsMultipleComponentChooser
{ {
typedef VecTraitsTagMultipleComponents Type; typedef VecTraitsTagMultipleComponents Type;
}; };
template<> template <>
struct VecTraitsMultipleComponentChooser<1> struct VecTraitsMultipleComponentChooser<1>
{ {
typedef VecTraitsTagSingleComponent Type; typedef VecTraitsTagSingleComponent Type;
@ -62,7 +72,7 @@ struct VecTraitsMultipleComponentChooser<1>
/// The VecTraits class gives several static members that define how /// The VecTraits class gives several static members that define how
/// to use a given type as a vector. /// to use a given type as a vector.
/// ///
template<class VecType> template <class VecType>
struct VecTraits struct VecTraits
#ifdef VTKM_DOXYGEN_ONLY #ifdef VTKM_DOXYGEN_ONLY
{ {
@ -78,15 +88,15 @@ struct VecTraits
/// Number of components in the given vector. /// Number of components in the given vector.
/// ///
static vtkm::IdComponent GetNumberOfComponents(const VecType &vec); static vtkm::IdComponent GetNumberOfComponents(const VecType& vec);
/// \brief A tag specifying whether this vector has multiple components (i.e. is a "real" vector). /// \brief A tag specifying whether this vector has multiple components (i.e. is a "real" vector).
/// ///
/// This tag can be useful for creating specialized functions when a vector /// This tag can be useful for creating specialized functions when a vector
/// is really just a scalar. /// is really just a scalar.
/// ///
typedef typename internal::VecTraitsMultipleComponentChooser< typedef typename internal::VecTraitsMultipleComponentChooser<NUM_COMPONENTS>::Type
NUM_COMPONENTS>::Type HasMultipleComponents; HasMultipleComponents;
/// \brief A tag specifying whether the size of this vector is known at compile time. /// \brief A tag specifying whether the size of this vector is known at compile time.
/// ///
@ -98,41 +108,37 @@ struct VecTraits
/// Returns the value in a given component of the vector. /// Returns the value in a given component of the vector.
/// ///
VTKM_EXEC_CONT static const ComponentType &GetComponent( VTKM_EXEC_CONT static const ComponentType& GetComponent(
const typename std::remove_const<VecType>::type &vector, const typename std::remove_const<VecType>::type& vector, vtkm::IdComponent component);
vtkm::IdComponent component); VTKM_EXEC_CONT static ComponentType& GetComponent(
VTKM_EXEC_CONT static ComponentType &GetComponent( typename std::remove_const<VecType>::type& vector, vtkm::IdComponent component);
typename std::remove_const<VecType>::type &vector,
vtkm::IdComponent component);
/// Changes the value in a given component of the vector. /// Changes the value in a given component of the vector.
/// ///
VTKM_EXEC_CONT static void SetComponent(VecType &vector, VTKM_EXEC_CONT static void SetComponent(VecType& vector, vtkm::IdComponent component,
vtkm::IdComponent component, ComponentType value);
ComponentType value);
/// Copies the components in the given vector into a given Vec object. /// Copies the components in the given vector into a given Vec object.
/// ///
template<vktm::IdComponent destSize> template <vktm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const VecType& src, vtkm::Vec<ComponentType, destSize>& dest);
static void
CopyInto(const VecType &src, vtkm::Vec<ComponentType,destSize> &dest);
}; };
#else // VTKM_DOXYGEN_ONLY #else // VTKM_DOXYGEN_ONLY
; ;
#endif // VTKM_DOXYGEN_ONLY #endif // VTKM_DOXYGEN_ONLY
// This partial specialization allows you to define a non-const version of // This partial specialization allows you to define a non-const version of
// VecTraits and have it still work for const version. // VecTraits and have it still work for const version.
// //
template<typename T> template <typename T>
struct VecTraits<const T> : VecTraits<T> struct VecTraits<const T> : VecTraits<T>
{ };
template<typename T, vtkm::IdComponent Size>
struct VecTraits<vtkm::Vec<T,Size> >
{ {
typedef vtkm::Vec<T,Size> VecType; };
template <typename T, vtkm::IdComponent Size>
struct VecTraits<vtkm::Vec<T, Size>>
{
typedef vtkm::Vec<T, Size> VecType;
/// Type of the components in the vector. /// Type of the components in the vector.
/// ///
@ -145,16 +151,14 @@ struct VecTraits<vtkm::Vec<T,Size> >
/// Number of components in the given vector. /// Number of components in the given vector.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const VecType &) { static vtkm::IdComponent GetNumberOfComponents(const VecType&) { return NUM_COMPONENTS; }
return NUM_COMPONENTS;
}
/// A tag specifying whether this vector has multiple components (i.e. is a /// A tag specifying whether this vector has multiple components (i.e. is a
/// "real" vector). This tag can be useful for creating specialized functions /// "real" vector). This tag can be useful for creating specialized functions
/// when a vector is really just a scalar. /// when a vector is really just a scalar.
/// ///
typedef typename internal::VecTraitsMultipleComponentChooser< typedef typename internal::VecTraitsMultipleComponentChooser<NUM_COMPONENTS>::Type
NUM_COMPONENTS>::Type HasMultipleComponents; HasMultipleComponents;
/// A tag specifying whether the size of this vector is known at compile /// A tag specifying whether the size of this vector is known at compile
/// time. If set to \c VecTraitsTagSizeStatic, then \c NUM_COMPONENTS is set. /// time. If set to \c VecTraitsTagSizeStatic, then \c NUM_COMPONENTS is set.
@ -167,37 +171,35 @@ struct VecTraits<vtkm::Vec<T,Size> >
/// Returns the value in a given component of the vector. /// Returns the value in a given component of the vector.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
static const ComponentType &GetComponent(const VecType &vector, static const ComponentType& GetComponent(const VecType& vector, vtkm::IdComponent component)
vtkm::IdComponent component)
{ {
return vector[component]; return vector[component];
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
static ComponentType &GetComponent(VecType &vector, vtkm::IdComponent component) { static ComponentType& GetComponent(VecType& vector, vtkm::IdComponent component)
{
return vector[component]; return vector[component];
} }
/// Changes the value in a given component of the vector. /// Changes the value in a given component of the vector.
/// ///
VTKM_EXEC_CONT static void SetComponent(VecType &vector, VTKM_EXEC_CONT static void SetComponent(VecType& vector, vtkm::IdComponent component,
vtkm::IdComponent component, ComponentType value)
ComponentType value) { {
vector[component] = value; vector[component] = value;
} }
/// Converts whatever type this vector is into the standard VTKm Tuple. /// Converts whatever type this vector is into the standard VTKm Tuple.
/// ///
template<vtkm::IdComponent destSize> template <vtkm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const VecType& src, vtkm::Vec<ComponentType, destSize>& dest)
static void
CopyInto(const VecType &src, vtkm::Vec<ComponentType,destSize> &dest)
{ {
src.CopyInto(dest); src.CopyInto(dest);
} }
}; };
template<typename T> template <typename T>
struct VecTraits<vtkm::VecC<T> > struct VecTraits<vtkm::VecC<T>>
{ {
using VecType = vtkm::VecC<T>; using VecType = vtkm::VecC<T>;
@ -208,7 +210,7 @@ struct VecTraits<vtkm::VecC<T> >
/// Number of components in the given vector. /// Number of components in the given vector.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const VecType &vector) static vtkm::IdComponent GetNumberOfComponents(const VecType& vector)
{ {
return vector.GetNumberOfComponents(); return vector.GetNumberOfComponents();
} }
@ -234,38 +236,35 @@ struct VecTraits<vtkm::VecC<T> >
/// Returns the value in a given component of the vector. /// Returns the value in a given component of the vector.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
static const ComponentType &GetComponent(const VecType &vector, static const ComponentType& GetComponent(const VecType& vector, vtkm::IdComponent component)
vtkm::IdComponent component)
{ {
return vector[component]; return vector[component];
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
static ComponentType &GetComponent(VecType &vector, vtkm::IdComponent component) { static ComponentType& GetComponent(VecType& vector, vtkm::IdComponent component)
{
return vector[component]; return vector[component];
} }
/// Changes the value in a given component of the vector. /// Changes the value in a given component of the vector.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
static void SetComponent(VecType &vector, static void SetComponent(VecType& vector, vtkm::IdComponent component, ComponentType value)
vtkm::IdComponent component, {
ComponentType value) {
vector[component] = value; vector[component] = value;
} }
/// Converts whatever type this vector is into the standard VTKm Tuple. /// Converts whatever type this vector is into the standard VTKm Tuple.
/// ///
template<vtkm::IdComponent destSize> template <vtkm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const VecType& src, vtkm::Vec<ComponentType, destSize>& dest)
static void
CopyInto(const VecType &src, vtkm::Vec<ComponentType,destSize> &dest)
{ {
src.CopyInto(dest); src.CopyInto(dest);
} }
}; };
template<typename T> template <typename T>
struct VecTraits<vtkm::VecCConst<T> > struct VecTraits<vtkm::VecCConst<T>>
{ {
using VecType = vtkm::VecCConst<T>; using VecType = vtkm::VecCConst<T>;
@ -276,7 +275,7 @@ struct VecTraits<vtkm::VecCConst<T> >
/// Number of components in the given vector. /// Number of components in the given vector.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const VecType &vector) static vtkm::IdComponent GetNumberOfComponents(const VecType& vector)
{ {
return vector.GetNumberOfComponents(); return vector.GetNumberOfComponents();
} }
@ -302,8 +301,7 @@ struct VecTraits<vtkm::VecCConst<T> >
/// Returns the value in a given component of the vector. /// Returns the value in a given component of the vector.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
static const ComponentType &GetComponent(const VecType &vector, static const ComponentType& GetComponent(const VecType& vector, vtkm::IdComponent component)
vtkm::IdComponent component)
{ {
return vector[component]; return vector[component];
} }
@ -311,59 +309,51 @@ struct VecTraits<vtkm::VecCConst<T> >
/// Changes the value in a given component of the vector. /// Changes the value in a given component of the vector.
/// ///
VTKM_EXEC_CONT VTKM_EXEC_CONT
static void SetComponent(VecType &vector, static void SetComponent(VecType& vector, vtkm::IdComponent component, ComponentType value)
vtkm::IdComponent component, {
ComponentType value) {
vector[component] = value; vector[component] = value;
} }
/// Converts whatever type this vector is into the standard VTKm Tuple. /// Converts whatever type this vector is into the standard VTKm Tuple.
/// ///
template<vtkm::IdComponent destSize> template <vtkm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const VecType& src, vtkm::Vec<ComponentType, destSize>& dest)
static void
CopyInto(const VecType &src, vtkm::Vec<ComponentType,destSize> &dest)
{ {
src.CopyInto(dest); src.CopyInto(dest);
} }
}; };
namespace internal { namespace internal
{
/// Used for overriding VecTraits for basic scalar types. /// Used for overriding VecTraits for basic scalar types.
/// ///
template<typename ScalarType> template <typename ScalarType>
struct VecTraitsBasic { struct VecTraitsBasic
{
typedef ScalarType ComponentType; typedef ScalarType ComponentType;
static const vtkm::IdComponent NUM_COMPONENTS = 1; static const vtkm::IdComponent NUM_COMPONENTS = 1;
typedef VecTraitsTagSingleComponent HasMultipleComponents; typedef VecTraitsTagSingleComponent HasMultipleComponents;
typedef vtkm::VecTraitsTagSizeStatic IsSizeStatic; typedef vtkm::VecTraitsTagSizeStatic IsSizeStatic;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const ScalarType &) { static vtkm::IdComponent GetNumberOfComponents(const ScalarType&) { return 1; }
return 1;
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
static const ComponentType &GetComponent( static const ComponentType& GetComponent(const ScalarType& vector, vtkm::IdComponent)
const ScalarType &vector, {
vtkm::IdComponent) {
return vector; return vector;
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
static ComponentType &GetComponent(ScalarType &vector, vtkm::IdComponent) { static ComponentType& GetComponent(ScalarType& vector, vtkm::IdComponent) { return vector; }
return vector;
}
VTKM_EXEC_CONT static void SetComponent(ScalarType &vector, VTKM_EXEC_CONT static void SetComponent(ScalarType& vector, vtkm::IdComponent,
vtkm::IdComponent, ComponentType value)
ComponentType value) { {
vector = value; vector = value;
} }
template<vtkm::IdComponent destSize> template <vtkm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const ScalarType& src, vtkm::Vec<ScalarType, destSize>& dest)
static void CopyInto(const ScalarType &src,
vtkm::Vec<ScalarType,destSize> &dest)
{ {
dest[0] = src; dest[0] = src;
} }
@ -377,19 +367,20 @@ struct VecTraitsBasic {
/// every component, and a pair in general has a different type for each /// every component, and a pair in general has a different type for each
/// component. Thus we treat a pair as a "scalar" unit. /// component. Thus we treat a pair as a "scalar" unit.
/// ///
template<typename T, typename U> template <typename T, typename U>
struct VecTraits<vtkm::Pair<T,U> > struct VecTraits<vtkm::Pair<T, U>> : public vtkm::internal::VecTraitsBasic<vtkm::Pair<T, U>>
: public vtkm::internal::VecTraitsBasic<vtkm::Pair<T, U> >
{ {
}; };
} // anonymous namespace } // anonymous namespace
#define VTKM_BASIC_TYPE_VECTOR(type) \ #define VTKM_BASIC_TYPE_VECTOR(type) \
namespace vtkm { \ namespace vtkm \
template<> \ { \
struct VecTraits<type> \ template <> \
: public vtkm::internal::VecTraitsBasic<type> { }; \ struct VecTraits<type> : public vtkm::internal::VecTraitsBasic<type> \
{ \
}; \
} }
/// Allows you to treat basic types as if they were vectors. /// Allows you to treat basic types as if they were vectors.
@ -409,7 +400,6 @@ VTKM_BASIC_TYPE_VECTOR(unsigned long)
VTKM_BASIC_TYPE_VECTOR(long long) VTKM_BASIC_TYPE_VECTOR(long long)
VTKM_BASIC_TYPE_VECTOR(unsigned long long) VTKM_BASIC_TYPE_VECTOR(unsigned long long)
//#undef VTKM_BASIC_TYPE_VECTOR //#undef VTKM_BASIC_TYPE_VECTOR
#endif //vtk_m_VecTraits_h #endif //vtk_m_VecTraits_h

@ -26,7 +26,8 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
#include <vtkm/VecTraits.h> #include <vtkm/VecTraits.h>
namespace vtkm { namespace vtkm
{
/// \brief A short variable-length array with maximum length. /// \brief A short variable-length array with maximum length.
/// ///
@ -35,18 +36,20 @@ namespace vtkm {
/// specified at compile time. Internally, \c VecVariable holds a \c Vec of /// specified at compile time. Internally, \c VecVariable holds a \c Vec of
/// the maximum length and exposes a subsection of it. /// the maximum length and exposes a subsection of it.
/// ///
template<typename T, vtkm::IdComponent MaxSize> template <typename T, vtkm::IdComponent MaxSize>
class VecVariable class VecVariable
{ {
public: public:
typedef T ComponentType; typedef T ComponentType;
VTKM_EXEC_CONT VTKM_EXEC_CONT
VecVariable() : NumComponents(0) { } VecVariable()
: NumComponents(0)
{
}
template<vtkm::IdComponent SrcSize> template <vtkm::IdComponent SrcSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT VecVariable(const vtkm::VecVariable<ComponentType, SrcSize>& src)
VecVariable(const vtkm::VecVariable<ComponentType,SrcSize> &src)
: NumComponents(src.GetNumberOfComponents()) : NumComponents(src.GetNumberOfComponents())
{ {
VTKM_ASSERT(this->NumComponents <= MaxSize); VTKM_ASSERT(this->NumComponents <= MaxSize);
@ -56,9 +59,8 @@ public:
} }
} }
template<vtkm::IdComponent SrcSize> template <vtkm::IdComponent SrcSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT VecVariable(const vtkm::Vec<ComponentType, SrcSize>& src)
VecVariable(const vtkm::Vec<ComponentType,SrcSize> &src)
: NumComponents(SrcSize) : NumComponents(SrcSize)
{ {
VTKM_ASSERT(this->NumComponents <= MaxSize); VTKM_ASSERT(this->NumComponents <= MaxSize);
@ -69,13 +71,10 @@ public:
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::IdComponent GetNumberOfComponents() const { vtkm::IdComponent GetNumberOfComponents() const { return this->NumComponents; }
return this->NumComponents;
}
template<vtkm::IdComponent DestSize> template <vtkm::IdComponent DestSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT void CopyInto(vtkm::Vec<ComponentType, DestSize>& dest) const
void CopyInto(vtkm::Vec<ComponentType,DestSize> &dest) const
{ {
vtkm::IdComponent numComponents = vtkm::Min(DestSize, this->NumComponents); vtkm::IdComponent numComponents = vtkm::Min(DestSize, this->NumComponents);
for (vtkm::IdComponent index = 0; index < numComponents; index++) for (vtkm::IdComponent index = 0; index < numComponents; index++)
@ -85,16 +84,10 @@ public:
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
const ComponentType &operator[](vtkm::IdComponent index) const const ComponentType& operator[](vtkm::IdComponent index) const { return this->Data[index]; }
{
return this->Data[index];
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
ComponentType &operator[](vtkm::IdComponent index) ComponentType& operator[](vtkm::IdComponent index) { return this->Data[index]; }
{
return this->Data[index];
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Append(ComponentType value) void Append(ComponentType value)
@ -105,62 +98,58 @@ public:
} }
private: private:
vtkm::Vec<T,MaxSize> Data; vtkm::Vec<T, MaxSize> Data;
vtkm::IdComponent NumComponents; vtkm::IdComponent NumComponents;
}; };
template<typename T, vtkm::IdComponent MaxSize> template <typename T, vtkm::IdComponent MaxSize>
struct TypeTraits<vtkm::VecVariable<T,MaxSize> > struct TypeTraits<vtkm::VecVariable<T, MaxSize>>
{ {
typedef typename vtkm::TypeTraits<T>::NumericTag NumericTag; typedef typename vtkm::TypeTraits<T>::NumericTag NumericTag;
typedef TypeTraitsVectorTag DimensionalityTag; typedef TypeTraitsVectorTag DimensionalityTag;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::VecVariable<T,MaxSize> ZeroInitialization() static vtkm::VecVariable<T, MaxSize> ZeroInitialization()
{ {
return vtkm::VecVariable<T,MaxSize>(); return vtkm::VecVariable<T, MaxSize>();
} }
}; };
template<typename T, vtkm::IdComponent MaxSize> template <typename T, vtkm::IdComponent MaxSize>
struct VecTraits<vtkm::VecVariable<T,MaxSize> > struct VecTraits<vtkm::VecVariable<T, MaxSize>>
{ {
typedef vtkm::VecVariable<T,MaxSize> VecType; typedef vtkm::VecVariable<T, MaxSize> VecType;
typedef typename VecType::ComponentType ComponentType; typedef typename VecType::ComponentType ComponentType;
typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents; typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents;
typedef vtkm::VecTraitsTagSizeVariable IsSizeStatic; typedef vtkm::VecTraitsTagSizeVariable IsSizeStatic;
VTKM_EXEC_CONT VTKM_EXEC_CONT
static vtkm::IdComponent GetNumberOfComponents(const VecType &vector) { static vtkm::IdComponent GetNumberOfComponents(const VecType& vector)
{
return vector.GetNumberOfComponents(); return vector.GetNumberOfComponents();
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
static const ComponentType &GetComponent(const VecType &vector, static const ComponentType& GetComponent(const VecType& vector, vtkm::IdComponent componentIndex)
vtkm::IdComponent componentIndex)
{ {
return vector[componentIndex]; return vector[componentIndex];
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
static ComponentType &GetComponent(VecType &vector, static ComponentType& GetComponent(VecType& vector, vtkm::IdComponent componentIndex)
vtkm::IdComponent componentIndex)
{ {
return vector[componentIndex]; return vector[componentIndex];
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
static void SetComponent(VecType &vector, static void SetComponent(VecType& vector, vtkm::IdComponent componentIndex,
vtkm::IdComponent componentIndex, const ComponentType& value)
const ComponentType &value)
{ {
vector[componentIndex] = value; vector[componentIndex] = value;
} }
template<vtkm::IdComponent destSize> template <vtkm::IdComponent destSize>
VTKM_EXEC_CONT VTKM_EXEC_CONT static void CopyInto(const VecType& src, vtkm::Vec<ComponentType, destSize>& dest)
static void CopyInto(const VecType &src,
vtkm::Vec<ComponentType,destSize> &dest)
{ {
src.CopyInto(dest); src.CopyInto(dest);
} }

@ -29,8 +29,8 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
#include <vtkm/VecTraits.h> #include <vtkm/VecTraits.h>
namespace vtkm { namespace vtkm
{
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/// \brief Returns the linear interpolation of two values based on weight /// \brief Returns the linear interpolation of two values based on weight
@ -40,30 +40,26 @@ namespace vtkm {
/// vector of the same length as x and y. If w is outside [0,1] then lerp /// vector of the same length as x and y. If w is outside [0,1] then lerp
/// extrapolates. If w=0 => v0 is returned if w=1 => v1 is returned. /// extrapolates. If w=0 => v0 is returned if w=1 => v1 is returned.
/// ///
template<typename ValueType, typename WeightType> template <typename ValueType, typename WeightType>
VTKM_EXEC_CONT VTKM_EXEC_CONT ValueType Lerp(const ValueType& value0, const ValueType& value1,
ValueType Lerp(const ValueType &value0, const WeightType& weight)
const ValueType &value1,
const WeightType &weight)
{ {
return static_cast<ValueType>((WeightType(1)-weight)*value0+weight*value1); return static_cast<ValueType>((WeightType(1) - weight) * value0 + weight * value1);
} }
template<typename ValueType, vtkm::IdComponent N, typename WeightType> template <typename ValueType, vtkm::IdComponent N, typename WeightType>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<ValueType, N> Lerp(const vtkm::Vec<ValueType, N>& value0,
vtkm::Vec<ValueType,N> Lerp(const vtkm::Vec<ValueType,N> &value0, const vtkm::Vec<ValueType, N>& value1,
const vtkm::Vec<ValueType,N> &value1, const WeightType& weight)
const WeightType &weight)
{ {
return (WeightType(1)-weight)*value0+weight*value1; return (WeightType(1) - weight) * value0 + weight * value1;
} }
template<typename ValueType, vtkm::IdComponent N> template <typename ValueType, vtkm::IdComponent N>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<ValueType, N> Lerp(const vtkm::Vec<ValueType, N>& value0,
vtkm::Vec<ValueType,N> Lerp(const vtkm::Vec<ValueType,N> &value0, const vtkm::Vec<ValueType, N>& value1,
const vtkm::Vec<ValueType,N> &value1, const vtkm::Vec<ValueType, N>& weight)
const vtkm::Vec<ValueType,N> &weight)
{ {
static const vtkm::Vec<ValueType,N> One(ValueType(1)); static const vtkm::Vec<ValueType, N> One(ValueType(1));
return (One-weight)*value0+weight*value1; return (One - weight) * value0 + weight * value1;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
@ -73,28 +69,25 @@ vtkm::Vec<ValueType,N> Lerp(const vtkm::Vec<ValueType,N> &value0,
/// square, so you should use this function in place of Magnitude or RMagnitude /// square, so you should use this function in place of Magnitude or RMagnitude
/// when possible. /// when possible.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT typename vtkm::VecTraits<T>::ComponentType MagnitudeSquared(const T& x)
typename vtkm::VecTraits<T>::ComponentType
MagnitudeSquared(const T &x)
{ {
return vtkm::dot(x,x); return vtkm::dot(x, x);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
namespace detail { namespace detail
template<typename T> {
VTKM_EXEC_CONT template <typename T>
typename detail::FloatingPointReturnType<T>::Type VTKM_EXEC_CONT typename detail::FloatingPointReturnType<T>::Type MagnitudeTemplate(
MagnitudeTemplate(T x, vtkm::TypeTraitsScalarTag) T x, vtkm::TypeTraitsScalarTag)
{ {
return static_cast<typename detail::FloatingPointReturnType<T>::Type>(vtkm::Abs(x)); return static_cast<typename detail::FloatingPointReturnType<T>::Type>(vtkm::Abs(x));
} }
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT typename detail::FloatingPointReturnType<T>::Type MagnitudeTemplate(
typename detail::FloatingPointReturnType<T>::Type const T& x, vtkm::TypeTraitsVectorTag)
MagnitudeTemplate(const T &x, vtkm::TypeTraitsVectorTag)
{ {
return vtkm::Sqrt(vtkm::MagnitudeSquared(x)); return vtkm::Sqrt(vtkm::MagnitudeSquared(x));
} }
@ -109,29 +102,25 @@ MagnitudeTemplate(const T &x, vtkm::TypeTraitsVectorTag)
/// to find the reciprocal magnitude, so RMagnitude should be used if you /// to find the reciprocal magnitude, so RMagnitude should be used if you
/// actually plan to divide by the magnitude. /// actually plan to divide by the magnitude.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT typename detail::FloatingPointReturnType<T>::Type Magnitude(const T& x)
typename detail::FloatingPointReturnType<T>::Type
Magnitude(const T &x)
{ {
return detail::MagnitudeTemplate( return detail::MagnitudeTemplate(x, typename vtkm::TypeTraits<T>::DimensionalityTag());
x, typename vtkm::TypeTraits<T>::DimensionalityTag());
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
namespace detail { namespace detail
template<typename T>
VTKM_EXEC_CONT
typename detail::FloatingPointReturnType<T>::Type
RMagnitudeTemplate(T x, vtkm::TypeTraitsScalarTag)
{ {
return T(1)/vtkm::Abs(x); template <typename T>
VTKM_EXEC_CONT typename detail::FloatingPointReturnType<T>::Type RMagnitudeTemplate(
T x, vtkm::TypeTraitsScalarTag)
{
return T(1) / vtkm::Abs(x);
} }
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT typename detail::FloatingPointReturnType<T>::Type RMagnitudeTemplate(
typename detail::FloatingPointReturnType<T>::Type const T& x, vtkm::TypeTraitsVectorTag)
RMagnitudeTemplate(const T &x, vtkm::TypeTraitsVectorTag)
{ {
return vtkm::RSqrt(vtkm::MagnitudeSquared(x)); return vtkm::RSqrt(vtkm::MagnitudeSquared(x));
} }
@ -142,29 +131,25 @@ RMagnitudeTemplate(const T &x, vtkm::TypeTraitsVectorTag)
/// On some hardware RMagnitude is faster than Magnitude, but neither is /// On some hardware RMagnitude is faster than Magnitude, but neither is
/// as fast as MagnitudeSquared. /// as fast as MagnitudeSquared.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT typename detail::FloatingPointReturnType<T>::Type RMagnitude(const T& x)
typename detail::FloatingPointReturnType<T>::Type
RMagnitude(const T &x)
{ {
return detail::RMagnitudeTemplate( return detail::RMagnitudeTemplate(x, typename vtkm::TypeTraits<T>::DimensionalityTag());
x, typename vtkm::TypeTraits<T>::DimensionalityTag());
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
namespace detail { namespace detail
template<typename T> {
VTKM_EXEC_CONT template <typename T>
T NormalTemplate(T x, vtkm::TypeTraitsScalarTag) VTKM_EXEC_CONT T NormalTemplate(T x, vtkm::TypeTraitsScalarTag)
{ {
return vtkm::CopySign(T(1), x); return vtkm::CopySign(T(1), x);
} }
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT T NormalTemplate(const T& x, vtkm::TypeTraitsVectorTag)
T NormalTemplate(const T &x, vtkm::TypeTraitsVectorTag)
{ {
return vtkm::RMagnitude(x)*x; return vtkm::RMagnitude(x) * x;
} }
} // namespace detail } // namespace detail
@ -172,12 +157,10 @@ T NormalTemplate(const T &x, vtkm::TypeTraitsVectorTag)
/// ///
/// The resulting vector points in the same direction but has unit length. /// The resulting vector points in the same direction but has unit length.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT T Normal(const T& x)
T Normal(const T &x)
{ {
return detail::NormalTemplate( return detail::NormalTemplate(x, typename vtkm::TypeTraits<T>::DimensionalityTag());
x, typename vtkm::TypeTraits<T>::DimensionalityTag());
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
@ -185,9 +168,8 @@ T Normal(const T &x)
/// ///
/// The given vector is scaled to be unit length. /// The given vector is scaled to be unit length.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT void Normalize(T& x)
void Normalize(T &x)
{ {
x = vtkm::Normal(x); x = vtkm::Normal(x);
} }
@ -195,14 +177,12 @@ void Normalize(T &x)
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/// \brief Find the cross product of two vectors. /// \brief Find the cross product of two vectors.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<typename detail::FloatingPointReturnType<T>::Type, 3> Cross(
vtkm::Vec<typename detail::FloatingPointReturnType<T>::Type,3> const vtkm::Vec<T, 3>& x, const vtkm::Vec<T, 3>& y)
Cross(const vtkm::Vec<T,3> &x, const vtkm::Vec<T,3> &y)
{ {
return vtkm::Vec<typename detail::FloatingPointReturnType<T>::Type,3>(x[1]*y[2] - x[2]*y[1], return vtkm::Vec<typename detail::FloatingPointReturnType<T>::Type, 3>(
x[2]*y[0] - x[0]*y[2], x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]);
x[0]*y[1] - x[1]*y[0]);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -212,17 +192,13 @@ Cross(const vtkm::Vec<T,3> &x, const vtkm::Vec<T,3> &y)
/// a triangle and the plane the triangle is on, returns a vector perpendicular /// a triangle and the plane the triangle is on, returns a vector perpendicular
/// to that triangle/plane. /// to that triangle/plane.
/// ///
template<typename T> template <typename T>
VTKM_EXEC_CONT VTKM_EXEC_CONT vtkm::Vec<typename detail::FloatingPointReturnType<T>::Type, 3> TriangleNormal(
vtkm::Vec<typename detail::FloatingPointReturnType<T>::Type,3> const vtkm::Vec<T, 3>& a, const vtkm::Vec<T, 3>& b, const vtkm::Vec<T, 3>& c)
TriangleNormal(const vtkm::Vec<T,3> &a,
const vtkm::Vec<T,3> &b,
const vtkm::Vec<T,3> &c)
{ {
return vtkm::Cross(b-a, c-a); return vtkm::Cross(b - a, c - a);
} }
} // namespace vtkm } // namespace vtkm
#endif //vtk_m_VectorAnalysis_h #endif //vtk_m_VectorAnalysis_h

@ -33,7 +33,6 @@
#include <vtkm/cont/internal/DeviceAdapterError.h> #include <vtkm/cont/internal/DeviceAdapterError.h>
#include <vtkm/cont/testing/Testing.h> #include <vtkm/cont/testing/Testing.h>
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <random> #include <random>
@ -42,115 +41,132 @@
#include <vtkm/internal/Windows.h> #include <vtkm/internal/Windows.h>
namespace vtkm { namespace vtkm
namespace benchmarking { {
namespace benchmarking
{
#define ARRAY_SIZE (1 << 21) #define ARRAY_SIZE (1 << 21)
const static std::string DIVIDER(40, '-'); const static std::string DIVIDER(40, '-');
enum BenchmarkName { enum BenchmarkName
COPY = 1, {
COPY_IF = 1 << 1, COPY = 1,
LOWER_BOUNDS = 1 << 2, COPY_IF = 1 << 1,
REDUCE = 1 << 3, LOWER_BOUNDS = 1 << 2,
REDUCE_BY_KEY = 1 << 4, REDUCE = 1 << 3,
REDUCE_BY_KEY = 1 << 4,
SCAN_INCLUSIVE = 1 << 5, SCAN_INCLUSIVE = 1 << 5,
SCAN_EXCLUSIVE = 1 << 6, SCAN_EXCLUSIVE = 1 << 6,
SORT = 1 << 7, SORT = 1 << 7,
SORT_BY_KEY = 1 << 8, SORT_BY_KEY = 1 << 8,
UNIQUE = 1 << 9, UNIQUE = 1 << 9,
UPPER_BOUNDS = 1 << 10, UPPER_BOUNDS = 1 << 10,
ALL = COPY | COPY_IF | LOWER_BOUNDS | REDUCE | REDUCE_BY_KEY | SCAN_INCLUSIVE ALL = COPY | COPY_IF | LOWER_BOUNDS | REDUCE | REDUCE_BY_KEY | SCAN_INCLUSIVE | SCAN_EXCLUSIVE |
| SCAN_EXCLUSIVE | SORT | SORT_BY_KEY | UNIQUE | UPPER_BOUNDS SORT |
SORT_BY_KEY |
UNIQUE |
UPPER_BOUNDS
}; };
/// This class runs a series of micro-benchmarks to measure /// This class runs a series of micro-benchmarks to measure
/// performance of the parallel primitives provided by each /// performance of the parallel primitives provided by each
/// device adapter /// device adapter
template<class DeviceAdapterTag> template <class DeviceAdapterTag>
class BenchmarkDeviceAdapter { class BenchmarkDeviceAdapter
{
typedef vtkm::cont::StorageTagBasic StorageTag; typedef vtkm::cont::StorageTagBasic StorageTag;
typedef vtkm::cont::ArrayHandle<vtkm::Id, StorageTag> IdArrayHandle; typedef vtkm::cont::ArrayHandle<vtkm::Id, StorageTag> IdArrayHandle;
typedef vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag> typedef vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag> Algorithm;
Algorithm;
typedef vtkm::cont::Timer<DeviceAdapterTag> Timer; typedef vtkm::cont::Timer<DeviceAdapterTag> Timer;
public: public:
// Various kernels used by the different benchmarks to accelerate // Various kernels used by the different benchmarks to accelerate
// initialization of data // initialization of data
template<typename Value> template <typename Value>
struct FillTestValueKernel : vtkm::exec::FunctorBase { struct FillTestValueKernel : vtkm::exec::FunctorBase
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
typedef typename ValueArrayHandle::template ExecutionTypes<DeviceAdapterTag> typedef typename ValueArrayHandle::template ExecutionTypes<DeviceAdapterTag>::Portal PortalType;
::Portal PortalType;
PortalType Output; PortalType Output;
VTKM_CONT VTKM_CONT
FillTestValueKernel(PortalType out) : Output(out){} FillTestValueKernel(PortalType out)
: Output(out)
VTKM_EXEC void operator()(vtkm::Id i) const { {
Output.Set(i, TestValue(i, Value()));
} }
VTKM_EXEC void operator()(vtkm::Id i) const { Output.Set(i, TestValue(i, Value())); }
}; };
template<typename Value> template <typename Value>
struct FillScaledTestValueKernel : vtkm::exec::FunctorBase { struct FillScaledTestValueKernel : vtkm::exec::FunctorBase
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
typedef typename ValueArrayHandle::template ExecutionTypes<DeviceAdapterTag> typedef typename ValueArrayHandle::template ExecutionTypes<DeviceAdapterTag>::Portal PortalType;
::Portal PortalType;
PortalType Output; PortalType Output;
const vtkm::Id IdScale; const vtkm::Id IdScale;
VTKM_CONT VTKM_CONT
FillScaledTestValueKernel(vtkm::Id id_scale, PortalType out) : Output(out), IdScale(id_scale) {} FillScaledTestValueKernel(vtkm::Id id_scale, PortalType out)
: Output(out)
VTKM_EXEC void operator()(vtkm::Id i) const { , IdScale(id_scale)
Output.Set(i, TestValue(i * IdScale, Value())); {
} }
VTKM_EXEC void operator()(vtkm::Id i) const { Output.Set(i, TestValue(i * IdScale, Value())); }
}; };
template<typename Value> template <typename Value>
struct FillModuloTestValueKernel : vtkm::exec::FunctorBase { struct FillModuloTestValueKernel : vtkm::exec::FunctorBase
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
typedef typename ValueArrayHandle::template ExecutionTypes<DeviceAdapterTag> typedef typename ValueArrayHandle::template ExecutionTypes<DeviceAdapterTag>::Portal PortalType;
::Portal PortalType;
PortalType Output; PortalType Output;
const vtkm::Id Modulus; const vtkm::Id Modulus;
VTKM_CONT VTKM_CONT
FillModuloTestValueKernel(vtkm::Id modulus, PortalType out) : Output(out), Modulus(modulus) {} FillModuloTestValueKernel(vtkm::Id modulus, PortalType out)
: Output(out)
VTKM_EXEC void operator()(vtkm::Id i) const { , Modulus(modulus)
Output.Set(i, TestValue(i % Modulus, Value())); {
} }
VTKM_EXEC void operator()(vtkm::Id i) const { Output.Set(i, TestValue(i % Modulus, Value())); }
}; };
template<typename Value> template <typename Value>
struct FillBinaryTestValueKernel : vtkm::exec::FunctorBase { struct FillBinaryTestValueKernel : vtkm::exec::FunctorBase
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
typedef typename ValueArrayHandle::template ExecutionTypes<DeviceAdapterTag> typedef typename ValueArrayHandle::template ExecutionTypes<DeviceAdapterTag>::Portal PortalType;
::Portal PortalType;
PortalType Output; PortalType Output;
const vtkm::Id Modulus; const vtkm::Id Modulus;
VTKM_CONT VTKM_CONT
FillBinaryTestValueKernel(vtkm::Id modulus, PortalType out) : Output(out), Modulus(modulus) {} FillBinaryTestValueKernel(vtkm::Id modulus, PortalType out)
: Output(out)
, Modulus(modulus)
{
}
VTKM_EXEC void operator()(vtkm::Id i) const { VTKM_EXEC void operator()(vtkm::Id i) const
{
Output.Set(i, i % Modulus == 0 ? TestValue(vtkm::Id(1), Value()) : Value()); Output.Set(i, i % Modulus == 0 ? TestValue(vtkm::Id(1), Value()) : Value());
} }
}; };
private: private:
template<typename Value> template <typename Value>
struct BenchCopy { struct BenchCopy
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
ValueArrayHandle ValueHandle_src; ValueArrayHandle ValueHandle_src;
@ -158,32 +174,37 @@ private:
std::mt19937 Rng; std::mt19937 Rng;
VTKM_CONT VTKM_CONT
BenchCopy(){ BenchCopy()
{
ValueHandle_src.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag()); ValueHandle_src.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag());
ValueHandle_dst.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag()); ValueHandle_dst.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag());
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
for (vtkm::Id i = 0; i < ValueHandle_src.GetNumberOfValues(); ++i){ {
ValueHandle_src.GetPortalControl().Set(vtkm::Id(i), TestValue(vtkm::Id(Rng()), Value())); for (vtkm::Id i = 0; i < ValueHandle_src.GetNumberOfValues(); ++i)
{
ValueHandle_src.GetPortalControl().Set(vtkm::Id(i), TestValue(vtkm::Id(Rng()), Value()));
} }
Timer timer; Timer timer;
Algorithm::Copy(ValueHandle_src,ValueHandle_dst); Algorithm::Copy(ValueHandle_src, ValueHandle_dst);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Copy " << ARRAY_SIZE << " values"; description << "Copy " << ARRAY_SIZE << " values";
return description.str(); return description.str();
} }
}; };
VTKM_MAKE_BENCHMARK(Copy, BenchCopy); VTKM_MAKE_BENCHMARK(Copy, BenchCopy);
template<typename Value> template <typename Value>
struct BenchCopyIf { struct BenchCopyIf
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
const vtkm::Id N_VALID; const vtkm::Id N_VALID;
@ -191,28 +212,32 @@ private:
IdArrayHandle StencilHandle; IdArrayHandle StencilHandle;
VTKM_CONT VTKM_CONT
BenchCopyIf(vtkm::Id percent_valid) : N_VALID((ARRAY_SIZE * percent_valid) / 100) BenchCopyIf(vtkm::Id percent_valid)
: N_VALID((ARRAY_SIZE * percent_valid) / 100)
{ {
vtkm::Id modulo = ARRAY_SIZE / N_VALID; vtkm::Id modulo = ARRAY_SIZE / N_VALID;
Algorithm::Schedule(FillTestValueKernel<Value>( Algorithm::Schedule(
ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); FillTestValueKernel<Value>(ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
Algorithm::Schedule(FillBinaryTestValueKernel<vtkm::Id>(modulo, ARRAY_SIZE);
StencilHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); Algorithm::Schedule(FillBinaryTestValueKernel<vtkm::Id>(
modulo, StencilHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
ARRAY_SIZE);
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() { vtkm::Float64 operator()()
{
Timer timer; Timer timer;
Algorithm::CopyIf(ValueHandle, StencilHandle, OutHandle); Algorithm::CopyIf(ValueHandle, StencilHandle, OutHandle);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "CopyIf on " << ARRAY_SIZE << " " description << "CopyIf on " << ARRAY_SIZE << " "
<< " values with " << OutHandle.GetNumberOfValues() << " values with " << OutHandle.GetNumberOfValues() << " valid values";
<< " valid values";
return description.str(); return description.str();
} }
}; };
@ -223,8 +248,9 @@ private:
VTKM_MAKE_BENCHMARK(CopyIf25, BenchCopyIf, 25); VTKM_MAKE_BENCHMARK(CopyIf25, BenchCopyIf, 25);
VTKM_MAKE_BENCHMARK(CopyIf30, BenchCopyIf, 30); VTKM_MAKE_BENCHMARK(CopyIf30, BenchCopyIf, 30);
template<typename Value> template <typename Value>
struct BenchLowerBounds { struct BenchLowerBounds
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
const vtkm::Id N_VALS; const vtkm::Id N_VALS;
@ -232,26 +258,30 @@ private:
IdArrayHandle OutHandle; IdArrayHandle OutHandle;
VTKM_CONT VTKM_CONT
BenchLowerBounds(vtkm::Id value_percent) : N_VALS((ARRAY_SIZE * value_percent) / 100) BenchLowerBounds(vtkm::Id value_percent)
: N_VALS((ARRAY_SIZE * value_percent) / 100)
{ {
Algorithm::Schedule(FillTestValueKernel<Value>( Algorithm::Schedule(
InputHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); FillTestValueKernel<Value>(InputHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
Algorithm::Schedule(FillScaledTestValueKernel<Value>(2, ARRAY_SIZE);
ValueHandle.PrepareForOutput(N_VALS, DeviceAdapterTag())), N_VALS); Algorithm::Schedule(FillScaledTestValueKernel<Value>(
2, ValueHandle.PrepareForOutput(N_VALS, DeviceAdapterTag())),
N_VALS);
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
{
Timer timer; Timer timer;
Algorithm::LowerBounds(InputHandle, ValueHandle, OutHandle); Algorithm::LowerBounds(InputHandle, ValueHandle, OutHandle);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "LowerBounds on " << ARRAY_SIZE << " input and " description << "LowerBounds on " << ARRAY_SIZE << " input and " << N_VALS << " values";
<< N_VALS << " values";
return description.str(); return description.str();
} }
}; };
@ -262,27 +292,32 @@ private:
VTKM_MAKE_BENCHMARK(LowerBounds25, BenchLowerBounds, 25); VTKM_MAKE_BENCHMARK(LowerBounds25, BenchLowerBounds, 25);
VTKM_MAKE_BENCHMARK(LowerBounds30, BenchLowerBounds, 30); VTKM_MAKE_BENCHMARK(LowerBounds30, BenchLowerBounds, 30);
template<typename Value> template <typename Value>
struct BenchReduce { struct BenchReduce
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
ValueArrayHandle InputHandle; ValueArrayHandle InputHandle;
VTKM_CONT VTKM_CONT
BenchReduce(){ BenchReduce()
Algorithm::Schedule(FillTestValueKernel<Value>( {
InputHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); Algorithm::Schedule(
FillTestValueKernel<Value>(InputHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
ARRAY_SIZE);
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
{
Timer timer; Timer timer;
Algorithm::Reduce(InputHandle, Value()); Algorithm::Reduce(InputHandle, Value());
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Reduce on " << ARRAY_SIZE << " values"; description << "Reduce on " << ARRAY_SIZE << " values";
return description.str(); return description.str();
@ -290,8 +325,9 @@ private:
}; };
VTKM_MAKE_BENCHMARK(Reduce, BenchReduce); VTKM_MAKE_BENCHMARK(Reduce, BenchReduce);
template<typename Value> template <typename Value>
struct BenchReduceByKey { struct BenchReduceByKey
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
const vtkm::Id N_KEYS; const vtkm::Id N_KEYS;
@ -299,28 +335,32 @@ private:
IdArrayHandle KeyHandle, KeysOut; IdArrayHandle KeyHandle, KeysOut;
VTKM_CONT VTKM_CONT
BenchReduceByKey(vtkm::Id key_percent) : N_KEYS((ARRAY_SIZE * key_percent) / 100) BenchReduceByKey(vtkm::Id key_percent)
: N_KEYS((ARRAY_SIZE * key_percent) / 100)
{ {
Algorithm::Schedule(FillTestValueKernel<Value>( Algorithm::Schedule(
ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); FillTestValueKernel<Value>(ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
Algorithm::Schedule(FillModuloTestValueKernel<vtkm::Id>(N_KEYS, ARRAY_SIZE);
KeyHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); Algorithm::Schedule(FillModuloTestValueKernel<vtkm::Id>(
N_KEYS, KeyHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
ARRAY_SIZE);
Algorithm::SortByKey(KeyHandle, ValueHandle); Algorithm::SortByKey(KeyHandle, ValueHandle);
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
{
Timer timer; Timer timer;
Algorithm::ReduceByKey(KeyHandle, ValueHandle, KeysOut, ValuesOut, Algorithm::ReduceByKey(KeyHandle, ValueHandle, KeysOut, ValuesOut, vtkm::Add());
vtkm::Add());
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "ReduceByKey on " << ARRAY_SIZE description << "ReduceByKey on " << ARRAY_SIZE << " values with " << N_KEYS
<< " values with " << N_KEYS << " distinct vtkm::Id keys"; << " distinct vtkm::Id keys";
return description.str(); return description.str();
} }
}; };
@ -331,26 +371,31 @@ private:
VTKM_MAKE_BENCHMARK(ReduceByKey25, BenchReduceByKey, 25); VTKM_MAKE_BENCHMARK(ReduceByKey25, BenchReduceByKey, 25);
VTKM_MAKE_BENCHMARK(ReduceByKey30, BenchReduceByKey, 30); VTKM_MAKE_BENCHMARK(ReduceByKey30, BenchReduceByKey, 30);
template<typename Value> template <typename Value>
struct BenchScanInclusive { struct BenchScanInclusive
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
ValueArrayHandle ValueHandle, OutHandle; ValueArrayHandle ValueHandle, OutHandle;
VTKM_CONT VTKM_CONT
BenchScanInclusive(){ BenchScanInclusive()
Algorithm::Schedule(FillTestValueKernel<Value>( {
ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); Algorithm::Schedule(
FillTestValueKernel<Value>(ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
ARRAY_SIZE);
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
{
Timer timer; Timer timer;
Algorithm::ScanInclusive(ValueHandle, OutHandle); Algorithm::ScanInclusive(ValueHandle, OutHandle);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "ScanInclusive on " << ARRAY_SIZE << " values"; description << "ScanInclusive on " << ARRAY_SIZE << " values";
return description.str(); return description.str();
@ -358,27 +403,32 @@ private:
}; };
VTKM_MAKE_BENCHMARK(ScanInclusive, BenchScanInclusive); VTKM_MAKE_BENCHMARK(ScanInclusive, BenchScanInclusive);
template<typename Value> template <typename Value>
struct BenchScanExclusive { struct BenchScanExclusive
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
ValueArrayHandle ValueHandle, OutHandle; ValueArrayHandle ValueHandle, OutHandle;
VTKM_CONT VTKM_CONT
BenchScanExclusive(){ BenchScanExclusive()
Algorithm::Schedule(FillTestValueKernel<Value>( {
ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); Algorithm::Schedule(
FillTestValueKernel<Value>(ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
ARRAY_SIZE);
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
{
Timer timer; Timer timer;
Algorithm::ScanExclusive(ValueHandle, OutHandle); Algorithm::ScanExclusive(ValueHandle, OutHandle);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "ScanExclusive on " << ARRAY_SIZE << " values"; description << "ScanExclusive on " << ARRAY_SIZE << " values";
return description.str(); return description.str();
@ -386,21 +436,22 @@ private:
}; };
VTKM_MAKE_BENCHMARK(ScanExclusive, BenchScanExclusive); VTKM_MAKE_BENCHMARK(ScanExclusive, BenchScanExclusive);
template<typename Value> template <typename Value>
struct BenchSort { struct BenchSort
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
ValueArrayHandle ValueHandle; ValueArrayHandle ValueHandle;
std::mt19937 Rng; std::mt19937 Rng;
VTKM_CONT VTKM_CONT
BenchSort(){ BenchSort() { ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag()); }
ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag());
}
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
for (vtkm::Id i = 0; i < ValueHandle.GetNumberOfValues(); ++i){ {
for (vtkm::Id i = 0; i < ValueHandle.GetNumberOfValues(); ++i)
{
ValueHandle.GetPortalControl().Set(vtkm::Id(i), TestValue(vtkm::Id(Rng()), Value())); ValueHandle.GetPortalControl().Set(vtkm::Id(i), TestValue(vtkm::Id(Rng()), Value()));
} }
Timer timer; Timer timer;
@ -409,7 +460,8 @@ private:
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Sort on " << ARRAY_SIZE << " random values"; description << "Sort on " << ARRAY_SIZE << " random values";
return description.str(); return description.str();
@ -417,8 +469,9 @@ private:
}; };
VTKM_MAKE_BENCHMARK(Sort, BenchSort); VTKM_MAKE_BENCHMARK(Sort, BenchSort);
template<typename Value> template <typename Value>
struct BenchSortByKey { struct BenchSortByKey
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
std::mt19937 Rng; std::mt19937 Rng;
@ -427,27 +480,33 @@ private:
IdArrayHandle KeyHandle; IdArrayHandle KeyHandle;
VTKM_CONT VTKM_CONT
BenchSortByKey(vtkm::Id percent_key) : N_KEYS((ARRAY_SIZE * percent_key) / 100){ BenchSortByKey(vtkm::Id percent_key)
: N_KEYS((ARRAY_SIZE * percent_key) / 100)
{
ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag()); ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag());
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
for (vtkm::Id i = 0; i < ValueHandle.GetNumberOfValues(); ++i){ {
for (vtkm::Id i = 0; i < ValueHandle.GetNumberOfValues(); ++i)
{
ValueHandle.GetPortalControl().Set(vtkm::Id(i), TestValue(vtkm::Id(Rng()), Value())); ValueHandle.GetPortalControl().Set(vtkm::Id(i), TestValue(vtkm::Id(Rng()), Value()));
} }
Algorithm::Schedule(FillModuloTestValueKernel<vtkm::Id>(N_KEYS, Algorithm::Schedule(FillModuloTestValueKernel<vtkm::Id>(
KeyHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); N_KEYS, KeyHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
ARRAY_SIZE);
Timer timer; Timer timer;
Algorithm::SortByKey(ValueHandle, KeyHandle); Algorithm::SortByKey(ValueHandle, KeyHandle);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "SortByKey on " << ARRAY_SIZE description << "SortByKey on " << ARRAY_SIZE << " random values with " << N_KEYS
<< " random values with " << N_KEYS << " different vtkm::Id keys"; << " different vtkm::Id keys";
return description.str(); return description.str();
} }
}; };
@ -458,21 +517,26 @@ private:
VTKM_MAKE_BENCHMARK(SortByKey25, BenchSortByKey, 25); VTKM_MAKE_BENCHMARK(SortByKey25, BenchSortByKey, 25);
VTKM_MAKE_BENCHMARK(SortByKey30, BenchSortByKey, 30); VTKM_MAKE_BENCHMARK(SortByKey30, BenchSortByKey, 30);
template<typename Value> template <typename Value>
struct BenchUnique { struct BenchUnique
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
const vtkm::Id N_VALID; const vtkm::Id N_VALID;
ValueArrayHandle ValueHandle; ValueArrayHandle ValueHandle;
VTKM_CONT VTKM_CONT
BenchUnique(vtkm::Id percent_valid) : N_VALID((ARRAY_SIZE * percent_valid) / 100) BenchUnique(vtkm::Id percent_valid)
{} : N_VALID((ARRAY_SIZE * percent_valid) / 100)
{
}
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
Algorithm::Schedule(FillModuloTestValueKernel<Value>(N_VALID, {
ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); Algorithm::Schedule(FillModuloTestValueKernel<Value>(
N_VALID, ValueHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
ARRAY_SIZE);
Algorithm::Sort(ValueHandle); Algorithm::Sort(ValueHandle);
Timer timer; Timer timer;
Algorithm::Unique(ValueHandle); Algorithm::Unique(ValueHandle);
@ -480,10 +544,11 @@ private:
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Unique on " << ARRAY_SIZE << " values with " description << "Unique on " << ARRAY_SIZE << " values with "
<< ValueHandle.GetNumberOfValues() << " valid values"; << ValueHandle.GetNumberOfValues() << " valid values";
return description.str(); return description.str();
} }
}; };
@ -494,8 +559,9 @@ private:
VTKM_MAKE_BENCHMARK(Unique25, BenchUnique, 25); VTKM_MAKE_BENCHMARK(Unique25, BenchUnique, 25);
VTKM_MAKE_BENCHMARK(Unique30, BenchUnique, 30); VTKM_MAKE_BENCHMARK(Unique30, BenchUnique, 30);
template<typename Value> template <typename Value>
struct BenchUpperBounds { struct BenchUpperBounds
{
typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle; typedef vtkm::cont::ArrayHandle<Value, StorageTag> ValueArrayHandle;
const vtkm::Id N_VALS; const vtkm::Id N_VALS;
@ -503,26 +569,30 @@ private:
IdArrayHandle OutHandle; IdArrayHandle OutHandle;
VTKM_CONT VTKM_CONT
BenchUpperBounds(vtkm::Id percent_vals) : N_VALS((ARRAY_SIZE * percent_vals) / 100) BenchUpperBounds(vtkm::Id percent_vals)
: N_VALS((ARRAY_SIZE * percent_vals) / 100)
{ {
Algorithm::Schedule(FillTestValueKernel<Value>( Algorithm::Schedule(
InputHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())), ARRAY_SIZE); FillTestValueKernel<Value>(InputHandle.PrepareForOutput(ARRAY_SIZE, DeviceAdapterTag())),
Algorithm::Schedule(FillScaledTestValueKernel<Value>(2, ARRAY_SIZE);
ValueHandle.PrepareForOutput(N_VALS, DeviceAdapterTag())), N_VALS); Algorithm::Schedule(FillScaledTestValueKernel<Value>(
2, ValueHandle.PrepareForOutput(N_VALS, DeviceAdapterTag())),
N_VALS);
} }
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()(){ vtkm::Float64 operator()()
{
Timer timer; Timer timer;
Algorithm::UpperBounds(InputHandle, ValueHandle, OutHandle); Algorithm::UpperBounds(InputHandle, ValueHandle, OutHandle);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "UpperBounds on " << ARRAY_SIZE << " input and " description << "UpperBounds on " << ARRAY_SIZE << " input and " << N_VALS << " values";
<< N_VALS << " values";
return description.str(); return description.str();
} }
}; };
@ -534,22 +604,25 @@ private:
VTKM_MAKE_BENCHMARK(UpperBounds30, BenchUpperBounds, 30); VTKM_MAKE_BENCHMARK(UpperBounds30, BenchUpperBounds, 30);
public: public:
struct ValueTypes
: vtkm::ListTagBase<vtkm::UInt8, vtkm::UInt32, vtkm::Int32, vtkm::Int64,
vtkm::Vec<vtkm::Int32, 2>, vtkm::Vec<vtkm::UInt8, 4>, vtkm::Float32,
vtkm::Float64, vtkm::Vec<vtkm::Float64, 3>, vtkm::Vec<vtkm::Float32, 4>>
{
};
struct ValueTypes : vtkm::ListTagBase<vtkm::UInt8, vtkm::UInt32, vtkm::Int32, static VTKM_CONT int Run(int benchmarks)
vtkm::Int64, vtkm::Vec<vtkm::Int32, 2>, {
vtkm::Vec<vtkm::UInt8, 4>, vtkm::Float32,
vtkm::Float64, vtkm::Vec<vtkm::Float64, 3>,
vtkm::Vec<vtkm::Float32, 4> >{};
static VTKM_CONT int Run(int benchmarks){
std::cout << DIVIDER << "\nRunning DeviceAdapter benchmarks\n"; std::cout << DIVIDER << "\nRunning DeviceAdapter benchmarks\n";
if (benchmarks & COPY) { if (benchmarks & COPY)
{
std::cout << DIVIDER << "\nBenchmarking Copy\n"; std::cout << DIVIDER << "\nBenchmarking Copy\n";
VTKM_RUN_BENCHMARK(Copy, ValueTypes()); VTKM_RUN_BENCHMARK(Copy, ValueTypes());
} }
if (benchmarks & COPY_IF){ if (benchmarks & COPY_IF)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking CopyIf\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking CopyIf\n";
VTKM_RUN_BENCHMARK(CopyIf5, ValueTypes()); VTKM_RUN_BENCHMARK(CopyIf5, ValueTypes());
VTKM_RUN_BENCHMARK(CopyIf10, ValueTypes()); VTKM_RUN_BENCHMARK(CopyIf10, ValueTypes());
@ -559,7 +632,8 @@ public:
VTKM_RUN_BENCHMARK(CopyIf30, ValueTypes()); VTKM_RUN_BENCHMARK(CopyIf30, ValueTypes());
} }
if (benchmarks & LOWER_BOUNDS){ if (benchmarks & LOWER_BOUNDS)
{
std::cout << DIVIDER << "\nBenchmarking LowerBounds\n"; std::cout << DIVIDER << "\nBenchmarking LowerBounds\n";
VTKM_RUN_BENCHMARK(LowerBounds5, ValueTypes()); VTKM_RUN_BENCHMARK(LowerBounds5, ValueTypes());
VTKM_RUN_BENCHMARK(LowerBounds10, ValueTypes()); VTKM_RUN_BENCHMARK(LowerBounds10, ValueTypes());
@ -569,12 +643,14 @@ public:
VTKM_RUN_BENCHMARK(LowerBounds30, ValueTypes()); VTKM_RUN_BENCHMARK(LowerBounds30, ValueTypes());
} }
if (benchmarks & REDUCE){ if (benchmarks & REDUCE)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking Reduce\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking Reduce\n";
VTKM_RUN_BENCHMARK(Reduce, ValueTypes()); VTKM_RUN_BENCHMARK(Reduce, ValueTypes());
} }
if (benchmarks & REDUCE_BY_KEY){ if (benchmarks & REDUCE_BY_KEY)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking ReduceByKey\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking ReduceByKey\n";
VTKM_RUN_BENCHMARK(ReduceByKey5, ValueTypes()); VTKM_RUN_BENCHMARK(ReduceByKey5, ValueTypes());
VTKM_RUN_BENCHMARK(ReduceByKey10, ValueTypes()); VTKM_RUN_BENCHMARK(ReduceByKey10, ValueTypes());
@ -584,22 +660,26 @@ public:
VTKM_RUN_BENCHMARK(ReduceByKey30, ValueTypes()); VTKM_RUN_BENCHMARK(ReduceByKey30, ValueTypes());
} }
if (benchmarks & SCAN_INCLUSIVE){ if (benchmarks & SCAN_INCLUSIVE)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking ScanInclusive\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking ScanInclusive\n";
VTKM_RUN_BENCHMARK(ScanInclusive, ValueTypes()); VTKM_RUN_BENCHMARK(ScanInclusive, ValueTypes());
} }
if (benchmarks & SCAN_EXCLUSIVE){ if (benchmarks & SCAN_EXCLUSIVE)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking ScanExclusive\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking ScanExclusive\n";
VTKM_RUN_BENCHMARK(ScanExclusive, ValueTypes()); VTKM_RUN_BENCHMARK(ScanExclusive, ValueTypes());
} }
if (benchmarks & SORT){ if (benchmarks & SORT)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking Sort\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking Sort\n";
VTKM_RUN_BENCHMARK(Sort, ValueTypes()); VTKM_RUN_BENCHMARK(Sort, ValueTypes());
} }
if (benchmarks & SORT_BY_KEY){ if (benchmarks & SORT_BY_KEY)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking SortByKey\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking SortByKey\n";
VTKM_RUN_BENCHMARK(SortByKey5, ValueTypes()); VTKM_RUN_BENCHMARK(SortByKey5, ValueTypes());
VTKM_RUN_BENCHMARK(SortByKey10, ValueTypes()); VTKM_RUN_BENCHMARK(SortByKey10, ValueTypes());
@ -609,7 +689,8 @@ public:
VTKM_RUN_BENCHMARK(SortByKey30, ValueTypes()); VTKM_RUN_BENCHMARK(SortByKey30, ValueTypes());
} }
if (benchmarks & UNIQUE){ if (benchmarks & UNIQUE)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking Unique\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking Unique\n";
VTKM_RUN_BENCHMARK(Unique5, ValueTypes()); VTKM_RUN_BENCHMARK(Unique5, ValueTypes());
VTKM_RUN_BENCHMARK(Unique10, ValueTypes()); VTKM_RUN_BENCHMARK(Unique10, ValueTypes());
@ -619,7 +700,8 @@ public:
VTKM_RUN_BENCHMARK(Unique30, ValueTypes()); VTKM_RUN_BENCHMARK(Unique30, ValueTypes());
} }
if (benchmarks & UPPER_BOUNDS){ if (benchmarks & UPPER_BOUNDS)
{
std::cout << "\n" << DIVIDER << "\nBenchmarking UpperBounds\n"; std::cout << "\n" << DIVIDER << "\nBenchmarking UpperBounds\n";
VTKM_RUN_BENCHMARK(UpperBounds5, ValueTypes()); VTKM_RUN_BENCHMARK(UpperBounds5, ValueTypes());
VTKM_RUN_BENCHMARK(UpperBounds10, ValueTypes()); VTKM_RUN_BENCHMARK(UpperBounds10, ValueTypes());
@ -633,54 +715,68 @@ public:
}; };
#undef ARRAY_SIZE #undef ARRAY_SIZE
} }
} // namespace vtkm::benchmarking } // namespace vtkm::benchmarking
int main(int argc, char *argv[]) int main(int argc, char* argv[])
{ {
int benchmarks = 0; int benchmarks = 0;
if (argc < 2){ if (argc < 2)
{
benchmarks = vtkm::benchmarking::ALL; benchmarks = vtkm::benchmarking::ALL;
} }
else { else
for (int i = 1; i < argc; ++i){ {
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i]; std::string arg = argv[i];
std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower); std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
if (arg == "copy"){ if (arg == "copy")
{
benchmarks |= vtkm::benchmarking::COPY; benchmarks |= vtkm::benchmarking::COPY;
} }
else if (arg == "copyif"){ else if (arg == "copyif")
{
benchmarks |= vtkm::benchmarking::COPY_IF; benchmarks |= vtkm::benchmarking::COPY_IF;
} }
else if (arg == "lowerbounds"){ else if (arg == "lowerbounds")
{
benchmarks |= vtkm::benchmarking::LOWER_BOUNDS; benchmarks |= vtkm::benchmarking::LOWER_BOUNDS;
} }
else if (arg == "reduce"){ else if (arg == "reduce")
{
benchmarks |= vtkm::benchmarking::REDUCE; benchmarks |= vtkm::benchmarking::REDUCE;
} }
else if (arg == "reducebykey"){ else if (arg == "reducebykey")
{
benchmarks |= vtkm::benchmarking::REDUCE_BY_KEY; benchmarks |= vtkm::benchmarking::REDUCE_BY_KEY;
} }
else if (arg == "scaninclusive"){ else if (arg == "scaninclusive")
{
benchmarks |= vtkm::benchmarking::SCAN_INCLUSIVE; benchmarks |= vtkm::benchmarking::SCAN_INCLUSIVE;
} }
else if (arg == "scanexclusive"){ else if (arg == "scanexclusive")
{
benchmarks |= vtkm::benchmarking::SCAN_EXCLUSIVE; benchmarks |= vtkm::benchmarking::SCAN_EXCLUSIVE;
} }
else if (arg == "sort"){ else if (arg == "sort")
{
benchmarks |= vtkm::benchmarking::SORT; benchmarks |= vtkm::benchmarking::SORT;
} }
else if (arg == "sortbykey"){ else if (arg == "sortbykey")
{
benchmarks |= vtkm::benchmarking::SORT_BY_KEY; benchmarks |= vtkm::benchmarking::SORT_BY_KEY;
} }
else if (arg == "unique"){ else if (arg == "unique")
{
benchmarks |= vtkm::benchmarking::UNIQUE; benchmarks |= vtkm::benchmarking::UNIQUE;
} }
else if (arg == "upperbounds"){ else if (arg == "upperbounds")
{
benchmarks |= vtkm::benchmarking::UPPER_BOUNDS; benchmarks |= vtkm::benchmarking::UPPER_BOUNDS;
} }
else { else
{
std::cout << "Unrecognized benchmark: " << argv[i] << std::endl; std::cout << "Unrecognized benchmark: " << argv[i] << std::endl;
return 1; return 1;
} }
@ -688,7 +784,6 @@ int main(int argc, char *argv[])
} }
//now actually execute the benchmarks //now actually execute the benchmarks
return vtkm::benchmarking::BenchmarkDeviceAdapter return vtkm::benchmarking::BenchmarkDeviceAdapter<VTKM_DEFAULT_DEVICE_ADAPTER_TAG>::Run(
<VTKM_DEFAULT_DEVICE_ADAPTER_TAG>::Run(benchmarks); benchmarks);
} }

@ -18,7 +18,6 @@
// this software. // this software.
//============================================================================ //============================================================================
#include <vtkm/Math.h> #include <vtkm/Math.h>
#include <vtkm/VectorAnalysis.h> #include <vtkm/VectorAnalysis.h>
@ -39,101 +38,100 @@
#include <random> #include <random>
#include <string> #include <string>
namespace vtkm { namespace vtkm
namespace benchmarking { {
namespace benchmarking
{
#define ARRAY_SIZE (1 << 22) #define ARRAY_SIZE (1 << 22)
#define CUBE_SIZE 256 #define CUBE_SIZE 256
const static std::string DIVIDER(40, '-'); const static std::string DIVIDER(40, '-');
enum BenchmarkName { enum BenchmarkName
{
BLACK_SCHOLES = 1, BLACK_SCHOLES = 1,
MATH = 1 << 1, MATH = 1 << 1,
FUSED_MATH = 1 << 2, FUSED_MATH = 1 << 2,
INTERPOLATE_FIELD = 1 << 3, INTERPOLATE_FIELD = 1 << 3,
IMPLICIT_FUNCTION = 1 << 4, IMPLICIT_FUNCTION = 1 << 4,
ALL = BLACK_SCHOLES | ALL = BLACK_SCHOLES | MATH | FUSED_MATH | INTERPOLATE_FIELD | IMPLICIT_FUNCTION
MATH |
FUSED_MATH |
INTERPOLATE_FIELD |
IMPLICIT_FUNCTION
}; };
template<typename T> template <typename T>
class BlackScholes : public vtkm::worklet::WorkletMapField class BlackScholes : public vtkm::worklet::WorkletMapField
{ {
T Riskfree; T Riskfree;
T Volatility; T Volatility;
public:
typedef void ControlSignature(FieldIn<Scalar>, FieldIn<Scalar>,
FieldIn<Scalar>, FieldOut<Scalar>,
FieldOut<Scalar>);
typedef void ExecutionSignature(_1,_2,_3,_4,_5);
BlackScholes(T risk, T volatility): public:
Riskfree(risk), typedef void ControlSignature(FieldIn<Scalar>, FieldIn<Scalar>, FieldIn<Scalar>, FieldOut<Scalar>,
Volatility(volatility) FieldOut<Scalar>);
typedef void ExecutionSignature(_1, _2, _3, _4, _5);
BlackScholes(T risk, T volatility)
: Riskfree(risk)
, Volatility(volatility)
{ {
} }
VTKM_EXEC VTKM_EXEC
T CumulativeNormalDistribution(T d) const T CumulativeNormalDistribution(T d) const
{ {
const vtkm::Float32 A1 = 0.31938153f; const vtkm::Float32 A1 = 0.31938153f;
const vtkm::Float32 A2 = -0.356563782f; const vtkm::Float32 A2 = -0.356563782f;
const vtkm::Float32 A3 = 1.781477937f; const vtkm::Float32 A3 = 1.781477937f;
const vtkm::Float32 A4 = -1.821255978f; const vtkm::Float32 A4 = -1.821255978f;
const vtkm::Float32 A5 = 1.330274429f; const vtkm::Float32 A5 = 1.330274429f;
const vtkm::Float32 RSQRT2PI = 0.39894228040143267793994605993438f; const vtkm::Float32 RSQRT2PI = 0.39894228040143267793994605993438f;
const vtkm::Float32 df = static_cast<vtkm::Float32>(d); const vtkm::Float32 df = static_cast<vtkm::Float32>(d);
const vtkm::Float32 K = 1.0f / ( 1.0f + 0.2316419f * vtkm::Abs(df)); const vtkm::Float32 K = 1.0f / (1.0f + 0.2316419f * vtkm::Abs(df));
vtkm::Float32 cnd = RSQRT2PI * vtkm::Exp(-0.5f * df * df) * vtkm::Float32 cnd =
(K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5))))); RSQRT2PI * vtkm::Exp(-0.5f * df * df) * (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))));
if(df > 0.0f) if (df > 0.0f)
{ {
cnd = 1.0f - cnd; cnd = 1.0f - cnd;
} }
return static_cast<T>(cnd); return static_cast<T>(cnd);
} }
template <typename U, typename V, typename W> template <typename U, typename V, typename W>
VTKM_EXEC void operator()(const U& sp, const V& os, const W& oy, VTKM_EXEC void operator()(const U& sp, const V& os, const W& oy, T& callResult,
T& callResult, T& putResult) const T& putResult) const
{ {
const T stockPrice = static_cast<T>(sp); const T stockPrice = static_cast<T>(sp);
const T optionStrike = static_cast<T>(os); const T optionStrike = static_cast<T>(os);
const T optionYears = static_cast<T>(oy); const T optionYears = static_cast<T>(oy);
// Black-Scholes formula for both call and put // Black-Scholes formula for both call and put
const T sqrtYears = vtkm::Sqrt(optionYears); const T sqrtYears = vtkm::Sqrt(optionYears);
const T volMultSqY = this->Volatility * sqrtYears; const T volMultSqY = this->Volatility * sqrtYears;
const T d1 = ( vtkm::Log(stockPrice / optionStrike) + (this->Riskfree + 0.5f * Volatility * Volatility) * optionYears) / (volMultSqY); const T d1 = (vtkm::Log(stockPrice / optionStrike) +
const T d2 = d1 - volMultSqY; (this->Riskfree + 0.5f * Volatility * Volatility) * optionYears) /
const T CNDD1 = CumulativeNormalDistribution(d1); (volMultSqY);
const T CNDD2 = CumulativeNormalDistribution(d2); const T d2 = d1 - volMultSqY;
const T CNDD1 = CumulativeNormalDistribution(d1);
const T CNDD2 = CumulativeNormalDistribution(d2);
//Calculate Call and Put simultaneously //Calculate Call and Put simultaneously
T expRT = vtkm::Exp( - this->Riskfree * optionYears); T expRT = vtkm::Exp(-this->Riskfree * optionYears);
callResult = stockPrice * CNDD1 - optionStrike * expRT * CNDD2; callResult = stockPrice * CNDD1 - optionStrike * expRT * CNDD2;
putResult = optionStrike * expRT * (1.0f - CNDD2) - stockPrice * (1.0f - CNDD1); putResult = optionStrike * expRT * (1.0f - CNDD2) - stockPrice * (1.0f - CNDD1);
} }
}; };
class Mag : public vtkm::worklet::WorkletMapField class Mag : public vtkm::worklet::WorkletMapField
{ {
public: public:
typedef void ControlSignature(FieldIn<Vec3>, FieldOut<Scalar>); typedef void ControlSignature(FieldIn<Vec3>, FieldOut<Scalar>);
typedef void ExecutionSignature(_1,_2); typedef void ExecutionSignature(_1, _2);
template<typename T, typename U> template <typename T, typename U>
VTKM_EXEC VTKM_EXEC void operator()(const vtkm::Vec<T, 3>& vec, U& result) const
void operator()(const vtkm::Vec<T,3>& vec, U& result) const
{ {
result = static_cast<U>(vtkm::Magnitude(vec)); result = static_cast<U>(vtkm::Magnitude(vec));
} }
@ -143,11 +141,10 @@ class Square : public vtkm::worklet::WorkletMapField
{ {
public: public:
typedef void ControlSignature(FieldIn<Scalar>, FieldOut<Scalar>); typedef void ControlSignature(FieldIn<Scalar>, FieldOut<Scalar>);
typedef void ExecutionSignature(_1,_2); typedef void ExecutionSignature(_1, _2);
template<typename T, typename U> template <typename T, typename U>
VTKM_EXEC VTKM_EXEC void operator()(T input, U& output) const
void operator()(T input, U& output) const
{ {
output = static_cast<U>(input * input); output = static_cast<U>(input * input);
} }
@ -157,11 +154,10 @@ class Sin : public vtkm::worklet::WorkletMapField
{ {
public: public:
typedef void ControlSignature(FieldIn<Scalar>, FieldOut<Scalar>); typedef void ControlSignature(FieldIn<Scalar>, FieldOut<Scalar>);
typedef void ExecutionSignature(_1,_2); typedef void ExecutionSignature(_1, _2);
template<typename T, typename U> template <typename T, typename U>
VTKM_EXEC VTKM_EXEC void operator()(T input, U& output) const
void operator()(T input, U& output) const
{ {
output = static_cast<U>(vtkm::Sin(input)); output = static_cast<U>(vtkm::Sin(input));
} }
@ -171,11 +167,10 @@ class Cos : public vtkm::worklet::WorkletMapField
{ {
public: public:
typedef void ControlSignature(FieldIn<Scalar>, FieldOut<Scalar>); typedef void ControlSignature(FieldIn<Scalar>, FieldOut<Scalar>);
typedef void ExecutionSignature(_1,_2); typedef void ExecutionSignature(_1, _2);
template<typename T, typename U> template <typename T, typename U>
VTKM_EXEC VTKM_EXEC void operator()(T input, U& output) const
void operator()(T input, U& output) const
{ {
output = static_cast<U>(vtkm::Cos(input)); output = static_cast<U>(vtkm::Cos(input));
} }
@ -185,19 +180,17 @@ class FusedMath : public vtkm::worklet::WorkletMapField
{ {
public: public:
typedef void ControlSignature(FieldIn<Vec3>, FieldOut<Scalar>); typedef void ControlSignature(FieldIn<Vec3>, FieldOut<Scalar>);
typedef void ExecutionSignature(_1,_2); typedef void ExecutionSignature(_1, _2);
template<typename T> template <typename T>
VTKM_EXEC VTKM_EXEC void operator()(const vtkm::Vec<T, 3>& vec, T& result) const
void operator()(const vtkm::Vec<T,3>& vec, T& result) const
{ {
const T m = vtkm::Magnitude(vec); const T m = vtkm::Magnitude(vec);
result = vtkm::Cos( vtkm::Sin(m) * vtkm::Sin(m) ); result = vtkm::Cos(vtkm::Sin(m) * vtkm::Sin(m));
} }
template<typename T, typename U> template <typename T, typename U>
VTKM_EXEC VTKM_EXEC void operator()(const vtkm::Vec<T, 3>&, U&) const
void operator()(const vtkm::Vec<T,3>& , U& ) const
{ {
this->RaiseError("Mixed types unsupported."); this->RaiseError("Mixed types unsupported.");
} }
@ -206,30 +199,25 @@ public:
class GenerateEdges : public vtkm::worklet::WorkletMapPointToCell class GenerateEdges : public vtkm::worklet::WorkletMapPointToCell
{ {
public: public:
typedef void ControlSignature( CellSetIn cellset, WholeArrayOut< > edgeIds); typedef void ControlSignature(CellSetIn cellset, WholeArrayOut<> edgeIds);
typedef void ExecutionSignature(PointIndices, ThreadIndices, _2); typedef void ExecutionSignature(PointIndices, ThreadIndices, _2);
typedef _1 InputDomain; typedef _1 InputDomain;
template<typename ConnectivityInVec, template <typename ConnectivityInVec, typename ThreadIndicesType, typename IdPairTableType>
typename ThreadIndicesType, VTKM_EXEC void operator()(const ConnectivityInVec& connectivity,
typename IdPairTableType> const ThreadIndicesType threadIndices,
VTKM_EXEC const IdPairTableType& edgeIds) const
void operator()(const ConnectivityInVec &connectivity,
const ThreadIndicesType threadIndices,
const IdPairTableType &edgeIds) const
{ {
const vtkm::Id writeOffset = (threadIndices.GetInputIndex() * 12); const vtkm::Id writeOffset = (threadIndices.GetInputIndex() * 12);
const vtkm::IdComponent edgeTable[24] = { 0, 1, 1, 2, 3, 2, 0, 3, const vtkm::IdComponent edgeTable[24] = { 0, 1, 1, 2, 3, 2, 0, 3, 4, 5, 5, 6,
4, 5, 5, 6, 7, 6, 4, 7, 7, 6, 4, 7, 0, 4, 1, 5, 2, 6, 3, 7 };
0, 4, 1, 5, 2, 6, 3, 7 };
for(vtkm::Id i=0; i < 12; ++i) for (vtkm::Id i = 0; i < 12; ++i)
{ {
const vtkm::Id offset = (i*2); const vtkm::Id offset = (i * 2);
const vtkm::Id2 edge( connectivity[ edgeTable[offset] ], const vtkm::Id2 edge(connectivity[edgeTable[offset]], connectivity[edgeTable[offset + 1]]);
connectivity[ edgeTable[offset+1] ] ); edgeIds.Set(writeOffset + i, edge);
edgeIds.Set(writeOffset+i, edge);
} }
} }
}; };
@ -237,33 +225,24 @@ public:
class InterpolateField : public vtkm::worklet::WorkletMapField class InterpolateField : public vtkm::worklet::WorkletMapField
{ {
public: public:
typedef void ControlSignature(FieldIn< Id2Type > interpolation_ids, typedef void ControlSignature(FieldIn<Id2Type> interpolation_ids,
FieldIn< Scalar > interpolation_weights, FieldIn<Scalar> interpolation_weights, WholeArrayIn<> inputField,
WholeArrayIn<> inputField, FieldOut<> output);
FieldOut<> output
);
typedef void ExecutionSignature(_1, _2, _3, _4); typedef void ExecutionSignature(_1, _2, _3, _4);
typedef _1 InputDomain; typedef _1 InputDomain;
template <typename WeightType, typename T, typename S, typename D> template <typename WeightType, typename T, typename S, typename D>
VTKM_EXEC VTKM_EXEC void operator()(const vtkm::Id2& low_high, const WeightType& weight,
void operator()(const vtkm::Id2& low_high, const vtkm::exec::ExecutionWholeArrayConst<T, S, D>& inPortal,
const WeightType &weight, T& result) const
const vtkm::exec::ExecutionWholeArrayConst<T,S,D>& inPortal,
T &result) const
{ {
//fetch the low / high values from inPortal //fetch the low / high values from inPortal
result = vtkm::Lerp(inPortal.Get(low_high[0]), result = vtkm::Lerp(inPortal.Get(low_high[0]), inPortal.Get(low_high[1]), weight);
inPortal.Get(low_high[1]),
weight);
} }
template <typename WeightType, typename T, typename S, typename D, typename U> template <typename WeightType, typename T, typename S, typename D, typename U>
VTKM_EXEC VTKM_EXEC void operator()(const vtkm::Id2&, const WeightType&,
void operator()(const vtkm::Id2& , const vtkm::exec::ExecutionWholeArrayConst<T, S, D>&, U&) const
const WeightType &,
const vtkm::exec::ExecutionWholeArrayConst<T,S,D>& ,
U &) const
{ {
//the inPortal and result need to be the same type so this version only //the inPortal and result need to be the same type so this version only
//exists to generate code when using dynamic arrays //exists to generate code when using dynamic arrays
@ -278,13 +257,13 @@ public:
typedef void ControlSignature(FieldIn<Vec3>, FieldOut<Scalar>); typedef void ControlSignature(FieldIn<Vec3>, FieldOut<Scalar>);
typedef void ExecutionSignature(_1, _2); typedef void ExecutionSignature(_1, _2);
EvaluateImplicitFunction(const ImplicitFunction &function) EvaluateImplicitFunction(const ImplicitFunction& function)
: Function(function) : Function(function)
{ } {
}
template<typename VecType, typename ScalarType> template <typename VecType, typename ScalarType>
VTKM_EXEC VTKM_EXEC void operator()(const VecType& point, ScalarType& val) const
void operator()(const VecType &point, ScalarType &val) const
{ {
val = this->Function.Value(point); val = this->Function.Value(point);
} }
@ -300,13 +279,14 @@ public:
typedef void ControlSignature(FieldIn<Vec3>, FieldOut<Scalar>); typedef void ControlSignature(FieldIn<Vec3>, FieldOut<Scalar>);
typedef void ExecutionSignature(_1, _2); typedef void ExecutionSignature(_1, _2);
Evaluate2ImplicitFunctions(const T1 &f1, const T2 &f2) Evaluate2ImplicitFunctions(const T1& f1, const T2& f2)
: Function1(f1), Function2(f2) : Function1(f1)
{ } , Function2(f2)
{
}
template<typename VecType, typename ScalarType> template <typename VecType, typename ScalarType>
VTKM_EXEC VTKM_EXEC void operator()(const VecType& point, ScalarType& val) const
void operator()(const VecType &point, ScalarType &val) const
{ {
val = this->Function1.Value(point) + this->Function2.Value(point); val = this->Function1.Value(point) + this->Function2.Value(point);
} }
@ -316,35 +296,37 @@ private:
T2 Function2; T2 Function2;
}; };
struct ValueTypes : vtkm::ListTagBase<vtkm::Float32, vtkm::Float64>{}; struct ValueTypes : vtkm::ListTagBase<vtkm::Float32, vtkm::Float64>
{
};
struct InterpValueTypes : vtkm::ListTagBase<vtkm::Float32, struct InterpValueTypes
vtkm::Float64, : vtkm::ListTagBase<vtkm::Float32, vtkm::Float64, vtkm::Vec<vtkm::Float32, 3>,
vtkm::Vec< vtkm::Float32, 3>, vtkm::Vec<vtkm::Float64, 3>>
vtkm::Vec< vtkm::Float64, 3> {
>{}; };
using StorageListTag = ::vtkm::cont::StorageListTagBasic; using StorageListTag = ::vtkm::cont::StorageListTagBasic;
/// This class runs a series of micro-benchmarks to measure /// This class runs a series of micro-benchmarks to measure
/// performance of different field operations /// performance of different field operations
template<class DeviceAdapterTag> template <class DeviceAdapterTag>
class BenchmarkFieldAlgorithms { class BenchmarkFieldAlgorithms
{
typedef vtkm::cont::StorageTagBasic StorageTag; typedef vtkm::cont::StorageTagBasic StorageTag;
typedef vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag> Algorithm; typedef vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag> Algorithm;
typedef vtkm::cont::Timer<DeviceAdapterTag> Timer; typedef vtkm::cont::Timer<DeviceAdapterTag> Timer;
using ValueDynamicHandle = using ValueDynamicHandle = vtkm::cont::DynamicArrayHandleBase<ValueTypes, StorageListTag>;
vtkm::cont::DynamicArrayHandleBase<ValueTypes, StorageListTag>; using InterpDynamicHandle = vtkm::cont::DynamicArrayHandleBase<InterpValueTypes, StorageListTag>;
using InterpDynamicHandle =
vtkm::cont::DynamicArrayHandleBase<InterpValueTypes, StorageListTag>;
using IdDynamicHandle = using IdDynamicHandle =
vtkm::cont::DynamicArrayHandleBase<vtkm::TypeListTagIndex, StorageListTag>; vtkm::cont::DynamicArrayHandleBase<vtkm::TypeListTagIndex, StorageListTag>;
private: private:
template<typename Value> template <typename Value>
struct BenchBlackScholes { struct BenchBlackScholes
{
using ValueArrayHandle = vtkm::cont::ArrayHandle<Value, StorageTag>; using ValueArrayHandle = vtkm::cont::ArrayHandle<Value, StorageTag>;
ValueArrayHandle StockPrice; ValueArrayHandle StockPrice;
@ -359,14 +341,14 @@ private:
BenchBlackScholes() BenchBlackScholes()
{ {
std::mt19937 rng; std::mt19937 rng;
std::uniform_real_distribution<Value> price_range(Value(5.0f),Value(30.0f)); std::uniform_real_distribution<Value> price_range(Value(5.0f), Value(30.0f));
std::uniform_real_distribution<Value> strike_range(Value(1.0f),Value(100.0f)); std::uniform_real_distribution<Value> strike_range(Value(1.0f), Value(100.0f));
std::uniform_real_distribution<Value> year_range(Value(0.25f),Value(10.0f)); std::uniform_real_distribution<Value> year_range(Value(0.25f), Value(10.0f));
this->price.resize(ARRAY_SIZE); this->price.resize(ARRAY_SIZE);
this->strike.resize(ARRAY_SIZE); this->strike.resize(ARRAY_SIZE);
this->years.resize(ARRAY_SIZE); this->years.resize(ARRAY_SIZE);
for(std::size_t i=0; i < ARRAY_SIZE; ++i ) for (std::size_t i = 0; i < ARRAY_SIZE; ++i)
{ {
this->price[i] = price_range(rng); this->price[i] = price_range(rng);
this->strike[i] = strike_range(rng); this->strike[i] = strike_range(rng);
@ -387,14 +369,10 @@ private:
Timer timer; Timer timer;
BlackScholes<Value> worklet(RISKFREE, VOLATILITY); BlackScholes<Value> worklet(RISKFREE, VOLATILITY);
vtkm::worklet::DispatcherMapField< BlackScholes<Value> > dispatcher(worklet); vtkm::worklet::DispatcherMapField<BlackScholes<Value>> dispatcher(worklet);
dispatcher.Invoke( this->StockPrice, dispatcher.Invoke(this->StockPrice, this->OptionStrike, this->OptionYears, callResultHandle,
this->OptionStrike, putResultHandle);
this->OptionYears,
callResultHandle,
putResultHandle
);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
@ -402,7 +380,8 @@ private:
virtual std::string Type() const { return std::string("Static"); } virtual std::string Type() const { return std::string("Static"); }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "BlackScholes " description << "BlackScholes "
<< "[" << this->Type() << "] " << "[" << this->Type() << "] "
@ -411,8 +390,9 @@ private:
} }
}; };
template<typename Value> template <typename Value>
struct BenchBlackScholesDynamic : public BenchBlackScholes<Value> { struct BenchBlackScholesDynamic : public BenchBlackScholes<Value>
{
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
@ -427,30 +407,24 @@ private:
Timer timer; Timer timer;
BlackScholes<Value> worklet(RISKFREE, VOLATILITY); BlackScholes<Value> worklet(RISKFREE, VOLATILITY);
vtkm::worklet::DispatcherMapField< BlackScholes<Value> > dispatcher(worklet); vtkm::worklet::DispatcherMapField<BlackScholes<Value>> dispatcher(worklet);
dispatcher.Invoke( dstocks, dispatcher.Invoke(dstocks, dstrikes, doptions, callResultHandle, putResultHandle);
dstrikes,
doptions,
callResultHandle,
putResultHandle
);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
virtual std::string Type() const { return std::string("Dynamic"); } virtual std::string Type() const { return std::string("Dynamic"); }
}; };
VTKM_MAKE_BENCHMARK(BlackScholes, BenchBlackScholes); VTKM_MAKE_BENCHMARK(BlackScholes, BenchBlackScholes);
VTKM_MAKE_BENCHMARK(BlackScholesDynamic, BenchBlackScholesDynamic); VTKM_MAKE_BENCHMARK(BlackScholesDynamic, BenchBlackScholesDynamic);
template <typename Value>
template<typename Value> struct BenchMath
struct BenchMath { {
std::vector< vtkm::Vec<Value, 3> > input; std::vector<vtkm::Vec<Value, 3>> input;
vtkm::cont::ArrayHandle< vtkm::Vec<Value, 3>, StorageTag> InputHandle; vtkm::cont::ArrayHandle<vtkm::Vec<Value, 3>, StorageTag> InputHandle;
VTKM_CONT VTKM_CONT
BenchMath() BenchMath()
@ -459,11 +433,9 @@ private:
std::uniform_real_distribution<Value> range; std::uniform_real_distribution<Value> range;
this->input.resize(ARRAY_SIZE); this->input.resize(ARRAY_SIZE);
for(std::size_t i=0; i < ARRAY_SIZE; ++i ) for (std::size_t i = 0; i < ARRAY_SIZE; ++i)
{ {
this->input[i] = vtkm::Vec<Value, 3>(range(rng), this->input[i] = vtkm::Vec<Value, 3>(range(rng), range(rng), range(rng));
range(rng),
range(rng));
} }
this->InputHandle = vtkm::cont::make_ArrayHandle(this->input); this->InputHandle = vtkm::cont::make_ArrayHandle(this->input);
@ -477,10 +449,10 @@ private:
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapField< Mag >().Invoke( InputHandle, tempHandle1 ); vtkm::worklet::DispatcherMapField<Mag>().Invoke(InputHandle, tempHandle1);
vtkm::worklet::DispatcherMapField< Sin >().Invoke( tempHandle1, tempHandle2 ); vtkm::worklet::DispatcherMapField<Sin>().Invoke(tempHandle1, tempHandle2);
vtkm::worklet::DispatcherMapField< Square >().Invoke( tempHandle2, tempHandle1 ); vtkm::worklet::DispatcherMapField<Square>().Invoke(tempHandle2, tempHandle1);
vtkm::worklet::DispatcherMapField< Cos >().Invoke( tempHandle1, tempHandle2 ); vtkm::worklet::DispatcherMapField<Cos>().Invoke(tempHandle1, tempHandle2);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
@ -488,7 +460,8 @@ private:
virtual std::string Type() const { return std::string("Static"); } virtual std::string Type() const { return std::string("Static"); }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Magnitude -> Sine -> Square -> Cosine " description << "Magnitude -> Sine -> Square -> Cosine "
<< "[" << this->Type() << "] " << "[" << this->Type() << "] "
@ -497,15 +470,14 @@ private:
} }
}; };
template<typename Value> template <typename Value>
struct BenchMathDynamic : public BenchMath<Value> { struct BenchMathDynamic : public BenchMath<Value>
{
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
using MathTypes = vtkm::ListTagBase<vtkm::Vec< vtkm::Float32, 3>, using MathTypes = vtkm::ListTagBase<vtkm::Vec<vtkm::Float32, 3>, vtkm::Vec<vtkm::Float64, 3>>;
vtkm::Vec< vtkm::Float64, 3>
>;
vtkm::cont::ArrayHandle<Value> temp1; vtkm::cont::ArrayHandle<Value> temp1;
vtkm::cont::ArrayHandle<Value> temp2; vtkm::cont::ArrayHandle<Value> temp2;
@ -515,25 +487,25 @@ private:
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapField< Mag >().Invoke( dinput, dtemp1 ); vtkm::worklet::DispatcherMapField<Mag>().Invoke(dinput, dtemp1);
vtkm::worklet::DispatcherMapField< Sin >().Invoke( dtemp1, dtemp2 ); vtkm::worklet::DispatcherMapField<Sin>().Invoke(dtemp1, dtemp2);
vtkm::worklet::DispatcherMapField< Square >().Invoke( dtemp2, dtemp1 ); vtkm::worklet::DispatcherMapField<Square>().Invoke(dtemp2, dtemp1);
vtkm::worklet::DispatcherMapField< Cos >().Invoke( dtemp1, dtemp2 ); vtkm::worklet::DispatcherMapField<Cos>().Invoke(dtemp1, dtemp2);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
virtual std::string Type() const { return std::string("Dynamic"); } virtual std::string Type() const { return std::string("Dynamic"); }
}; };
VTKM_MAKE_BENCHMARK(Math, BenchMath); VTKM_MAKE_BENCHMARK(Math, BenchMath);
VTKM_MAKE_BENCHMARK(MathDynamic, BenchMathDynamic); VTKM_MAKE_BENCHMARK(MathDynamic, BenchMathDynamic);
template<typename Value> template <typename Value>
struct BenchFusedMath { struct BenchFusedMath
std::vector< vtkm::Vec<Value, 3> > input; {
vtkm::cont::ArrayHandle< vtkm::Vec<Value, 3>, StorageTag> InputHandle; std::vector<vtkm::Vec<Value, 3>> input;
vtkm::cont::ArrayHandle<vtkm::Vec<Value, 3>, StorageTag> InputHandle;
VTKM_CONT VTKM_CONT
BenchFusedMath() BenchFusedMath()
@ -542,11 +514,9 @@ private:
std::uniform_real_distribution<Value> range; std::uniform_real_distribution<Value> range;
this->input.resize(ARRAY_SIZE); this->input.resize(ARRAY_SIZE);
for(std::size_t i=0; i < ARRAY_SIZE; ++i ) for (std::size_t i = 0; i < ARRAY_SIZE; ++i)
{ {
this->input[i] = vtkm::Vec<Value, 3>(range(rng), this->input[i] = vtkm::Vec<Value, 3>(range(rng), range(rng), range(rng));
range(rng),
range(rng));
} }
this->InputHandle = vtkm::cont::make_ArrayHandle(this->input); this->InputHandle = vtkm::cont::make_ArrayHandle(this->input);
@ -558,14 +528,15 @@ private:
vtkm::cont::ArrayHandle<Value> result; vtkm::cont::ArrayHandle<Value> result;
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapField< FusedMath >().Invoke( this->InputHandle, result ); vtkm::worklet::DispatcherMapField<FusedMath>().Invoke(this->InputHandle, result);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
virtual std::string Type() const { return std::string("Static"); } virtual std::string Type() const { return std::string("Static"); }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Fused Magnitude -> Sine -> Square -> Cosine " description << "Fused Magnitude -> Sine -> Square -> Cosine "
<< "[" << this->Type() << "] " << "[" << this->Type() << "] "
@ -574,22 +545,21 @@ private:
} }
}; };
template<typename Value> template <typename Value>
struct BenchFusedMathDynamic : public BenchFusedMath<Value> { struct BenchFusedMathDynamic : public BenchFusedMath<Value>
{
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
using MathTypes = vtkm::ListTagBase<vtkm::Vec< vtkm::Float32, 3>, using MathTypes = vtkm::ListTagBase<vtkm::Vec<vtkm::Float32, 3>, vtkm::Vec<vtkm::Float64, 3>>;
vtkm::Vec< vtkm::Float64, 3>
>;
vtkm::cont::DynamicArrayHandleBase<MathTypes, StorageListTag> dinput(this->InputHandle); vtkm::cont::DynamicArrayHandleBase<MathTypes, StorageListTag> dinput(this->InputHandle);
vtkm::cont::ArrayHandle<Value, StorageTag> result; vtkm::cont::ArrayHandle<Value, StorageTag> result;
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapField< FusedMath >().Invoke( dinput, result ); vtkm::worklet::DispatcherMapField<FusedMath>().Invoke(dinput, result);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
@ -599,21 +569,22 @@ private:
VTKM_MAKE_BENCHMARK(FusedMath, BenchFusedMath); VTKM_MAKE_BENCHMARK(FusedMath, BenchFusedMath);
VTKM_MAKE_BENCHMARK(FusedMathDynamic, BenchFusedMathDynamic); VTKM_MAKE_BENCHMARK(FusedMathDynamic, BenchFusedMathDynamic);
template<typename Value> template <typename Value>
struct BenchEdgeInterp { struct BenchEdgeInterp
{
std::vector<vtkm::Float32> weight; std::vector<vtkm::Float32> weight;
std::vector<Value> field; std::vector<Value> field;
vtkm::cont::ArrayHandle< vtkm::Float32, StorageTag> WeightHandle; vtkm::cont::ArrayHandle<vtkm::Float32, StorageTag> WeightHandle;
vtkm::cont::ArrayHandle<Value, StorageTag> FieldHandle; vtkm::cont::ArrayHandle<Value, StorageTag> FieldHandle;
vtkm::cont::ArrayHandle< vtkm::Id2, StorageTag> EdgePairHandle; vtkm::cont::ArrayHandle<vtkm::Id2, StorageTag> EdgePairHandle;
VTKM_CONT VTKM_CONT
BenchEdgeInterp() BenchEdgeInterp()
{ {
using CT = typename vtkm::VecTraits<Value>::ComponentType; using CT = typename vtkm::VecTraits<Value>::ComponentType;
std::mt19937 rng; std::mt19937 rng;
std::uniform_real_distribution<vtkm::Float32> weight_range(0.0f,1.0f); std::uniform_real_distribution<vtkm::Float32> weight_range(0.0f, 1.0f);
std::uniform_real_distribution<CT> field_range; std::uniform_real_distribution<CT> field_range;
//basically the core challenge is to generate an array whose //basically the core challenge is to generate an array whose
@ -623,24 +594,23 @@ private:
//cell and place them into array. //cell and place them into array.
// //
vtkm::cont::CellSetStructured<3> cellSet; vtkm::cont::CellSetStructured<3> cellSet;
cellSet.SetPointDimensions( vtkm::Id3(CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) ); cellSet.SetPointDimensions(vtkm::Id3(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE));
const vtkm::Id numberOfEdges = cellSet.GetNumberOfCells() * 12; const vtkm::Id numberOfEdges = cellSet.GetNumberOfCells() * 12;
const std::size_t esize = static_cast<std::size_t>(numberOfEdges); const std::size_t esize = static_cast<std::size_t>(numberOfEdges);
const std::size_t psize = static_cast<std::size_t>(cellSet.GetNumberOfPoints()); const std::size_t psize = static_cast<std::size_t>(cellSet.GetNumberOfPoints());
this->EdgePairHandle.Allocate( numberOfEdges ); this->EdgePairHandle.Allocate(numberOfEdges);
vtkm::worklet::DispatcherMapTopology< GenerateEdges >().Invoke( cellSet, vtkm::worklet::DispatcherMapTopology<GenerateEdges>().Invoke(cellSet, this->EdgePairHandle);
this->EdgePairHandle );
this->weight.resize( esize ); this->weight.resize(esize);
for(std::size_t i=0; i < esize; ++i ) for (std::size_t i = 0; i < esize; ++i)
{ {
this->weight[i] = weight_range(rng); this->weight[i] = weight_range(rng);
} }
this->field.resize( psize ); this->field.resize(psize);
for(std::size_t i=0; i < psize; ++i ) for (std::size_t i = 0; i < psize; ++i)
{ {
this->field[i] = Value(field_range(rng)); this->field[i] = Value(field_range(rng));
} }
@ -655,21 +625,18 @@ private:
vtkm::cont::ArrayHandle<Value> result; vtkm::cont::ArrayHandle<Value> result;
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapField< vtkm::worklet::DispatcherMapField<InterpolateField, DeviceAdapterTag>().Invoke(
InterpolateField, this->EdgePairHandle, this->WeightHandle, this->FieldHandle, result);
DeviceAdapterTag>().Invoke(this->EdgePairHandle,
this->WeightHandle,
this->FieldHandle,
result);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
virtual std::string Type() const { return std::string("Static"); } virtual std::string Type() const { return std::string("Static"); }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
const std::size_t size = (CUBE_SIZE-1)*(CUBE_SIZE-1)*(CUBE_SIZE-1)*12; const std::size_t size = (CUBE_SIZE - 1) * (CUBE_SIZE - 1) * (CUBE_SIZE - 1) * 12;
description << "Edge Interpolation " description << "Edge Interpolation "
<< "[" << this->Type() << "] " << "[" << this->Type() << "] "
<< "with a domain size of: " << size; << "with a domain size of: " << size;
@ -677,8 +644,9 @@ private:
} }
}; };
template<typename Value> template <typename Value>
struct BenchEdgeInterpDynamic : public BenchEdgeInterp<Value> { struct BenchEdgeInterpDynamic : public BenchEdgeInterp<Value>
{
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
@ -689,12 +657,8 @@ private:
vtkm::cont::ArrayHandle<Value> result; vtkm::cont::ArrayHandle<Value> result;
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapField< vtkm::worklet::DispatcherMapField<InterpolateField, DeviceAdapterTag>().Invoke(
InterpolateField, dedges, dweight, dfield, result);
DeviceAdapterTag>().Invoke(dedges,
dweight,
dfield,
result);
return timer.GetElapsedTime(); return timer.GetElapsedTime();
} }
@ -704,7 +668,6 @@ private:
VTKM_MAKE_BENCHMARK(EdgeInterp, BenchEdgeInterp); VTKM_MAKE_BENCHMARK(EdgeInterp, BenchEdgeInterp);
VTKM_MAKE_BENCHMARK(EdgeInterpDynamic, BenchEdgeInterpDynamic); VTKM_MAKE_BENCHMARK(EdgeInterpDynamic, BenchEdgeInterpDynamic);
struct ImplicitFunctionBenchData struct ImplicitFunctionBenchData
{ {
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::FloatDefault, 3>> Points; vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::FloatDefault, 3>> Points;
@ -732,18 +695,19 @@ private:
portal.Set(i, vtkm::make_Vec(distx(rangen), disty(rangen), distz(rangen))); portal.Set(i, vtkm::make_Vec(distx(rangen), disty(rangen), distz(rangen)));
} }
data.Sphere1 = vtkm::cont::Sphere({0.22f, 0.33f, 0.44f}, 0.55f); data.Sphere1 = vtkm::cont::Sphere({ 0.22f, 0.33f, 0.44f }, 0.55f);
data.Sphere2 = vtkm::cont::Sphere({0.22f, 0.33f, 0.11f}, 0.77f); data.Sphere2 = vtkm::cont::Sphere({ 0.22f, 0.33f, 0.11f }, 0.77f);
return data; return data;
} }
template<typename Value> template <typename Value>
struct BenchImplicitFunction struct BenchImplicitFunction
{ {
BenchImplicitFunction() BenchImplicitFunction()
: Internal(MakeImplicitFunctionBenchData()) : Internal(MakeImplicitFunctionBenchData())
{ } {
}
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
@ -763,20 +727,20 @@ private:
{ {
std::stringstream description; std::stringstream description;
description << "Implicit Function (vtkm::cont::Sphere) on " description << "Implicit Function (vtkm::cont::Sphere) on "
<< Internal.Points.GetNumberOfValues() << Internal.Points.GetNumberOfValues() << " points";
<< " points";
return description.str(); return description.str();
} }
ImplicitFunctionBenchData Internal; ImplicitFunctionBenchData Internal;
}; };
template<typename Value> template <typename Value>
struct BenchDynamicImplicitFunction struct BenchDynamicImplicitFunction
{ {
BenchDynamicImplicitFunction() BenchDynamicImplicitFunction()
: Internal(MakeImplicitFunctionBenchData()) : Internal(MakeImplicitFunctionBenchData())
{ } {
}
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
@ -796,20 +760,20 @@ private:
{ {
std::stringstream description; std::stringstream description;
description << "Implicit Function (DynamicImplicitFunction) on " description << "Implicit Function (DynamicImplicitFunction) on "
<< Internal.Points.GetNumberOfValues() << Internal.Points.GetNumberOfValues() << " points";
<< " points";
return description.str(); return description.str();
} }
ImplicitFunctionBenchData Internal; ImplicitFunctionBenchData Internal;
}; };
template<typename Value> template <typename Value>
struct Bench2ImplicitFunctions struct Bench2ImplicitFunctions
{ {
Bench2ImplicitFunctions() Bench2ImplicitFunctions()
: Internal(MakeImplicitFunctionBenchData()) : Internal(MakeImplicitFunctionBenchData())
{ } {
}
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
@ -829,26 +793,26 @@ private:
{ {
std::stringstream description; std::stringstream description;
description << "Implicit Function 2x(vtkm::cont::Sphere) on " description << "Implicit Function 2x(vtkm::cont::Sphere) on "
<< Internal.Points.GetNumberOfValues() << Internal.Points.GetNumberOfValues() << " points";
<< " points";
return description.str(); return description.str();
} }
ImplicitFunctionBenchData Internal; ImplicitFunctionBenchData Internal;
}; };
template<typename Value> template <typename Value>
struct Bench2DynamicImplicitFunctions struct Bench2DynamicImplicitFunctions
{ {
Bench2DynamicImplicitFunctions() Bench2DynamicImplicitFunctions()
: Internal(MakeImplicitFunctionBenchData()) : Internal(MakeImplicitFunctionBenchData())
{ } {
}
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
using EvalWorklet = Evaluate2ImplicitFunctions<vtkm::exec::ImplicitFunction, using EvalWorklet =
vtkm::exec::ImplicitFunction>; Evaluate2ImplicitFunctions<vtkm::exec::ImplicitFunction, vtkm::exec::ImplicitFunction>;
using EvalDispatcher = vtkm::worklet::DispatcherMapField<EvalWorklet, DeviceAdapterTag>; using EvalDispatcher = vtkm::worklet::DispatcherMapField<EvalWorklet, DeviceAdapterTag>;
EvalWorklet eval(Internal.Sphere1.PrepareForExecution(DeviceAdapterTag()), EvalWorklet eval(Internal.Sphere1.PrepareForExecution(DeviceAdapterTag()),
@ -864,8 +828,7 @@ private:
{ {
std::stringstream description; std::stringstream description;
description << "Implicit Function 2x(DynamicImplicitFunction) on " description << "Implicit Function 2x(DynamicImplicitFunction) on "
<< Internal.Points.GetNumberOfValues() << Internal.Points.GetNumberOfValues() << " points";
<< " points";
return description.str(); return description.str();
} }
@ -878,35 +841,40 @@ private:
VTKM_MAKE_BENCHMARK(ImplicitFunctionDynamic2, Bench2DynamicImplicitFunctions); VTKM_MAKE_BENCHMARK(ImplicitFunctionDynamic2, Bench2DynamicImplicitFunctions);
public: public:
static VTKM_CONT int Run(int benchmarks)
static VTKM_CONT int Run(int benchmarks){ {
std::cout << DIVIDER << "\nRunning Field Algorithm benchmarks\n"; std::cout << DIVIDER << "\nRunning Field Algorithm benchmarks\n";
if (benchmarks & BLACK_SCHOLES) { if (benchmarks & BLACK_SCHOLES)
{
std::cout << DIVIDER << "\nBenchmarking BlackScholes\n"; std::cout << DIVIDER << "\nBenchmarking BlackScholes\n";
VTKM_RUN_BENCHMARK(BlackScholes, ValueTypes()); VTKM_RUN_BENCHMARK(BlackScholes, ValueTypes());
VTKM_RUN_BENCHMARK(BlackScholesDynamic, ValueTypes()); VTKM_RUN_BENCHMARK(BlackScholesDynamic, ValueTypes());
} }
if (benchmarks & MATH){ if (benchmarks & MATH)
{
std::cout << DIVIDER << "\nBenchmarking Multiple Math Worklets\n"; std::cout << DIVIDER << "\nBenchmarking Multiple Math Worklets\n";
VTKM_RUN_BENCHMARK(Math, ValueTypes()); VTKM_RUN_BENCHMARK(Math, ValueTypes());
VTKM_RUN_BENCHMARK(MathDynamic, ValueTypes()); VTKM_RUN_BENCHMARK(MathDynamic, ValueTypes());
} }
if (benchmarks & FUSED_MATH){ if (benchmarks & FUSED_MATH)
{
std::cout << DIVIDER << "\nBenchmarking Single Fused Math Worklet\n"; std::cout << DIVIDER << "\nBenchmarking Single Fused Math Worklet\n";
VTKM_RUN_BENCHMARK(FusedMath, ValueTypes()); VTKM_RUN_BENCHMARK(FusedMath, ValueTypes());
VTKM_RUN_BENCHMARK(FusedMathDynamic, ValueTypes()); VTKM_RUN_BENCHMARK(FusedMathDynamic, ValueTypes());
} }
if (benchmarks & INTERPOLATE_FIELD){ if (benchmarks & INTERPOLATE_FIELD)
{
std::cout << DIVIDER << "\nBenchmarking Edge Based Field InterpolationWorklet\n"; std::cout << DIVIDER << "\nBenchmarking Edge Based Field InterpolationWorklet\n";
VTKM_RUN_BENCHMARK(EdgeInterp, InterpValueTypes()); VTKM_RUN_BENCHMARK(EdgeInterp, InterpValueTypes());
VTKM_RUN_BENCHMARK(EdgeInterpDynamic, InterpValueTypes()); VTKM_RUN_BENCHMARK(EdgeInterpDynamic, InterpValueTypes());
} }
if (benchmarks & IMPLICIT_FUNCTION) { if (benchmarks & IMPLICIT_FUNCTION)
{
using FloatDefaultType = vtkm::ListTagBase<vtkm::FloatDefault>; using FloatDefaultType = vtkm::ListTagBase<vtkm::FloatDefault>;
std::cout << "\nBenchmarking Implicit Function\n"; std::cout << "\nBenchmarking Implicit Function\n";
@ -920,20 +888,21 @@ public:
} }
}; };
#undef ARRAY_SIZE #undef ARRAY_SIZE
} }
} // namespace vtkm::benchmarking } // namespace vtkm::benchmarking
int main(int argc, char *argv[]) int main(int argc, char* argv[])
{ {
int benchmarks = 0; int benchmarks = 0;
if (argc < 2){ if (argc < 2)
{
benchmarks = vtkm::benchmarking::ALL; benchmarks = vtkm::benchmarking::ALL;
} }
else { else
for (int i = 1; i < argc; ++i){ {
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i]; std::string arg = argv[i];
std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower); std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
if (arg == "blackscholes") if (arg == "blackscholes")
@ -965,6 +934,6 @@ int main(int argc, char *argv[])
} }
//now actually execute the benchmarks //now actually execute the benchmarks
return vtkm::benchmarking::BenchmarkFieldAlgorithms return vtkm::benchmarking::BenchmarkFieldAlgorithms<VTKM_DEFAULT_DEVICE_ADAPTER_TAG>::Run(
<VTKM_DEFAULT_DEVICE_ADAPTER_TAG>::Run(benchmarks); benchmarks);
} }

@ -35,41 +35,39 @@
#include <random> #include <random>
#include <string> #include <string>
namespace vtkm { namespace vtkm
namespace benchmarking { {
namespace benchmarking
{
#define CUBE_SIZE 256 #define CUBE_SIZE 256
const static std::string DIVIDER(40, '-'); const static std::string DIVIDER(40, '-');
enum BenchmarkName { enum BenchmarkName
{
CELL_TO_POINT = 1 << 1, CELL_TO_POINT = 1 << 1,
POINT_TO_CELL = 1 << 2, POINT_TO_CELL = 1 << 2,
MC_CLASSIFY = 1 << 3, MC_CLASSIFY = 1 << 3,
ALL = CELL_TO_POINT | ALL = CELL_TO_POINT | POINT_TO_CELL | MC_CLASSIFY
POINT_TO_CELL |
MC_CLASSIFY
}; };
class AveragePointToCell : public vtkm::worklet::WorkletMapPointToCell class AveragePointToCell : public vtkm::worklet::WorkletMapPointToCell
{ {
public: public:
typedef void ControlSignature(FieldInPoint<> inPoints, typedef void ControlSignature(FieldInPoint<> inPoints, CellSetIn cellset,
CellSetIn cellset,
FieldOutCell<> outCells); FieldOutCell<> outCells);
typedef void ExecutionSignature(_1, PointCount, _3); typedef void ExecutionSignature(_1, PointCount, _3);
typedef _2 InputDomain; typedef _2 InputDomain;
template<typename PointValueVecType, typename OutType> template <typename PointValueVecType, typename OutType>
VTKM_EXEC VTKM_EXEC void operator()(const PointValueVecType& pointValues,
void operator()(const PointValueVecType &pointValues, const vtkm::IdComponent& numPoints, OutType& average) const
const vtkm::IdComponent &numPoints,
OutType &average) const
{ {
OutType sum = static_cast<OutType>(pointValues[0]); OutType sum = static_cast<OutType>(pointValues[0]);
for (vtkm::IdComponent pointIndex = 1; pointIndex < numPoints; ++pointIndex) for (vtkm::IdComponent pointIndex = 1; pointIndex < numPoints; ++pointIndex)
{ {
sum = sum + static_cast<OutType>(pointValues[pointIndex]); sum = sum + static_cast<OutType>(pointValues[pointIndex]);
} }
average = sum / static_cast<OutType>(numPoints); average = sum / static_cast<OutType>(numPoints);
} }
@ -78,17 +76,13 @@ public:
class AverageCellToPoint : public vtkm::worklet::WorkletMapCellToPoint class AverageCellToPoint : public vtkm::worklet::WorkletMapCellToPoint
{ {
public: public:
typedef void ControlSignature(FieldInCell<> inCells, typedef void ControlSignature(FieldInCell<> inCells, CellSetIn topology, FieldOut<> outPoints);
CellSetIn topology,
FieldOut<> outPoints);
typedef void ExecutionSignature(_1, _3, CellCount); typedef void ExecutionSignature(_1, _3, CellCount);
typedef _2 InputDomain; typedef _2 InputDomain;
template<typename CellVecType, typename OutType> template <typename CellVecType, typename OutType>
VTKM_EXEC VTKM_EXEC void operator()(const CellVecType& cellValues, OutType& avgVal,
void operator()(const CellVecType &cellValues, const vtkm::IdComponent& numCellIDs) const
OutType &avgVal,
const vtkm::IdComponent &numCellIDs) const
{ {
//simple functor that returns the average cell Value. //simple functor that returns the average cell Value.
avgVal = static_cast<OutType>(cellValues[0]); avgVal = static_cast<OutType>(cellValues[0]);
@ -101,107 +95,102 @@ public:
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
template<typename T> template <typename T>
class Classification : public vtkm::worklet::WorkletMapPointToCell class Classification : public vtkm::worklet::WorkletMapPointToCell
{ {
public: public:
typedef void ControlSignature( typedef void ControlSignature(FieldInPoint<> inNodes, CellSetIn cellset,
FieldInPoint<> inNodes, FieldOutCell<IdComponentType> outCaseId);
CellSetIn cellset,
FieldOutCell< IdComponentType > outCaseId);
typedef void ExecutionSignature(_1, _3); typedef void ExecutionSignature(_1, _3);
typedef _2 InputDomain; typedef _2 InputDomain;
T IsoValue; T IsoValue;
VTKM_CONT VTKM_CONT
Classification(T isovalue) : Classification(T isovalue)
IsoValue(isovalue) : IsoValue(isovalue)
{ {
} }
template<typename FieldInType> template <typename FieldInType>
VTKM_EXEC VTKM_EXEC void operator()(const FieldInType& fieldIn, vtkm::IdComponent& caseNumber) const
void operator()(const FieldInType &fieldIn,
vtkm::IdComponent &caseNumber) const
{ {
typedef typename vtkm::VecTraits<FieldInType>::ComponentType FieldType; typedef typename vtkm::VecTraits<FieldInType>::ComponentType FieldType;
const FieldType iso = static_cast<FieldType>(this->IsoValue); const FieldType iso = static_cast<FieldType>(this->IsoValue);
caseNumber= ((fieldIn[0] > iso) | caseNumber = ((fieldIn[0] > iso) | (fieldIn[1] > iso) << 1 | (fieldIn[2] > iso) << 2 |
(fieldIn[1] > iso) << 1 | (fieldIn[3] > iso) << 3 | (fieldIn[4] > iso) << 4 | (fieldIn[5] > iso) << 5 |
(fieldIn[2] > iso) << 2 | (fieldIn[6] > iso) << 6 | (fieldIn[7] > iso) << 7);
(fieldIn[3] > iso) << 3 |
(fieldIn[4] > iso) << 4 |
(fieldIn[5] > iso) << 5 |
(fieldIn[6] > iso) << 6 |
(fieldIn[7] > iso) << 7);
} }
}; };
struct ValueTypes : vtkm::ListTagBase<vtkm::UInt32, vtkm::Int32, vtkm::Int64, struct ValueTypes
vtkm::Float32, vtkm::Float64 >{}; : vtkm::ListTagBase<vtkm::UInt32, vtkm::Int32, vtkm::Int64, vtkm::Float32, vtkm::Float64>
{
};
using StorageListTag = ::vtkm::cont::StorageListTagBasic; using StorageListTag = ::vtkm::cont::StorageListTagBasic;
/// This class runs a series of micro-benchmarks to measure /// This class runs a series of micro-benchmarks to measure
/// performance of different field operations /// performance of different field operations
template<class DeviceAdapterTag> template <class DeviceAdapterTag>
class BenchmarkTopologyAlgorithms { class BenchmarkTopologyAlgorithms
{
typedef vtkm::cont::StorageTagBasic StorageTag; typedef vtkm::cont::StorageTagBasic StorageTag;
typedef vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag> Algorithm; typedef vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag> Algorithm;
typedef vtkm::cont::Timer<DeviceAdapterTag> Timer; typedef vtkm::cont::Timer<DeviceAdapterTag> Timer;
using ValueDynamicHandle = using ValueDynamicHandle = vtkm::cont::DynamicArrayHandleBase<ValueTypes, StorageListTag>;
vtkm::cont::DynamicArrayHandleBase<ValueTypes, StorageListTag>;
private: private:
template <typename T, typename Enable = void>
struct NumberGenerator
{
};
template<typename T, typename Enable= void> struct NumberGenerator {}; template <typename T>
struct NumberGenerator<T, typename std::enable_if<std::is_floating_point<T>::value>::type>
template<typename T>
struct NumberGenerator<T,
typename std::enable_if<
std::is_floating_point<T>::value
>::type
>
{ {
std::mt19937 rng; std::mt19937 rng;
std::uniform_real_distribution<T> distribution; std::uniform_real_distribution<T> distribution;
NumberGenerator(T low, T high): rng(), distribution(low,high) {} NumberGenerator(T low, T high)
: rng()
, distribution(low, high)
{
}
T next() { return distribution(rng); } T next() { return distribution(rng); }
}; };
template<typename T> template <typename T>
struct NumberGenerator<T, struct NumberGenerator<T, typename std::enable_if<!std::is_floating_point<T>::value>::type>
typename std::enable_if<
!std::is_floating_point<T>::value
>::type
>
{ {
std::mt19937 rng; std::mt19937 rng;
std::uniform_int_distribution<T> distribution; std::uniform_int_distribution<T> distribution;
NumberGenerator(T low, T high): rng(), distribution(low,high) {} NumberGenerator(T low, T high)
: rng()
, distribution(low, high)
{
}
T next() { return distribution(rng); } T next() { return distribution(rng); }
}; };
template<typename Value> template <typename Value>
struct BenchCellToPointAvg { struct BenchCellToPointAvg
std::vector< Value > input; {
vtkm::cont::ArrayHandle< Value, StorageTag> InputHandle; std::vector<Value> input;
vtkm::cont::ArrayHandle<Value, StorageTag> InputHandle;
std::size_t DomainSize; std::size_t DomainSize;
VTKM_CONT VTKM_CONT
BenchCellToPointAvg() BenchCellToPointAvg()
{ {
NumberGenerator<Value> generator(static_cast<Value>(1.0), NumberGenerator<Value> generator(static_cast<Value>(1.0), static_cast<Value>(100.0));
static_cast<Value>(100.0));
//cube size is points in each dim //cube size is points in each dim
this->DomainSize = (CUBE_SIZE-1)*(CUBE_SIZE-1)*(CUBE_SIZE-1); this->DomainSize = (CUBE_SIZE - 1) * (CUBE_SIZE - 1) * (CUBE_SIZE - 1);
this->input.resize( DomainSize ); this->input.resize(DomainSize);
for(std::size_t i=0; i < DomainSize; ++i ) for (std::size_t i = 0; i < DomainSize; ++i)
{ {
this->input[i] = generator.next(); this->input[i] = generator.next();
} }
@ -212,15 +201,13 @@ private:
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
vtkm::cont::CellSetStructured<3> cellSet; vtkm::cont::CellSetStructured<3> cellSet;
cellSet.SetPointDimensions( vtkm::Id3(CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) ); cellSet.SetPointDimensions(vtkm::Id3(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE));
vtkm::cont::ArrayHandle<Value,StorageTag> result; vtkm::cont::ArrayHandle<Value, StorageTag> result;
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapTopology< AverageCellToPoint > dispatcher; vtkm::worklet::DispatcherMapTopology<AverageCellToPoint> dispatcher;
dispatcher.Invoke( this->InputHandle, dispatcher.Invoke(this->InputHandle, cellSet, result);
cellSet,
result);
//result.SyncControlArray(); //result.SyncControlArray();
return timer.GetElapsedTime(); return timer.GetElapsedTime();
@ -229,7 +216,8 @@ private:
virtual std::string Type() const { return std::string("Static"); } virtual std::string Type() const { return std::string("Static"); }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Computing Cell To Point Average " description << "Computing Cell To Point Average "
@ -239,25 +227,24 @@ private:
} }
}; };
template<typename Value> template <typename Value>
struct BenchCellToPointAvgDynamic : public BenchCellToPointAvg<Value> { struct BenchCellToPointAvgDynamic : public BenchCellToPointAvg<Value>
{
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
vtkm::cont::CellSetStructured<3> cellSet; vtkm::cont::CellSetStructured<3> cellSet;
cellSet.SetPointDimensions( vtkm::Id3(CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) ); cellSet.SetPointDimensions(vtkm::Id3(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE));
ValueDynamicHandle dinput(this->InputHandle); ValueDynamicHandle dinput(this->InputHandle);
vtkm::cont::ArrayHandle<Value,StorageTag> result; vtkm::cont::ArrayHandle<Value, StorageTag> result;
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapTopology< AverageCellToPoint > dispatcher; vtkm::worklet::DispatcherMapTopology<AverageCellToPoint> dispatcher;
dispatcher.Invoke( dinput, dispatcher.Invoke(dinput, cellSet, result);
cellSet,
result);
//result.SyncControlArray(); //result.SyncControlArray();
return timer.GetElapsedTime(); return timer.GetElapsedTime();
@ -269,21 +256,21 @@ private:
VTKM_MAKE_BENCHMARK(CellToPointAvg, BenchCellToPointAvg); VTKM_MAKE_BENCHMARK(CellToPointAvg, BenchCellToPointAvg);
VTKM_MAKE_BENCHMARK(CellToPointAvgDynamic, BenchCellToPointAvgDynamic); VTKM_MAKE_BENCHMARK(CellToPointAvgDynamic, BenchCellToPointAvgDynamic);
template<typename Value> template <typename Value>
struct BenchPointToCellAvg { struct BenchPointToCellAvg
std::vector< Value > input; {
vtkm::cont::ArrayHandle< Value, StorageTag> InputHandle; std::vector<Value> input;
vtkm::cont::ArrayHandle<Value, StorageTag> InputHandle;
std::size_t DomainSize; std::size_t DomainSize;
VTKM_CONT VTKM_CONT
BenchPointToCellAvg() BenchPointToCellAvg()
{ {
NumberGenerator<Value> generator(static_cast<Value>(1.0), NumberGenerator<Value> generator(static_cast<Value>(1.0), static_cast<Value>(100.0));
static_cast<Value>(100.0));
this->DomainSize = (CUBE_SIZE)*(CUBE_SIZE)*(CUBE_SIZE); this->DomainSize = (CUBE_SIZE) * (CUBE_SIZE) * (CUBE_SIZE);
this->input.resize( DomainSize ); this->input.resize(DomainSize);
for(std::size_t i=0; i < DomainSize; ++i ) for (std::size_t i = 0; i < DomainSize; ++i)
{ {
this->input[i] = generator.next(); this->input[i] = generator.next();
} }
@ -294,15 +281,13 @@ private:
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
vtkm::cont::CellSetStructured<3> cellSet; vtkm::cont::CellSetStructured<3> cellSet;
cellSet.SetPointDimensions( vtkm::Id3(CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) ); cellSet.SetPointDimensions(vtkm::Id3(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE));
vtkm::cont::ArrayHandle<Value,StorageTag> result; vtkm::cont::ArrayHandle<Value, StorageTag> result;
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapTopology< AveragePointToCell > dispatcher; vtkm::worklet::DispatcherMapTopology<AveragePointToCell> dispatcher;
dispatcher.Invoke( this->InputHandle, dispatcher.Invoke(this->InputHandle, cellSet, result);
cellSet,
result);
//result.SyncControlArray(); //result.SyncControlArray();
return timer.GetElapsedTime(); return timer.GetElapsedTime();
@ -311,7 +296,8 @@ private:
virtual std::string Type() const { return std::string("Static"); } virtual std::string Type() const { return std::string("Static"); }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Computing Point To Cell Average " description << "Computing Point To Cell Average "
@ -321,24 +307,23 @@ private:
} }
}; };
template<typename Value> template <typename Value>
struct BenchPointToCellAvgDynamic : public BenchPointToCellAvg<Value> { struct BenchPointToCellAvgDynamic : public BenchPointToCellAvg<Value>
{
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
vtkm::cont::CellSetStructured<3> cellSet; vtkm::cont::CellSetStructured<3> cellSet;
cellSet.SetPointDimensions( vtkm::Id3(CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) ); cellSet.SetPointDimensions(vtkm::Id3(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE));
ValueDynamicHandle dinput(this->InputHandle); ValueDynamicHandle dinput(this->InputHandle);
vtkm::cont::ArrayHandle<Value,StorageTag> result; vtkm::cont::ArrayHandle<Value, StorageTag> result;
Timer timer; Timer timer;
vtkm::worklet::DispatcherMapTopology< AveragePointToCell > dispatcher; vtkm::worklet::DispatcherMapTopology<AveragePointToCell> dispatcher;
dispatcher.Invoke( dinput, dispatcher.Invoke(dinput, cellSet, result);
cellSet,
result);
//result.SyncControlArray(); //result.SyncControlArray();
return timer.GetElapsedTime(); return timer.GetElapsedTime();
@ -350,22 +335,22 @@ private:
VTKM_MAKE_BENCHMARK(PointToCellAvg, BenchPointToCellAvg); VTKM_MAKE_BENCHMARK(PointToCellAvg, BenchPointToCellAvg);
VTKM_MAKE_BENCHMARK(PointToCellAvgDynamic, BenchPointToCellAvgDynamic); VTKM_MAKE_BENCHMARK(PointToCellAvgDynamic, BenchPointToCellAvgDynamic);
template<typename Value> template <typename Value>
struct BenchClassification { struct BenchClassification
std::vector< Value > input; {
vtkm::cont::ArrayHandle< Value, StorageTag> InputHandle; std::vector<Value> input;
vtkm::cont::ArrayHandle<Value, StorageTag> InputHandle;
Value IsoValue; Value IsoValue;
size_t DomainSize; size_t DomainSize;
VTKM_CONT VTKM_CONT
BenchClassification() BenchClassification()
{ {
NumberGenerator<Value> generator(static_cast<Value>(1.0), NumberGenerator<Value> generator(static_cast<Value>(1.0), static_cast<Value>(100.0));
static_cast<Value>(100.0));
this->DomainSize = (CUBE_SIZE)*(CUBE_SIZE)*(CUBE_SIZE); this->DomainSize = (CUBE_SIZE) * (CUBE_SIZE) * (CUBE_SIZE);
this->input.resize( DomainSize ); this->input.resize(DomainSize);
for(std::size_t i=0; i < DomainSize; ++i ) for (std::size_t i = 0; i < DomainSize; ++i)
{ {
this->input[i] = generator.next(); this->input[i] = generator.next();
} }
@ -377,18 +362,16 @@ private:
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
vtkm::cont::CellSetStructured<3> cellSet; vtkm::cont::CellSetStructured<3> cellSet;
cellSet.SetPointDimensions( vtkm::Id3(CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) ); cellSet.SetPointDimensions(vtkm::Id3(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE));
vtkm::cont::ArrayHandle< vtkm::IdComponent, StorageTag> result; vtkm::cont::ArrayHandle<vtkm::IdComponent, StorageTag> result;
ValueDynamicHandle dinput(this->InputHandle); ValueDynamicHandle dinput(this->InputHandle);
Timer timer; Timer timer;
Classification<Value> worklet(this->IsoValue); Classification<Value> worklet(this->IsoValue);
vtkm::worklet::DispatcherMapTopology< Classification<Value> > dispatcher(worklet); vtkm::worklet::DispatcherMapTopology<Classification<Value>> dispatcher(worklet);
dispatcher.Invoke( dinput, dispatcher.Invoke(dinput, cellSet, result);
cellSet,
result);
//result.SyncControlArray(); //result.SyncControlArray();
return timer.GetElapsedTime(); return timer.GetElapsedTime();
@ -397,7 +380,8 @@ private:
virtual std::string Type() const { return std::string("Static"); } virtual std::string Type() const { return std::string("Static"); }
VTKM_CONT VTKM_CONT
std::string Description() const { std::string Description() const
{
std::stringstream description; std::stringstream description;
description << "Computing Marching Cubes Classification " description << "Computing Marching Cubes Classification "
@ -407,22 +391,21 @@ private:
} }
}; };
template<typename Value> template <typename Value>
struct BenchClassificationDynamic : public BenchClassification<Value> { struct BenchClassificationDynamic : public BenchClassification<Value>
{
VTKM_CONT VTKM_CONT
vtkm::Float64 operator()() vtkm::Float64 operator()()
{ {
vtkm::cont::CellSetStructured<3> cellSet; vtkm::cont::CellSetStructured<3> cellSet;
cellSet.SetPointDimensions( vtkm::Id3(CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) ); cellSet.SetPointDimensions(vtkm::Id3(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE));
vtkm::cont::ArrayHandle< vtkm::IdComponent, StorageTag> result; vtkm::cont::ArrayHandle<vtkm::IdComponent, StorageTag> result;
Timer timer; Timer timer;
Classification<Value> worklet(this->IsoValue); Classification<Value> worklet(this->IsoValue);
vtkm::worklet::DispatcherMapTopology< Classification<Value> > dispatcher(worklet); vtkm::worklet::DispatcherMapTopology<Classification<Value>> dispatcher(worklet);
dispatcher.Invoke( this->InputHandle, dispatcher.Invoke(this->InputHandle, cellSet, result);
cellSet,
result);
//result.SyncControlArray(); //result.SyncControlArray();
return timer.GetElapsedTime(); return timer.GetElapsedTime();
@ -435,23 +418,26 @@ private:
VTKM_MAKE_BENCHMARK(ClassificationDynamic, BenchClassificationDynamic); VTKM_MAKE_BENCHMARK(ClassificationDynamic, BenchClassificationDynamic);
public: public:
static VTKM_CONT int Run(int benchmarks)
static VTKM_CONT int Run(int benchmarks){ {
std::cout << DIVIDER << "\nRunning Topology Algorithm benchmarks\n"; std::cout << DIVIDER << "\nRunning Topology Algorithm benchmarks\n";
if (benchmarks & CELL_TO_POINT) { if (benchmarks & CELL_TO_POINT)
{
std::cout << DIVIDER << "\nBenchmarking Cell To Point Average\n"; std::cout << DIVIDER << "\nBenchmarking Cell To Point Average\n";
VTKM_RUN_BENCHMARK(CellToPointAvg, ValueTypes()); VTKM_RUN_BENCHMARK(CellToPointAvg, ValueTypes());
VTKM_RUN_BENCHMARK(CellToPointAvgDynamic, ValueTypes()); VTKM_RUN_BENCHMARK(CellToPointAvgDynamic, ValueTypes());
} }
if (benchmarks & POINT_TO_CELL){ if (benchmarks & POINT_TO_CELL)
{
std::cout << DIVIDER << "\nBenchmarking Point to Cell Average\n"; std::cout << DIVIDER << "\nBenchmarking Point to Cell Average\n";
VTKM_RUN_BENCHMARK(PointToCellAvg, ValueTypes()); VTKM_RUN_BENCHMARK(PointToCellAvg, ValueTypes());
VTKM_RUN_BENCHMARK(PointToCellAvgDynamic, ValueTypes()); VTKM_RUN_BENCHMARK(PointToCellAvgDynamic, ValueTypes());
} }
if (benchmarks & MC_CLASSIFY){ if (benchmarks & MC_CLASSIFY)
{
std::cout << DIVIDER << "\nBenchmarking Hex/Voxel MC Classification\n"; std::cout << DIVIDER << "\nBenchmarking Hex/Voxel MC Classification\n";
VTKM_RUN_BENCHMARK(Classification, ValueTypes()); VTKM_RUN_BENCHMARK(Classification, ValueTypes());
VTKM_RUN_BENCHMARK(ClassificationDynamic, ValueTypes()); VTKM_RUN_BENCHMARK(ClassificationDynamic, ValueTypes());
@ -461,20 +447,21 @@ public:
} }
}; };
#undef ARRAY_SIZE #undef ARRAY_SIZE
} }
} // namespace vtkm::benchmarking } // namespace vtkm::benchmarking
int main(int argc, char *argv[]) int main(int argc, char* argv[])
{ {
int benchmarks = 0; int benchmarks = 0;
if (argc < 2){ if (argc < 2)
{
benchmarks = vtkm::benchmarking::ALL; benchmarks = vtkm::benchmarking::ALL;
} }
else { else
for (int i = 1; i < argc; ++i){ {
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i]; std::string arg = argv[i];
std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower); std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
if (arg == "celltopoint") if (arg == "celltopoint")
@ -489,7 +476,8 @@ int main(int argc, char *argv[])
{ {
benchmarks |= vtkm::benchmarking::MC_CLASSIFY; benchmarks |= vtkm::benchmarking::MC_CLASSIFY;
} }
else { else
{
std::cout << "Unrecognized benchmark: " << argv[i] << std::endl; std::cout << "Unrecognized benchmark: " << argv[i] << std::endl;
return 1; return 1;
} }
@ -497,6 +485,6 @@ int main(int argc, char *argv[])
} }
//now actually execute the benchmarks //now actually execute the benchmarks
return vtkm::benchmarking::BenchmarkTopologyAlgorithms return vtkm::benchmarking::BenchmarkTopologyAlgorithms<VTKM_DEFAULT_DEVICE_ADAPTER_TAG>::Run(
<VTKM_DEFAULT_DEVICE_ADAPTER_TAG>::Run(benchmarks); benchmarks);
} }

@ -87,13 +87,14 @@
* instance of your benchmark for the type being benchmarked. The VA_ARGS are used to * instance of your benchmark for the type being benchmarked. The VA_ARGS are used to
* pass any extra arguments needed by your benchmark * pass any extra arguments needed by your benchmark
*/ */
#define VTKM_MAKE_BENCHMARK(Name, Bench, ...) \ #define VTKM_MAKE_BENCHMARK(Name, Bench, ...) \
struct MakeBench##Name { \ struct MakeBench##Name \
template<typename Value> \ { \
VTKM_CONT \ template <typename Value> \
Bench<Value> operator()(const Value vtkmNotUsed(v)) const { \ VTKM_CONT Bench<Value> operator()(const Value vtkmNotUsed(v)) const \
return Bench<Value>(__VA_ARGS__); \ { \
} \ return Bench<Value>(__VA_ARGS__); \
} \
} }
/* /*
@ -101,20 +102,26 @@
* You must have previously defined a maker functor with VTKM_MAKE_BENCHMARK that this * You must have previously defined a maker functor with VTKM_MAKE_BENCHMARK that this
* macro will look for and use * macro will look for and use
*/ */
#define VTKM_RUN_BENCHMARK(Name, Types) \ #define VTKM_RUN_BENCHMARK(Name, Types) \
vtkm::benchmarking::BenchmarkTypes(MakeBench##Name(), (Types)) vtkm::benchmarking::BenchmarkTypes(MakeBench##Name(), (Types))
namespace vtkm { namespace vtkm
namespace benchmarking { {
namespace stats { namespace benchmarking
{
namespace stats
{
// Checks that the sequence is sorted, returns true if it's sorted, false // Checks that the sequence is sorted, returns true if it's sorted, false
// otherwise // otherwise
template<typename ForwardIt> template <typename ForwardIt>
bool is_sorted(ForwardIt first, ForwardIt last){ bool is_sorted(ForwardIt first, ForwardIt last)
{
ForwardIt next = first; ForwardIt next = first;
++next; ++next;
for (; next != last; ++next, ++first){ for (; next != last; ++next, ++first)
if (*first > *next){ {
if (*first > *next)
{
return false; return false;
} }
} }
@ -123,16 +130,19 @@ bool is_sorted(ForwardIt first, ForwardIt last){
// Get the value representing the `percent` percentile of the // Get the value representing the `percent` percentile of the
// sorted samples using linear interpolation // sorted samples using linear interpolation
vtkm::Float64 PercentileValue(const std::vector<vtkm::Float64> &samples, const vtkm::Float64 percent){ vtkm::Float64 PercentileValue(const std::vector<vtkm::Float64>& samples,
const vtkm::Float64 percent)
{
VTKM_ASSERT(!samples.empty()); VTKM_ASSERT(!samples.empty());
if (samples.size() == 1){ if (samples.size() == 1)
{
return samples.front(); return samples.front();
} }
VTKM_ASSERT(percent >= 0.0); VTKM_ASSERT(percent >= 0.0);
VTKM_ASSERT(percent <= 100.0); VTKM_ASSERT(percent <= 100.0);
VTKM_ASSERT( VTKM_ASSERT(vtkm::benchmarking::stats::is_sorted(samples.begin(), samples.end()));
vtkm::benchmarking::stats::is_sorted(samples.begin(), samples.end())); if (percent == 100.0)
if (percent == 100.0){ {
return samples.back(); return samples.back();
} }
// Find the two nearest percentile values and linearly // Find the two nearest percentile values and linearly
@ -149,45 +159,56 @@ vtkm::Float64 PercentileValue(const std::vector<vtkm::Float64> &samples, const v
// Will replace all samples below `percent` and above 100 - `percent` percentiles // Will replace all samples below `percent` and above 100 - `percent` percentiles
// with the value at the percentile // with the value at the percentile
// NOTE: Assumes the samples have been sorted, as we make use of PercentileValue // NOTE: Assumes the samples have been sorted, as we make use of PercentileValue
void Winsorize(std::vector<vtkm::Float64> &samples, const vtkm::Float64 percent){ void Winsorize(std::vector<vtkm::Float64>& samples, const vtkm::Float64 percent)
{
const vtkm::Float64 low_percentile = PercentileValue(samples, percent); const vtkm::Float64 low_percentile = PercentileValue(samples, percent);
const vtkm::Float64 high_percentile = PercentileValue(samples, 100.0 - percent); const vtkm::Float64 high_percentile = PercentileValue(samples, 100.0 - percent);
for (std::vector<vtkm::Float64>::iterator it = samples.begin(); it != samples.end(); ++it){ for (std::vector<vtkm::Float64>::iterator it = samples.begin(); it != samples.end(); ++it)
if (*it < low_percentile){ {
if (*it < low_percentile)
{
*it = low_percentile; *it = low_percentile;
} }
else if (*it > high_percentile){ else if (*it > high_percentile)
{
*it = high_percentile; *it = high_percentile;
} }
} }
} }
// Compute the mean value of the dataset // Compute the mean value of the dataset
vtkm::Float64 Mean(const std::vector<vtkm::Float64> &samples){ vtkm::Float64 Mean(const std::vector<vtkm::Float64>& samples)
{
vtkm::Float64 mean = 0; vtkm::Float64 mean = 0;
for (std::vector<vtkm::Float64>::const_iterator it = samples.begin(); it != samples.end(); ++it){ for (std::vector<vtkm::Float64>::const_iterator it = samples.begin(); it != samples.end(); ++it)
{
mean += *it; mean += *it;
} }
return mean / static_cast<vtkm::Float64>(samples.size()); return mean / static_cast<vtkm::Float64>(samples.size());
} }
// Compute the sample variance of the samples // Compute the sample variance of the samples
vtkm::Float64 Variance(const std::vector<vtkm::Float64> &samples){ vtkm::Float64 Variance(const std::vector<vtkm::Float64>& samples)
{
vtkm::Float64 mean = Mean(samples); vtkm::Float64 mean = Mean(samples);
vtkm::Float64 square_deviations = 0; vtkm::Float64 square_deviations = 0;
for (std::vector<vtkm::Float64>::const_iterator it = samples.begin(); it != samples.end(); ++it){ for (std::vector<vtkm::Float64>::const_iterator it = samples.begin(); it != samples.end(); ++it)
{
square_deviations += vtkm::Pow(*it - mean, 2.0); square_deviations += vtkm::Pow(*it - mean, 2.0);
} }
return square_deviations / (static_cast<vtkm::Float64>(samples.size()) - 1.0); return square_deviations / (static_cast<vtkm::Float64>(samples.size()) - 1.0);
} }
// Compute the standard deviation of the samples // Compute the standard deviation of the samples
vtkm::Float64 StandardDeviation(const std::vector<vtkm::Float64> &samples){ vtkm::Float64 StandardDeviation(const std::vector<vtkm::Float64>& samples)
{
return vtkm::Sqrt(Variance(samples)); return vtkm::Sqrt(Variance(samples));
} }
// Compute the median absolute deviation of the dataset // Compute the median absolute deviation of the dataset
vtkm::Float64 MedianAbsDeviation(const std::vector<vtkm::Float64> &samples){ vtkm::Float64 MedianAbsDeviation(const std::vector<vtkm::Float64>& samples)
{
std::vector<vtkm::Float64> abs_deviations; std::vector<vtkm::Float64> abs_deviations;
abs_deviations.reserve(samples.size()); abs_deviations.reserve(samples.size());
const vtkm::Float64 median = PercentileValue(samples, 50.0); const vtkm::Float64 median = PercentileValue(samples, 50.0);
for (std::vector<vtkm::Float64>::const_iterator it = samples.begin(); it != samples.end(); ++it){ for (std::vector<vtkm::Float64>::const_iterator it = samples.begin(); it != samples.end(); ++it)
{
abs_deviations.push_back(vtkm::Abs(*it - median)); abs_deviations.push_back(vtkm::Abs(*it - median));
} }
std::sort(abs_deviations.begin(), abs_deviations.end()); std::sort(abs_deviations.begin(), abs_deviations.end());
@ -202,15 +223,20 @@ vtkm::Float64 MedianAbsDeviation(const std::vector<vtkm::Float64> &samples){
* in seconds, this lets us avoid including any per-run setup time in the benchmark. * in seconds, this lets us avoid including any per-run setup time in the benchmark.
* However any one-time setup should be done in the functor's constructor * However any one-time setup should be done in the functor's constructor
*/ */
struct Benchmarker { struct Benchmarker
{
const vtkm::Float64 MAX_RUNTIME; const vtkm::Float64 MAX_RUNTIME;
const size_t MAX_ITERATIONS; const size_t MAX_ITERATIONS;
Benchmarker() : MAX_RUNTIME(30), MAX_ITERATIONS(500){} Benchmarker()
: MAX_RUNTIME(30)
, MAX_ITERATIONS(500)
{
}
template<typename Functor> template <typename Functor>
VTKM_CONT VTKM_CONT void operator()(Functor func) const
void operator()(Functor func) const { {
std::vector<vtkm::Float64> samples; std::vector<vtkm::Float64> samples;
// Do a warm-up run. If the benchmark allocates any additional memory // Do a warm-up run. If the benchmark allocates any additional memory
// eg. storage for output results, this will let it do that and // eg. storage for output results, this will let it do that and
@ -224,50 +250,49 @@ struct Benchmarker {
// could be increased // could be increased
size_t iter = 0; size_t iter = 0;
for (vtkm::Float64 elapsed = 0.0; elapsed < MAX_RUNTIME && iter < MAX_ITERATIONS; for (vtkm::Float64 elapsed = 0.0; elapsed < MAX_RUNTIME && iter < MAX_ITERATIONS;
elapsed += samples.back(), ++iter) elapsed += samples.back(), ++iter)
{ {
samples.push_back(func()); samples.push_back(func());
} }
std::sort(samples.begin(), samples.end()); std::sort(samples.begin(), samples.end());
stats::Winsorize(samples, 5.0); stats::Winsorize(samples, 5.0);
std::cout << "Benchmark \'" std::cout << "Benchmark \'" << func.Description() << "\' results:\n"
<< func.Description() << "\' results:\n" << "\tmedian = " << stats::PercentileValue(samples, 50.0) << "s\n"
<< "\tmedian = " << stats::PercentileValue(samples, 50.0) << "s\n" << "\tmedian abs dev = " << stats::MedianAbsDeviation(samples) << "s\n"
<< "\tmedian abs dev = " << stats::MedianAbsDeviation(samples) << "s\n" << "\tmean = " << stats::Mean(samples) << "s\n"
<< "\tmean = " << stats::Mean(samples) << "s\n" << "\tstd dev = " << stats::StandardDeviation(samples) << "s\n"
<< "\tstd dev = " << stats::StandardDeviation(samples) << "s\n" << "\tmin = " << samples.front() << "s\n"
<< "\tmin = " << samples.front() << "s\n" << "\tmax = " << samples.back() << "s\n";
<< "\tmax = " << samples.back() << "s\n";
} }
}; };
template<typename MakerFunctor> template <typename MakerFunctor>
class InternalPrintTypeAndBench { class InternalPrintTypeAndBench
{
MakerFunctor Maker; MakerFunctor Maker;
public: public:
VTKM_CONT VTKM_CONT
InternalPrintTypeAndBench(MakerFunctor maker) : Maker(maker) {} InternalPrintTypeAndBench(MakerFunctor maker)
: Maker(maker)
{
}
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT void operator()(T t) const
void operator()(T t) const { {
std::cout << "*** " std::cout << "*** " << vtkm::testing::TypeName<T>::Name() << " ***************" << std::endl;
<< vtkm::testing::TypeName<T>::Name()
<< " ***************" << std::endl;
Benchmarker bench; Benchmarker bench;
bench(Maker(t)); bench(Maker(t));
} }
}; };
template<class MakerFunctor, class TypeList> template <class MakerFunctor, class TypeList>
VTKM_CONT VTKM_CONT void BenchmarkTypes(const MakerFunctor& maker, TypeList)
void BenchmarkTypes(const MakerFunctor &maker, TypeList){ {
vtkm::ListForEach(InternalPrintTypeAndBench<MakerFunctor>(maker), TypeList()); vtkm::ListForEach(InternalPrintTypeAndBench<MakerFunctor>(maker), TypeList());
} }
} }
} }
#endif #endif

@ -22,11 +22,15 @@
#include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandle.h>
#ifdef VTKM_MSVC #ifdef VTKM_MSVC
#define _VTKM_SHARED_PTR_INSTANTIATE(Type) \ #define _VTKM_SHARED_PTR_INSTANTIATE(Type) \
template class VTKM_CONT_EXPORT std::shared_ptr< vtkm::cont::ArrayHandle<Type, vtkm::cont::StorageTagBasic>::InternalStruct >; \ template class VTKM_CONT_EXPORT \
template class VTKM_CONT_EXPORT std::shared_ptr< vtkm::cont::ArrayHandle<vtkm::Vec<Type, 2>, vtkm::cont::StorageTagBasic>::InternalStruct >; \ std::shared_ptr<vtkm::cont::ArrayHandle<Type, vtkm::cont::StorageTagBasic>::InternalStruct>; \
template class VTKM_CONT_EXPORT std::shared_ptr< vtkm::cont::ArrayHandle<vtkm::Vec<Type, 3>, vtkm::cont::StorageTagBasic>::InternalStruct >; \ template class VTKM_CONT_EXPORT std::shared_ptr< \
template class VTKM_CONT_EXPORT std::shared_ptr< vtkm::cont::ArrayHandle<vtkm::Vec<Type, 4>, vtkm::cont::StorageTagBasic>::InternalStruct >; vtkm::cont::ArrayHandle<vtkm::Vec<Type, 2>, vtkm::cont::StorageTagBasic>::InternalStruct>; \
template class VTKM_CONT_EXPORT std::shared_ptr< \
vtkm::cont::ArrayHandle<vtkm::Vec<Type, 3>, vtkm::cont::StorageTagBasic>::InternalStruct>; \
template class VTKM_CONT_EXPORT std::shared_ptr< \
vtkm::cont::ArrayHandle<vtkm::Vec<Type, 4>, vtkm::cont::StorageTagBasic>::InternalStruct>;
_VTKM_SHARED_PTR_INSTANTIATE(char) _VTKM_SHARED_PTR_INSTANTIATE(char)
_VTKM_SHARED_PTR_INSTANTIATE(vtkm::Int8) _VTKM_SHARED_PTR_INSTANTIATE(vtkm::Int8)
@ -43,23 +47,29 @@ _VTKM_SHARED_PTR_INSTANTIATE(vtkm::Float64)
#undef _VTKM_SHARED_PTR_INSTANTIATE #undef _VTKM_SHARED_PTR_INSTANTIATE
#endif // VTKM_MSVC #endif // VTKM_MSVC
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
#define _VTKM_ARRAYHANDLE_INSTANTIATE(Type) \ #define _VTKM_ARRAYHANDLE_INSTANTIATE(Type) \
template class VTKM_CONT_EXPORT ArrayHandle<Type, StorageTagBasic>; \ template class VTKM_CONT_EXPORT ArrayHandle<Type, StorageTagBasic>; \
template class VTKM_CONT_EXPORT ArrayHandle<vtkm::Vec<Type, 2>, StorageTagBasic>; \ template class VTKM_CONT_EXPORT ArrayHandle<vtkm::Vec<Type, 2>, StorageTagBasic>; \
template class VTKM_CONT_EXPORT ArrayHandle<vtkm::Vec<Type, 3>, StorageTagBasic>; \ template class VTKM_CONT_EXPORT ArrayHandle<vtkm::Vec<Type, 3>, StorageTagBasic>; \
template class VTKM_CONT_EXPORT ArrayHandle<vtkm::Vec<Type, 4>, StorageTagBasic>; \ template class VTKM_CONT_EXPORT ArrayHandle<vtkm::Vec<Type, 4>, StorageTagBasic>; \
namespace internal { \ namespace internal \
template class VTKM_CONT_EXPORT ArrayHandleExecutionManagerBase<Type, StorageTagBasic>; \ { \
template class VTKM_CONT_EXPORT ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 2>, StorageTagBasic>; \ template class VTKM_CONT_EXPORT ArrayHandleExecutionManagerBase<Type, StorageTagBasic>; \
template class VTKM_CONT_EXPORT ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 3>, StorageTagBasic>; \ template class VTKM_CONT_EXPORT \
template class VTKM_CONT_EXPORT ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 4>, StorageTagBasic>; \ ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 2>, StorageTagBasic>; \
template class VTKM_CONT_EXPORT ArrayPortalFromIterators<Type*>; \ template class VTKM_CONT_EXPORT \
template class VTKM_CONT_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 2>*>; \ ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 3>, StorageTagBasic>; \
template class VTKM_CONT_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 3>*>; \ template class VTKM_CONT_EXPORT \
template class VTKM_CONT_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 4>*>; \ ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 4>, StorageTagBasic>; \
template class VTKM_CONT_EXPORT ArrayPortalFromIterators<Type*>; \
template class VTKM_CONT_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 2>*>; \
template class VTKM_CONT_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 3>*>; \
template class VTKM_CONT_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 4>*>; \
} /* end namespace internal */ } /* end namespace internal */
_VTKM_ARRAYHANDLE_INSTANTIATE(char) _VTKM_ARRAYHANDLE_INSTANTIATE(char)
@ -75,6 +85,5 @@ _VTKM_ARRAYHANDLE_INSTANTIATE(vtkm::Float32)
_VTKM_ARRAYHANDLE_INSTANTIATE(vtkm::Float64) _VTKM_ARRAYHANDLE_INSTANTIATE(vtkm::Float64)
#undef _VTKM_ARRAYHANDLE_INSTANTIATE #undef _VTKM_ARRAYHANDLE_INSTANTIATE
} }
} // end vtkm::cont } // end vtkm::cont

@ -38,11 +38,13 @@
#include <vtkm/cont/internal/ArrayHandleExecutionManager.h> #include <vtkm/cont/internal/ArrayHandleExecutionManager.h>
#include <vtkm/cont/internal/ArrayPortalFromIterators.h> #include <vtkm/cont/internal/ArrayPortalFromIterators.h>
namespace vtkm
{
namespace cont
{
namespace vtkm { namespace internal
namespace cont { {
namespace internal {
/// \brief Base class of all ArrayHandle classes. /// \brief Base class of all ArrayHandle classes.
/// ///
@ -50,7 +52,9 @@ namespace internal {
/// ArrayHandle class (or at least something that behaves exactly like one). /// ArrayHandle class (or at least something that behaves exactly like one).
/// The \c ArrayHandle template class inherits from this. /// The \c ArrayHandle template class inherits from this.
/// ///
class VTKM_CONT_EXPORT ArrayHandleBase { }; class VTKM_CONT_EXPORT ArrayHandleBase
{
};
/// Checks to see if the given type and storage can form a valid array handle /// Checks to see if the given type and storage can form a valid array handle
/// (some storage objects cannot support all types). This check is compatible /// (some storage objects cannot support all types). This check is compatible
@ -58,14 +62,14 @@ class VTKM_CONT_EXPORT ArrayHandleBase { };
/// typedef named type that is either std::true_type or std::false_type. /// typedef named type that is either std::true_type or std::false_type.
/// Both of these have a typedef named value with the respective boolean value. /// Both of these have a typedef named value with the respective boolean value.
/// ///
template<typename T, typename StorageTag> template <typename T, typename StorageTag>
struct IsValidArrayHandle { struct IsValidArrayHandle
{
//need to add the not //need to add the not
using type = std::integral_constant<bool, using type =
!( std::is_base_of< std::integral_constant<bool,
vtkm::cont::internal::UndefinedStorage, !(std::is_base_of<vtkm::cont::internal::UndefinedStorage,
vtkm::cont::internal::Storage<T,StorageTag> vtkm::cont::internal::Storage<T, StorageTag>>::value)>;
>::value)>;
}; };
/// Checks to see if the ArrayHandle for the given DeviceAdatper allows /// Checks to see if the ArrayHandle for the given DeviceAdatper allows
@ -75,10 +79,11 @@ struct IsValidArrayHandle {
/// std::true_type or std::false_type. /// std::true_type or std::false_type.
/// Both of these have a typedef named value with the respective boolean value. /// Both of these have a typedef named value with the respective boolean value.
/// ///
template<typename ArrayHandle, typename DeviceAdapterTag> template <typename ArrayHandle, typename DeviceAdapterTag>
struct IsWriteableArrayHandle { struct IsWriteableArrayHandle
{
private: private:
template<typename T> template <typename T>
using ExecutionTypes = typename ArrayHandle::template ExecutionTypes<T>; using ExecutionTypes = typename ArrayHandle::template ExecutionTypes<T>;
using ValueType = typename ExecutionTypes<DeviceAdapterTag>::Portal::ValueType; using ValueType = typename ExecutionTypes<DeviceAdapterTag>::Portal::ValueType;
@ -87,6 +92,7 @@ private:
//will have a value type of void*, which is what we are trying to detect //will have a value type of void*, which is what we are trying to detect
using RawValueType = typename std::remove_pointer<ValueType>::type; using RawValueType = typename std::remove_pointer<ValueType>::type;
using IsVoidType = std::is_void<RawValueType>; using IsVoidType = std::is_void<RawValueType>;
public: public:
using type = std::integral_constant<bool, !IsVoidType::value>; using type = std::integral_constant<bool, !IsVoidType::value>;
}; };
@ -103,22 +109,23 @@ public:
/// class is used to ensure that a given type is an \c ArrayHandle. It is /// class is used to ensure that a given type is an \c ArrayHandle. It is
/// used internally in the VTKM_IS_ARRAY_HANDLE macro. /// used internally in the VTKM_IS_ARRAY_HANDLE macro.
/// ///
template<typename T> template <typename T>
struct ArrayHandleCheck struct ArrayHandleCheck
{ {
using type = typename std::is_base_of< using type = typename std::is_base_of<::vtkm::cont::internal::ArrayHandleBase, T>::type;
::vtkm::cont::internal::ArrayHandleBase, T>::type;
}; };
#define VTKM_IS_ARRAY_HANDLE(T) \ #define VTKM_IS_ARRAY_HANDLE(T) \
VTKM_STATIC_ASSERT(::vtkm::cont::internal::ArrayHandleCheck<T>::type::value) VTKM_STATIC_ASSERT(::vtkm::cont::internal::ArrayHandleCheck<T>::type::value)
} // namespace internal } // namespace internal
namespace detail { namespace detail
{
template<typename T> struct GetTypeInParentheses; template <typename T>
template<typename T> struct GetTypeInParentheses;
template <typename T>
struct GetTypeInParentheses<void(T)> struct GetTypeInParentheses<void(T)>
{ {
typedef T type; typedef T type;
@ -127,29 +134,39 @@ struct GetTypeInParentheses<void(T)>
} // namespace detail } // namespace detail
// Implementation for VTKM_ARRAY_HANDLE_SUBCLASS macros // Implementation for VTKM_ARRAY_HANDLE_SUBCLASS macros
#define VTK_M_ARRAY_HANDLE_SUBCLASS_IMPL(classname, fullclasstype, superclass, typename__) \ #define VTK_M_ARRAY_HANDLE_SUBCLASS_IMPL(classname, fullclasstype, superclass, typename__) \
typedef typename__ vtkm::cont::detail::GetTypeInParentheses<void fullclasstype>::type Thisclass;\ typedef typename__ vtkm::cont::detail::GetTypeInParentheses<void fullclasstype>::type Thisclass; \
typedef typename__ vtkm::cont::detail::GetTypeInParentheses<void superclass>::type Superclass;\ typedef typename__ vtkm::cont::detail::GetTypeInParentheses<void superclass>::type Superclass; \
\ \
VTKM_IS_ARRAY_HANDLE(Superclass); \ VTKM_IS_ARRAY_HANDLE(Superclass); \
\ \
VTKM_CONT \ VTKM_CONT \
classname() : Superclass() { } \ classname() \
\ : Superclass() \
VTKM_CONT \ { \
classname(const Thisclass &src) : Superclass(src) { } \ } \
\ \
VTKM_CONT \ VTKM_CONT \
classname(const vtkm::cont::ArrayHandle<typename__ Superclass::ValueType, typename__ Superclass::StorageTag> &src) : Superclass(src) { } \ classname(const Thisclass& src) \
\ : Superclass(src) \
VTKM_CONT \ { \
Thisclass &operator=(const Thisclass &src) \ } \
{ \ \
this->Superclass::operator=(src); \ VTKM_CONT \
return *this; \ classname(const vtkm::cont::ArrayHandle<typename__ Superclass::ValueType, \
} \ typename__ Superclass::StorageTag>& src) \
\ : Superclass(src) \
typedef typename__ Superclass::ValueType ValueType; \ { \
} \
\
VTKM_CONT \
Thisclass& operator=(const Thisclass& src) \
{ \
this->Superclass::operator=(src); \
return *this; \
} \
\
typedef typename__ Superclass::ValueType ValueType; \
typedef typename__ Superclass::StorageTag StorageTag typedef typename__ Superclass::StorageTag StorageTag
/// \brief Macro to make default methods in ArrayHandle subclasses. /// \brief Macro to make default methods in ArrayHandle subclasses.
@ -173,7 +190,7 @@ struct GetTypeInParentheses<void(T)>
/// templated. For ArrayHandle sublcasses that are not templates, use /// templated. For ArrayHandle sublcasses that are not templates, use
/// VTKM_ARRAY_HANDLE_SUBCLASS_NT. /// VTKM_ARRAY_HANDLE_SUBCLASS_NT.
/// ///
#define VTKM_ARRAY_HANDLE_SUBCLASS(classname, fullclasstype, superclass) \ #define VTKM_ARRAY_HANDLE_SUBCLASS(classname, fullclasstype, superclass) \
VTK_M_ARRAY_HANDLE_SUBCLASS_IMPL(classname, fullclasstype, superclass, typename) VTK_M_ARRAY_HANDLE_SUBCLASS_IMPL(classname, fullclasstype, superclass, typename)
/// \brief Macro to make default methods in ArrayHandle subclasses. /// \brief Macro to make default methods in ArrayHandle subclasses.
@ -196,7 +213,7 @@ struct GetTypeInParentheses<void(T)>
/// templated. For ArrayHandle sublcasses that are are templates, use /// templated. For ArrayHandle sublcasses that are are templates, use
/// VTKM_ARRAY_HANDLE_SUBCLASS. /// VTKM_ARRAY_HANDLE_SUBCLASS.
/// ///
#define VTKM_ARRAY_HANDLE_SUBCLASS_NT(classname, superclass) \ #define VTKM_ARRAY_HANDLE_SUBCLASS_NT(classname, superclass) \
VTK_M_ARRAY_HANDLE_SUBCLASS_IMPL(classname, (classname), superclass, ) VTK_M_ARRAY_HANDLE_SUBCLASS_IMPL(classname, (classname), superclass, )
/// \brief Manages an array-worth of data. /// \brief Manages an array-worth of data.
@ -220,16 +237,15 @@ struct GetTypeInParentheses<void(T)>
/// allocated memory is released. /// allocated memory is released.
/// ///
/// ///
template< template <typename T, typename StorageTag_ = VTKM_DEFAULT_STORAGE_TAG>
typename T,
typename StorageTag_ = VTKM_DEFAULT_STORAGE_TAG>
class VTKM_ALWAYS_EXPORT ArrayHandle : public internal::ArrayHandleBase class VTKM_ALWAYS_EXPORT ArrayHandle : public internal::ArrayHandleBase
{ {
private: private:
typedef vtkm::cont::internal::ArrayHandleExecutionManagerBase<T,StorageTag_> typedef vtkm::cont::internal::ArrayHandleExecutionManagerBase<T, StorageTag_>
ExecutionManagerType; ExecutionManagerType;
public: public:
typedef vtkm::cont::internal::Storage<T,StorageTag_> StorageType; typedef vtkm::cont::internal::Storage<T, StorageTag_> StorageType;
typedef T ValueType; typedef T ValueType;
typedef StorageTag_ StorageTag; typedef StorageTag_ StorageTag;
typedef typename StorageType::PortalType PortalControl; typedef typename StorageType::PortalType PortalControl;
@ -237,10 +253,9 @@ public:
template <typename DeviceAdapterTag> template <typename DeviceAdapterTag>
struct ExecutionTypes struct ExecutionTypes
{ {
typedef typename ExecutionManagerType typedef typename ExecutionManagerType::template ExecutionTypes<DeviceAdapterTag>::Portal Portal;
::template ExecutionTypes<DeviceAdapterTag>::Portal Portal; typedef typename ExecutionManagerType::template ExecutionTypes<DeviceAdapterTag>::PortalConst
typedef typename ExecutionManagerType PortalConst;
::template ExecutionTypes<DeviceAdapterTag>::PortalConst PortalConst;
}; };
/// Constructs an empty ArrayHandle. Typically used for output or /// Constructs an empty ArrayHandle. Typically used for output or
@ -255,7 +270,7 @@ public:
/// with CUDA), then the automatically generated copy constructor could be /// with CUDA), then the automatically generated copy constructor could be
/// created for all devices, and it would not be valid for all devices. /// created for all devices, and it would not be valid for all devices.
/// ///
ArrayHandle(const vtkm::cont::ArrayHandle<ValueType,StorageTag> &src); ArrayHandle(const vtkm::cont::ArrayHandle<ValueType, StorageTag>& src);
/// Move constructor. /// Move constructor.
/// ///
@ -264,14 +279,13 @@ public:
/// with CUDA), then the automatically generated move constructor could be /// with CUDA), then the automatically generated move constructor could be
/// created for all devices, and it would not be valid for all devices. /// created for all devices, and it would not be valid for all devices.
/// ///
ArrayHandle(vtkm::cont::ArrayHandle<ValueType,StorageTag> &&src); ArrayHandle(vtkm::cont::ArrayHandle<ValueType, StorageTag>&& src);
/// Special constructor for subclass specializations that need to set the /// Special constructor for subclass specializations that need to set the
/// initial state of the control array. When this constructor is used, it /// initial state of the control array. When this constructor is used, it
/// is assumed that the control array is valid. /// is assumed that the control array is valid.
/// ///
ArrayHandle(const StorageType &storage); ArrayHandle(const StorageType& storage);
/// Destructs an empty ArrayHandle. /// Destructs an empty ArrayHandle.
/// ///
@ -285,25 +299,25 @@ public:
/// \brief Copies an ArrayHandle /// \brief Copies an ArrayHandle
/// ///
VTKM_CONT VTKM_CONT
vtkm::cont::ArrayHandle<ValueType,StorageTag> & vtkm::cont::ArrayHandle<ValueType, StorageTag>& operator=(
operator=(const vtkm::cont::ArrayHandle<ValueType,StorageTag> &src); const vtkm::cont::ArrayHandle<ValueType, StorageTag>& src);
/// \brief Move and Assignment of an ArrayHandle /// \brief Move and Assignment of an ArrayHandle
/// ///
VTKM_CONT VTKM_CONT
vtkm::cont::ArrayHandle<ValueType,StorageTag> & vtkm::cont::ArrayHandle<ValueType, StorageTag>& operator=(
operator=(vtkm::cont::ArrayHandle<ValueType,StorageTag> &&src); vtkm::cont::ArrayHandle<ValueType, StorageTag>&& src);
/// Like a pointer, two \c ArrayHandles are considered equal if they point /// Like a pointer, two \c ArrayHandles are considered equal if they point
/// to the same location in memory. /// to the same location in memory.
/// ///
VTKM_CONT VTKM_CONT
bool operator==(const ArrayHandle<ValueType,StorageTag> &rhs) const bool operator==(const ArrayHandle<ValueType, StorageTag>& rhs) const
{ {
return (this->Internals == rhs.Internals); return (this->Internals == rhs.Internals);
} }
VTKM_CONT VTKM_CONT
bool operator!=(const ArrayHandle<ValueType,StorageTag> &rhs) const bool operator!=(const ArrayHandle<ValueType, StorageTag>& rhs) const
{ {
return (this->Internals != rhs.Internals); return (this->Internals != rhs.Internals);
} }
@ -331,7 +345,7 @@ public:
/// Copies data into the given iterator for the control environment. This /// Copies data into the given iterator for the control environment. This
/// method can skip copying into an internally managed control array. /// method can skip copying into an internally managed control array.
/// ///
template<typename IteratorType, typename DeviceAdapterTag> template <typename IteratorType, typename DeviceAdapterTag>
VTKM_CONT void CopyInto(IteratorType dest, DeviceAdapterTag) const; VTKM_CONT void CopyInto(IteratorType dest, DeviceAdapterTag) const;
/// \brief Allocates an array large enough to hold the given number of values. /// \brief Allocates an array large enough to hold the given number of values.
@ -385,16 +399,17 @@ public:
} }
} }
// clang-format off
/// Prepares this array to be used as an input to an operation in the /// Prepares this array to be used as an input to an operation in the
/// execution environment. If necessary, copies data to the execution /// execution environment. If necessary, copies data to the execution
/// environment. Can throw an exception if this array does not yet contain /// environment. Can throw an exception if this array does not yet contain
/// any data. Returns a portal that can be used in code running in the /// any data. Returns a portal that can be used in code running in the
/// execution environment. /// execution environment.
/// ///
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
VTKM_CONT VTKM_CONT
typename ExecutionTypes<DeviceAdapterTag>::PortalConst typename ExecutionTypes<DeviceAdapterTag>::PortalConst PrepareForInput(DeviceAdapterTag) const;
PrepareForInput(DeviceAdapterTag) const; // clang-format on
/// Prepares (allocates) this array to be used as an output from an operation /// Prepares (allocates) this array to be used as an output from an operation
/// in the execution environment. The internal state of this class is set to /// in the execution environment. The internal state of this class is set to
@ -403,10 +418,9 @@ public:
/// called). Returns a portal that can be used in code running in the /// called). Returns a portal that can be used in code running in the
/// execution environment. /// execution environment.
/// ///
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
VTKM_CONT VTKM_CONT typename ExecutionTypes<DeviceAdapterTag>::Portal PrepareForOutput(
typename ExecutionTypes<DeviceAdapterTag>::Portal vtkm::Id numberOfValues, DeviceAdapterTag);
PrepareForOutput(vtkm::Id numberOfValues, DeviceAdapterTag);
/// Prepares this array to be used in an in-place operation (both as input /// Prepares this array to be used in an in-place operation (both as input
/// and output) in the execution environment. If necessary, copies data to /// and output) in the execution environment. If necessary, copies data to
@ -414,19 +428,16 @@ public:
/// yet contain any data. Returns a portal that can be used in code running /// yet contain any data. Returns a portal that can be used in code running
/// in the execution environment. /// in the execution environment.
/// ///
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
VTKM_CONT VTKM_CONT typename ExecutionTypes<DeviceAdapterTag>::Portal PrepareForInPlace(DeviceAdapterTag);
typename ExecutionTypes<DeviceAdapterTag>::Portal
PrepareForInPlace(DeviceAdapterTag);
/// Gets this array handle ready to interact with the given device. If the /// Gets this array handle ready to interact with the given device. If the
/// array handle has already interacted with this device, then this method /// array handle has already interacted with this device, then this method
/// does nothing. Although the internal state of this class can change, the /// does nothing. Although the internal state of this class can change, the
/// method is declared const because logically the data does not. /// method is declared const because logically the data does not.
/// ///
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
VTKM_CONT VTKM_CONT void PrepareForDevice(DeviceAdapterTag) const;
void PrepareForDevice(DeviceAdapterTag) const;
/// Synchronizes the control array with the execution array. If either the /// Synchronizes the control array with the execution array. If either the
/// user array or control array is already valid, this method does nothing /// user array or control array is already valid, this method does nothing
@ -451,47 +462,40 @@ public:
StorageType ControlArray; StorageType ControlArray;
bool ControlArrayValid; bool ControlArrayValid;
std::unique_ptr< std::unique_ptr<vtkm::cont::internal::ArrayHandleExecutionManagerBase<ValueType, StorageTag>>
vtkm::cont::internal::ArrayHandleExecutionManagerBase< ExecutionArray;
ValueType,StorageTag> > ExecutionArray;
bool ExecutionArrayValid; bool ExecutionArrayValid;
}; };
VTKM_CONT VTKM_CONT
ArrayHandle(const std::shared_ptr<InternalStruct>& i) ArrayHandle(const std::shared_ptr<InternalStruct>& i)
: Internals(i) : Internals(i)
{ } {
}
std::shared_ptr<InternalStruct> Internals; std::shared_ptr<InternalStruct> Internals;
}; };
/// A convenience function for creating an ArrayHandle from a standard C array. /// A convenience function for creating an ArrayHandle from a standard C array.
/// ///
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandle<T, vtkm::cont::StorageTagBasic> make_ArrayHandle(const T* array,
vtkm::cont::ArrayHandle<T, vtkm::cont::StorageTagBasic> vtkm::Id length)
make_ArrayHandle(const T *array,
vtkm::Id length)
{ {
typedef vtkm::cont::ArrayHandle<T, vtkm::cont::StorageTagBasic> typedef vtkm::cont::ArrayHandle<T, vtkm::cont::StorageTagBasic> ArrayHandleType;
ArrayHandleType; typedef vtkm::cont::internal::Storage<T, vtkm::cont::StorageTagBasic> StorageType;
typedef vtkm::cont::internal::Storage<T, vtkm::cont::StorageTagBasic>
StorageType;
return ArrayHandleType(StorageType(array, length)); return ArrayHandleType(StorageType(array, length));
} }
/// A convenience function for creating an ArrayHandle from an std::vector. /// A convenience function for creating an ArrayHandle from an std::vector.
/// ///
template<typename T, template <typename T, typename Allocator>
typename Allocator> VTKM_CONT vtkm::cont::ArrayHandle<T, vtkm::cont::StorageTagBasic> make_ArrayHandle(
VTKM_CONT const std::vector<T, Allocator>& array)
vtkm::cont::ArrayHandle<T, vtkm::cont::StorageTagBasic>
make_ArrayHandle(const std::vector<T,Allocator> &array)
{ {
if (!array.empty()) if (!array.empty())
{ {
return make_ArrayHandle(&array.front(), return make_ArrayHandle(&array.front(), static_cast<vtkm::Id>(array.size()));
static_cast<vtkm::Id>(array.size()));
} }
else else
{ {
@ -500,43 +504,37 @@ make_ArrayHandle(const std::vector<T,Allocator> &array)
} }
} }
namespace detail { namespace detail
{
template<typename T> template <typename T>
VTKM_NEVER_EXPORT VTKM_NEVER_EXPORT VTKM_CONT inline void printSummary_ArrayHandle_Value(
VTKM_CONT const T& value, std::ostream& out, vtkm::VecTraitsTagSingleComponent)
inline void printSummary_ArrayHandle_Value(const T &value,
std::ostream &out,
vtkm::VecTraitsTagSingleComponent)
{ {
out << value; out << value;
} }
template<typename T> template <typename T>
VTKM_NEVER_EXPORT VTKM_NEVER_EXPORT VTKM_CONT inline void printSummary_ArrayHandle_Value(
VTKM_CONT const T& value, std::ostream& out, vtkm::VecTraitsTagMultipleComponents)
inline void printSummary_ArrayHandle_Value(const T &value,
std::ostream &out,
vtkm::VecTraitsTagMultipleComponents)
{ {
using Traits = vtkm::VecTraits<T>; using Traits = vtkm::VecTraits<T>;
using ComponentType = typename Traits::ComponentType; using ComponentType = typename Traits::ComponentType;
using IsVecOfVec = typename vtkm::VecTraits<ComponentType>::HasMultipleComponents; using IsVecOfVec = typename vtkm::VecTraits<ComponentType>::HasMultipleComponents;
vtkm::IdComponent numComponents = Traits::GetNumberOfComponents(value); vtkm::IdComponent numComponents = Traits::GetNumberOfComponents(value);
out << "("; out << "(";
printSummary_ArrayHandle_Value(Traits::GetComponent(value,0), out, IsVecOfVec()); printSummary_ArrayHandle_Value(Traits::GetComponent(value, 0), out, IsVecOfVec());
for (vtkm::IdComponent index = 1; index < numComponents; ++index) for (vtkm::IdComponent index = 1; index < numComponents; ++index)
{ {
out << ","; out << ",";
printSummary_ArrayHandle_Value(Traits::GetComponent(value,index), out, IsVecOfVec()); printSummary_ArrayHandle_Value(Traits::GetComponent(value, index), out, IsVecOfVec());
} }
out << ")"; out << ")";
} }
VTKM_NEVER_EXPORT VTKM_NEVER_EXPORT
VTKM_CONT VTKM_CONT
inline void printSummary_ArrayHandle_Value(UInt8 value, inline void printSummary_ArrayHandle_Value(UInt8 value, std::ostream& out,
std::ostream &out,
vtkm::VecTraitsTagSingleComponent) vtkm::VecTraitsTagSingleComponent)
{ {
out << static_cast<int>(value); out << static_cast<int>(value);
@ -544,62 +542,49 @@ inline void printSummary_ArrayHandle_Value(UInt8 value,
VTKM_NEVER_EXPORT VTKM_NEVER_EXPORT
VTKM_CONT VTKM_CONT
inline void printSummary_ArrayHandle_Value(Int8 value, inline void printSummary_ArrayHandle_Value(Int8 value, std::ostream& out,
std::ostream &out,
vtkm::VecTraitsTagSingleComponent) vtkm::VecTraitsTagSingleComponent)
{ {
out << static_cast<int>(value); out << static_cast<int>(value);
} }
template<typename T1, typename T2> template <typename T1, typename T2>
VTKM_NEVER_EXPORT VTKM_NEVER_EXPORT VTKM_CONT inline void printSummary_ArrayHandle_Value(
VTKM_CONT const vtkm::Pair<T1, T2>& value, std::ostream& out, vtkm::VecTraitsTagSingleComponent)
inline void printSummary_ArrayHandle_Value(const vtkm::Pair<T1,T2> &value,
std::ostream &out,
vtkm::VecTraitsTagSingleComponent)
{ {
out << "{"; out << "{";
printSummary_ArrayHandle_Value( printSummary_ArrayHandle_Value(value.first, out,
value.first, typename vtkm::VecTraits<T1>::HasMultipleComponents());
out,
typename vtkm::VecTraits<T1>::HasMultipleComponents());
out << ","; out << ",";
printSummary_ArrayHandle_Value( printSummary_ArrayHandle_Value(value.second, out,
value.second, typename vtkm::VecTraits<T2>::HasMultipleComponents());
out,
typename vtkm::VecTraits<T2>::HasMultipleComponents());
out << "}"; out << "}";
} }
} // namespace detail } // namespace detail
template<typename T, typename StorageT> template <typename T, typename StorageT>
VTKM_NEVER_EXPORT VTKM_NEVER_EXPORT VTKM_CONT inline void printSummary_ArrayHandle(
VTKM_CONT const vtkm::cont::ArrayHandle<T, StorageT>& array, std::ostream& out)
inline void
printSummary_ArrayHandle(const vtkm::cont::ArrayHandle<T,StorageT> &array,
std::ostream &out)
{ {
using ArrayType = vtkm::cont::ArrayHandle<T,StorageT>; using ArrayType = vtkm::cont::ArrayHandle<T, StorageT>;
using PortalType = typename ArrayType::PortalConstControl; using PortalType = typename ArrayType::PortalConstControl;
using IsVec = typename vtkm::VecTraits<T>::HasMultipleComponents; using IsVec = typename vtkm::VecTraits<T>::HasMultipleComponents;
vtkm::Id sz = array.GetNumberOfValues(); vtkm::Id sz = array.GetNumberOfValues();
out << "valueType=" << typeid(T).name() out << "valueType=" << typeid(T).name() << " storageType=" << typeid(StorageT).name()
<< " storageType=" << typeid(StorageT).name() << " numValues=" << sz << " [";
<< " numValues=" << sz
<< " [";
PortalType portal = array.GetPortalConstControl(); PortalType portal = array.GetPortalConstControl();
if (sz <= 7) if (sz <= 7)
{ {
for (vtkm::Id i = 0 ; i < sz; i++) for (vtkm::Id i = 0; i < sz; i++)
{ {
detail::printSummary_ArrayHandle_Value(portal.Get(i), out, IsVec()); detail::printSummary_ArrayHandle_Value(portal.Get(i), out, IsVec());
if (i != (sz-1)) if (i != (sz - 1))
{ {
out<<" "; out << " ";
} }
} }
} }
@ -611,15 +596,14 @@ printSummary_ArrayHandle(const vtkm::cont::ArrayHandle<T,StorageT> &array,
out << " "; out << " ";
detail::printSummary_ArrayHandle_Value(portal.Get(2), out, IsVec()); detail::printSummary_ArrayHandle_Value(portal.Get(2), out, IsVec());
out << " ... "; out << " ... ";
detail::printSummary_ArrayHandle_Value(portal.Get(sz-3), out, IsVec()); detail::printSummary_ArrayHandle_Value(portal.Get(sz - 3), out, IsVec());
out << " "; out << " ";
detail::printSummary_ArrayHandle_Value(portal.Get(sz-2), out, IsVec()); detail::printSummary_ArrayHandle_Value(portal.Get(sz - 2), out, IsVec());
out << " "; out << " ";
detail::printSummary_ArrayHandle_Value(portal.Get(sz-1), out, IsVec()); detail::printSummary_ArrayHandle_Value(portal.Get(sz - 1), out, IsVec());
} }
out<<"]\n"; out << "]\n";
} }
} }
} //namespace vtkm::cont } //namespace vtkm::cont
@ -629,11 +613,15 @@ printSummary_ArrayHandle(const vtkm::cont::ArrayHandle<T,StorageT> &array,
#ifndef vtkm_cont_ArrayHandle_cxx #ifndef vtkm_cont_ArrayHandle_cxx
#ifdef VTKM_MSVC #ifdef VTKM_MSVC
#define _VTKM_SHARED_PTR_EXPORT(Type) \ #define _VTKM_SHARED_PTR_EXPORT(Type) \
extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< vtkm::cont::ArrayHandle<Type, vtkm::cont::StorageTagBasic>::InternalStruct >; \ extern template class VTKM_CONT_TEMPLATE_EXPORT \
extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< vtkm::cont::ArrayHandle<vtkm::Vec<Type, 2>, vtkm::cont::StorageTagBasic>::InternalStruct >; \ std::shared_ptr<vtkm::cont::ArrayHandle<Type, vtkm::cont::StorageTagBasic>::InternalStruct>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< vtkm::cont::ArrayHandle<vtkm::Vec<Type, 3>, vtkm::cont::StorageTagBasic>::InternalStruct >; \ extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< \
extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< vtkm::cont::ArrayHandle<vtkm::Vec<Type, 4>, vtkm::cont::StorageTagBasic>::InternalStruct >; vtkm::cont::ArrayHandle<vtkm::Vec<Type, 2>, vtkm::cont::StorageTagBasic>::InternalStruct>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< \
vtkm::cont::ArrayHandle<vtkm::Vec<Type, 3>, vtkm::cont::StorageTagBasic>::InternalStruct>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< \
vtkm::cont::ArrayHandle<vtkm::Vec<Type, 4>, vtkm::cont::StorageTagBasic>::InternalStruct>;
_VTKM_SHARED_PTR_EXPORT(char) _VTKM_SHARED_PTR_EXPORT(char)
_VTKM_SHARED_PTR_EXPORT(vtkm::Int8) _VTKM_SHARED_PTR_EXPORT(vtkm::Int8)
@ -650,23 +638,33 @@ _VTKM_SHARED_PTR_EXPORT(vtkm::Float64)
#undef _VTKM_SHARED_PTR_EXPORT #undef _VTKM_SHARED_PTR_EXPORT
#endif // VTKM_MSVC #endif // VTKM_MSVC
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
#define _VTKM_ARRAYHANDLE_EXPORT(Type) \ #define _VTKM_ARRAYHANDLE_EXPORT(Type) \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandle<Type, StorageTagBasic>; \ extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandle<Type, StorageTagBasic>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandle<vtkm::Vec<Type, 2>, StorageTagBasic>; \ extern template class VTKM_CONT_TEMPLATE_EXPORT \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandle<vtkm::Vec<Type, 3>, StorageTagBasic>; \ ArrayHandle<vtkm::Vec<Type, 2>, StorageTagBasic>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandle<vtkm::Vec<Type, 4>, StorageTagBasic>; \ extern template class VTKM_CONT_TEMPLATE_EXPORT \
namespace internal { \ ArrayHandle<vtkm::Vec<Type, 3>, StorageTagBasic>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandleExecutionManagerBase<Type, StorageTagBasic>; \ extern template class VTKM_CONT_TEMPLATE_EXPORT \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 2>, StorageTagBasic>; \ ArrayHandle<vtkm::Vec<Type, 4>, StorageTagBasic>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 3>, StorageTagBasic>; \ namespace internal \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 4>, StorageTagBasic>; \ { \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayPortalFromIterators<Type*>; \ extern template class VTKM_CONT_TEMPLATE_EXPORT \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 2>*>; \ ArrayHandleExecutionManagerBase<Type, StorageTagBasic>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 3>*>; \ extern template class VTKM_CONT_TEMPLATE_EXPORT \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 4>*>; \ ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 2>, StorageTagBasic>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT \
ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 3>, StorageTagBasic>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT \
ArrayHandleExecutionManagerBase<vtkm::Vec<Type, 4>, StorageTagBasic>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayPortalFromIterators<Type*>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 2>*>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 3>*>; \
extern template class VTKM_CONT_TEMPLATE_EXPORT ArrayPortalFromIterators<vtkm::Vec<Type, 4>*>; \
} /* end namespace internal */ } /* end namespace internal */
_VTKM_ARRAYHANDLE_EXPORT(char) _VTKM_ARRAYHANDLE_EXPORT(char)
@ -682,7 +680,6 @@ _VTKM_ARRAYHANDLE_EXPORT(vtkm::Float32)
_VTKM_ARRAYHANDLE_EXPORT(vtkm::Float64) _VTKM_ARRAYHANDLE_EXPORT(vtkm::Float64)
#undef _VTKM_ARRAYHANDLE_EXPORT #undef _VTKM_ARRAYHANDLE_EXPORT
} }
} // end vtkm::cont } // end vtkm::cont

@ -18,29 +18,33 @@
// this software. // this software.
//============================================================================ //============================================================================
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
template<typename T, typename S> template <typename T, typename S>
ArrayHandle<T,S>::ArrayHandle() ArrayHandle<T, S>::ArrayHandle()
: Internals(new InternalStruct) : Internals(new InternalStruct)
{ {
this->Internals->ControlArrayValid = false; this->Internals->ControlArrayValid = false;
this->Internals->ExecutionArrayValid = false; this->Internals->ExecutionArrayValid = false;
} }
template<typename T, typename S> template <typename T, typename S>
ArrayHandle<T,S>::ArrayHandle(const ArrayHandle<T,S> &src) ArrayHandle<T, S>::ArrayHandle(const ArrayHandle<T, S>& src)
: Internals(src.Internals) : Internals(src.Internals)
{ } {
}
template<typename T, typename S> template <typename T, typename S>
ArrayHandle<T,S>::ArrayHandle(ArrayHandle<T,S> &&src) ArrayHandle<T, S>::ArrayHandle(ArrayHandle<T, S>&& src)
: Internals(std::move(src.Internals)) : Internals(std::move(src.Internals))
{ } {
}
template<typename T, typename S> template <typename T, typename S>
ArrayHandle<T,S>::ArrayHandle(const typename ArrayHandle<T,S>::StorageType &storage) ArrayHandle<T, S>::ArrayHandle(const typename ArrayHandle<T, S>::StorageType& storage)
: Internals(new InternalStruct) : Internals(new InternalStruct)
{ {
this->Internals->ControlArray = storage; this->Internals->ControlArray = storage;
@ -48,30 +52,27 @@ ArrayHandle<T,S>::ArrayHandle(const typename ArrayHandle<T,S>::StorageType &stor
this->Internals->ExecutionArrayValid = false; this->Internals->ExecutionArrayValid = false;
} }
template<typename T, typename S> template <typename T, typename S>
ArrayHandle<T,S>::~ArrayHandle() ArrayHandle<T, S>::~ArrayHandle()
{ {
} }
template<typename T, typename S> template <typename T, typename S>
ArrayHandle<T,S>& ArrayHandle<T, S>& ArrayHandle<T, S>::operator=(const ArrayHandle<T, S>& src)
ArrayHandle<T,S>::operator=(const ArrayHandle<T,S> &src)
{ {
this->Internals = src.Internals; this->Internals = src.Internals;
return *this; return *this;
} }
template<typename T, typename S> template <typename T, typename S>
ArrayHandle<T,S>& ArrayHandle<T, S>& ArrayHandle<T, S>::operator=(ArrayHandle<T, S>&& src)
ArrayHandle<T,S>::operator=(ArrayHandle<T,S> &&src)
{ {
this->Internals = std::move(src.Internals); this->Internals = std::move(src.Internals);
return *this; return *this;
} }
template<typename T, typename S> template <typename T, typename S>
typename ArrayHandle<T,S>::StorageType& typename ArrayHandle<T, S>::StorageType& ArrayHandle<T, S>::GetStorage()
ArrayHandle<T,S>::GetStorage()
{ {
this->SyncControlArray(); this->SyncControlArray();
if (this->Internals->ControlArrayValid) if (this->Internals->ControlArrayValid)
@ -85,9 +86,8 @@ ArrayHandle<T,S>::GetStorage()
} }
} }
template<typename T, typename S> template <typename T, typename S>
const typename ArrayHandle<T,S>::StorageType& const typename ArrayHandle<T, S>::StorageType& ArrayHandle<T, S>::GetStorage() const
ArrayHandle<T,S>::GetStorage() const
{ {
this->SyncControlArray(); this->SyncControlArray();
if (this->Internals->ControlArrayValid) if (this->Internals->ControlArrayValid)
@ -101,9 +101,8 @@ ArrayHandle<T,S>::GetStorage() const
} }
} }
template<typename T, typename S> template <typename T, typename S>
typename ArrayHandle<T,S>::PortalControl typename ArrayHandle<T, S>::PortalControl ArrayHandle<T, S>::GetPortalControl()
ArrayHandle<T,S>::GetPortalControl()
{ {
this->SyncControlArray(); this->SyncControlArray();
if (this->Internals->ControlArrayValid) if (this->Internals->ControlArrayValid)
@ -117,13 +116,12 @@ ArrayHandle<T,S>::GetPortalControl()
else else
{ {
throw vtkm::cont::ErrorInternal( throw vtkm::cont::ErrorInternal(
"ArrayHandle::SyncControlArray did not make control array valid."); "ArrayHandle::SyncControlArray did not make control array valid.");
} }
} }
template<typename T, typename S> template <typename T, typename S>
typename ArrayHandle<T,S>::PortalConstControl typename ArrayHandle<T, S>::PortalConstControl ArrayHandle<T, S>::GetPortalConstControl() const
ArrayHandle<T,S>::GetPortalConstControl() const
{ {
this->SyncControlArray(); this->SyncControlArray();
if (this->Internals->ControlArrayValid) if (this->Internals->ControlArrayValid)
@ -133,12 +131,12 @@ ArrayHandle<T,S>::GetPortalConstControl() const
else else
{ {
throw vtkm::cont::ErrorInternal( throw vtkm::cont::ErrorInternal(
"ArrayHandle::SyncControlArray did not make control array valid."); "ArrayHandle::SyncControlArray did not make control array valid.");
} }
} }
template<typename T, typename S> template <typename T, typename S>
vtkm::Id ArrayHandle<T,S>::GetNumberOfValues() const vtkm::Id ArrayHandle<T, S>::GetNumberOfValues() const
{ {
if (this->Internals->ControlArrayValid) if (this->Internals->ControlArrayValid)
{ {
@ -154,50 +152,46 @@ vtkm::Id ArrayHandle<T,S>::GetNumberOfValues() const
} }
} }
template<typename T, typename S> template <typename T, typename S>
template<typename IteratorType, typename DeviceAdapterTag> template <typename IteratorType, typename DeviceAdapterTag>
void ArrayHandle<T,S>::CopyInto(IteratorType dest, DeviceAdapterTag) const void ArrayHandle<T, S>::CopyInto(IteratorType dest, DeviceAdapterTag) const
{ {
using pointer_type = typename std::iterator_traits<IteratorType>::pointer; using pointer_type = typename std::iterator_traits<IteratorType>::pointer;
using value_type = typename std::remove_pointer<pointer_type>::type; using value_type = typename std::remove_pointer<pointer_type>::type;
static_assert( !std::is_const<value_type>::value, static_assert(!std::is_const<value_type>::value, "CopyInto requires a non const iterator.");
"CopyInto requires a non const iterator." );
VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag); VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag);
if (!this->Internals->ControlArrayValid && if (!this->Internals->ControlArrayValid && !this->Internals->ExecutionArrayValid)
!this->Internals->ExecutionArrayValid) {
{ throw vtkm::cont::ErrorBadValue("ArrayHandle has no data to copy into Iterator.");
throw vtkm::cont::ErrorBadValue( }
"ArrayHandle has no data to copy into Iterator.");
}
if (!this->Internals->ControlArrayValid && if (!this->Internals->ControlArrayValid &&
this->Internals->ExecutionArray->IsDeviceAdapter(DeviceAdapterTag())) this->Internals->ExecutionArray->IsDeviceAdapter(DeviceAdapterTag()))
{ {
/// Dynamically cast ArrayHandleExecutionManagerBase into a concrete /// Dynamically cast ArrayHandleExecutionManagerBase into a concrete
/// class and call CopyInto. The dynamic conversion will be sucessful /// class and call CopyInto. The dynamic conversion will be sucessful
/// becuase the check to ensure the ExecutionArray is of the type /// becuase the check to ensure the ExecutionArray is of the type
/// DeviceAdapterTag has already passed /// DeviceAdapterTag has already passed
typedef vtkm::cont::internal::ArrayHandleExecutionManager< typedef vtkm::cont::internal::ArrayHandleExecutionManager<T, StorageTag, DeviceAdapterTag>
T, StorageTag, DeviceAdapterTag> ConcreteType; ConcreteType;
ConcreteType *ConcreteExecutionArray = ConcreteType* ConcreteExecutionArray =
dynamic_cast<ConcreteType*>(this->Internals->ExecutionArray.get()); dynamic_cast<ConcreteType*>(this->Internals->ExecutionArray.get());
ConcreteExecutionArray->CopyInto(dest); ConcreteExecutionArray->CopyInto(dest);
} }
else else
{ {
PortalConstControl portal = this->GetPortalConstControl(); PortalConstControl portal = this->GetPortalConstControl();
std::copy(vtkm::cont::ArrayPortalToIteratorBegin(portal), std::copy(vtkm::cont::ArrayPortalToIteratorBegin(portal),
vtkm::cont::ArrayPortalToIteratorEnd(portal), vtkm::cont::ArrayPortalToIteratorEnd(portal), dest);
dest); }
}
} }
template<typename T, typename S> template <typename T, typename S>
void ArrayHandle<T,S>::Shrink(vtkm::Id numberOfValues) void ArrayHandle<T, S>::Shrink(vtkm::Id numberOfValues)
{ {
VTKM_ASSERT(numberOfValues >= 0); VTKM_ASSERT(numberOfValues >= 0);
@ -222,8 +216,7 @@ void ArrayHandle<T,S>::Shrink(vtkm::Id numberOfValues)
} }
else // numberOfValues > originalNumberOfValues else // numberOfValues > originalNumberOfValues
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("ArrayHandle::Shrink cannot be used to grow array.");
"ArrayHandle::Shrink cannot be used to grow array.");
} }
VTKM_ASSERT(this->GetNumberOfValues() == numberOfValues); VTKM_ASSERT(this->GetNumberOfValues() == numberOfValues);
@ -237,15 +230,14 @@ void ArrayHandle<T,S>::Shrink(vtkm::Id numberOfValues)
} }
} }
template<typename T, typename S> template <typename T, typename S>
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
typename ArrayHandle<T,S>::template ExecutionTypes<DeviceAdapterTag>::PortalConst typename ArrayHandle<T, S>::template ExecutionTypes<DeviceAdapterTag>::PortalConst
ArrayHandle<T,S>::PrepareForInput(DeviceAdapterTag) const ArrayHandle<T, S>::PrepareForInput(DeviceAdapterTag) const
{ {
VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag); VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag);
if (!this->Internals->ControlArrayValid if (!this->Internals->ControlArrayValid && !this->Internals->ExecutionArrayValid)
&& !this->Internals->ExecutionArrayValid)
{ {
// Want to use an empty array. // Want to use an empty array.
// Set up ArrayHandle state so this actually works. // Set up ArrayHandle state so this actually works.
@ -255,18 +247,18 @@ ArrayHandle<T,S>::PrepareForInput(DeviceAdapterTag) const
this->PrepareForDevice(DeviceAdapterTag()); this->PrepareForDevice(DeviceAdapterTag());
typename ExecutionTypes<DeviceAdapterTag>::PortalConst portal = typename ExecutionTypes<DeviceAdapterTag>::PortalConst portal =
this->Internals->ExecutionArray->PrepareForInput( this->Internals->ExecutionArray->PrepareForInput(!this->Internals->ExecutionArrayValid,
!this->Internals->ExecutionArrayValid, DeviceAdapterTag()); DeviceAdapterTag());
this->Internals->ExecutionArrayValid = true; this->Internals->ExecutionArrayValid = true;
return portal; return portal;
} }
template<typename T, typename S> template <typename T, typename S>
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
typename ArrayHandle<T,S>::template ExecutionTypes<DeviceAdapterTag>::Portal typename ArrayHandle<T, S>::template ExecutionTypes<DeviceAdapterTag>::Portal
ArrayHandle<T,S>::PrepareForOutput(vtkm::Id numberOfValues, DeviceAdapterTag) ArrayHandle<T, S>::PrepareForOutput(vtkm::Id numberOfValues, DeviceAdapterTag)
{ {
VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag); VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag);
@ -277,8 +269,7 @@ ArrayHandle<T,S>::PrepareForOutput(vtkm::Id numberOfValues, DeviceAdapterTag)
this->PrepareForDevice(DeviceAdapterTag()); this->PrepareForDevice(DeviceAdapterTag());
typename ExecutionTypes<DeviceAdapterTag>::Portal portal = typename ExecutionTypes<DeviceAdapterTag>::Portal portal =
this->Internals->ExecutionArray->PrepareForOutput(numberOfValues, this->Internals->ExecutionArray->PrepareForOutput(numberOfValues, DeviceAdapterTag());
DeviceAdapterTag());
// We are assuming that the calling code will fill the array using the // We are assuming that the calling code will fill the array using the
// iterators we are returning, so go ahead and mark the execution array as // iterators we are returning, so go ahead and mark the execution array as
@ -294,15 +285,14 @@ ArrayHandle<T,S>::PrepareForOutput(vtkm::Id numberOfValues, DeviceAdapterTag)
return portal; return portal;
} }
template<typename T, typename S> template <typename T, typename S>
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
typename ArrayHandle<T,S>::template ExecutionTypes<DeviceAdapterTag>::Portal typename ArrayHandle<T, S>::template ExecutionTypes<DeviceAdapterTag>::Portal
ArrayHandle<T,S>::PrepareForInPlace(DeviceAdapterTag) ArrayHandle<T, S>::PrepareForInPlace(DeviceAdapterTag)
{ {
VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag); VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag);
if (!this->Internals->ControlArrayValid if (!this->Internals->ControlArrayValid && !this->Internals->ExecutionArrayValid)
&& !this->Internals->ExecutionArrayValid)
{ {
// Want to use an empty array. // Want to use an empty array.
// Set up ArrayHandle state so this actually works. // Set up ArrayHandle state so this actually works.
@ -312,8 +302,8 @@ ArrayHandle<T,S>::PrepareForInPlace(DeviceAdapterTag)
this->PrepareForDevice(DeviceAdapterTag()); this->PrepareForDevice(DeviceAdapterTag());
typename ExecutionTypes<DeviceAdapterTag>::Portal portal = typename ExecutionTypes<DeviceAdapterTag>::Portal portal =
this->Internals->ExecutionArray->PrepareForInPlace( this->Internals->ExecutionArray->PrepareForInPlace(!this->Internals->ExecutionArrayValid,
!this->Internals->ExecutionArrayValid, DeviceAdapterTag()); DeviceAdapterTag());
this->Internals->ExecutionArrayValid = true; this->Internals->ExecutionArrayValid = true;
@ -325,9 +315,9 @@ ArrayHandle<T,S>::PrepareForInPlace(DeviceAdapterTag)
return portal; return portal;
} }
template<typename T, typename S> template <typename T, typename S>
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
void ArrayHandle<T,S>::PrepareForDevice(DeviceAdapterTag) const void ArrayHandle<T, S>::PrepareForDevice(DeviceAdapterTag) const
{ {
if (this->Internals->ExecutionArray != nullptr) if (this->Internals->ExecutionArray != nullptr)
{ {
@ -347,34 +337,30 @@ void ArrayHandle<T,S>::PrepareForDevice(DeviceAdapterTag) const
this->SyncControlArray(); this->SyncControlArray();
// Need to change some state that does not change the logical state from // Need to change some state that does not change the logical state from
// an external point of view. // an external point of view.
InternalStruct *internals InternalStruct* internals = const_cast<InternalStruct*>(this->Internals.get());
= const_cast<InternalStruct*>(this->Internals.get());
internals->ExecutionArray.reset(); internals->ExecutionArray.reset();
internals->ExecutionArrayValid = false; internals->ExecutionArrayValid = false;
}
} }
}
VTKM_ASSERT(this->Internals->ExecutionArray == nullptr); VTKM_ASSERT(this->Internals->ExecutionArray == nullptr);
VTKM_ASSERT(!this->Internals->ExecutionArrayValid); VTKM_ASSERT(!this->Internals->ExecutionArrayValid);
// Need to change some state that does not change the logical state from // Need to change some state that does not change the logical state from
// an external point of view. // an external point of view.
InternalStruct *internals InternalStruct* internals = const_cast<InternalStruct*>(this->Internals.get());
= const_cast<InternalStruct*>(this->Internals.get());
internals->ExecutionArray.reset( internals->ExecutionArray.reset(
new vtkm::cont::internal::ArrayHandleExecutionManager< new vtkm::cont::internal::ArrayHandleExecutionManager<T, StorageTag, DeviceAdapterTag>(
T, StorageTag, DeviceAdapterTag>(&internals->ControlArray)); &internals->ControlArray));
} }
template <typename T, typename S>
template<typename T, typename S> void ArrayHandle<T, S>::SyncControlArray() const
void ArrayHandle<T,S>::SyncControlArray() const
{ {
if (!this->Internals->ControlArrayValid) if (!this->Internals->ControlArrayValid)
{ {
// Need to change some state that does not change the logical state from // Need to change some state that does not change the logical state from
// an external point of view. // an external point of view.
InternalStruct *internals InternalStruct* internals = const_cast<InternalStruct*>(this->Internals.get());
= const_cast<InternalStruct*>(this->Internals.get());
if (this->Internals->ExecutionArrayValid) if (this->Internals->ExecutionArrayValid)
{ {
internals->ExecutionArray->RetrieveOutputData(&internals->ControlArray); internals->ExecutionArray->RetrieveOutputData(&internals->ControlArray);
@ -390,7 +376,5 @@ void ArrayHandle<T,S>::SyncControlArray() const
} }
} }
} }
} }
} }

@ -25,16 +25,17 @@
#include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandle.h>
#include <vtkm/cont/ErrorBadAllocation.h> #include <vtkm/cont/ErrorBadAllocation.h>
namespace vtkm { namespace vtkm
namespace exec { {
namespace internal { namespace exec
{
namespace internal
{
/// \brief An array portal that acts as a 3D cartesian product of 3 arrays. /// \brief An array portal that acts as a 3D cartesian product of 3 arrays.
/// ///
template<typename ValueType_, template <typename ValueType_, typename PortalTypeFirst_, typename PortalTypeSecond_,
typename PortalTypeFirst_, typename PortalTypeThird_>
typename PortalTypeSecond_,
typename PortalTypeThird_>
class VTKM_ALWAYS_EXPORT ArrayPortalCartesianProduct class VTKM_ALWAYS_EXPORT ArrayPortalCartesianProduct
{ {
public: public:
@ -47,37 +48,42 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalCartesianProduct() ArrayPortalCartesianProduct()
: PortalFirst(), PortalSecond(), PortalThird() : PortalFirst()
{ } //needs to be host and device so that cuda can create lvalue of these , PortalSecond()
, PortalThird()
{
} //needs to be host and device so that cuda can create lvalue of these
VTKM_CONT VTKM_CONT
ArrayPortalCartesianProduct(const PortalTypeFirst &portalfirst, ArrayPortalCartesianProduct(const PortalTypeFirst& portalfirst,
const PortalTypeSecond &portalsecond, const PortalTypeSecond& portalsecond,
const PortalTypeThird &portalthird) const PortalTypeThird& portalthird)
: PortalFirst(portalfirst), PortalSecond(portalsecond), PortalThird(portalthird) : PortalFirst(portalfirst)
{ } , PortalSecond(portalsecond)
, PortalThird(portalthird)
{
}
/// Copy constructor for any other ArrayPortalCartesianProduct with an iterator /// Copy constructor for any other ArrayPortalCartesianProduct with an iterator
/// type that can be copied to this iterator type. This allows us to do any /// type that can be copied to this iterator type. This allows us to do any
/// type casting that the iterators do (like the non-const to const cast). /// type casting that the iterators do (like the non-const to const cast).
/// ///
template<class OtherV, class OtherP1, class OtherP2, class OtherP3> template <class OtherV, class OtherP1, class OtherP2, class OtherP3>
VTKM_CONT VTKM_CONT ArrayPortalCartesianProduct(
ArrayPortalCartesianProduct(const ArrayPortalCartesianProduct<OtherV,OtherP1,OtherP2,OtherP3> &src) const ArrayPortalCartesianProduct<OtherV, OtherP1, OtherP2, OtherP3>& src)
: PortalFirst(src.GetPortalFirst()), : PortalFirst(src.GetPortalFirst())
PortalSecond(src.GetPortalSecond()), , PortalSecond(src.GetPortalSecond())
PortalThird(src.GetPortalThird()) , PortalThird(src.GetPortalThird())
{ } {
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
return this->PortalFirst.GetNumberOfValues() * return this->PortalFirst.GetNumberOfValues() * this->PortalSecond.GetNumberOfValues() *
this->PortalSecond.GetNumberOfValues() * this->PortalThird.GetNumberOfValues();
this->PortalThird.GetNumberOfValues();
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
@ -89,27 +95,26 @@ public:
vtkm::Id dim1 = this->PortalFirst.GetNumberOfValues(); vtkm::Id dim1 = this->PortalFirst.GetNumberOfValues();
vtkm::Id dim2 = this->PortalSecond.GetNumberOfValues(); vtkm::Id dim2 = this->PortalSecond.GetNumberOfValues();
vtkm::Id dim12 = dim1*dim2; vtkm::Id dim12 = dim1 * dim2;
vtkm::Id idx12 = index % dim12; vtkm::Id idx12 = index % dim12;
vtkm::Id i1 = idx12 % dim1; vtkm::Id i1 = idx12 % dim1;
vtkm::Id i2 = idx12 / dim1; vtkm::Id i2 = idx12 / dim1;
vtkm::Id i3 = index / dim12; vtkm::Id i3 = index / dim12;
return vtkm::make_Vec(this->PortalFirst.Get(i1), return vtkm::make_Vec(this->PortalFirst.Get(i1), this->PortalSecond.Get(i2),
this->PortalSecond.Get(i2),
this->PortalThird.Get(i3)); this->PortalThird.Get(i3));
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set(vtkm::Id index, const ValueType &value) const void Set(vtkm::Id index, const ValueType& value) const
{ {
VTKM_ASSERT(index >= 0); VTKM_ASSERT(index >= 0);
VTKM_ASSERT(index < this->GetNumberOfValues()); VTKM_ASSERT(index < this->GetNumberOfValues());
vtkm::Id dim1 = this->PortalFirst.GetNumberOfValues(); vtkm::Id dim1 = this->PortalFirst.GetNumberOfValues();
vtkm::Id dim2 = this->PortalSecond.GetNumberOfValues(); vtkm::Id dim2 = this->PortalSecond.GetNumberOfValues();
vtkm::Id dim12 = dim1*dim2; vtkm::Id dim12 = dim1 * dim2;
vtkm::Id idx12 = index % dim12; vtkm::Id idx12 = index % dim12;
vtkm::Id i1 = idx12 % dim1; vtkm::Id i1 = idx12 % dim1;
@ -123,57 +128,59 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const PortalTypeFirst &GetFirstPortal() const { return this->PortalFirst; } const PortalTypeFirst& GetFirstPortal() const { return this->PortalFirst; }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const PortalTypeSecond &GetSecondPortal() const { return this->PortalSecond; } const PortalTypeSecond& GetSecondPortal() const { return this->PortalSecond; }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const PortalTypeThird &GetThirdPortal() const { return this->PortalThird; } const PortalTypeThird& GetThirdPortal() const { return this->PortalThird; }
private: private:
PortalTypeFirst PortalFirst; PortalTypeFirst PortalFirst;
PortalTypeSecond PortalSecond; PortalTypeSecond PortalSecond;
PortalTypeThird PortalThird; PortalTypeThird PortalThird;
}; };
} }
} }
} // namespace vtkm::exec::internal } // namespace vtkm::exec::internal
namespace vtkm
{
namespace cont
{
namespace vtkm { namespace internal
namespace cont { {
namespace internal { template <typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType>
struct VTKM_ALWAYS_EXPORT StorageTagCartesianProduct
template<typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType> {
struct VTKM_ALWAYS_EXPORT StorageTagCartesianProduct { }; };
/// This helper struct defines the value type for a zip container containing /// This helper struct defines the value type for a zip container containing
/// the given two array handles. /// the given two array handles.
/// ///
template<typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType> template <typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType>
struct ArrayHandleCartesianProductTraits { struct ArrayHandleCartesianProductTraits
{
/// The ValueType (a pair containing the value types of the two arrays). /// The ValueType (a pair containing the value types of the two arrays).
/// ///
typedef vtkm::Vec<typename FirstHandleType::ValueType,3> ValueType; typedef vtkm::Vec<typename FirstHandleType::ValueType, 3> ValueType;
/// The appropriately templated tag. /// The appropriately templated tag.
/// ///
typedef StorageTagCartesianProduct<FirstHandleType,SecondHandleType,ThirdHandleType> Tag; typedef StorageTagCartesianProduct<FirstHandleType, SecondHandleType, ThirdHandleType> Tag;
/// The superclass for ArrayHandleCartesianProduct. /// The superclass for ArrayHandleCartesianProduct.
/// ///
typedef vtkm::cont::ArrayHandle<ValueType,Tag> Superclass; typedef vtkm::cont::ArrayHandle<ValueType, Tag> Superclass;
}; };
template <typename T, typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType>
template<typename T, typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType> class Storage<T, StorageTagCartesianProduct<FirstHandleType, SecondHandleType, ThirdHandleType>>
class Storage<T, StorageTagCartesianProduct<FirstHandleType, SecondHandleType, ThirdHandleType > >
{ {
VTKM_IS_ARRAY_HANDLE(FirstHandleType); VTKM_IS_ARRAY_HANDLE(FirstHandleType);
VTKM_IS_ARRAY_HANDLE(SecondHandleType); VTKM_IS_ARRAY_HANDLE(SecondHandleType);
@ -182,60 +189,64 @@ class Storage<T, StorageTagCartesianProduct<FirstHandleType, SecondHandleType, T
public: public:
typedef T ValueType; typedef T ValueType;
typedef vtkm::exec::internal::ArrayPortalCartesianProduct< ValueType, typedef vtkm::exec::internal::ArrayPortalCartesianProduct<
typename FirstHandleType::PortalControl, ValueType, typename FirstHandleType::PortalControl, typename SecondHandleType::PortalControl,
typename SecondHandleType::PortalControl, typename ThirdHandleType::PortalControl>
typename ThirdHandleType::PortalControl> PortalType; PortalType;
typedef vtkm::exec::internal::ArrayPortalCartesianProduct< ValueType, typedef vtkm::exec::internal::ArrayPortalCartesianProduct<
typename FirstHandleType::PortalConstControl, ValueType, typename FirstHandleType::PortalConstControl,
typename SecondHandleType::PortalConstControl, typename SecondHandleType::PortalConstControl, typename ThirdHandleType::PortalConstControl>
typename ThirdHandleType::PortalConstControl> PortalConstType;
PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : FirstArray(), SecondArray(), ThirdArray() { } Storage()
: FirstArray()
VTKM_CONT , SecondArray()
Storage(const FirstHandleType &array1, const SecondHandleType &array2, const ThirdHandleType &array3) , ThirdArray()
: FirstArray(array1), SecondArray(array2), ThirdArray(array3)
{ {
}
VTKM_CONT
Storage(const FirstHandleType& array1, const SecondHandleType& array2,
const ThirdHandleType& array3)
: FirstArray(array1)
, SecondArray(array2)
, ThirdArray(array3)
{
} }
VTKM_CONT VTKM_CONT
PortalType GetPortal() PortalType GetPortal()
{ {
return PortalType(this->FirstArray.GetPortalControl(), return PortalType(this->FirstArray.GetPortalControl(), this->SecondArray.GetPortalControl(),
this->SecondArray.GetPortalControl(), this->ThirdArray.GetPortalControl());
this->ThirdArray.GetPortalControl());
} }
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const PortalConstType GetPortalConst() const
{ {
return PortalConstType(this->FirstArray.GetPortalConstControl(), return PortalConstType(this->FirstArray.GetPortalConstControl(),
this->SecondArray.GetPortalConstControl(), this->SecondArray.GetPortalConstControl(),
this->ThirdArray.GetPortalConstControl()); this->ThirdArray.GetPortalConstControl());
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
return this->FirstArray.GetNumberOfValues() * return this->FirstArray.GetNumberOfValues() * this->SecondArray.GetNumberOfValues() *
this->SecondArray.GetNumberOfValues() * this->ThirdArray.GetNumberOfValues();
this->ThirdArray.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id /*numberOfValues*/) void Allocate(vtkm::Id /*numberOfValues*/)
{ {
throw vtkm::cont::ErrorBadAllocation("Does not make sense."); throw vtkm::cont::ErrorBadAllocation("Does not make sense.");
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id /*numberOfValues*/) void Shrink(vtkm::Id /*numberOfValues*/)
{ {
throw vtkm::cont::ErrorBadAllocation("Does not make sense."); throw vtkm::cont::ErrorBadAllocation("Does not make sense.");
} }
VTKM_CONT VTKM_CONT
@ -246,22 +257,13 @@ public:
} }
VTKM_CONT VTKM_CONT
const FirstHandleType &GetFirstArray() const const FirstHandleType& GetFirstArray() const { return this->FirstArray; }
{
return this->FirstArray;
}
VTKM_CONT VTKM_CONT
const SecondHandleType &GetSecondArray() const const SecondHandleType& GetSecondArray() const { return this->SecondArray; }
{
return this->SecondArray;
}
VTKM_CONT VTKM_CONT
const ThirdHandleType &GetThirdArray() const const ThirdHandleType& GetThirdArray() const { return this->ThirdArray; }
{
return this->ThirdArray;
}
private: private:
FirstHandleType FirstArray; FirstHandleType FirstArray;
@ -269,15 +271,12 @@ private:
ThirdHandleType ThirdArray; ThirdHandleType ThirdArray;
}; };
template<typename T, template <typename T, typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType,
typename FirstHandleType, typename Device>
typename SecondHandleType,
typename ThirdHandleType,
typename Device>
class ArrayTransfer< class ArrayTransfer<
T, StorageTagCartesianProduct<FirstHandleType,SecondHandleType,ThirdHandleType>, Device> T, StorageTagCartesianProduct<FirstHandleType, SecondHandleType, ThirdHandleType>, Device>
{ {
typedef StorageTagCartesianProduct<FirstHandleType,SecondHandleType,ThirdHandleType> StorageTag; typedef StorageTagCartesianProduct<FirstHandleType, SecondHandleType, ThirdHandleType> StorageTag;
typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType;
public: public:
@ -287,38 +286,35 @@ public:
typedef typename StorageType::PortalConstType PortalConstControl; typedef typename StorageType::PortalConstType PortalConstControl;
typedef vtkm::exec::internal::ArrayPortalCartesianProduct< typedef vtkm::exec::internal::ArrayPortalCartesianProduct<
ValueType, ValueType, typename FirstHandleType::template ExecutionTypes<Device>::Portal,
typename FirstHandleType::template ExecutionTypes<Device>::Portal, typename SecondHandleType::template ExecutionTypes<Device>::Portal,
typename SecondHandleType::template ExecutionTypes<Device>::Portal, typename ThirdHandleType::template ExecutionTypes<Device>::Portal>
typename ThirdHandleType::template ExecutionTypes<Device>::Portal PortalExecution;
> PortalExecution;
typedef vtkm::exec::internal::ArrayPortalCartesianProduct< typedef vtkm::exec::internal::ArrayPortalCartesianProduct<
ValueType, ValueType, typename FirstHandleType::template ExecutionTypes<Device>::PortalConst,
typename FirstHandleType::template ExecutionTypes<Device>::PortalConst, typename SecondHandleType::template ExecutionTypes<Device>::PortalConst,
typename SecondHandleType::template ExecutionTypes<Device>::PortalConst, typename ThirdHandleType::template ExecutionTypes<Device>::PortalConst>
typename ThirdHandleType::template ExecutionTypes<Device>::PortalConst PortalConstExecution;
> PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) ArrayTransfer(StorageType* storage)
: FirstArray(storage->GetFirstArray()), : FirstArray(storage->GetFirstArray())
SecondArray(storage->GetSecondArray()), , SecondArray(storage->GetSecondArray())
ThirdArray(storage->GetThirdArray()) , ThirdArray(storage->GetThirdArray())
{ } {
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
return this->FirstArray.GetNumberOfValues() * return this->FirstArray.GetNumberOfValues() * this->SecondArray.GetNumberOfValues() *
this->SecondArray.GetNumberOfValues() * this->ThirdArray.GetNumberOfValues();
this->ThirdArray.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) { PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{
return PortalConstExecution(this->FirstArray.PrepareForInput(Device()), return PortalConstExecution(this->FirstArray.PrepareForInput(Device()),
this->SecondArray.PrepareForInput(Device()), this->SecondArray.PrepareForInput(Device()),
this->ThirdArray.PrepareForInput(Device())); this->ThirdArray.PrepareForInput(Device()));
@ -328,20 +324,20 @@ public:
PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData)) PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData))
{ {
throw vtkm::cont::ErrorBadAllocation( throw vtkm::cont::ErrorBadAllocation(
"Cannot write to an ArrayHandleCartesianProduct. It does not make " "Cannot write to an ArrayHandleCartesianProduct. It does not make "
"sense because there is overlap in the data."); "sense because there is overlap in the data.");
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForOutput(vtkm::Id vtkmNotUsed(numberOfValues)) PortalExecution PrepareForOutput(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
throw vtkm::cont::ErrorBadAllocation( throw vtkm::cont::ErrorBadAllocation(
"Cannot write to an ArrayHandleCartesianProduct. It does not make " "Cannot write to an ArrayHandleCartesianProduct. It does not make "
"sense because there is overlap in the data."); "sense because there is overlap in the data.");
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *vtkmNotUsed(storage)) const void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{ {
// Implementation of this method should be unnecessary. The internal // Implementation of this method should be unnecessary. The internal
// first and second array handles should automatically retrieve the // first and second array handles should automatically retrieve the
@ -351,7 +347,7 @@ public:
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id /*numberOfValues*/) void Shrink(vtkm::Id /*numberOfValues*/)
{ {
throw vtkm::cont::ErrorBadAllocation("Does not make sense."); throw vtkm::cont::ErrorBadAllocation("Does not make sense.");
} }
VTKM_CONT VTKM_CONT
@ -362,7 +358,6 @@ public:
this->ThirdArray.ReleaseResourcesExecution(); this->ThirdArray.ReleaseResourcesExecution();
} }
private: private:
FirstHandleType FirstArray; FirstHandleType FirstArray;
SecondHandleType SecondArray; SecondHandleType SecondArray;
@ -374,11 +369,10 @@ private:
/// array handle and makes a new handle that access the corresponding entries /// array handle and makes a new handle that access the corresponding entries
/// in these arrays as a pair. /// in these arrays as a pair.
/// ///
template<typename FirstHandleType, template <typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType>
typename SecondHandleType,
typename ThirdHandleType>
class ArrayHandleCartesianProduct class ArrayHandleCartesianProduct
: public internal::ArrayHandleCartesianProductTraits<FirstHandleType,SecondHandleType,ThirdHandleType>::Superclass : public internal::ArrayHandleCartesianProductTraits<FirstHandleType, SecondHandleType,
ThirdHandleType>::Superclass
{ {
// If the following line gives a compile error, then the FirstHandleType // If the following line gives a compile error, then the FirstHandleType
// template argument is not a valid ArrayHandle type. // template argument is not a valid ArrayHandle type.
@ -388,37 +382,36 @@ class ArrayHandleCartesianProduct
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleCartesianProduct, ArrayHandleCartesianProduct,
(ArrayHandleCartesianProduct<FirstHandleType,SecondHandleType,ThirdHandleType>), (ArrayHandleCartesianProduct<FirstHandleType, SecondHandleType, ThirdHandleType>),
(typename internal::ArrayHandleCartesianProductTraits< (typename internal::ArrayHandleCartesianProductTraits<FirstHandleType, SecondHandleType,
FirstHandleType,SecondHandleType,ThirdHandleType>::Superclass)); ThirdHandleType>::Superclass));
private: private:
typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
VTKM_CONT VTKM_CONT
ArrayHandleCartesianProduct(const FirstHandleType &firstArray, ArrayHandleCartesianProduct(const FirstHandleType& firstArray,
const SecondHandleType &secondArray, const SecondHandleType& secondArray,
const ThirdHandleType &thirdArray) const ThirdHandleType& thirdArray)
: Superclass(StorageType(firstArray, secondArray, thirdArray)) { } : Superclass(StorageType(firstArray, secondArray, thirdArray))
{
}
}; };
/// A convenience function for creating an ArrayHandleCartesianProduct. It takes the two /// A convenience function for creating an ArrayHandleCartesianProduct. It takes the two
/// arrays to be zipped together. /// arrays to be zipped together.
/// ///
template<typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType> template <typename FirstHandleType, typename SecondHandleType, typename ThirdHandleType>
VTKM_CONT VTKM_CONT
vtkm::cont::ArrayHandleCartesianProduct<FirstHandleType,SecondHandleType,ThirdHandleType> vtkm::cont::ArrayHandleCartesianProduct<FirstHandleType, SecondHandleType, ThirdHandleType>
make_ArrayHandleCartesianProduct(const FirstHandleType &first, make_ArrayHandleCartesianProduct(const FirstHandleType& first, const SecondHandleType& second,
const SecondHandleType &second, const ThirdHandleType& third)
const ThirdHandleType &third)
{ {
return ArrayHandleCartesianProduct<FirstHandleType, return ArrayHandleCartesianProduct<FirstHandleType, SecondHandleType, ThirdHandleType>(
SecondHandleType, first, second, third);
ThirdHandleType>(first, second,third);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -24,24 +24,23 @@
#include <vtkm/cont/ArrayHandleTransform.h> #include <vtkm/cont/ArrayHandleTransform.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace internal { namespace internal
{
template<typename FromType, typename ToType> template <typename FromType, typename ToType>
struct VTKM_ALWAYS_EXPORT Cast struct VTKM_ALWAYS_EXPORT Cast
{ {
VTKM_EXEC_CONT VTKM_EXEC_CONT
ToType operator()(const FromType &val) const ToType operator()(const FromType& val) const { return static_cast<ToType>(val); }
{
return static_cast<ToType>(val);
}
}; };
} // namespace internal } // namespace internal
/// \brief Cast the values of an array to the specified type, on demand. /// \brief Cast the values of an array to the specified type, on demand.
/// ///
/// ArrayHandleCast is a specialization of ArrayHandleTransform. Given an ArrayHandle /// ArrayHandleCast is a specialization of ArrayHandleTransform. Given an ArrayHandle
@ -49,39 +48,33 @@ struct VTKM_ALWAYS_EXPORT Cast
/// to the specified type. /// to the specified type.
/// ///
template <typename T, typename ArrayHandleType> template <typename T, typename ArrayHandleType>
class ArrayHandleCast : class ArrayHandleCast
public vtkm::cont::ArrayHandleTransform< : public vtkm::cont::ArrayHandleTransform<T, ArrayHandleType,
T, internal::Cast<typename ArrayHandleType::ValueType, T>,
ArrayHandleType, internal::Cast<T, typename ArrayHandleType::ValueType>>
internal::Cast<typename ArrayHandleType::ValueType, T>,
internal::Cast<T, typename ArrayHandleType::ValueType> >
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleCast, ArrayHandleCast, (ArrayHandleCast<T, ArrayHandleType>),
(ArrayHandleCast<T, ArrayHandleType>), (vtkm::cont::ArrayHandleTransform<T, ArrayHandleType,
(vtkm::cont::ArrayHandleTransform< internal::Cast<typename ArrayHandleType::ValueType, T>,
T, internal::Cast<T, typename ArrayHandleType::ValueType>>));
ArrayHandleType,
internal::Cast<typename ArrayHandleType::ValueType, T>,
internal::Cast<T, typename ArrayHandleType::ValueType> >));
ArrayHandleCast(const ArrayHandleType &handle) ArrayHandleCast(const ArrayHandleType& handle)
: Superclass(handle) : Superclass(handle)
{ } {
}
}; };
/// make_ArrayHandleCast is convenience function to generate an /// make_ArrayHandleCast is convenience function to generate an
/// ArrayHandleCast. /// ArrayHandleCast.
/// ///
template <typename T, typename HandleType> template <typename T, typename HandleType>
VTKM_CONT VTKM_CONT ArrayHandleCast<T, HandleType> make_ArrayHandleCast(const HandleType& handle,
ArrayHandleCast<T, HandleType> make_ArrayHandleCast(const HandleType &handle, const T& = T())
const T& = T())
{ {
return ArrayHandleCast<T, HandleType>(handle); return ArrayHandleCast<T, HandleType>(handle);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -31,133 +31,138 @@
#include <sstream> #include <sstream>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace internal { namespace internal
{
namespace detail { namespace detail
{
template<typename ValueType> template <typename ValueType>
struct VTKM_ALWAYS_EXPORT CompositeVectorSwizzleFunctor struct VTKM_ALWAYS_EXPORT CompositeVectorSwizzleFunctor
{ {
static const vtkm::IdComponent NUM_COMPONENTS = static const vtkm::IdComponent NUM_COMPONENTS = vtkm::VecTraits<ValueType>::NUM_COMPONENTS;
vtkm::VecTraits<ValueType>::NUM_COMPONENTS;
typedef vtkm::Vec<vtkm::IdComponent, NUM_COMPONENTS> ComponentMapType; typedef vtkm::Vec<vtkm::IdComponent, NUM_COMPONENTS> ComponentMapType;
// Caution! This is a reference. // Caution! This is a reference.
const ComponentMapType &SourceComponents; const ComponentMapType& SourceComponents;
VTKM_EXEC_CONT VTKM_EXEC_CONT
CompositeVectorSwizzleFunctor(const ComponentMapType &sourceComponents) CompositeVectorSwizzleFunctor(const ComponentMapType& sourceComponents)
: SourceComponents(sourceComponents) { } : SourceComponents(sourceComponents)
{
}
// Currently only supporting 1-4 components. // Currently only supporting 1-4 components.
template<typename T1> template <typename T1>
VTKM_EXEC_CONT VTKM_EXEC_CONT ValueType operator()(const T1& p1) const
ValueType operator()(const T1 &p1) const { {
return ValueType( return ValueType(vtkm::VecTraits<T1>::GetComponent(p1, this->SourceComponents[0]));
vtkm::VecTraits<T1>::GetComponent(p1, this->SourceComponents[0]));
} }
template<typename T1, typename T2> template <typename T1, typename T2>
VTKM_EXEC_CONT VTKM_EXEC_CONT ValueType operator()(const T1& p1, const T2& p2) const
ValueType operator()(const T1 &p1, const T2 &p2) const { {
return ValueType( return ValueType(vtkm::VecTraits<T1>::GetComponent(p1, this->SourceComponents[0]),
vtkm::VecTraits<T1>::GetComponent(p1, this->SourceComponents[0]), vtkm::VecTraits<T2>::GetComponent(p2, this->SourceComponents[1]));
vtkm::VecTraits<T2>::GetComponent(p2, this->SourceComponents[1]));
} }
template<typename T1, typename T2, typename T3> template <typename T1, typename T2, typename T3>
VTKM_EXEC_CONT VTKM_EXEC_CONT ValueType operator()(const T1& p1, const T2& p2, const T3& p3) const
ValueType operator()(const T1 &p1, const T2 &p2, const T3 &p3) const { {
return ValueType( return ValueType(vtkm::VecTraits<T1>::GetComponent(p1, this->SourceComponents[0]),
vtkm::VecTraits<T1>::GetComponent(p1, this->SourceComponents[0]), vtkm::VecTraits<T2>::GetComponent(p2, this->SourceComponents[1]),
vtkm::VecTraits<T2>::GetComponent(p2, this->SourceComponents[1]), vtkm::VecTraits<T3>::GetComponent(p3, this->SourceComponents[2]));
vtkm::VecTraits<T3>::GetComponent(p3, this->SourceComponents[2]));
} }
template<typename T1, typename T2, typename T3, typename T4> template <typename T1, typename T2, typename T3, typename T4>
VTKM_EXEC_CONT VTKM_EXEC_CONT ValueType operator()(const T1& p1, const T2& p2, const T3& p3, const T4& p4) const
ValueType operator()(const T1 &p1, {
const T2 &p2, return ValueType(vtkm::VecTraits<T1>::GetComponent(p1, this->SourceComponents[0]),
const T3 &p3, vtkm::VecTraits<T2>::GetComponent(p2, this->SourceComponents[1]),
const T4 &p4) const { vtkm::VecTraits<T3>::GetComponent(p3, this->SourceComponents[2]),
return ValueType( vtkm::VecTraits<T4>::GetComponent(p4, this->SourceComponents[3]));
vtkm::VecTraits<T1>::GetComponent(p1, this->SourceComponents[0]),
vtkm::VecTraits<T2>::GetComponent(p2, this->SourceComponents[1]),
vtkm::VecTraits<T3>::GetComponent(p3, this->SourceComponents[2]),
vtkm::VecTraits<T4>::GetComponent(p4, this->SourceComponents[3]));
} }
}; };
template<typename ReturnValueType> template <typename ReturnValueType>
struct VTKM_ALWAYS_EXPORT CompositeVectorPullValueFunctor struct VTKM_ALWAYS_EXPORT CompositeVectorPullValueFunctor
{ {
vtkm::Id Index; vtkm::Id Index;
VTKM_EXEC VTKM_EXEC
CompositeVectorPullValueFunctor(vtkm::Id index) : Index(index) { } CompositeVectorPullValueFunctor(vtkm::Id index)
: Index(index)
{
}
// This form is to pull values out of array arguments. // This form is to pull values out of array arguments.
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<typename PortalType> template <typename PortalType>
VTKM_EXEC_CONT VTKM_EXEC_CONT typename PortalType::ValueType operator()(const PortalType& portal) const
typename PortalType::ValueType operator()(const PortalType &portal) const { {
return portal.Get(this->Index); return portal.Get(this->Index);
} }
// This form is an identity to pass the return value back. // This form is an identity to pass the return value back.
VTKM_EXEC_CONT VTKM_EXEC_CONT
const ReturnValueType &operator()(const ReturnValueType &value) const { const ReturnValueType& operator()(const ReturnValueType& value) const { return value; }
return value;
}
}; };
struct CompositeVectorArrayToPortalCont { struct CompositeVectorArrayToPortalCont
template<typename ArrayHandleType, vtkm::IdComponent Index> {
struct ReturnType { template <typename ArrayHandleType, vtkm::IdComponent Index>
struct ReturnType
{
typedef typename ArrayHandleType::PortalConstControl type; typedef typename ArrayHandleType::PortalConstControl type;
}; };
template<typename ArrayHandleType, vtkm::IdComponent Index> template <typename ArrayHandleType, vtkm::IdComponent Index>
VTKM_CONT VTKM_CONT typename ReturnType<ArrayHandleType, Index>::type operator()(
typename ReturnType<ArrayHandleType, Index>::type const ArrayHandleType& array, vtkm::internal::IndexTag<Index>) const
operator()(const ArrayHandleType &array, {
vtkm::internal::IndexTag<Index>) const {
return array.GetPortalConstControl(); return array.GetPortalConstControl();
} }
}; };
template<typename DeviceAdapterTag> template <typename DeviceAdapterTag>
struct CompositeVectorArrayToPortalExec { struct CompositeVectorArrayToPortalExec
template<typename ArrayHandleType, vtkm::IdComponent Index> {
struct ReturnType { template <typename ArrayHandleType, vtkm::IdComponent Index>
typedef typename ArrayHandleType::template ExecutionTypes< struct ReturnType
DeviceAdapterTag>::PortalConst type; {
typedef typename ArrayHandleType::template ExecutionTypes<DeviceAdapterTag>::PortalConst type;
}; };
template<typename ArrayHandleType, vtkm::IdComponent Index> template <typename ArrayHandleType, vtkm::IdComponent Index>
VTKM_CONT VTKM_CONT typename ReturnType<ArrayHandleType, Index>::type operator()(
typename ReturnType<ArrayHandleType, Index>::type const ArrayHandleType& array, vtkm::internal::IndexTag<Index>) const
operator()(const ArrayHandleType &array, {
vtkm::internal::IndexTag<Index>) const {
return array.PrepareForInput(DeviceAdapterTag()); return array.PrepareForInput(DeviceAdapterTag());
} }
}; };
struct CheckArraySizeFunctor { struct CheckArraySizeFunctor
{
vtkm::Id ExpectedSize; vtkm::Id ExpectedSize;
CheckArraySizeFunctor(vtkm::Id expectedSize) : ExpectedSize(expectedSize) { } CheckArraySizeFunctor(vtkm::Id expectedSize)
: ExpectedSize(expectedSize)
{
}
template<typename T, vtkm::IdComponent Index> template <typename T, vtkm::IdComponent Index>
void operator()(const T &a, vtkm::internal::IndexTag<Index>) const { void operator()(const T& a, vtkm::internal::IndexTag<Index>) const
{
if (a.GetNumberOfValues() != this->ExpectedSize) if (a.GetNumberOfValues() != this->ExpectedSize)
{ {
std::stringstream message; std::stringstream message;
message << "All input arrays to ArrayHandleCompositeVector must be the same size.\n" message << "All input arrays to ArrayHandleCompositeVector must be the same size.\n"
<< "Array " << Index-1 << " has " << a.GetNumberOfValues() << "Array " << Index - 1 << " has " << a.GetNumberOfValues() << ". Expected "
<< ". Expected " << this->ExpectedSize << "."; << this->ExpectedSize << ".";
throw vtkm::cont::ErrorBadValue(message.str().c_str()); throw vtkm::cont::ErrorBadValue(message.str().c_str());
} }
} }
@ -169,15 +174,14 @@ struct CheckArraySizeFunctor {
/// ///
/// This is the portal used within ArrayHandleCompositeVector. /// This is the portal used within ArrayHandleCompositeVector.
/// ///
template<typename SignatureWithPortals> template <typename SignatureWithPortals>
class VTKM_ALWAYS_EXPORT ArrayPortalCompositeVector class VTKM_ALWAYS_EXPORT ArrayPortalCompositeVector
{ {
typedef vtkm::internal::FunctionInterface<SignatureWithPortals> PortalTypes; typedef vtkm::internal::FunctionInterface<SignatureWithPortals> PortalTypes;
public: public:
typedef typename PortalTypes::ResultType ValueType; typedef typename PortalTypes::ResultType ValueType;
static const vtkm::IdComponent NUM_COMPONENTS = static const vtkm::IdComponent NUM_COMPONENTS = vtkm::VecTraits<ValueType>::NUM_COMPONENTS;
vtkm::VecTraits<ValueType>::NUM_COMPONENTS;
// Used internally. // Used internally.
typedef vtkm::Vec<vtkm::IdComponent, NUM_COMPONENTS> ComponentMapType; typedef vtkm::Vec<vtkm::IdComponent, NUM_COMPONENTS> ComponentMapType;
@ -186,61 +190,64 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalCompositeVector() { } ArrayPortalCompositeVector() {}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_CONT VTKM_CONT
ArrayPortalCompositeVector( ArrayPortalCompositeVector(const PortalTypes portals,
const PortalTypes portals, vtkm::Vec<vtkm::IdComponent, NUM_COMPONENTS> sourceComponents)
vtkm::Vec<vtkm::IdComponent, NUM_COMPONENTS> sourceComponents) : Portals(portals)
: Portals(portals), SourceComponents(sourceComponents) { } , SourceComponents(sourceComponents)
{
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const { vtkm::Id GetNumberOfValues() const
{
return this->Portals.template GetParameter<1>().GetNumberOfValues(); return this->Portals.template GetParameter<1>().GetNumberOfValues();
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ValueType Get(vtkm::Id index) const { ValueType Get(vtkm::Id index) const
{
// This might be inefficient because we are copying all the portals only // This might be inefficient because we are copying all the portals only
// because they are coupled with the return value. // because they are coupled with the return value.
PortalTypes localPortals = this->Portals; PortalTypes localPortals = this->Portals;
localPortals.InvokeExec( localPortals.InvokeExec(
detail::CompositeVectorSwizzleFunctor<ValueType>(this->SourceComponents), detail::CompositeVectorSwizzleFunctor<ValueType>(this->SourceComponents),
detail::CompositeVectorPullValueFunctor<ValueType>(index)); detail::CompositeVectorPullValueFunctor<ValueType>(index));
return localPortals.GetReturnValue(); return localPortals.GetReturnValue();
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set(vtkm::Id vtkmNotUsed(index), void Set(vtkm::Id vtkmNotUsed(index), const ValueType& vtkmNotUsed(value)) const
const ValueType &vtkmNotUsed(value)) const
{ {
// There is no technical reason why this cannot be implemented. As of this // There is no technical reason why this cannot be implemented. As of this
// writing no one has needed to write to a composite vector yet. // writing no one has needed to write to a composite vector yet.
VTKM_ASSERT(false && "Set not yet implemented for composite vector. Do you volunteer to implement it?"); VTKM_ASSERT(false &&
"Set not yet implemented for composite vector. Do you volunteer to implement it?");
} }
private: private:
PortalTypes Portals; PortalTypes Portals;
ComponentMapType SourceComponents; ComponentMapType SourceComponents;
}; };
template<typename SignatureWithArrays> template <typename SignatureWithArrays>
struct VTKM_ALWAYS_EXPORT StorageTagCompositeVector { }; struct VTKM_ALWAYS_EXPORT StorageTagCompositeVector
{
};
/// A convenience class that provides a typedef to the appropriate tag for /// A convenience class that provides a typedef to the appropriate tag for
/// a composite storage. /// a composite storage.
template<typename SignatureWithArrays> template <typename SignatureWithArrays>
struct ArrayHandleCompositeVectorTraits struct ArrayHandleCompositeVectorTraits
{ {
typedef vtkm::cont::internal::StorageTagCompositeVector<SignatureWithArrays> typedef vtkm::cont::internal::StorageTagCompositeVector<SignatureWithArrays> Tag;
Tag; typedef typename vtkm::internal::FunctionInterface<SignatureWithArrays>::ResultType ValueType;
typedef typename vtkm::internal::FunctionInterface<SignatureWithArrays>::ResultType
ValueType;
typedef vtkm::cont::internal::Storage<ValueType, Tag> StorageType; typedef vtkm::cont::internal::Storage<ValueType, Tag> StorageType;
typedef vtkm::cont::ArrayHandle<ValueType, Tag> Superclass; typedef vtkm::cont::ArrayHandle<ValueType, Tag> Superclass;
}; };
@ -248,19 +255,16 @@ struct ArrayHandleCompositeVectorTraits
// It may seem weird that this specialization throws an exception for // It may seem weird that this specialization throws an exception for
// everything, but that is because all the functionality is handled in the // everything, but that is because all the functionality is handled in the
// ArrayTransfer class. // ArrayTransfer class.
template<typename SignatureWithArrays> template <typename SignatureWithArrays>
class Storage< class Storage<typename ArrayHandleCompositeVectorTraits<SignatureWithArrays>::ValueType,
typename ArrayHandleCompositeVectorTraits<SignatureWithArrays>::ValueType, vtkm::cont::internal::StorageTagCompositeVector<SignatureWithArrays>>
vtkm::cont::internal::StorageTagCompositeVector<SignatureWithArrays> >
{ {
typedef vtkm::internal::FunctionInterface<SignatureWithArrays> typedef vtkm::internal::FunctionInterface<SignatureWithArrays> FunctionInterfaceWithArrays;
FunctionInterfaceWithArrays;
static const vtkm::IdComponent NUM_COMPONENTS = FunctionInterfaceWithArrays::ARITY; static const vtkm::IdComponent NUM_COMPONENTS = FunctionInterfaceWithArrays::ARITY;
typedef vtkm::Vec<vtkm::IdComponent, NUM_COMPONENTS> ComponentMapType; typedef vtkm::Vec<vtkm::IdComponent, NUM_COMPONENTS> ComponentMapType;
typedef typename FunctionInterfaceWithArrays::template StaticTransformType< typedef typename FunctionInterfaceWithArrays::template StaticTransformType<
detail::CompositeVectorArrayToPortalCont>::type detail::CompositeVectorArrayToPortalCont>::type FunctionInterfaceWithPortals;
FunctionInterfaceWithPortals;
typedef typename FunctionInterfaceWithPortals::Signature SignatureWithPortals; typedef typename FunctionInterfaceWithPortals::Signature SignatureWithPortals;
public: public:
@ -269,64 +273,71 @@ public:
typedef typename PortalType::ValueType ValueType; typedef typename PortalType::ValueType ValueType;
VTKM_CONT VTKM_CONT
Storage() : Valid(false) { } Storage()
: Valid(false)
VTKM_CONT
Storage(const FunctionInterfaceWithArrays &arrays,
const ComponentMapType &sourceComponents)
: Arrays(arrays), SourceComponents(sourceComponents), Valid(true)
{ {
arrays.ForEachCont(
detail::CheckArraySizeFunctor(this->GetNumberOfValues()));
} }
VTKM_CONT VTKM_CONT
PortalType GetPortal() { Storage(const FunctionInterfaceWithArrays& arrays, const ComponentMapType& sourceComponents)
throw vtkm::cont::ErrorBadValue( : Arrays(arrays)
"Composite vector arrays are read only."); , SourceComponents(sourceComponents)
, Valid(true)
{
arrays.ForEachCont(detail::CheckArraySizeFunctor(this->GetNumberOfValues()));
} }
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const { PortalType GetPortal()
{
throw vtkm::cont::ErrorBadValue("Composite vector arrays are read only.");
}
VTKM_CONT
PortalConstType GetPortalConst() const
{
if (!this->Valid) if (!this->Valid)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"Tried to use an ArrayHandleCompositeHandle without dependent arrays."); "Tried to use an ArrayHandleCompositeHandle without dependent arrays.");
} }
return PortalConstType(this->Arrays.StaticTransformCont( return PortalConstType(
detail::CompositeVectorArrayToPortalCont()), this->Arrays.StaticTransformCont(detail::CompositeVectorArrayToPortalCont()),
this->SourceComponents); this->SourceComponents);
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const { vtkm::Id GetNumberOfValues() const
{
if (!this->Valid) if (!this->Valid)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"Tried to use an ArrayHandleCompositeHandle without dependent arrays."); "Tried to use an ArrayHandleCompositeHandle without dependent arrays.");
} }
return this->Arrays.template GetParameter<1>().GetNumberOfValues(); return this->Arrays.template GetParameter<1>().GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id vtkmNotUsed(numberOfValues)) { void Allocate(vtkm::Id vtkmNotUsed(numberOfValues))
{
throw vtkm::cont::ErrorInternal( throw vtkm::cont::ErrorInternal(
"The allocate method for the composite vector storage should never " "The allocate method for the composite vector storage should never "
"have been called. The allocate is generally only called by the " "have been called. The allocate is generally only called by the "
"execution array manager, and the array transfer for the composite " "execution array manager, and the array transfer for the composite "
"storage should prevent the execution array manager from being " "storage should prevent the execution array manager from being "
"directly used."); "directly used.");
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id vtkmNotUsed(numberOfValues)) { void Shrink(vtkm::Id vtkmNotUsed(numberOfValues))
throw vtkm::cont::ErrorBadValue( {
"Composite vector arrays are read-only."); throw vtkm::cont::ErrorBadValue("Composite vector arrays are read-only.");
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources()
{
if (this->Valid) if (this->Valid)
{ {
// TODO: Implement this. // TODO: Implement this.
@ -334,13 +345,15 @@ public:
} }
VTKM_CONT VTKM_CONT
const FunctionInterfaceWithArrays &GetArrays() const { const FunctionInterfaceWithArrays& GetArrays() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->Arrays; return this->Arrays;
} }
VTKM_CONT VTKM_CONT
const ComponentMapType &GetSourceComponents() const { const ComponentMapType& GetSourceComponents() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->SourceComponents; return this->SourceComponents;
} }
@ -351,27 +364,22 @@ private:
bool Valid; bool Valid;
}; };
template<typename SignatureWithArrays, typename DeviceAdapterTag> template <typename SignatureWithArrays, typename DeviceAdapterTag>
class ArrayTransfer< class ArrayTransfer<typename ArrayHandleCompositeVectorTraits<SignatureWithArrays>::ValueType,
typename ArrayHandleCompositeVectorTraits<SignatureWithArrays>::ValueType, vtkm::cont::internal::StorageTagCompositeVector<SignatureWithArrays>,
vtkm::cont::internal::StorageTagCompositeVector<SignatureWithArrays>, DeviceAdapterTag>
DeviceAdapterTag>
{ {
VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag); VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag);
typedef typename ArrayHandleCompositeVectorTraits<SignatureWithArrays>::StorageType typedef typename ArrayHandleCompositeVectorTraits<SignatureWithArrays>::StorageType StorageType;
StorageType;
typedef vtkm::internal::FunctionInterface<SignatureWithArrays> typedef vtkm::internal::FunctionInterface<SignatureWithArrays> FunctionWithArrays;
FunctionWithArrays;
typedef typename FunctionWithArrays::template StaticTransformType< typedef typename FunctionWithArrays::template StaticTransformType<
detail::CompositeVectorArrayToPortalExec<DeviceAdapterTag> >::type detail::CompositeVectorArrayToPortalExec<DeviceAdapterTag>>::type FunctionWithPortals;
FunctionWithPortals;
typedef typename FunctionWithPortals::Signature SignatureWithPortals; typedef typename FunctionWithPortals::Signature SignatureWithPortals;
public: public:
typedef typename ArrayHandleCompositeVectorTraits<SignatureWithArrays>::ValueType typedef typename ArrayHandleCompositeVectorTraits<SignatureWithArrays>::ValueType ValueType;
ValueType;
// These are not currently fully implemented. // These are not currently fully implemented.
typedef typename StorageType::PortalType PortalControl; typedef typename StorageType::PortalType PortalControl;
@ -381,21 +389,20 @@ public:
typedef ArrayPortalCompositeVector<SignatureWithPortals> PortalConstExecution; typedef ArrayPortalCompositeVector<SignatureWithPortals> PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) : Storage(storage) { } ArrayTransfer(StorageType* storage)
: Storage(storage)
{
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const { vtkm::Id GetNumberOfValues() const { return this->Storage->GetNumberOfValues(); }
return this->Storage->GetNumberOfValues();
}
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) const PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) const
{ {
return return PortalConstExecution(this->Storage->GetArrays().StaticTransformCont(
PortalConstExecution( detail::CompositeVectorArrayToPortalExec<DeviceAdapterTag>()),
this->Storage->GetArrays().StaticTransformCont( this->Storage->GetSourceComponents());
detail::CompositeVectorArrayToPortalExec<DeviceAdapterTag>()),
this->Storage->GetSourceComponents());
} }
VTKM_CONT VTKM_CONT
@ -404,7 +411,7 @@ public:
// It may be the case a composite vector could be used for in place // It may be the case a composite vector could be used for in place
// operations, but this is not implemented currently. // operations, but this is not implemented currently.
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"Composite vector arrays cannot be used for output or in place."); "Composite vector arrays cannot be used for output or in place.");
} }
VTKM_CONT VTKM_CONT
@ -413,31 +420,26 @@ public:
// It may be the case a composite vector could be used for output if you // It may be the case a composite vector could be used for output if you
// want the delegate arrays to be resized, but this is not implemented // want the delegate arrays to be resized, but this is not implemented
// currently. // currently.
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Composite vector arrays cannot be used for output.");
"Composite vector arrays cannot be used for output.");
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *vtkmNotUsed(storage)) const void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Composite vector arrays cannot be used for output.");
"Composite vector arrays cannot be used for output.");
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id vtkmNotUsed(numberOfValues)) void Shrink(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Composite vector arrays cannot be resized.");
"Composite vector arrays cannot be resized.");
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources() { this->Storage->ReleaseResources(); }
this->Storage->ReleaseResources();
}
private: private:
StorageType *Storage; StorageType* Storage;
}; };
} // namespace internal } // namespace internal
@ -452,91 +454,70 @@ private:
/// The easiest way to create and type an \c ArrayHandleCompositeVector is /// The easiest way to create and type an \c ArrayHandleCompositeVector is
/// to use the \c make_ArrayHandleCompositeVector functions. /// to use the \c make_ArrayHandleCompositeVector functions.
/// ///
template<typename Signature> template <typename Signature>
class ArrayHandleCompositeVector class ArrayHandleCompositeVector
: public internal::ArrayHandleCompositeVectorTraits<Signature>::Superclass : public internal::ArrayHandleCompositeVectorTraits<Signature>::Superclass
{ {
typedef typename internal::ArrayHandleCompositeVectorTraits<Signature>::StorageType typedef typename internal::ArrayHandleCompositeVectorTraits<Signature>::StorageType StorageType;
StorageType; typedef
typedef typename internal::ArrayPortalCompositeVector<Signature>::ComponentMapType typename internal::ArrayPortalCompositeVector<Signature>::ComponentMapType ComponentMapType;
ComponentMapType;
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleCompositeVector, ArrayHandleCompositeVector, (ArrayHandleCompositeVector<Signature>),
(ArrayHandleCompositeVector<Signature>), (typename internal::ArrayHandleCompositeVectorTraits<Signature>::Superclass));
(typename internal::ArrayHandleCompositeVectorTraits<Signature>::Superclass));
VTKM_CONT VTKM_CONT
ArrayHandleCompositeVector( ArrayHandleCompositeVector(const vtkm::internal::FunctionInterface<Signature>& arrays,
const vtkm::internal::FunctionInterface<Signature> &arrays, const ComponentMapType& sourceComponents)
const ComponentMapType &sourceComponents)
: Superclass(StorageType(arrays, sourceComponents)) : Superclass(StorageType(arrays, sourceComponents))
{ } {
}
/// Template constructors for passing in types. You'll get weird compile /// Template constructors for passing in types. You'll get weird compile
/// errors if the argument types do not actually match the types in the /// errors if the argument types do not actually match the types in the
/// signature. /// signature.
/// ///
template<typename ArrayHandleType1> template <typename ArrayHandleType1>
VTKM_CONT VTKM_CONT ArrayHandleCompositeVector(const ArrayHandleType1& array1,
ArrayHandleCompositeVector(const ArrayHandleType1 &array1, vtkm::IdComponent sourceComponent1)
vtkm::IdComponent sourceComponent1) : Superclass(StorageType(vtkm::internal::make_FunctionInterface<ValueType>(array1),
ComponentMapType(sourceComponent1)))
{
}
template <typename ArrayHandleType1, typename ArrayHandleType2>
VTKM_CONT ArrayHandleCompositeVector(const ArrayHandleType1& array1,
vtkm::IdComponent sourceComponent1,
const ArrayHandleType2& array2,
vtkm::IdComponent sourceComponent2)
: Superclass(StorageType(vtkm::internal::make_FunctionInterface<ValueType>(array1, array2),
ComponentMapType(sourceComponent1, sourceComponent2)))
{
}
template <typename ArrayHandleType1, typename ArrayHandleType2, typename ArrayHandleType3>
VTKM_CONT ArrayHandleCompositeVector(const ArrayHandleType1& array1,
vtkm::IdComponent sourceComponent1,
const ArrayHandleType2& array2,
vtkm::IdComponent sourceComponent2,
const ArrayHandleType3& array3,
vtkm::IdComponent sourceComponent3)
: Superclass(
StorageType(vtkm::internal::make_FunctionInterface<ValueType>(array1, array2, array3),
ComponentMapType(sourceComponent1, sourceComponent2, sourceComponent3)))
{
}
template <typename ArrayHandleType1, typename ArrayHandleType2, typename ArrayHandleType3,
typename ArrayHandleType4>
VTKM_CONT ArrayHandleCompositeVector(
const ArrayHandleType1& array1, vtkm::IdComponent sourceComponent1,
const ArrayHandleType2& array2, vtkm::IdComponent sourceComponent2,
const ArrayHandleType3& array3, vtkm::IdComponent sourceComponent3,
const ArrayHandleType4& array4, vtkm::IdComponent sourceComponent4)
: Superclass(StorageType( : Superclass(StorageType(
vtkm::internal::make_FunctionInterface<ValueType>(array1), vtkm::internal::make_FunctionInterface<ValueType>(array1, array2, array3, array4),
ComponentMapType(sourceComponent1))) ComponentMapType(sourceComponent1, sourceComponent2, sourceComponent3, sourceComponent4)))
{ } {
template<typename ArrayHandleType1, }
typename ArrayHandleType2>
VTKM_CONT
ArrayHandleCompositeVector(const ArrayHandleType1 &array1,
vtkm::IdComponent sourceComponent1,
const ArrayHandleType2 &array2,
vtkm::IdComponent sourceComponent2)
: Superclass(StorageType(
vtkm::internal::make_FunctionInterface<ValueType>(
array1, array2),
ComponentMapType(sourceComponent1,
sourceComponent2)))
{ }
template<typename ArrayHandleType1,
typename ArrayHandleType2,
typename ArrayHandleType3>
VTKM_CONT
ArrayHandleCompositeVector(const ArrayHandleType1 &array1,
vtkm::IdComponent sourceComponent1,
const ArrayHandleType2 &array2,
vtkm::IdComponent sourceComponent2,
const ArrayHandleType3 &array3,
vtkm::IdComponent sourceComponent3)
: Superclass(StorageType(
vtkm::internal::make_FunctionInterface<ValueType>(
array1, array2, array3),
ComponentMapType(sourceComponent1,
sourceComponent2,
sourceComponent3)))
{ }
template<typename ArrayHandleType1,
typename ArrayHandleType2,
typename ArrayHandleType3,
typename ArrayHandleType4>
VTKM_CONT
ArrayHandleCompositeVector(const ArrayHandleType1 &array1,
vtkm::IdComponent sourceComponent1,
const ArrayHandleType2 &array2,
vtkm::IdComponent sourceComponent2,
const ArrayHandleType3 &array3,
vtkm::IdComponent sourceComponent3,
const ArrayHandleType4 &array4,
vtkm::IdComponent sourceComponent4)
: Superclass(StorageType(
vtkm::internal::make_FunctionInterface<ValueType>(
array1, array2, array3, array4),
ComponentMapType(sourceComponent1,
sourceComponent2,
sourceComponent3,
sourceComponent4)))
{ }
}; };
/// \brief Get the type for an ArrayHandleCompositeVector /// \brief Get the type for an ArrayHandleCompositeVector
@ -552,164 +533,138 @@ public:
/// OutArrayType outArray = vtkm::cont::make_ArrayHandleCompositeVector(a1,a2); /// OutArrayType outArray = vtkm::cont::make_ArrayHandleCompositeVector(a1,a2);
/// \endcode /// \endcode
/// ///
template<typename ArrayHandleType1, template <typename ArrayHandleType1, typename ArrayHandleType2 = void,
typename ArrayHandleType2 = void, typename ArrayHandleType3 = void, typename ArrayHandleType4 = void>
typename ArrayHandleType3 = void,
typename ArrayHandleType4 = void>
struct ArrayHandleCompositeVectorType struct ArrayHandleCompositeVectorType
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType1); VTKM_IS_ARRAY_HANDLE(ArrayHandleType1);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType2); VTKM_IS_ARRAY_HANDLE(ArrayHandleType2);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType3); VTKM_IS_ARRAY_HANDLE(ArrayHandleType3);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType4); VTKM_IS_ARRAY_HANDLE(ArrayHandleType4);
private: private:
typedef typename vtkm::VecTraits<typename ArrayHandleType1::ValueType>::ComponentType typedef
ComponentType; typename vtkm::VecTraits<typename ArrayHandleType1::ValueType>::ComponentType ComponentType;
typedef vtkm::Vec<ComponentType,4> Signature( typedef vtkm::Vec<ComponentType, 4> Signature(ArrayHandleType1, ArrayHandleType2,
ArrayHandleType1,ArrayHandleType2,ArrayHandleType3,ArrayHandleType4); ArrayHandleType3, ArrayHandleType4);
public: public:
typedef vtkm::cont::ArrayHandleCompositeVector<Signature> type; typedef vtkm::cont::ArrayHandleCompositeVector<Signature> type;
}; };
template<typename ArrayHandleType1, template <typename ArrayHandleType1, typename ArrayHandleType2, typename ArrayHandleType3>
typename ArrayHandleType2, struct ArrayHandleCompositeVectorType<ArrayHandleType1, ArrayHandleType2, ArrayHandleType3>
typename ArrayHandleType3>
struct ArrayHandleCompositeVectorType<
ArrayHandleType1,ArrayHandleType2,ArrayHandleType3>
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType1); VTKM_IS_ARRAY_HANDLE(ArrayHandleType1);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType2); VTKM_IS_ARRAY_HANDLE(ArrayHandleType2);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType3); VTKM_IS_ARRAY_HANDLE(ArrayHandleType3);
private: private:
typedef typename vtkm::VecTraits<typename ArrayHandleType1::ValueType>::ComponentType typedef
ComponentType; typename vtkm::VecTraits<typename ArrayHandleType1::ValueType>::ComponentType ComponentType;
typedef vtkm::Vec<ComponentType,3> Signature( typedef vtkm::Vec<ComponentType, 3> Signature(ArrayHandleType1, ArrayHandleType2,
ArrayHandleType1,ArrayHandleType2,ArrayHandleType3); ArrayHandleType3);
public: public:
typedef vtkm::cont::ArrayHandleCompositeVector<Signature> type; typedef vtkm::cont::ArrayHandleCompositeVector<Signature> type;
}; };
template<typename ArrayHandleType1, template <typename ArrayHandleType1, typename ArrayHandleType2>
typename ArrayHandleType2> struct ArrayHandleCompositeVectorType<ArrayHandleType1, ArrayHandleType2>
struct ArrayHandleCompositeVectorType<ArrayHandleType1,ArrayHandleType2>
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType1); VTKM_IS_ARRAY_HANDLE(ArrayHandleType1);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType2); VTKM_IS_ARRAY_HANDLE(ArrayHandleType2);
private: private:
typedef typename vtkm::VecTraits<typename ArrayHandleType1::ValueType>::ComponentType typedef
ComponentType; typename vtkm::VecTraits<typename ArrayHandleType1::ValueType>::ComponentType ComponentType;
typedef vtkm::Vec<ComponentType,2> Signature( typedef vtkm::Vec<ComponentType, 2> Signature(ArrayHandleType1, ArrayHandleType2);
ArrayHandleType1,ArrayHandleType2);
public: public:
typedef vtkm::cont::ArrayHandleCompositeVector<Signature> type; typedef vtkm::cont::ArrayHandleCompositeVector<Signature> type;
}; };
template<typename ArrayHandleType1> template <typename ArrayHandleType1>
struct ArrayHandleCompositeVectorType<ArrayHandleType1> struct ArrayHandleCompositeVectorType<ArrayHandleType1>
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType1); VTKM_IS_ARRAY_HANDLE(ArrayHandleType1);
private: private:
typedef typename vtkm::VecTraits<typename ArrayHandleType1::ValueType>::ComponentType typedef
ComponentType; typename vtkm::VecTraits<typename ArrayHandleType1::ValueType>::ComponentType ComponentType;
typedef ComponentType Signature(ArrayHandleType1); typedef ComponentType Signature(ArrayHandleType1);
public: public:
typedef vtkm::cont::ArrayHandleCompositeVector<Signature> type; typedef vtkm::cont::ArrayHandleCompositeVector<Signature> type;
}; };
// clang-format off
/// Create a composite vector array from other arrays. /// Create a composite vector array from other arrays.
/// ///
template<typename ValueType1, typename Storage1> template <typename ValueType1, typename Storage1>
VTKM_CONT VTKM_CONT
typename ArrayHandleCompositeVectorType< typename ArrayHandleCompositeVectorType<vtkm::cont::ArrayHandle<ValueType1, Storage1>>::type
vtkm::cont::ArrayHandle<ValueType1,Storage1> >::type make_ArrayHandleCompositeVector(const vtkm::cont::ArrayHandle<ValueType1, Storage1>& array1,
make_ArrayHandleCompositeVector(
const vtkm::cont::ArrayHandle<ValueType1,Storage1> &array1,
vtkm::IdComponent sourceComponent1)
{
return typename ArrayHandleCompositeVectorType<
vtkm::cont::ArrayHandle<ValueType1,Storage1> >::type(array1,
sourceComponent1);
}
template<typename ArrayHandleType1>
VTKM_CONT
typename ArrayHandleCompositeVectorType<ArrayHandleType1>::type
make_ArrayHandleCompositeVector(const ArrayHandleType1 &array1,
vtkm::IdComponent sourceComponent1) vtkm::IdComponent sourceComponent1)
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType1); return
return typename ArrayHandleCompositeVectorType< typename ArrayHandleCompositeVectorType<vtkm::cont::ArrayHandle<ValueType1, Storage1>>::type(
ArrayHandleType1>::type(array1, sourceComponent1); array1, sourceComponent1);
} }
template<typename ArrayHandleType1, // clang-format on
typename ArrayHandleType2>
VTKM_CONT template <typename ArrayHandleType1>
typename ArrayHandleCompositeVectorType< VTKM_CONT typename ArrayHandleCompositeVectorType<ArrayHandleType1>::type
ArrayHandleType1, ArrayHandleType2>::type make_ArrayHandleCompositeVector(const ArrayHandleType1& array1, vtkm::IdComponent sourceComponent1)
make_ArrayHandleCompositeVector(const ArrayHandleType1 &array1, {
vtkm::IdComponent sourceComponent1, VTKM_IS_ARRAY_HANDLE(ArrayHandleType1);
const ArrayHandleType2 &array2, return typename ArrayHandleCompositeVectorType<ArrayHandleType1>::type(array1, sourceComponent1);
vtkm::IdComponent sourceComponent2) }
template <typename ArrayHandleType1, typename ArrayHandleType2>
VTKM_CONT typename ArrayHandleCompositeVectorType<ArrayHandleType1, ArrayHandleType2>::type
make_ArrayHandleCompositeVector(const ArrayHandleType1& array1, vtkm::IdComponent sourceComponent1,
const ArrayHandleType2& array2, vtkm::IdComponent sourceComponent2)
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType1); VTKM_IS_ARRAY_HANDLE(ArrayHandleType1);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType2); VTKM_IS_ARRAY_HANDLE(ArrayHandleType2);
return typename ArrayHandleCompositeVectorType< return typename ArrayHandleCompositeVectorType<ArrayHandleType1, ArrayHandleType2>::type(
ArrayHandleType1, array1, sourceComponent1, array2, sourceComponent2);
ArrayHandleType2>::type(array1, sourceComponent1,
array2, sourceComponent2);
} }
template<typename ArrayHandleType1, template <typename ArrayHandleType1, typename ArrayHandleType2, typename ArrayHandleType3>
typename ArrayHandleType2, VTKM_CONT typename ArrayHandleCompositeVectorType<ArrayHandleType1, ArrayHandleType2,
typename ArrayHandleType3> ArrayHandleType3>::type
VTKM_CONT make_ArrayHandleCompositeVector(const ArrayHandleType1& array1, vtkm::IdComponent sourceComponent1,
typename ArrayHandleCompositeVectorType< const ArrayHandleType2& array2, vtkm::IdComponent sourceComponent2,
ArrayHandleType1, ArrayHandleType2, ArrayHandleType3>::type const ArrayHandleType3& array3, vtkm::IdComponent sourceComponent3)
make_ArrayHandleCompositeVector(const ArrayHandleType1 &array1,
vtkm::IdComponent sourceComponent1,
const ArrayHandleType2 &array2,
vtkm::IdComponent sourceComponent2,
const ArrayHandleType3 &array3,
vtkm::IdComponent sourceComponent3)
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType1); VTKM_IS_ARRAY_HANDLE(ArrayHandleType1);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType2); VTKM_IS_ARRAY_HANDLE(ArrayHandleType2);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType3); VTKM_IS_ARRAY_HANDLE(ArrayHandleType3);
return typename ArrayHandleCompositeVectorType< return typename ArrayHandleCompositeVectorType<ArrayHandleType1, ArrayHandleType2,
ArrayHandleType1, ArrayHandleType3>::type(array1, sourceComponent1,
ArrayHandleType2, array2, sourceComponent2,
ArrayHandleType3>::type(array1, sourceComponent1, array3, sourceComponent3);
array2, sourceComponent2,
array3, sourceComponent3);
} }
template<typename ArrayHandleType1, template <typename ArrayHandleType1, typename ArrayHandleType2, typename ArrayHandleType3,
typename ArrayHandleType2, typename ArrayHandleType4>
typename ArrayHandleType3, VTKM_CONT typename ArrayHandleCompositeVectorType<ArrayHandleType1, ArrayHandleType2,
typename ArrayHandleType4> ArrayHandleType3, ArrayHandleType4>::type
VTKM_CONT make_ArrayHandleCompositeVector(const ArrayHandleType1& array1, vtkm::IdComponent sourceComponent1,
typename ArrayHandleCompositeVectorType< const ArrayHandleType2& array2, vtkm::IdComponent sourceComponent2,
ArrayHandleType1, ArrayHandleType2, ArrayHandleType3, ArrayHandleType4>::type const ArrayHandleType3& array3, vtkm::IdComponent sourceComponent3,
make_ArrayHandleCompositeVector(const ArrayHandleType1 &array1, const ArrayHandleType4& array4, vtkm::IdComponent sourceComponent4)
vtkm::IdComponent sourceComponent1,
const ArrayHandleType2 &array2,
vtkm::IdComponent sourceComponent2,
const ArrayHandleType3 &array3,
vtkm::IdComponent sourceComponent3,
const ArrayHandleType4 &array4,
vtkm::IdComponent sourceComponent4)
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType1); VTKM_IS_ARRAY_HANDLE(ArrayHandleType1);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType2); VTKM_IS_ARRAY_HANDLE(ArrayHandleType2);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType3); VTKM_IS_ARRAY_HANDLE(ArrayHandleType3);
VTKM_IS_ARRAY_HANDLE(ArrayHandleType4); VTKM_IS_ARRAY_HANDLE(ArrayHandleType4);
return typename ArrayHandleCompositeVectorType< return
ArrayHandleType1, typename ArrayHandleCompositeVectorType<ArrayHandleType1, ArrayHandleType2, ArrayHandleType3,
ArrayHandleType2, ArrayHandleType4>::type(array1, sourceComponent1,
ArrayHandleType3, array2, sourceComponent2,
ArrayHandleType4>::type(array1, sourceComponent1, array3, sourceComponent3,
array2, sourceComponent2, array4, sourceComponent4);
array3, sourceComponent3,
array4, sourceComponent4);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -24,243 +24,252 @@
#include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandle.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace internal { namespace cont
{
namespace internal
{
template< typename PortalType1, typename PortalType2 > template <typename PortalType1, typename PortalType2>
class VTKM_ALWAYS_EXPORT ArrayPortalConcatenate class VTKM_ALWAYS_EXPORT ArrayPortalConcatenate
{ {
public: public:
typedef typename PortalType1::ValueType ValueType; typedef typename PortalType1::ValueType ValueType;
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalConcatenate() : portal1(), portal2() {} ArrayPortalConcatenate()
: portal1()
, portal2()
{
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalConcatenate( const PortalType1 &p1, const PortalType2 &p2 ) ArrayPortalConcatenate(const PortalType1& p1, const PortalType2& p2)
: portal1( p1 ), portal2( p2 ) {} : portal1(p1)
, portal2(p2)
{
}
// Copy constructor // Copy constructor
template< typename OtherP1, typename OtherP2 > template <typename OtherP1, typename OtherP2>
VTKM_EXEC_CONT VTKM_EXEC_CONT ArrayPortalConcatenate(const ArrayPortalConcatenate<OtherP1, OtherP2>& src)
ArrayPortalConcatenate( const ArrayPortalConcatenate< OtherP1, OtherP2 > &src ) : portal1(src.GetPortal1())
: portal1( src.GetPortal1() ), portal2( src.GetPortal2() ) {} , portal2(src.GetPortal2())
{
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
return this->portal1.GetNumberOfValues() + return this->portal1.GetNumberOfValues() + this->portal2.GetNumberOfValues();
this->portal2.GetNumberOfValues() ;
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
ValueType Get( vtkm::Id index) const ValueType Get(vtkm::Id index) const
{ {
if( index < this->portal1.GetNumberOfValues() ) if (index < this->portal1.GetNumberOfValues())
return this->portal1.Get( index ); return this->portal1.Get(index);
else else
return this->portal2.Get( index - this->portal1.GetNumberOfValues() ); return this->portal2.Get(index - this->portal1.GetNumberOfValues());
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set( vtkm::Id index, const ValueType &value ) const void Set(vtkm::Id index, const ValueType& value) const
{ {
if( index < this->portal1.GetNumberOfValues() ) if (index < this->portal1.GetNumberOfValues())
this->portal1.Set( index, value ); this->portal1.Set(index, value);
else else
this->portal2.Set( index - this->portal1.GetNumberOfValues(), value ); this->portal2.Set(index - this->portal1.GetNumberOfValues(), value);
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
const PortalType1 &GetPortal1() const const PortalType1& GetPortal1() const { return this->portal1; }
{
return this->portal1;
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
const PortalType2 &GetPortal2() const const PortalType2& GetPortal2() const { return this->portal2; }
{
return this->portal2;
}
private: private:
PortalType1 portal1; PortalType1 portal1;
PortalType2 portal2; PortalType2 portal2;
}; // class ArrayPortalConcatenate }; // class ArrayPortalConcatenate
} // namespace internal } // namespace internal
template <typename ArrayHandleType1, typename ArrayHandleType2>
class StorageTagConcatenate
{
};
template< typename ArrayHandleType1, typename ArrayHandleType2 > namespace internal
class StorageTagConcatenate {}; {
template <typename ArrayHandleType1, typename ArrayHandleType2>
namespace internal { class Storage<typename ArrayHandleType1::ValueType,
StorageTagConcatenate<ArrayHandleType1, ArrayHandleType2>>
template< typename ArrayHandleType1, typename ArrayHandleType2 >
class Storage< typename ArrayHandleType1::ValueType,
StorageTagConcatenate< ArrayHandleType1, ArrayHandleType2> >
{ {
public: public:
typedef typename ArrayHandleType1::ValueType ValueType; typedef typename ArrayHandleType1::ValueType ValueType;
typedef ArrayPortalConcatenate< typename ArrayHandleType1::PortalControl, typedef ArrayPortalConcatenate<typename ArrayHandleType1::PortalControl,
typename ArrayHandleType2::PortalControl > PortalType; typename ArrayHandleType2::PortalControl>
typedef ArrayPortalConcatenate< PortalType;
typename ArrayHandleType1::PortalConstControl, typedef ArrayPortalConcatenate<typename ArrayHandleType1::PortalConstControl,
typename ArrayHandleType2::PortalConstControl > PortalConstType; typename ArrayHandleType2::PortalConstControl>
PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : valid( false ) { } Storage()
: valid(false)
{
}
VTKM_CONT VTKM_CONT
Storage( const ArrayHandleType1 &a1, const ArrayHandleType2 &a2 ) Storage(const ArrayHandleType1& a1, const ArrayHandleType2& a2)
: array1( a1 ), array2( a2 ), valid( true ) {}; : array1(a1)
, array2(a2)
, valid(true){};
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const PortalConstType GetPortalConst() const
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return PortalConstType( this->array1.GetPortalConstControl(), return PortalConstType(this->array1.GetPortalConstControl(),
this->array2.GetPortalConstControl() ); this->array2.GetPortalConstControl());
} }
VTKM_CONT VTKM_CONT
PortalType GetPortal() PortalType GetPortal()
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return PortalType( this->array1.GetPortalControl(), return PortalType(this->array1.GetPortalControl(), this->array2.GetPortalControl());
this->array2.GetPortalControl() );
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return this->array1.GetNumberOfValues() + this->array2.GetNumberOfValues(); return this->array1.GetNumberOfValues() + this->array2.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
void Allocate( vtkm::Id vtkmNotUsed(numberOfValues) ) void Allocate(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
throw vtkm::cont::ErrorInternal( throw vtkm::cont::ErrorInternal("ArrayHandleConcatenate should not be allocated explicitly. ");
"ArrayHandleConcatenate should not be allocated explicitly. " );
} }
VTKM_CONT VTKM_CONT
void Shrink( vtkm::Id numberOfValues ) void Shrink(vtkm::Id numberOfValues)
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
if( numberOfValues < this->array1.GetNumberOfValues() ) if (numberOfValues < this->array1.GetNumberOfValues())
{ {
this->array1.Shrink( numberOfValues ); this->array1.Shrink(numberOfValues);
this->array2.Shrink( 0 ); this->array2.Shrink(0);
} }
else else
this->array2.Shrink( numberOfValues - this->array1.GetNumberOfValues() ); this->array2.Shrink(numberOfValues - this->array1.GetNumberOfValues());
} }
VTKM_CONT VTKM_CONT
void ReleaseResources( ) void ReleaseResources()
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
this->array1.ReleaseResources(); this->array1.ReleaseResources();
this->array2.ReleaseResources(); this->array2.ReleaseResources();
} }
VTKM_CONT VTKM_CONT
const ArrayHandleType1 &GetArray1() const const ArrayHandleType1& GetArray1() const
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return this->array1; return this->array1;
} }
VTKM_CONT VTKM_CONT
const ArrayHandleType2 &GetArray2() const const ArrayHandleType2& GetArray2() const
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return this->array2; return this->array2;
} }
private: private:
ArrayHandleType1 array1; ArrayHandleType1 array1;
ArrayHandleType2 array2; ArrayHandleType2 array2;
bool valid; bool valid;
}; // class Storage }; // class Storage
template <typename ArrayHandleType1, typename ArrayHandleType2, typename Device>
template< typename ArrayHandleType1, typename ArrayHandleType2, typename Device > class ArrayTransfer<typename ArrayHandleType1::ValueType,
class ArrayTransfer< typename ArrayHandleType1::ValueType, StorageTagConcatenate<ArrayHandleType1, ArrayHandleType2>, Device>
StorageTagConcatenate< ArrayHandleType1, ArrayHandleType2>,
Device >
{ {
public: public:
typedef typename ArrayHandleType1::ValueType ValueType; typedef typename ArrayHandleType1::ValueType ValueType;
private: private:
typedef StorageTagConcatenate< ArrayHandleType1, ArrayHandleType2 > StorageTag; typedef StorageTagConcatenate<ArrayHandleType1, ArrayHandleType2> StorageTag;
typedef vtkm::cont::internal::Storage< ValueType, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
typedef typename StorageType::PortalType PortalControl; typedef typename StorageType::PortalType PortalControl;
typedef typename StorageType::PortalConstType PortalConstControl; typedef typename StorageType::PortalConstType PortalConstControl;
typedef ArrayPortalConcatenate<typename ArrayHandleType1::template ExecutionTypes<Device>::Portal,
typename ArrayHandleType2::template ExecutionTypes<Device>::Portal>
PortalExecution;
typedef ArrayPortalConcatenate< typedef ArrayPortalConcatenate<
typename ArrayHandleType1::template ExecutionTypes< Device >::Portal, typename ArrayHandleType1::template ExecutionTypes<Device>::PortalConst,
typename ArrayHandleType2::template ExecutionTypes< Device >::Portal > typename ArrayHandleType2::template ExecutionTypes<Device>::PortalConst>
PortalExecution; PortalConstExecution;
typedef ArrayPortalConcatenate<
typename ArrayHandleType1::template ExecutionTypes< Device >::PortalConst,
typename ArrayHandleType2::template ExecutionTypes< Device >::PortalConst >
PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer( StorageType* storage ) ArrayTransfer(StorageType* storage)
: array1( storage->GetArray1() ), array2( storage->GetArray2() ) {} : array1(storage->GetArray1())
, array2(storage->GetArray2())
{
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
return this->array1.GetNumberOfValues() + this->array2.GetNumberOfValues() ; return this->array1.GetNumberOfValues() + this->array2.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput( bool vtkmNotUsed( updateData ) ) PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{ {
return PortalConstExecution( this->array1.PrepareForInput( Device() ), return PortalConstExecution(this->array1.PrepareForInput(Device()),
this->array2.PrepareForInput( Device() )); this->array2.PrepareForInput(Device()));
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForInPlace( bool vtkmNotUsed( updateData ) ) PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData))
{ {
return PortalExecution( this->array1.PrepareForInPlace( Device() ), return PortalExecution(this->array1.PrepareForInPlace(Device()),
this->array2.PrepareForInPlace( Device() )); this->array2.PrepareForInPlace(Device()));
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForOutput( vtkm::Id vtkmNotUsed(numberOfValues) ) PortalExecution PrepareForOutput(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
throw vtkm::cont::ErrorInternal( throw vtkm::cont::ErrorInternal("ArrayHandleConcatenate is derived and read-only. ");
"ArrayHandleConcatenate is derived and read-only. " );
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData( StorageType* vtkmNotUsed(storage) ) const void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{ {
// not need to implement // not need to implement
} }
VTKM_CONT VTKM_CONT
void Shrink( vtkm::Id numberOfValues ) void Shrink(vtkm::Id numberOfValues)
{ {
if( numberOfValues < this->array1.GetNumberOfValues() ) if (numberOfValues < this->array1.GetNumberOfValues())
{ {
this->array1.Shrink( numberOfValues ); this->array1.Shrink(numberOfValues);
this->array2.Shrink( 0 ); this->array2.Shrink(0);
} }
else else
this->array2.Shrink( numberOfValues - this->array1.GetNumberOfValues() ); this->array2.Shrink(numberOfValues - this->array1.GetNumberOfValues());
} }
VTKM_CONT VTKM_CONT
@ -273,53 +282,45 @@ public:
private: private:
ArrayHandleType1 array1; ArrayHandleType1 array1;
ArrayHandleType2 array2; ArrayHandleType2 array2;
}; };
} }
} }
} // namespace vtkm::cont::internal } // namespace vtkm::cont::internal
namespace vtkm
{
namespace cont
{
template <typename ArrayHandleType1, typename ArrayHandleType2>
namespace vtkm {
namespace cont {
template< typename ArrayHandleType1, typename ArrayHandleType2 >
class ArrayHandleConcatenate class ArrayHandleConcatenate
: public vtkm::cont::ArrayHandle< typename ArrayHandleType1::ValueType, : public vtkm::cont::ArrayHandle<typename ArrayHandleType1::ValueType,
StorageTagConcatenate< ArrayHandleType1, ArrayHandleType2> > StorageTagConcatenate<ArrayHandleType1, ArrayHandleType2>>
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( ArrayHandleConcatenate, VTKM_ARRAY_HANDLE_SUBCLASS(
( ArrayHandleConcatenate< ArrayHandleType1, ArrayHandleType2> ), ArrayHandleConcatenate, (ArrayHandleConcatenate<ArrayHandleType1, ArrayHandleType2>),
( vtkm::cont::ArrayHandle< typename ArrayHandleType1::ValueType, (vtkm::cont::ArrayHandle<typename ArrayHandleType1::ValueType,
StorageTagConcatenate< ArrayHandleType1, ArrayHandleType2 > > )); StorageTagConcatenate<ArrayHandleType1, ArrayHandleType2>>));
protected: protected:
typedef vtkm::cont::internal::Storage< ValueType, StorageTag > StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
VTKM_CONT VTKM_CONT
ArrayHandleConcatenate( const ArrayHandleType1 &array1, ArrayHandleConcatenate(const ArrayHandleType1& array1, const ArrayHandleType2& array2)
const ArrayHandleType2 &array2 ) : Superclass(StorageType(array1, array2))
: Superclass( StorageType( array1, array2 ) ) {
{} }
}; };
template <typename ArrayHandleType1, typename ArrayHandleType2>
template< typename ArrayHandleType1, typename ArrayHandleType2 > VTKM_CONT ArrayHandleConcatenate<ArrayHandleType1, ArrayHandleType2> make_ArrayHandleConcatenate(
VTKM_CONT const ArrayHandleType1& array1, const ArrayHandleType2& array2)
ArrayHandleConcatenate< ArrayHandleType1, ArrayHandleType2 >
make_ArrayHandleConcatenate( const ArrayHandleType1 &array1,
const ArrayHandleType2 &array2 )
{ {
return ArrayHandleConcatenate< ArrayHandleType1, ArrayHandleType2 >( array1, array2 ); return ArrayHandleConcatenate<ArrayHandleType1, ArrayHandleType2>(array1, array2);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont
#endif //vtk_m_ArrayHandleConcatenate_h #endif //vtk_m_ArrayHandleConcatenate_h

@ -24,22 +24,25 @@
#include <vtkm/cont/ArrayHandleImplicit.h> #include <vtkm/cont/ArrayHandleImplicit.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace detail { namespace detail
{
template<typename ValueType> template <typename ValueType>
struct VTKM_ALWAYS_EXPORT ConstantFunctor struct VTKM_ALWAYS_EXPORT ConstantFunctor
{ {
VTKM_EXEC_CONT VTKM_EXEC_CONT
ConstantFunctor(const ValueType &value = ValueType()) : Value(value) { } ConstantFunctor(const ValueType& value = ValueType())
: Value(value)
{
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
ValueType operator()(vtkm::Id vtkmNotUsed(index)) const ValueType operator()(vtkm::Id vtkmNotUsed(index)) const { return this->Value; }
{
return this->Value;
}
private: private:
ValueType Value; ValueType Value;
@ -55,32 +58,29 @@ private:
/// given in the constructor. The array is defined implicitly, so there it /// given in the constructor. The array is defined implicitly, so there it
/// takes (almost) no memory. /// takes (almost) no memory.
/// ///
template<typename T> template <typename T>
class ArrayHandleConstant class ArrayHandleConstant : public vtkm::cont::ArrayHandleImplicit<T, detail::ConstantFunctor<T>>
: public vtkm::cont::ArrayHandleImplicit<T, detail::ConstantFunctor<T> >
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(ArrayHandleConstant, (ArrayHandleConstant<T>),
ArrayHandleConstant, (vtkm::cont::ArrayHandleImplicit<T, detail::ConstantFunctor<T>>));
(ArrayHandleConstant<T>),
(vtkm::cont::ArrayHandleImplicit<T, detail::ConstantFunctor<T> >));
VTKM_CONT VTKM_CONT
ArrayHandleConstant(T value, vtkm::Id numberOfValues = 0) ArrayHandleConstant(T value, vtkm::Id numberOfValues = 0)
: Superclass(detail::ConstantFunctor<T>(value), numberOfValues) { } : Superclass(detail::ConstantFunctor<T>(value), numberOfValues)
{
}
}; };
/// make_ArrayHandleConstant is convenience function to generate an /// make_ArrayHandleConstant is convenience function to generate an
/// ArrayHandleImplicit. It takes a functor and the virtual length of the /// ArrayHandleImplicit. It takes a functor and the virtual length of the
/// array. /// array.
/// ///
template<typename T> template <typename T>
vtkm::cont::ArrayHandleConstant<T> vtkm::cont::ArrayHandleConstant<T> make_ArrayHandleConstant(T value, vtkm::Id numberOfValues)
make_ArrayHandleConstant(T value, vtkm::Id numberOfValues)
{ {
return vtkm::cont::ArrayHandleConstant<T>(value, numberOfValues); return vtkm::cont::ArrayHandleConstant<T>(value, numberOfValues);
} }
} }
} // vtkm::cont } // vtkm::cont

@ -25,49 +25,52 @@
#include <vtkm/VecTraits.h> #include <vtkm/VecTraits.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace internal { namespace internal
{
/// \brief An implicit array portal that returns an counting value. /// \brief An implicit array portal that returns an counting value.
template <class CountingValueType> template <class CountingValueType>
class VTKM_ALWAYS_EXPORT ArrayPortalCounting class VTKM_ALWAYS_EXPORT ArrayPortalCounting
{ {
typedef typename vtkm::VecTraits<CountingValueType>::ComponentType typedef typename vtkm::VecTraits<CountingValueType>::ComponentType ComponentType;
ComponentType;
public: public:
typedef CountingValueType ValueType; typedef CountingValueType ValueType;
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalCounting() : ArrayPortalCounting()
Start(0), : Start(0)
Step(1), , Step(1)
NumberOfValues(0) , NumberOfValues(0)
{ }
VTKM_EXEC_CONT
ArrayPortalCounting(ValueType start, ValueType step, vtkm::Id numValues) :
Start(start),
Step(step),
NumberOfValues(numValues)
{ }
template<typename OtherValueType>
VTKM_EXEC_CONT
ArrayPortalCounting(const ArrayPortalCounting<OtherValueType> &src)
: Start(src.Start),
Step(src.Step),
NumberOfValues(src.NumberOfValues)
{ }
template<typename OtherValueType>
VTKM_EXEC_CONT
ArrayPortalCounting<ValueType> &operator=(
const ArrayPortalCounting<OtherValueType> &src)
{ {
this->Start= src.Start; }
VTKM_EXEC_CONT
ArrayPortalCounting(ValueType start, ValueType step, vtkm::Id numValues)
: Start(start)
, Step(step)
, NumberOfValues(numValues)
{
}
template <typename OtherValueType>
VTKM_EXEC_CONT ArrayPortalCounting(const ArrayPortalCounting<OtherValueType>& src)
: Start(src.Start)
, Step(src.Step)
, NumberOfValues(src.NumberOfValues)
{
}
template <typename OtherValueType>
VTKM_EXEC_CONT ArrayPortalCounting<ValueType>& operator=(
const ArrayPortalCounting<OtherValueType>& src)
{
this->Start = src.Start;
this->Step = src.Step; this->Step = src.Step;
this->NumberOfValues = src.NumberOfValues; this->NumberOfValues = src.NumberOfValues;
return *this; return *this;
@ -77,14 +80,13 @@ public:
vtkm::Id GetNumberOfValues() const { return this->NumberOfValues; } vtkm::Id GetNumberOfValues() const { return this->NumberOfValues; }
VTKM_EXEC_CONT VTKM_EXEC_CONT
ValueType Get(vtkm::Id index) const { ValueType Get(vtkm::Id index) const
return ValueType(this->Start + {
this->Step*ValueType(static_cast<ComponentType>(index))); return ValueType(this->Start + this->Step * ValueType(static_cast<ComponentType>(index)));
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set(vtkm::Id vtkmNotUsed(index), void Set(vtkm::Id vtkmNotUsed(index), const ValueType& vtkmNotUsed(value)) const
const ValueType &vtkmNotUsed(value)) const
{ {
VTKM_ASSERT(false && "Cannot write to read-only counting array."); VTKM_ASSERT(false && "Cannot write to read-only counting array.");
} }
@ -97,11 +99,12 @@ private:
/// A convenience class that provides a typedef to the appropriate tag for /// A convenience class that provides a typedef to the appropriate tag for
/// a counting storage. /// a counting storage.
template<typename ConstantValueType> template <typename ConstantValueType>
struct ArrayHandleCountingTraits struct ArrayHandleCountingTraits
{ {
typedef vtkm::cont::StorageTagImplicit< typedef vtkm::cont::StorageTagImplicit<
vtkm::cont::internal::ArrayPortalCounting<ConstantValueType> > Tag; vtkm::cont::internal::ArrayPortalCounting<ConstantValueType>>
Tag;
}; };
} // namespace internal } // namespace internal
@ -111,43 +114,30 @@ struct ArrayHandleCountingTraits
/// and the passed in length /// and the passed in length
template <typename CountingValueType> template <typename CountingValueType>
class ArrayHandleCounting class ArrayHandleCounting
: public vtkm::cont::ArrayHandle < : public vtkm::cont::ArrayHandle<
CountingValueType, CountingValueType, typename internal::ArrayHandleCountingTraits<CountingValueType>::Tag>
typename internal::ArrayHandleCountingTraits<CountingValueType>::Tag
>
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleCounting, ArrayHandleCounting, (ArrayHandleCounting<CountingValueType>),
(ArrayHandleCounting<CountingValueType>), (vtkm::cont::ArrayHandle<
(vtkm::cont::ArrayHandle< CountingValueType, typename internal::ArrayHandleCountingTraits<CountingValueType>::Tag>));
CountingValueType,
typename internal::ArrayHandleCountingTraits<CountingValueType>::Tag
>));
VTKM_CONT VTKM_CONT
ArrayHandleCounting(CountingValueType start, ArrayHandleCounting(CountingValueType start, CountingValueType step, vtkm::Id length)
CountingValueType step, : Superclass(typename Superclass::PortalConstControl(start, step, length))
vtkm::Id length)
:Superclass(typename Superclass::PortalConstControl(start, step, length))
{ {
} }
}; };
/// A convenience function for creating an ArrayHandleCounting. It takes the /// A convenience function for creating an ArrayHandleCounting. It takes the
/// value to start counting from and and the number of times to increment. /// value to start counting from and and the number of times to increment.
template<typename CountingValueType> template <typename CountingValueType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandleCounting<CountingValueType> make_ArrayHandleCounting(
vtkm::cont::ArrayHandleCounting<CountingValueType> CountingValueType start, CountingValueType step, vtkm::Id length)
make_ArrayHandleCounting(CountingValueType start,
CountingValueType step,
vtkm::Id length)
{ {
return vtkm::cont::ArrayHandleCounting<CountingValueType>(start, return vtkm::cont::ArrayHandleCounting<CountingValueType>(start, step, length);
step,
length);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -23,9 +23,12 @@
#include <vtkm/TypeTraits.h> #include <vtkm/TypeTraits.h>
#include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandle.h>
namespace vtkm { namespace vtkm
namespace exec { {
namespace internal { namespace exec
{
namespace internal
{
/// \brief An output-only array portal with no storage. All written values are /// \brief An output-only array portal with no storage. All written values are
/// discarded. /// discarded.
@ -39,30 +42,30 @@ public:
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalDiscard() ArrayPortalDiscard()
: NumberOfValues(0) : NumberOfValues(0)
{ } // needs to be host and device so that cuda can create lvalue of these {
} // needs to be host and device so that cuda can create lvalue of these
VTKM_CONT VTKM_CONT
explicit ArrayPortalDiscard(vtkm::Id numValues) explicit ArrayPortalDiscard(vtkm::Id numValues)
: NumberOfValues(numValues) : NumberOfValues(numValues)
{ } {
}
/// Copy constructor for any other ArrayPortalDiscard with an iterator /// Copy constructor for any other ArrayPortalDiscard with an iterator
/// type that can be copied to this iterator type. This allows us to do any /// type that can be copied to this iterator type. This allows us to do any
/// type casting that the iterators do (like the non-const to const cast). /// type casting that the iterators do (like the non-const to const cast).
/// ///
template<class OtherV> template <class OtherV>
VTKM_CONT VTKM_CONT ArrayPortalDiscard(const ArrayPortalDiscard<OtherV>& src)
ArrayPortalDiscard(const ArrayPortalDiscard<OtherV> &src)
: NumberOfValues(src.NumberOfValues) : NumberOfValues(src.NumberOfValues)
{ }
VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const
{ {
return this->NumberOfValues;
} }
ValueType Get(vtkm::Id index) const { VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const { return this->NumberOfValues; }
ValueType Get(vtkm::Id index) const
{
VTKM_ASSERT(index < this->GetNumberOfValues()); VTKM_ASSERT(index < this->GetNumberOfValues());
VTKM_ASSERT("Method not supported for ArrayPortalDiscard." && false); VTKM_ASSERT("Method not supported for ArrayPortalDiscard." && false);
(void)index; (void)index;
@ -70,7 +73,7 @@ public:
} }
VTKM_EXEC VTKM_EXEC
void Set(vtkm::Id index, const ValueType &) const void Set(vtkm::Id index, const ValueType&) const
{ {
VTKM_ASSERT(index < this->GetNumberOfValues()); VTKM_ASSERT(index < this->GetNumberOfValues());
(void)index; (void)index;
@ -84,11 +87,15 @@ private:
} // end namespace internal } // end namespace internal
} // end namespace exec } // end namespace exec
namespace cont { namespace cont
{
namespace internal { namespace internal
{
struct VTKM_ALWAYS_EXPORT StorageTagDiscard { }; struct VTKM_ALWAYS_EXPORT StorageTagDiscard
{
};
template <typename ValueType_> template <typename ValueType_>
class Storage<ValueType_, StorageTagDiscard> class Storage<ValueType_, StorageTagDiscard>
@ -99,43 +106,25 @@ public:
using PortalConstType = vtkm::exec::internal::ArrayPortalDiscard<ValueType>; using PortalConstType = vtkm::exec::internal::ArrayPortalDiscard<ValueType>;
VTKM_CONT VTKM_CONT
Storage() { } Storage() {}
VTKM_CONT VTKM_CONT
PortalType GetPortal() PortalType GetPortal() { return PortalType(this->NumberOfValues); }
{
return PortalType(this->NumberOfValues);
}
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() PortalConstType GetPortalConst() { return PortalConstType(this->NumberOfValues); }
{
return PortalConstType(this->NumberOfValues);
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const { return this->NumberOfValues; }
{
return this->NumberOfValues;
}
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id numValues) void Allocate(vtkm::Id numValues) { this->NumberOfValues = numValues; }
{
this->NumberOfValues = numValues;
}
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numValues) void Shrink(vtkm::Id numValues) { this->NumberOfValues = numValues; }
{
this->NumberOfValues = numValues;
}
VTKM_CONT VTKM_CONT
void ReleaseResources() void ReleaseResources() { this->NumberOfValues = 0; }
{
this->NumberOfValues = 0;
}
private: private:
vtkm::Id NumberOfValues; vtkm::Id NumberOfValues;
@ -155,9 +144,10 @@ public:
using PortalConstExecution = vtkm::exec::internal::ArrayPortalDiscard<ValueType>; using PortalConstExecution = vtkm::exec::internal::ArrayPortalDiscard<ValueType>;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) ArrayTransfer(StorageType* storage)
: Internal(storage) : Internal(storage)
{ } {
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
@ -169,17 +159,15 @@ public:
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Input access not supported: "
"Input access not supported: " "Cannot read from an ArrayHandleDiscard.");
"Cannot read from an ArrayHandleDiscard.");
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData)) PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData))
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("InPlace access not supported: "
"InPlace access not supported: " "Cannot read from an ArrayHandleDiscard.");
"Cannot read from an ArrayHandleDiscard.");
} }
VTKM_CONT VTKM_CONT
@ -191,7 +179,7 @@ public:
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *storage) const void RetrieveOutputData(StorageType* storage) const
{ {
VTKM_ASSERT(storage == this->Internal); VTKM_ASSERT(storage == this->Internal);
(void)storage; (void)storage;
@ -213,7 +201,7 @@ public:
} }
private: private:
StorageType *Internal; StorageType* Internal;
}; };
template <typename ValueType_> template <typename ValueType_>
@ -230,14 +218,11 @@ struct ArrayHandleDiscardTraits
/// it. This can be used to save memory when a filter provides optional outputs /// it. This can be used to save memory when a filter provides optional outputs
/// that are not needed. /// that are not needed.
template <typename ValueType_> template <typename ValueType_>
class ArrayHandleDiscard class ArrayHandleDiscard : public internal::ArrayHandleDiscardTraits<ValueType_>::Superclass
: public internal::ArrayHandleDiscardTraits<ValueType_>::Superclass
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(ArrayHandleDiscard, (ArrayHandleDiscard<ValueType_>),
ArrayHandleDiscard, (typename internal::ArrayHandleDiscardTraits<ValueType_>::Superclass));
(ArrayHandleDiscard<ValueType_>),
(typename internal::ArrayHandleDiscardTraits<ValueType_>::Superclass));
}; };
} // end namespace cont } // end namespace cont

@ -24,47 +24,54 @@
#include <vtkm/cont/ArrayPortal.h> #include <vtkm/cont/ArrayPortal.h>
#include <vtkm/cont/ErrorBadValue.h> #include <vtkm/cont/ErrorBadValue.h>
namespace vtkm { namespace vtkm
namespace exec { {
namespace exec
{
namespace internal { namespace internal
{
template<typename _SourcePortalType, vtkm::IdComponent _NUM_COMPONENTS> template <typename _SourcePortalType, vtkm::IdComponent _NUM_COMPONENTS>
class VTKM_ALWAYS_EXPORT ArrayPortalGroupVec class VTKM_ALWAYS_EXPORT ArrayPortalGroupVec
{ {
public: public:
static const vtkm::IdComponent NUM_COMPONENTS = _NUM_COMPONENTS; static const vtkm::IdComponent NUM_COMPONENTS = _NUM_COMPONENTS;
typedef _SourcePortalType SourcePortalType; typedef _SourcePortalType SourcePortalType;
typedef typename typedef typename std::remove_const<typename SourcePortalType::ValueType>::type ComponentType;
std::remove_const<typename SourcePortalType::ValueType>::type
ComponentType;
typedef vtkm::Vec<ComponentType, NUM_COMPONENTS> ValueType; typedef vtkm::Vec<ComponentType, NUM_COMPONENTS> ValueType;
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalGroupVec() : SourcePortal() { } ArrayPortalGroupVec()
: SourcePortal()
{
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalGroupVec(const SourcePortalType &sourcePortal) ArrayPortalGroupVec(const SourcePortalType& sourcePortal)
: SourcePortal(sourcePortal) { } : SourcePortal(sourcePortal)
{
}
/// Copy constructor for any other ArrayPortalConcatenate with a portal type /// Copy constructor for any other ArrayPortalConcatenate with a portal type
/// that can be copied to this portal type. This allows us to do any type /// that can be copied to this portal type. This allows us to do any type
/// casting that the portals do (like the non-const to const cast). /// casting that the portals do (like the non-const to const cast).
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<typename OtherSourcePortalType> template <typename OtherSourcePortalType>
VTKM_EXEC_CONT VTKM_EXEC_CONT ArrayPortalGroupVec(
ArrayPortalGroupVec( const ArrayPortalGroupVec<OtherSourcePortalType, NUM_COMPONENTS>& src)
const ArrayPortalGroupVec<OtherSourcePortalType, NUM_COMPONENTS> &src) : SourcePortal(src.GetPortal())
: SourcePortal(src.GetPortal()) { } {
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
return this->SourcePortal.GetNumberOfValues()/NUM_COMPONENTS; return this->SourcePortal.GetNumberOfValues() / NUM_COMPONENTS;
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
@ -72,10 +79,8 @@ public:
ValueType Get(vtkm::Id index) const ValueType Get(vtkm::Id index) const
{ {
ValueType result; ValueType result;
vtkm::Id sourceIndex = index*NUM_COMPONENTS; vtkm::Id sourceIndex = index * NUM_COMPONENTS;
for (vtkm::IdComponent componentIndex = 0; for (vtkm::IdComponent componentIndex = 0; componentIndex < NUM_COMPONENTS; componentIndex++)
componentIndex < NUM_COMPONENTS;
componentIndex++)
{ {
result[componentIndex] = this->SourcePortal.Get(sourceIndex); result[componentIndex] = this->SourcePortal.Get(sourceIndex);
sourceIndex++; sourceIndex++;
@ -85,12 +90,10 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set(vtkm::Id index, const ValueType &value) const void Set(vtkm::Id index, const ValueType& value) const
{ {
vtkm::Id sourceIndex = index*NUM_COMPONENTS; vtkm::Id sourceIndex = index * NUM_COMPONENTS;
for (vtkm::IdComponent componentIndex = 0; for (vtkm::IdComponent componentIndex = 0; componentIndex < NUM_COMPONENTS; componentIndex++)
componentIndex < NUM_COMPONENTS;
componentIndex++)
{ {
this->SourcePortal.Set(sourceIndex, value[componentIndex]); this->SourcePortal.Set(sourceIndex, value[componentIndex]);
sourceIndex++; sourceIndex++;
@ -99,49 +102,56 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const SourcePortalType &GetPortal() const { return this->SourcePortal; } const SourcePortalType& GetPortal() const { return this->SourcePortal; }
private: private:
SourcePortalType SourcePortal; SourcePortalType SourcePortal;
}; };
} }
} }
} // namespace vtkm::exec::internal } // namespace vtkm::exec::internal
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace internal { namespace internal
{
template<typename SourceArrayHandleType, vtkm::IdComponent NUM_COMPONENTS> template <typename SourceArrayHandleType, vtkm::IdComponent NUM_COMPONENTS>
struct VTKM_ALWAYS_EXPORT StorageTagGroupVec { }; struct VTKM_ALWAYS_EXPORT StorageTagGroupVec
{
};
template<typename SourceArrayHandleType, template <typename SourceArrayHandleType, vtkm::IdComponent NUM_COMPONENTS>
vtkm::IdComponent NUM_COMPONENTS> class Storage<vtkm::Vec<typename SourceArrayHandleType::ValueType, NUM_COMPONENTS>,
class Storage< vtkm::cont::internal::StorageTagGroupVec<SourceArrayHandleType, NUM_COMPONENTS>>
vtkm::Vec<typename SourceArrayHandleType::ValueType,NUM_COMPONENTS>,
vtkm::cont::internal::StorageTagGroupVec<
SourceArrayHandleType, NUM_COMPONENTS> >
{ {
typedef typename SourceArrayHandleType::ValueType ComponentType; typedef typename SourceArrayHandleType::ValueType ComponentType;
public: public:
typedef vtkm::Vec<ComponentType,NUM_COMPONENTS> ValueType; typedef vtkm::Vec<ComponentType, NUM_COMPONENTS> ValueType;
typedef vtkm::exec::internal::ArrayPortalGroupVec<typename SourceArrayHandleType::PortalControl,
NUM_COMPONENTS>
PortalType;
typedef vtkm::exec::internal::ArrayPortalGroupVec< typedef vtkm::exec::internal::ArrayPortalGroupVec<
typename SourceArrayHandleType::PortalControl, typename SourceArrayHandleType::PortalConstControl, NUM_COMPONENTS>
NUM_COMPONENTS> PortalType; PortalConstType;
typedef vtkm::exec::internal::ArrayPortalGroupVec<
typename SourceArrayHandleType::PortalConstControl,
NUM_COMPONENTS> PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : Valid(false) { } Storage()
: Valid(false)
{
}
VTKM_CONT VTKM_CONT
Storage(const SourceArrayHandleType &sourceArray) Storage(const SourceArrayHandleType& sourceArray)
: SourceArray(sourceArray), Valid(true) { } : SourceArray(sourceArray)
, Valid(true)
{
}
VTKM_CONT VTKM_CONT
PortalType GetPortal() PortalType GetPortal()
@ -162,26 +172,26 @@ public:
{ {
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
vtkm::Id sourceSize = this->SourceArray.GetNumberOfValues(); vtkm::Id sourceSize = this->SourceArray.GetNumberOfValues();
if(sourceSize%NUM_COMPONENTS != 0) if (sourceSize % NUM_COMPONENTS != 0)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"ArrayHandleGroupVec's source array does not divide evenly into Vecs."); "ArrayHandleGroupVec's source array does not divide evenly into Vecs.");
} }
return sourceSize/NUM_COMPONENTS; return sourceSize / NUM_COMPONENTS;
} }
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id numberOfValues) void Allocate(vtkm::Id numberOfValues)
{ {
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
this->SourceArray.Allocate(numberOfValues*NUM_COMPONENTS); this->SourceArray.Allocate(numberOfValues * NUM_COMPONENTS);
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numberOfValues) void Shrink(vtkm::Id numberOfValues)
{ {
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
this->SourceArray.Shrink(numberOfValues*NUM_COMPONENTS); this->SourceArray.Shrink(numberOfValues * NUM_COMPONENTS);
} }
VTKM_CONT VTKM_CONT
@ -195,7 +205,7 @@ public:
// Required for later use in ArrayTransfer class // Required for later use in ArrayTransfer class
VTKM_CONT VTKM_CONT
const SourceArrayHandleType &GetSourceArray() const const SourceArrayHandleType& GetSourceArray() const
{ {
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->SourceArray; return this->SourceArray;
@ -206,22 +216,18 @@ private:
bool Valid; bool Valid;
}; };
template<typename SourceArrayHandleType, template <typename SourceArrayHandleType, vtkm::IdComponent NUM_COMPONENTS, typename Device>
vtkm::IdComponent NUM_COMPONENTS, class ArrayTransfer<vtkm::Vec<typename SourceArrayHandleType::ValueType, NUM_COMPONENTS>,
typename Device> vtkm::cont::internal::StorageTagGroupVec<SourceArrayHandleType, NUM_COMPONENTS>,
class ArrayTransfer< Device>
vtkm::Vec<typename SourceArrayHandleType::ValueType, NUM_COMPONENTS>,
vtkm::cont::internal::StorageTagGroupVec<
SourceArrayHandleType, NUM_COMPONENTS>,
Device>
{ {
public: public:
typedef typename SourceArrayHandleType::ValueType ComponentType; typedef typename SourceArrayHandleType::ValueType ComponentType;
typedef vtkm::Vec<ComponentType, NUM_COMPONENTS> ValueType; typedef vtkm::Vec<ComponentType, NUM_COMPONENTS> ValueType;
private: private:
typedef vtkm::cont::internal::StorageTagGroupVec< typedef vtkm::cont::internal::StorageTagGroupVec<SourceArrayHandleType, NUM_COMPONENTS>
SourceArrayHandleType, NUM_COMPONENTS> StorageTag; StorageTag;
typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
@ -229,37 +235,37 @@ public:
typedef typename StorageType::PortalConstType PortalConstControl; typedef typename StorageType::PortalConstType PortalConstControl;
typedef vtkm::exec::internal::ArrayPortalGroupVec< typedef vtkm::exec::internal::ArrayPortalGroupVec<
typename SourceArrayHandleType::template ExecutionTypes<Device>::Portal, typename SourceArrayHandleType::template ExecutionTypes<Device>::Portal, NUM_COMPONENTS>
NUM_COMPONENTS>
PortalExecution; PortalExecution;
typedef vtkm::exec::internal::ArrayPortalGroupVec< typedef vtkm::exec::internal::ArrayPortalGroupVec<
typename SourceArrayHandleType::template ExecutionTypes<Device>::PortalConst, typename SourceArrayHandleType::template ExecutionTypes<Device>::PortalConst, NUM_COMPONENTS>
NUM_COMPONENTS>
PortalConstExecution; PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) ArrayTransfer(StorageType* storage)
: SourceArray(storage->GetSourceArray()) { } : SourceArray(storage->GetSourceArray())
{
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
vtkm::Id sourceSize = this->SourceArray.GetNumberOfValues(); vtkm::Id sourceSize = this->SourceArray.GetNumberOfValues();
if (sourceSize%NUM_COMPONENTS != 0) if (sourceSize % NUM_COMPONENTS != 0)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"ArrayHandleGroupVec's source array does not divide evenly into Vecs."); "ArrayHandleGroupVec's source array does not divide evenly into Vecs.");
} }
return sourceSize/NUM_COMPONENTS; return sourceSize / NUM_COMPONENTS;
} }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{ {
if (this->SourceArray.GetNumberOfValues()%NUM_COMPONENTS != 0) if (this->SourceArray.GetNumberOfValues() % NUM_COMPONENTS != 0)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"ArrayHandleGroupVec's source array does not divide evenly into Vecs."); "ArrayHandleGroupVec's source array does not divide evenly into Vecs.");
} }
return PortalConstExecution(this->SourceArray.PrepareForInput(Device())); return PortalConstExecution(this->SourceArray.PrepareForInput(Device()));
} }
@ -267,10 +273,10 @@ public:
VTKM_CONT VTKM_CONT
PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData)) PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData))
{ {
if (this->SourceArray.GetNumberOfValues()%NUM_COMPONENTS != 0) if (this->SourceArray.GetNumberOfValues() % NUM_COMPONENTS != 0)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"ArrayHandleGroupVec's source array does not divide evenly into Vecs."); "ArrayHandleGroupVec's source array does not divide evenly into Vecs.");
} }
return PortalExecution(this->SourceArray.PrepareForInPlace(Device())); return PortalExecution(this->SourceArray.PrepareForInPlace(Device()));
} }
@ -278,12 +284,12 @@ public:
VTKM_CONT VTKM_CONT
PortalExecution PrepareForOutput(vtkm::Id numberOfValues) PortalExecution PrepareForOutput(vtkm::Id numberOfValues)
{ {
return PortalExecution(this->SourceArray.PrepareForOutput( return PortalExecution(
numberOfValues*NUM_COMPONENTS, Device())); this->SourceArray.PrepareForOutput(numberOfValues * NUM_COMPONENTS, Device()));
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *vtkmNotUsed(storage)) const void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{ {
// Implementation of this method should be unnecessary. The internal // Implementation of this method should be unnecessary. The internal
// array handles should automatically retrieve the output data as // array handles should automatically retrieve the output data as
@ -293,14 +299,11 @@ public:
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numberOfValues) void Shrink(vtkm::Id numberOfValues)
{ {
this->SourceArray.Shrink(numberOfValues*NUM_COMPONENTS); this->SourceArray.Shrink(numberOfValues * NUM_COMPONENTS);
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() void ReleaseResources() { this->SourceArray.ReleaseResourcesExecution(); }
{
this->SourceArray.ReleaseResourcesExecution();
}
private: private:
SourceArrayHandleType SourceArray; SourceArrayHandleType SourceArray;
@ -320,23 +323,20 @@ private:
/// to 3, you get an array that looks like it contains two values of \c Vec /// to 3, you get an array that looks like it contains two values of \c Vec
/// values of size 3 with the data [0,1,2], [3,4,5]. /// values of size 3 with the data [0,1,2], [3,4,5].
/// ///
template<typename SourceArrayHandleType, vtkm::IdComponent NUM_COMPONENTS> template <typename SourceArrayHandleType, vtkm::IdComponent NUM_COMPONENTS>
class ArrayHandleGroupVec class ArrayHandleGroupVec
: public vtkm::cont::ArrayHandle< : public vtkm::cont::ArrayHandle<
vtkm::Vec<typename SourceArrayHandleType::ValueType, NUM_COMPONENTS>, vtkm::Vec<typename SourceArrayHandleType::ValueType, NUM_COMPONENTS>,
vtkm::cont::internal::StorageTagGroupVec< vtkm::cont::internal::StorageTagGroupVec<SourceArrayHandleType, NUM_COMPONENTS>>
SourceArrayHandleType, NUM_COMPONENTS> >
{ {
VTKM_IS_ARRAY_HANDLE(SourceArrayHandleType); VTKM_IS_ARRAY_HANDLE(SourceArrayHandleType);
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleGroupVec, ArrayHandleGroupVec, (ArrayHandleGroupVec<SourceArrayHandleType, NUM_COMPONENTS>),
(ArrayHandleGroupVec<SourceArrayHandleType, NUM_COMPONENTS>), (vtkm::cont::ArrayHandle<
(vtkm::cont::ArrayHandle< vtkm::Vec<typename SourceArrayHandleType::ValueType, NUM_COMPONENTS>,
vtkm::Vec<typename SourceArrayHandleType::ValueType, NUM_COMPONENTS>, vtkm::cont::internal::StorageTagGroupVec<SourceArrayHandleType, NUM_COMPONENTS>>));
vtkm::cont::internal::StorageTagGroupVec<
SourceArrayHandleType, NUM_COMPONENTS> >));
typedef typename SourceArrayHandleType::ValueType ComponentType; typedef typename SourceArrayHandleType::ValueType ComponentType;
@ -345,8 +345,10 @@ private:
public: public:
VTKM_CONT VTKM_CONT
ArrayHandleGroupVec(const SourceArrayHandleType &sourceArray) ArrayHandleGroupVec(const SourceArrayHandleType& sourceArray)
: Superclass(StorageType(sourceArray)) { } : Superclass(StorageType(sourceArray))
{
}
}; };
/// \c make_ArrayHandleGroupVec is convenience function to generate an /// \c make_ArrayHandleGroupVec is convenience function to generate an
@ -354,15 +356,12 @@ public:
/// (as a specified template parameter), and returns an array handle with /// (as a specified template parameter), and returns an array handle with
/// consecutive entries grouped in a Vec. /// consecutive entries grouped in a Vec.
/// ///
template<vtkm::IdComponent NUM_COMPONENTS, template <vtkm::IdComponent NUM_COMPONENTS, typename ArrayHandleType>
typename ArrayHandleType> VTKM_CONT vtkm::cont::ArrayHandleGroupVec<ArrayHandleType, NUM_COMPONENTS> make_ArrayHandleGroupVec(
VTKM_CONT const ArrayHandleType& array)
vtkm::cont::ArrayHandleGroupVec<ArrayHandleType, NUM_COMPONENTS>
make_ArrayHandleGroupVec(const ArrayHandleType &array)
{ {
return vtkm::cont::ArrayHandleGroupVec<ArrayHandleType,NUM_COMPONENTS>(array); return vtkm::cont::ArrayHandleGroupVec<ArrayHandleType, NUM_COMPONENTS>(array);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -32,47 +32,53 @@
#include <vtkm/exec/arg/FetchTagArrayDirectOut.h> #include <vtkm/exec/arg/FetchTagArrayDirectOut.h>
namespace vtkm { namespace vtkm
namespace exec { {
namespace exec
{
namespace internal { namespace internal
{
template<typename SourcePortalType, typename OffsetsPortalType> template <typename SourcePortalType, typename OffsetsPortalType>
class VTKM_ALWAYS_EXPORT ArrayPortalGroupVecVariable class VTKM_ALWAYS_EXPORT ArrayPortalGroupVecVariable
{ {
public: public:
using ComponentType = using ComponentType = typename std::remove_const<typename SourcePortalType::ValueType>::type;
typename std::remove_const<typename SourcePortalType::ValueType>::type;
using ValueType = vtkm::VecFromPortal<SourcePortalType>; using ValueType = vtkm::VecFromPortal<SourcePortalType>;
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalGroupVecVariable() : SourcePortal(), OffsetsPortal() { } ArrayPortalGroupVecVariable()
: SourcePortal()
, OffsetsPortal()
{
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalGroupVecVariable(const SourcePortalType &sourcePortal, ArrayPortalGroupVecVariable(const SourcePortalType& sourcePortal,
const OffsetsPortalType &offsetsPortal) const OffsetsPortalType& offsetsPortal)
: SourcePortal(sourcePortal), OffsetsPortal(offsetsPortal) { } : SourcePortal(sourcePortal)
, OffsetsPortal(offsetsPortal)
{
}
/// Copy constructor for any other ArrayPortalConcatenate with a portal type /// Copy constructor for any other ArrayPortalConcatenate with a portal type
/// that can be copied to this portal type. This allows us to do any type /// that can be copied to this portal type. This allows us to do any type
/// casting that the portals do (like the non-const to const cast). /// casting that the portals do (like the non-const to const cast).
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<typename OtherSourcePortalType, typename OtherOffsetsPortalType> template <typename OtherSourcePortalType, typename OtherOffsetsPortalType>
VTKM_EXEC_CONT VTKM_EXEC_CONT ArrayPortalGroupVecVariable(
ArrayPortalGroupVecVariable( const ArrayPortalGroupVecVariable<OtherSourcePortalType, OtherOffsetsPortalType>& src)
const ArrayPortalGroupVecVariable<OtherSourcePortalType, OtherOffsetsPortalType> &src) : SourcePortal(src.GetSourcePortal())
: SourcePortal(src.GetSourcePortal()), , OffsetsPortal(src.GetOffsetsPortal())
OffsetsPortal(src.GetOffsetsPortal()) {
{ } }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const { return this->OffsetsPortal.GetNumberOfValues(); }
{
return this->OffsetsPortal.GetNumberOfValues();
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
@ -80,25 +86,22 @@ public:
{ {
vtkm::Id offsetIndex = this->OffsetsPortal.Get(index); vtkm::Id offsetIndex = this->OffsetsPortal.Get(index);
vtkm::Id nextOffsetIndex; vtkm::Id nextOffsetIndex;
if (index+1 < this->GetNumberOfValues()) if (index + 1 < this->GetNumberOfValues())
{ {
nextOffsetIndex = this->OffsetsPortal.Get(index+1); nextOffsetIndex = this->OffsetsPortal.Get(index + 1);
} }
else else
{ {
nextOffsetIndex = this->SourcePortal.GetNumberOfValues(); nextOffsetIndex = this->SourcePortal.GetNumberOfValues();
} }
return return ValueType(this->SourcePortal,
ValueType(this->SourcePortal, static_cast<vtkm::IdComponent>(nextOffsetIndex - offsetIndex), offsetIndex);
static_cast<vtkm::IdComponent>(nextOffsetIndex-offsetIndex),
offsetIndex);
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set(vtkm::Id vtkmNotUsed(index), void Set(vtkm::Id vtkmNotUsed(index), const ValueType& vtkmNotUsed(value)) const
const ValueType &vtkmNotUsed(value)) const
{ {
// The ValueType (VecFromPortal) operates on demand. Thus, if you set // The ValueType (VecFromPortal) operates on demand. Thus, if you set
// something in the value, it has already been passed to the array. Perhaps // something in the value, it has already been passed to the array. Perhaps
@ -108,17 +111,11 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const SourcePortalType &GetSourcePortal() const const SourcePortalType& GetSourcePortal() const { return this->SourcePortal; }
{
return this->SourcePortal;
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const OffsetsPortalType &GetOffsetsPortal() const const OffsetsPortalType& GetOffsetsPortal() const { return this->OffsetsPortal; }
{
return this->OffsetsPortal;
}
private: private:
SourcePortalType SourcePortal; SourcePortalType SourcePortal;
@ -127,7 +124,8 @@ private:
} // namespace internal (in vtkm::exec) } // namespace internal (in vtkm::exec)
namespace arg { namespace arg
{
// We need to override the fetch for output fields using // We need to override the fetch for output fields using
// ArrayPortalGroupVecVariable because this portal does not behave like most // ArrayPortalGroupVecVariable because this portal does not behave like most
@ -136,33 +134,25 @@ namespace arg {
// Instead, you need to implement the Load to point to the array portal. You // Instead, you need to implement the Load to point to the array portal. You
// can also ignore the Store because the data is already set in the array at // can also ignore the Store because the data is already set in the array at
// that point. // that point.
template<typename ThreadIndicesType, template <typename ThreadIndicesType, typename SourcePortalType, typename OffsetsPortalType>
typename SourcePortalType, struct Fetch<vtkm::exec::arg::FetchTagArrayDirectOut, vtkm::exec::arg::AspectTagDefault,
typename OffsetsPortalType> ThreadIndicesType,
struct Fetch< vtkm::exec::internal::ArrayPortalGroupVecVariable<SourcePortalType, OffsetsPortalType>>
vtkm::exec::arg::FetchTagArrayDirectOut,
vtkm::exec::arg::AspectTagDefault,
ThreadIndicesType,
vtkm::exec::internal::ArrayPortalGroupVecVariable<SourcePortalType,OffsetsPortalType> >
{ {
using ExecObjectType = using ExecObjectType =
vtkm::exec::internal::ArrayPortalGroupVecVariable< vtkm::exec::internal::ArrayPortalGroupVecVariable<SourcePortalType, OffsetsPortalType>;
SourcePortalType,OffsetsPortalType>;
using ValueType = typename ExecObjectType::ValueType; using ValueType = typename ExecObjectType::ValueType;
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC VTKM_EXEC
ValueType Load(const ThreadIndicesType &indices, ValueType Load(const ThreadIndicesType& indices, const ExecObjectType& arrayPortal) const
const ExecObjectType &arrayPortal) const
{ {
return arrayPortal.Get(indices.GetOutputIndex()); return arrayPortal.Get(indices.GetOutputIndex());
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC VTKM_EXEC
void Store(const ThreadIndicesType &, void Store(const ThreadIndicesType&, const ExecObjectType&, const ValueType&) const
const ExecObjectType &,
const ValueType &) const
{ {
// We can actually ignore this because the VecFromPortal will already have // We can actually ignore this because the VecFromPortal will already have
// set new values in the array. // set new values in the array.
@ -170,52 +160,56 @@ struct Fetch<
}; };
} // namespace arg (in vtkm::exec) } // namespace arg (in vtkm::exec)
} }
} // namespace vtkm::exec } // namespace vtkm::exec
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace internal { namespace internal
{
template<typename SourceArrayHandleType, typename OffsetsArrayHandleType> template <typename SourceArrayHandleType, typename OffsetsArrayHandleType>
struct VTKM_ALWAYS_EXPORT StorageTagGroupVecVariable { }; struct VTKM_ALWAYS_EXPORT StorageTagGroupVecVariable
{
};
template<typename SourceArrayHandleType, typename OffsetsArrayHandleType> template <typename SourceArrayHandleType, typename OffsetsArrayHandleType>
class Storage< class Storage<
vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>, vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>,
vtkm::cont::internal::StorageTagGroupVecVariable< vtkm::cont::internal::StorageTagGroupVecVariable<SourceArrayHandleType, OffsetsArrayHandleType>>
SourceArrayHandleType, OffsetsArrayHandleType> >
{ {
using ComponentType = typename SourceArrayHandleType::ValueType; using ComponentType = typename SourceArrayHandleType::ValueType;
public: public:
using ValueType = using ValueType = vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>;
vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>;
using PortalType = using PortalType = vtkm::exec::internal::ArrayPortalGroupVecVariable<
vtkm::exec::internal::ArrayPortalGroupVecVariable< typename SourceArrayHandleType::PortalControl, typename OffsetsArrayHandleType::PortalControl>;
typename SourceArrayHandleType::PortalControl, using PortalConstType = vtkm::exec::internal::ArrayPortalGroupVecVariable<
typename OffsetsArrayHandleType::PortalControl>; typename SourceArrayHandleType::PortalConstControl,
using PortalConstType = typename OffsetsArrayHandleType::PortalConstControl>;
vtkm::exec::internal::ArrayPortalGroupVecVariable<
typename SourceArrayHandleType::PortalConstControl,
typename OffsetsArrayHandleType::PortalConstControl>;
VTKM_CONT VTKM_CONT
Storage() : Valid(false) { } Storage()
: Valid(false)
{
}
VTKM_CONT VTKM_CONT
Storage(const SourceArrayHandleType &sourceArray, Storage(const SourceArrayHandleType& sourceArray, const OffsetsArrayHandleType& offsetsArray)
const OffsetsArrayHandleType &offsetsArray) : SourceArray(sourceArray)
: SourceArray(sourceArray), OffsetsArray(offsetsArray), Valid(true) { } , OffsetsArray(offsetsArray)
, Valid(true)
{
}
VTKM_CONT VTKM_CONT
PortalType GetPortal() PortalType GetPortal()
{ {
return PortalType(this->SourceArray.GetPortalControl(), return PortalType(this->SourceArray.GetPortalControl(), this->OffsetsArray.GetPortalControl());
this->OffsetsArray.GetPortalControl());
} }
VTKM_CONT VTKM_CONT
@ -235,8 +229,7 @@ public:
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id vtkmNotUsed(numberOfValues)) void Allocate(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
VTKM_ASSERT( VTKM_ASSERT("Allocate not supported for ArrayhandleGroupVecVariable" && false);
"Allocate not supported for ArrayhandleGroupVecVariable" && false);
} }
VTKM_CONT VTKM_CONT
@ -258,7 +251,7 @@ public:
// Required for later use in ArrayTransfer class // Required for later use in ArrayTransfer class
VTKM_CONT VTKM_CONT
const SourceArrayHandleType &GetSourceArray() const const SourceArrayHandleType& GetSourceArray() const
{ {
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->SourceArray; return this->SourceArray;
@ -266,7 +259,7 @@ public:
// Required for later use in ArrayTransfer class // Required for later use in ArrayTransfer class
VTKM_CONT VTKM_CONT
const OffsetsArrayHandleType &GetOffsetsArray() const const OffsetsArrayHandleType& GetOffsetsArray() const
{ {
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->OffsetsArray; return this->OffsetsArray;
@ -278,51 +271,42 @@ private:
bool Valid; bool Valid;
}; };
template<typename SourceArrayHandleType, template <typename SourceArrayHandleType, typename OffsetsArrayHandleType, typename Device>
typename OffsetsArrayHandleType,
typename Device>
class ArrayTransfer< class ArrayTransfer<
vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>, vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>,
vtkm::cont::internal::StorageTagGroupVecVariable< vtkm::cont::internal::StorageTagGroupVecVariable<SourceArrayHandleType, OffsetsArrayHandleType>,
SourceArrayHandleType, OffsetsArrayHandleType>, Device>
Device>
{ {
public: public:
using ComponentType = typename SourceArrayHandleType::ValueType; using ComponentType = typename SourceArrayHandleType::ValueType;
using ValueType = using ValueType = vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>;
vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>;
private: private:
using StorageTag = using StorageTag =
vtkm::cont::internal::StorageTagGroupVecVariable< vtkm::cont::internal::StorageTagGroupVecVariable<SourceArrayHandleType, OffsetsArrayHandleType>;
SourceArrayHandleType, OffsetsArrayHandleType>;
using StorageType = vtkm::cont::internal::Storage<ValueType, StorageTag>; using StorageType = vtkm::cont::internal::Storage<ValueType, StorageTag>;
public: public:
using PortalControl = typename StorageType::PortalType; using PortalControl = typename StorageType::PortalType;
using PortalConstControl = typename StorageType::PortalConstType; using PortalConstControl = typename StorageType::PortalConstType;
using PortalExecution = using PortalExecution = vtkm::exec::internal::ArrayPortalGroupVecVariable<
vtkm::exec::internal::ArrayPortalGroupVecVariable< typename SourceArrayHandleType::template ExecutionTypes<Device>::Portal,
typename SourceArrayHandleType::template ExecutionTypes<Device>::Portal, typename OffsetsArrayHandleType::template ExecutionTypes<Device>::PortalConst>;
typename OffsetsArrayHandleType::template ExecutionTypes<Device>::PortalConst>; using PortalConstExecution = vtkm::exec::internal::ArrayPortalGroupVecVariable<
using PortalConstExecution = typename SourceArrayHandleType::template ExecutionTypes<Device>::PortalConst,
vtkm::exec::internal::ArrayPortalGroupVecVariable< typename OffsetsArrayHandleType::template ExecutionTypes<Device>::PortalConst>;
typename SourceArrayHandleType::template ExecutionTypes<Device>::PortalConst,
typename OffsetsArrayHandleType::template ExecutionTypes<Device>::PortalConst>;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) ArrayTransfer(StorageType* storage)
: SourceArray(storage->GetSourceArray()), : SourceArray(storage->GetSourceArray())
OffsetsArray(storage->GetOffsetsArray()) , OffsetsArray(storage->GetOffsetsArray())
{ }
VTKM_CONT
vtkm::Id GetNumberOfValues() const
{ {
return this->OffsetsArray.GetNumberOfValues();
} }
VTKM_CONT
vtkm::Id GetNumberOfValues() const { return this->OffsetsArray.GetNumberOfValues(); }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{ {
@ -342,13 +326,13 @@ public:
{ {
// Cannot reallocate an ArrayHandleGroupVecVariable // Cannot reallocate an ArrayHandleGroupVecVariable
VTKM_ASSERT(numberOfValues == this->OffsetsArray.GetNumberOfValues()); VTKM_ASSERT(numberOfValues == this->OffsetsArray.GetNumberOfValues());
return PortalExecution(this->SourceArray.PrepareForOutput( return PortalExecution(
this->SourceArray.GetNumberOfValues(), Device()), this->SourceArray.PrepareForOutput(this->SourceArray.GetNumberOfValues(), Device()),
this->OffsetsArray.PrepareForInput(Device())); this->OffsetsArray.PrepareForInput(Device()));
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *vtkmNotUsed(storage)) const void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{ {
// Implementation of this method should be unnecessary. The internal // Implementation of this method should be unnecessary. The internal
// array handles should automatically retrieve the output data as // array handles should automatically retrieve the output data as
@ -356,10 +340,7 @@ public:
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numberOfValues) void Shrink(vtkm::Id numberOfValues) { this->OffsetsArray.Shrink(numberOfValues); }
{
this->OffsetsArray.Shrink(numberOfValues);
}
VTKM_CONT VTKM_CONT
void ReleaseResources() void ReleaseResources()
@ -407,24 +388,23 @@ private:
/// components for each entry) and get an array of offsets needed for \c /// components for each entry) and get an array of offsets needed for \c
/// ArrayHandleGroupVecVariable. /// ArrayHandleGroupVecVariable.
/// ///
template<typename SourceArrayHandleType, typename OffsetsArrayHandleType> template <typename SourceArrayHandleType, typename OffsetsArrayHandleType>
class ArrayHandleGroupVecVariable class ArrayHandleGroupVecVariable
: public vtkm::cont::ArrayHandle< : public vtkm::cont::ArrayHandle<
vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>, vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>,
vtkm::cont::internal::StorageTagGroupVecVariable< vtkm::cont::internal::StorageTagGroupVecVariable<SourceArrayHandleType,
SourceArrayHandleType, OffsetsArrayHandleType> > OffsetsArrayHandleType>>
{ {
VTKM_IS_ARRAY_HANDLE(SourceArrayHandleType); VTKM_IS_ARRAY_HANDLE(SourceArrayHandleType);
VTKM_IS_ARRAY_HANDLE(OffsetsArrayHandleType); VTKM_IS_ARRAY_HANDLE(OffsetsArrayHandleType);
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleGroupVecVariable, ArrayHandleGroupVecVariable,
(ArrayHandleGroupVecVariable<SourceArrayHandleType, OffsetsArrayHandleType>), (ArrayHandleGroupVecVariable<SourceArrayHandleType, OffsetsArrayHandleType>),
(vtkm::cont::ArrayHandle< (vtkm::cont::ArrayHandle<vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>,
vtkm::VecFromPortal<typename SourceArrayHandleType::PortalControl>, vtkm::cont::internal::StorageTagGroupVecVariable<
vtkm::cont::internal::StorageTagGroupVecVariable< SourceArrayHandleType, OffsetsArrayHandleType>>));
SourceArrayHandleType, OffsetsArrayHandleType> >));
using ComponentType = typename SourceArrayHandleType::ValueType; using ComponentType = typename SourceArrayHandleType::ValueType;
@ -433,9 +413,11 @@ private:
public: public:
VTKM_CONT VTKM_CONT
ArrayHandleGroupVecVariable(const SourceArrayHandleType &sourceArray, ArrayHandleGroupVecVariable(const SourceArrayHandleType& sourceArray,
const OffsetsArrayHandleType &offsetsArray) const OffsetsArrayHandleType& offsetsArray)
: Superclass(StorageType(sourceArray, offsetsArray)) { } : Superclass(StorageType(sourceArray, offsetsArray))
{
}
}; };
/// \c make_ArrayHandleGroupVecVariable is convenience function to generate an /// \c make_ArrayHandleGroupVecVariable is convenience function to generate an
@ -443,21 +425,19 @@ public:
/// array handle of offsets and returns an array handle with consecutive /// array handle of offsets and returns an array handle with consecutive
/// entries grouped in a Vec. /// entries grouped in a Vec.
/// ///
template<typename SourceArrayHandleType, typename OffsetsArrayHandleType> template <typename SourceArrayHandleType, typename OffsetsArrayHandleType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandleGroupVecVariable<SourceArrayHandleType, OffsetsArrayHandleType>
vtkm::cont::ArrayHandleGroupVecVariable< make_ArrayHandleGroupVecVariable(const SourceArrayHandleType& sourceArray,
SourceArrayHandleType, OffsetsArrayHandleType> const OffsetsArrayHandleType& offsetsArray)
make_ArrayHandleGroupVecVariable(const SourceArrayHandleType &sourceArray,
const OffsetsArrayHandleType &offsetsArray)
{ {
return vtkm::cont::ArrayHandleGroupVecVariable< return vtkm::cont::ArrayHandleGroupVecVariable<SourceArrayHandleType, OffsetsArrayHandleType>(
SourceArrayHandleType, OffsetsArrayHandleType>(sourceArray, offsetsArray); sourceArray, offsetsArray);
} }
namespace detail { namespace detail
{
template<typename NumComponentsArrayType, template <typename NumComponentsArrayType, typename OffsetsArrayType>
typename OffsetsArrayType>
struct ConvertNumComponentsToOffsetsFunctor struct ConvertNumComponentsToOffsetsFunctor
{ {
const NumComponentsArrayType NumComponentsArray; const NumComponentsArrayType NumComponentsArray;
@ -465,43 +445,38 @@ struct ConvertNumComponentsToOffsetsFunctor
vtkm::Id SourceArraySize; vtkm::Id SourceArraySize;
VTKM_CONT VTKM_CONT
ConvertNumComponentsToOffsetsFunctor( ConvertNumComponentsToOffsetsFunctor(const NumComponentsArrayType& numCompArray)
const NumComponentsArrayType &numCompArray) : NumComponentsArray(numCompArray)
: NumComponentsArray(numCompArray), SourceArraySize(0) , SourceArraySize(0)
{ }
template<typename Device>
VTKM_CONT
bool operator()(Device)
{ {
this->SourceArraySize = }
vtkm::cont::DeviceAdapterAlgorithm<Device>::
ScanExclusive(this->NumComponentsArray, this->OffsetsArray); template <typename Device>
VTKM_CONT bool operator()(Device)
{
this->SourceArraySize = vtkm::cont::DeviceAdapterAlgorithm<Device>::ScanExclusive(
this->NumComponentsArray, this->OffsetsArray);
return true; return true;
} }
}; };
template<typename NumComponentsArrayType, template <typename NumComponentsArrayType, typename OffsetsArrayType>
typename OffsetsArrayType> VTKM_CONT void DoConvertNumComponentsToOffsets(const NumComponentsArrayType& numComponentsArray,
VTKM_CONT OffsetsArrayType& offsetsArray,
void DoConvertNumComponentsToOffsets( vtkm::Id& sourceArraySize)
const NumComponentsArrayType &numComponentsArray,
OffsetsArrayType &offsetsArray,
vtkm::Id &sourceArraySize)
{ {
VTKM_IS_ARRAY_HANDLE(NumComponentsArrayType); VTKM_IS_ARRAY_HANDLE(NumComponentsArrayType);
VTKM_IS_ARRAY_HANDLE(OffsetsArrayType); VTKM_IS_ARRAY_HANDLE(OffsetsArrayType);
detail::ConvertNumComponentsToOffsetsFunctor< detail::ConvertNumComponentsToOffsetsFunctor<NumComponentsArrayType, OffsetsArrayType> functor(
NumComponentsArrayType,OffsetsArrayType> functor(numComponentsArray); numComponentsArray);
bool success = vtkm::cont::TryExecute(functor); bool success = vtkm::cont::TryExecute(functor);
if (!success) if (!success)
{ {
// Internal error? Maybe need to make a failed to execute error. // Internal error? Maybe need to make a failed to execute error.
throw vtkm::cont::ErrorInternal( throw vtkm::cont::ErrorInternal("Failed to run ExclusiveScan on any device.");
"Failed to run ExclusiveScan on any device.");
} }
sourceArraySize = functor.SourceArraySize; sourceArraySize = functor.SourceArraySize;
@ -518,54 +493,41 @@ void DoConvertNumComponentsToOffsets(
/// If an optional second parameter is given, the expected size of the source /// If an optional second parameter is given, the expected size of the source
/// values array is returned in it. /// values array is returned in it.
/// ///
template<typename NumComponentsArrayType, template <typename NumComponentsArrayType, typename OffsetsStorage>
typename OffsetsStorage> VTKM_CONT void ConvertNumComponentsToOffsets(
VTKM_CONT const NumComponentsArrayType& numComponentsArray,
void ConvertNumComponentsToOffsets( vtkm::cont::ArrayHandle<vtkm::Id, OffsetsStorage>& offsetsArray, vtkm::Id& sourceArraySize)
const NumComponentsArrayType &numComponentsArray,
vtkm::cont::ArrayHandle<vtkm::Id,OffsetsStorage> &offsetsArray,
vtkm::Id &sourceArraySize)
{ {
VTKM_IS_ARRAY_HANDLE(NumComponentsArrayType); VTKM_IS_ARRAY_HANDLE(NumComponentsArrayType);
detail::DoConvertNumComponentsToOffsets( detail::DoConvertNumComponentsToOffsets(
vtkm::cont::make_ArrayHandleCast<vtkm::Id>(numComponentsArray), vtkm::cont::make_ArrayHandleCast<vtkm::Id>(numComponentsArray), offsetsArray, sourceArraySize);
offsetsArray,
sourceArraySize);
} }
template<typename NumComponentsArrayType, template <typename NumComponentsArrayType, typename OffsetsStorage>
typename OffsetsStorage> VTKM_CONT void ConvertNumComponentsToOffsets(
VTKM_CONT const NumComponentsArrayType& numComponentsArray,
void ConvertNumComponentsToOffsets( vtkm::cont::ArrayHandle<vtkm::Id, OffsetsStorage>& offsetsArray)
const NumComponentsArrayType &numComponentsArray,
vtkm::cont::ArrayHandle<vtkm::Id,OffsetsStorage> &offsetsArray)
{ {
vtkm::Id dummy; vtkm::Id dummy;
vtkm::cont::ConvertNumComponentsToOffsets( vtkm::cont::ConvertNumComponentsToOffsets(numComponentsArray, offsetsArray, dummy);
numComponentsArray, offsetsArray, dummy);
} }
template<typename NumComponentsArrayType> template <typename NumComponentsArrayType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandle<vtkm::Id> ConvertNumComponentsToOffsets(
vtkm::cont::ArrayHandle<vtkm::Id> const NumComponentsArrayType& numComponentsArray, vtkm::Id& sourceArraySize)
ConvertNumComponentsToOffsets(const NumComponentsArrayType &numComponentsArray,
vtkm::Id &sourceArraySize)
{ {
VTKM_IS_ARRAY_HANDLE(NumComponentsArrayType); VTKM_IS_ARRAY_HANDLE(NumComponentsArrayType);
vtkm::cont::ArrayHandle<vtkm::Id> offsetsArray; vtkm::cont::ArrayHandle<vtkm::Id> offsetsArray;
vtkm::cont::ConvertNumComponentsToOffsets( vtkm::cont::ConvertNumComponentsToOffsets(numComponentsArray, offsetsArray, sourceArraySize);
numComponentsArray, offsetsArray, sourceArraySize);
return offsetsArray; return offsetsArray;
} }
template<typename NumComponentsArrayType> template <typename NumComponentsArrayType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandle<vtkm::Id> ConvertNumComponentsToOffsets(
vtkm::cont::ArrayHandle<vtkm::Id> const NumComponentsArrayType& numComponentsArray)
ConvertNumComponentsToOffsets(const NumComponentsArrayType &numComponentsArray)
{ {
vtkm::Id dummy; vtkm::Id dummy;
return vtkm::cont::ConvertNumComponentsToOffsets(numComponentsArray, dummy); return vtkm::cont::ConvertNumComponentsToOffsets(numComponentsArray, dummy);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -25,11 +25,13 @@
#include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandle.h>
#include <vtkm/cont/StorageImplicit.h> #include <vtkm/cont/StorageImplicit.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace detail
namespace detail { {
/// \brief An array portal that returns the result of a functor /// \brief An array portal that returns the result of a functor
/// ///
/// This array portal is similar to an implicit array i.e an array that is /// This array portal is similar to an implicit array i.e an array that is
@ -39,7 +41,7 @@ namespace detail {
/// The \c ArrayPortalImplicit is used in an ArrayHandle with an /// The \c ArrayPortalImplicit is used in an ArrayHandle with an
/// \c StorageImplicit container. /// \c StorageImplicit container.
/// ///
template <class ValueType_, class FunctorType_ > template <class ValueType_, class FunctorType_>
class VTKM_ALWAYS_EXPORT ArrayPortalImplicit class VTKM_ALWAYS_EXPORT ArrayPortalImplicit
{ {
public: public:
@ -47,15 +49,18 @@ public:
typedef FunctorType_ FunctorType; typedef FunctorType_ FunctorType;
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalImplicit() : ArrayPortalImplicit()
Functor(), : Functor()
NumberOfValues(0) { } , NumberOfValues(0)
{
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalImplicit(FunctorType f, vtkm::Id numValues) : ArrayPortalImplicit(FunctorType f, vtkm::Id numValues)
Functor(f), : Functor(f)
NumberOfValues(numValues) , NumberOfValues(numValues)
{ } {
}
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const { return this->NumberOfValues; } vtkm::Id GetNumberOfValues() const { return this->NumberOfValues; }
@ -65,22 +70,18 @@ public:
ValueType Get(vtkm::Id index) const { return this->Functor(index); } ValueType Get(vtkm::Id index) const { return this->Functor(index); }
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set(vtkm::Id vtkmNotUsed(index), void Set(vtkm::Id vtkmNotUsed(index), const ValueType& vtkmNotUsed(value)) const
const ValueType &vtkmNotUsed(value)) const
{ {
#if !(defined(VTKM_MSVC) && defined(VTKM_CUDA)) #if !(defined(VTKM_MSVC) && defined(VTKM_CUDA))
VTKM_ASSERT(false && "Cannot write to read-only implicit array."); VTKM_ASSERT(false && "Cannot write to read-only implicit array.");
#endif #endif
} }
typedef vtkm::cont::internal::IteratorFromArrayPortal< typedef vtkm::cont::internal::IteratorFromArrayPortal<ArrayPortalImplicit<ValueType, FunctorType>>
ArrayPortalImplicit<ValueType,FunctorType> > IteratorType; IteratorType;
VTKM_CONT VTKM_CONT
IteratorType GetIteratorBegin() const IteratorType GetIteratorBegin() const { return IteratorType(*this); }
{
return IteratorType(*this);
}
private: private:
FunctorType Functor; FunctorType Functor;
@ -89,18 +90,17 @@ private:
/// A convenience class that provides a typedef to the appropriate tag for /// A convenience class that provides a typedef to the appropriate tag for
/// a implicit array container. /// a implicit array container.
template<typename ValueType, typename FunctorType> template <typename ValueType, typename FunctorType>
struct ArrayHandleImplicitTraits struct ArrayHandleImplicitTraits
{ {
typedef vtkm::cont::StorageTagImplicit< typedef vtkm::cont::StorageTagImplicit<
vtkm::cont::detail::ArrayPortalImplicit<ValueType, vtkm::cont::detail::ArrayPortalImplicit<ValueType, FunctorType>>
FunctorType> > StorageTag; StorageTag;
typedef vtkm::cont::ArrayHandle<ValueType,StorageTag> Superclass; typedef vtkm::cont::ArrayHandle<ValueType, StorageTag> Superclass;
}; };
} // namespace detail } // namespace detail
/// \brief An \c ArrayHandle that computes values on the fly. /// \brief An \c ArrayHandle that computes values on the fly.
/// ///
/// \c ArrayHandleImplicit is a specialization of ArrayHandle. /// \c ArrayHandleImplicit is a specialization of ArrayHandle.
@ -108,24 +108,21 @@ struct ArrayHandleImplicitTraits
/// The functor returns the result of the functor as the value of this /// The functor returns the result of the functor as the value of this
/// array at that position. /// array at that position.
/// ///
template <typename T, template <typename T, class FunctorType>
class FunctorType> class ArrayHandleImplicit : public detail::ArrayHandleImplicitTraits<T, FunctorType>::Superclass
class ArrayHandleImplicit
: public detail::ArrayHandleImplicitTraits<T,FunctorType>::Superclass
{ {
private: private:
typedef typename detail::ArrayHandleImplicitTraits<T,FunctorType> ArrayTraits; typedef typename detail::ArrayHandleImplicitTraits<T, FunctorType> ArrayTraits;
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(ArrayHandleImplicit, (ArrayHandleImplicit<T, FunctorType>),
ArrayHandleImplicit, (typename ArrayTraits::Superclass));
(ArrayHandleImplicit<T,FunctorType>),
(typename ArrayTraits::Superclass));
VTKM_CONT VTKM_CONT
ArrayHandleImplicit(FunctorType functor, vtkm::Id length) ArrayHandleImplicit(FunctorType functor, vtkm::Id length)
: Superclass(typename Superclass::PortalConstControl(functor,length)) : Superclass(typename Superclass::PortalConstControl(functor, length))
{ } {
}
}; };
/// make_ArrayHandleImplicit is convenience function to generate an /// make_ArrayHandleImplicit is convenience function to generate an
@ -133,14 +130,11 @@ public:
/// arry. /// arry.
template <typename T, typename FunctorType> template <typename T, typename FunctorType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandleImplicit<T, FunctorType> make_ArrayHandleImplicit(
vtkm::cont::ArrayHandleImplicit<T, FunctorType> FunctorType functor, vtkm::Id length)
make_ArrayHandleImplicit(FunctorType functor, vtkm::Id length)
{ {
return ArrayHandleImplicit<T,FunctorType>(functor,length); return ArrayHandleImplicit<T, FunctorType>(functor, length);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -24,12 +24,16 @@
#include <vtkm/cont/ArrayHandleImplicit.h> #include <vtkm/cont/ArrayHandleImplicit.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace detail { namespace detail
{
struct VTKM_ALWAYS_EXPORT IndexFunctor { struct VTKM_ALWAYS_EXPORT IndexFunctor
{
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Id operator()(vtkm::Id index) const { return index; } vtkm::Id operator()(vtkm::Id index) const { return index; }
}; };
@ -42,19 +46,18 @@ struct VTKM_ALWAYS_EXPORT IndexFunctor {
/// 0, 1, 2, 3,... to a specified size. Every value in the array is the same /// 0, 1, 2, 3,... to a specified size. Every value in the array is the same
/// as the index to that value. /// as the index to that value.
/// ///
class ArrayHandleIndex class ArrayHandleIndex : public vtkm::cont::ArrayHandleImplicit<vtkm::Id, detail::IndexFunctor>
: public vtkm::cont::ArrayHandleImplicit<vtkm::Id, detail::IndexFunctor>
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS_NT( VTKM_ARRAY_HANDLE_SUBCLASS_NT(ArrayHandleIndex,
ArrayHandleIndex, (vtkm::cont::ArrayHandleImplicit<vtkm::Id, detail::IndexFunctor>));
(vtkm::cont::ArrayHandleImplicit<vtkm::Id, detail::IndexFunctor>));
VTKM_CONT VTKM_CONT
ArrayHandleIndex(vtkm::Id length) ArrayHandleIndex(vtkm::Id length)
: Superclass(detail::IndexFunctor(), length) { } : Superclass(detail::IndexFunctor(), length)
{
}
}; };
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -26,11 +26,14 @@
#include <vtkm/cont/ErrorBadType.h> #include <vtkm/cont/ErrorBadType.h>
#include <vtkm/cont/ErrorBadValue.h> #include <vtkm/cont/ErrorBadValue.h>
namespace vtkm { namespace vtkm
namespace exec { {
namespace internal { namespace exec
{
namespace internal
{
template<typename IndexPortalType, typename ValuePortalType> template <typename IndexPortalType, typename ValuePortalType>
class VTKM_ALWAYS_EXPORT ArrayPortalPermutation class VTKM_ALWAYS_EXPORT ArrayPortalPermutation
{ {
public: public:
@ -38,15 +41,19 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalPermutation( ) ArrayPortalPermutation()
: IndexPortal(), ValuePortal() { } : IndexPortal()
, ValuePortal()
{
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalPermutation( ArrayPortalPermutation(const IndexPortalType& indexPortal, const ValuePortalType& valuePortal)
const IndexPortalType &indexPortal, : IndexPortal(indexPortal)
const ValuePortalType &valuePortal) , ValuePortal(valuePortal)
: IndexPortal(indexPortal), ValuePortal(valuePortal) { } {
}
/// Copy constructor for any other ArrayPortalPermutation with delegate /// Copy constructor for any other ArrayPortalPermutation with delegate
/// portal types that can be copied to these portal types. This allows us to /// portal types that can be copied to these portal types. This allows us to
@ -54,62 +61,65 @@ public:
/// const cast). /// const cast).
/// ///
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<typename OtherIP, typename OtherVP> template <typename OtherIP, typename OtherVP>
VTKM_EXEC_CONT VTKM_EXEC_CONT ArrayPortalPermutation(const ArrayPortalPermutation<OtherIP, OtherVP>& src)
ArrayPortalPermutation( : IndexPortal(src.GetIndexPortal())
const ArrayPortalPermutation<OtherIP,OtherVP> &src) , ValuePortal(src.GetValuePortal())
: IndexPortal(src.GetIndexPortal()), ValuePortal(src.GetValuePortal()) {
{ }
VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const {
return this->IndexPortal.GetNumberOfValues();
} }
VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const { return this->IndexPortal.GetNumberOfValues(); }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC VTKM_EXEC
ValueType Get(vtkm::Id index) const { ValueType Get(vtkm::Id index) const
{
vtkm::Id permutedIndex = this->IndexPortal.Get(index); vtkm::Id permutedIndex = this->IndexPortal.Get(index);
return this->ValuePortal.Get(permutedIndex); return this->ValuePortal.Get(permutedIndex);
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC VTKM_EXEC
void Set(vtkm::Id index, const ValueType &value) const { void Set(vtkm::Id index, const ValueType& value) const
{
vtkm::Id permutedIndex = this->IndexPortal.Get(index); vtkm::Id permutedIndex = this->IndexPortal.Get(index);
this->ValuePortal.Set(permutedIndex, value); this->ValuePortal.Set(permutedIndex, value);
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const IndexPortalType &GetIndexPortal() const { return this->IndexPortal; } const IndexPortalType& GetIndexPortal() const { return this->IndexPortal; }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const ValuePortalType &GetValuePortal() const { return this->ValuePortal; } const ValuePortalType& GetValuePortal() const { return this->ValuePortal; }
private: private:
IndexPortalType IndexPortal; IndexPortalType IndexPortal;
ValuePortalType ValuePortal; ValuePortalType ValuePortal;
}; };
} }
} }
} // namespace vtkm::exec::internal } // namespace vtkm::exec::internal
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace internal { namespace internal
{
template<typename IndexArrayType, typename ValueArrayType> template <typename IndexArrayType, typename ValueArrayType>
struct VTKM_ALWAYS_EXPORT StorageTagPermutation { }; struct VTKM_ALWAYS_EXPORT StorageTagPermutation
{
};
template<typename IndexArrayType, typename ValueArrayType> template <typename IndexArrayType, typename ValueArrayType>
class Storage< class Storage<typename ValueArrayType::ValueType,
typename ValueArrayType::ValueType, StorageTagPermutation<IndexArrayType, ValueArrayType>>
StorageTagPermutation<IndexArrayType, ValueArrayType> >
{ {
VTKM_IS_ARRAY_HANDLE(IndexArrayType); VTKM_IS_ARRAY_HANDLE(IndexArrayType);
VTKM_IS_ARRAY_HANDLE(ValueArrayType); VTKM_IS_ARRAY_HANDLE(ValueArrayType);
@ -117,64 +127,75 @@ class Storage<
public: public:
typedef typename ValueArrayType::ValueType ValueType; typedef typename ValueArrayType::ValueType ValueType;
typedef vtkm::exec::internal::ArrayPortalPermutation< typedef vtkm::exec::internal::ArrayPortalPermutation<typename IndexArrayType::PortalConstControl,
typename IndexArrayType::PortalConstControl, typename ValueArrayType::PortalControl>
typename ValueArrayType::PortalControl> PortalType; PortalType;
typedef vtkm::exec::internal::ArrayPortalPermutation< typedef vtkm::exec::internal::ArrayPortalPermutation<typename IndexArrayType::PortalConstControl,
typename IndexArrayType::PortalConstControl, typename ValueArrayType::PortalConstControl>
typename ValueArrayType::PortalConstControl> PortalConstType; PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : Valid(false) { } Storage()
: Valid(false)
{
}
VTKM_CONT VTKM_CONT
Storage(const IndexArrayType &indexArray, const ValueArrayType &valueArray) Storage(const IndexArrayType& indexArray, const ValueArrayType& valueArray)
: IndexArray(indexArray), ValueArray(valueArray), Valid(true) { } : IndexArray(indexArray)
, ValueArray(valueArray)
, Valid(true)
{
}
VTKM_CONT VTKM_CONT
PortalType GetPortal() { PortalType GetPortal()
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return PortalType(this->IndexArray.GetPortalConstControl(), return PortalType(this->IndexArray.GetPortalConstControl(),
this->ValueArray.GetPortalControl()); this->ValueArray.GetPortalControl());
} }
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const { PortalConstType GetPortalConst() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return PortalConstType(this->IndexArray.GetPortalConstControl(), return PortalConstType(this->IndexArray.GetPortalConstControl(),
this->ValueArray.GetPortalConstControl()); this->ValueArray.GetPortalConstControl());
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const { vtkm::Id GetNumberOfValues() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->IndexArray.GetNumberOfValues(); return this->IndexArray.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id vtkmNotUsed(numberOfValues)) { void Allocate(vtkm::Id vtkmNotUsed(numberOfValues))
throw vtkm::cont::ErrorBadType( {
"ArrayHandlePermutation cannot be allocated."); throw vtkm::cont::ErrorBadType("ArrayHandlePermutation cannot be allocated.");
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id vtkmNotUsed(numberOfValues)) { void Shrink(vtkm::Id vtkmNotUsed(numberOfValues))
throw vtkm::cont::ErrorBadType( {
"ArrayHandlePermutation cannot shrink."); throw vtkm::cont::ErrorBadType("ArrayHandlePermutation cannot shrink.");
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources()
{
// This request is ignored since it is asking to release the resources // This request is ignored since it is asking to release the resources
// of the delegate array, which may be used elsewhere. Should the behavior // of the delegate array, which may be used elsewhere. Should the behavior
// be different? // be different?
} }
VTKM_CONT VTKM_CONT
const IndexArrayType &GetIndexArray() const { return this->IndexArray; } const IndexArrayType& GetIndexArray() const { return this->IndexArray; }
VTKM_CONT VTKM_CONT
const ValueArrayType &GetValueArray() const { return this->ValueArray; } const ValueArrayType& GetValueArray() const { return this->ValueArray; }
private: private:
IndexArrayType IndexArray; IndexArrayType IndexArray;
@ -182,11 +203,9 @@ private:
bool Valid; bool Valid;
}; };
template<typename IndexArrayType, typename ValueArrayType, typename Device> template <typename IndexArrayType, typename ValueArrayType, typename Device>
class ArrayTransfer< class ArrayTransfer<typename ValueArrayType::ValueType,
typename ValueArrayType::ValueType, StorageTagPermutation<IndexArrayType, ValueArrayType>, Device>
StorageTagPermutation<IndexArrayType, ValueArrayType>,
Device>
{ {
public: public:
typedef typename ValueArrayType::ValueType ValueType; typedef typename ValueArrayType::ValueType ValueType;
@ -200,32 +219,34 @@ public:
typedef typename StorageType::PortalConstType PortalConstControl; typedef typename StorageType::PortalConstType PortalConstControl;
typedef vtkm::exec::internal::ArrayPortalPermutation< typedef vtkm::exec::internal::ArrayPortalPermutation<
typename IndexArrayType::template ExecutionTypes<Device>::PortalConst, typename IndexArrayType::template ExecutionTypes<Device>::PortalConst,
typename ValueArrayType::template ExecutionTypes<Device>::Portal> typename ValueArrayType::template ExecutionTypes<Device>::Portal>
PortalExecution; PortalExecution;
typedef vtkm::exec::internal::ArrayPortalPermutation< typedef vtkm::exec::internal::ArrayPortalPermutation<
typename IndexArrayType::template ExecutionTypes<Device>::PortalConst, typename IndexArrayType::template ExecutionTypes<Device>::PortalConst,
typename ValueArrayType::template ExecutionTypes<Device>::PortalConst> typename ValueArrayType::template ExecutionTypes<Device>::PortalConst>
PortalConstExecution; PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) ArrayTransfer(StorageType* storage)
: IndexArray(storage->GetIndexArray()), : IndexArray(storage->GetIndexArray())
ValueArray(storage->GetValueArray()) { } , ValueArray(storage->GetValueArray())
{
VTKM_CONT
vtkm::Id GetNumberOfValues() const {
return this->IndexArray.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) { vtkm::Id GetNumberOfValues() const { return this->IndexArray.GetNumberOfValues(); }
VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{
return PortalConstExecution(this->IndexArray.PrepareForInput(Device()), return PortalConstExecution(this->IndexArray.PrepareForInput(Device()),
this->ValueArray.PrepareForInput(Device())); this->ValueArray.PrepareForInput(Device()));
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData)) { PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData))
{
return PortalExecution(this->IndexArray.PrepareForInput(Device()), return PortalExecution(this->IndexArray.PrepareForInput(Device()),
this->ValueArray.PrepareForInPlace(Device())); this->ValueArray.PrepareForInPlace(Device()));
} }
@ -233,11 +254,12 @@ public:
VTKM_CONT VTKM_CONT
PortalExecution PrepareForOutput(vtkm::Id numberOfValues) PortalExecution PrepareForOutput(vtkm::Id numberOfValues)
{ {
if (numberOfValues != this->GetNumberOfValues()) { if (numberOfValues != this->GetNumberOfValues())
{
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"An ArrayHandlePermutation can be used as an output array, " "An ArrayHandlePermutation can be used as an output array, "
"but it cannot be resized. Make sure the index array is sized " "but it cannot be resized. Make sure the index array is sized "
"to the appropriate length before trying to prepare for output."); "to the appropriate length before trying to prepare for output.");
} }
// We cannot practically allocate ValueArray because we do not know the // We cannot practically allocate ValueArray because we do not know the
@ -247,30 +269,32 @@ public:
if ((numberOfValues > 0) && (this->ValueArray.GetNumberOfValues() < 1)) if ((numberOfValues > 0) && (this->ValueArray.GetNumberOfValues() < 1))
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"The value array must be pre-allocated before it is used for the " "The value array must be pre-allocated before it is used for the "
"output of ArrayHandlePermutation."); "output of ArrayHandlePermutation.");
} }
return PortalExecution(this->IndexArray.PrepareForInput(Device()), return PortalExecution(
this->ValueArray.PrepareForOutput( this->IndexArray.PrepareForInput(Device()),
this->ValueArray.GetNumberOfValues(), Device())); this->ValueArray.PrepareForOutput(this->ValueArray.GetNumberOfValues(), Device()));
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *vtkmNotUsed(storage)) const { void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{
// Implementation of this method should be unnecessary. The internal // Implementation of this method should be unnecessary. The internal
// array handles should automatically retrieve the output data as // array handles should automatically retrieve the output data as
// necessary. // necessary.
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id vtkmNotUsed(numberOfValues)) { void Shrink(vtkm::Id vtkmNotUsed(numberOfValues))
throw vtkm::cont::ErrorBadType( {
"ArrayHandlePermutation cannot shrink."); throw vtkm::cont::ErrorBadType("ArrayHandlePermutation cannot shrink.");
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources()
{
this->IndexArray.ReleaseResourcesExecution(); this->IndexArray.ReleaseResourcesExecution();
this->ValueArray.ReleaseResourcesExecution(); this->ValueArray.ReleaseResourcesExecution();
} }
@ -307,9 +331,9 @@ private:
/// ///
template <typename IndexArrayHandleType, typename ValueArrayHandleType> template <typename IndexArrayHandleType, typename ValueArrayHandleType>
class ArrayHandlePermutation class ArrayHandlePermutation
: public vtkm::cont::ArrayHandle< : public vtkm::cont::ArrayHandle<
typename ValueArrayHandleType::ValueType, typename ValueArrayHandleType::ValueType,
internal::StorageTagPermutation<IndexArrayHandleType, ValueArrayHandleType> > internal::StorageTagPermutation<IndexArrayHandleType, ValueArrayHandleType>>
{ {
// If the following line gives a compile error, then the ArrayHandleType // If the following line gives a compile error, then the ArrayHandleType
// template argument is not a valid ArrayHandle type. // template argument is not a valid ArrayHandle type.
@ -318,22 +342,21 @@ class ArrayHandlePermutation
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandlePermutation, ArrayHandlePermutation, (ArrayHandlePermutation<IndexArrayHandleType, ValueArrayHandleType>),
(ArrayHandlePermutation<IndexArrayHandleType,ValueArrayHandleType>), (vtkm::cont::ArrayHandle<
(vtkm::cont::ArrayHandle< typename ValueArrayHandleType::ValueType,
typename ValueArrayHandleType::ValueType, internal::StorageTagPermutation<IndexArrayHandleType, ValueArrayHandleType>>));
internal::StorageTagPermutation<
IndexArrayHandleType,ValueArrayHandleType> >));
private: private:
typedef vtkm::cont::internal::Storage<ValueType, StorageTag> typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
StorageType;
public: public:
VTKM_CONT VTKM_CONT
ArrayHandlePermutation(const IndexArrayHandleType &indexArray, ArrayHandlePermutation(const IndexArrayHandleType& indexArray,
const ValueArrayHandleType &valueArray) const ValueArrayHandleType& valueArray)
: Superclass(StorageType(indexArray, valueArray)) { } : Superclass(StorageType(indexArray, valueArray))
{
}
}; };
/// make_ArrayHandleTransform is convenience function to generate an /// make_ArrayHandleTransform is convenience function to generate an
@ -341,15 +364,11 @@ private:
/// to apply to each element of the Handle. /// to apply to each element of the Handle.
template <typename IndexArrayHandleType, typename ValueArrayHandleType> template <typename IndexArrayHandleType, typename ValueArrayHandleType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandlePermutation<IndexArrayHandleType, ValueArrayHandleType>
vtkm::cont::ArrayHandlePermutation<IndexArrayHandleType, ValueArrayHandleType> make_ArrayHandlePermutation(IndexArrayHandleType indexArray, ValueArrayHandleType valueArray)
make_ArrayHandlePermutation(IndexArrayHandleType indexArray,
ValueArrayHandleType valueArray)
{ {
return ArrayHandlePermutation<IndexArrayHandleType,ValueArrayHandleType>( return ArrayHandlePermutation<IndexArrayHandleType, ValueArrayHandleType>(indexArray, valueArray);
indexArray, valueArray);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -20,113 +20,126 @@
// //
//============================================================================= //=============================================================================
#ifndef vtk_m_cont_ArrayHandleReverse_h #ifndef vtk_m_cont_ArrayHandleReverse_h
#define vtk_m_cont_ArrayHandleReverse_h #define vtk_m_cont_ArrayHandleReverse_h
#include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandle.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace internal { namespace internal
{
template< typename PortalType > template <typename PortalType>
class VTKM_ALWAYS_EXPORT ArrayPortalReverse class VTKM_ALWAYS_EXPORT ArrayPortalReverse
{ {
public: public:
typedef typename PortalType::ValueType ValueType; typedef typename PortalType::ValueType ValueType;
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalReverse() : portal() {} ArrayPortalReverse()
: portal()
VTKM_EXEC_CONT {
ArrayPortalReverse(const PortalType &p) : portal(p) {}
template< typename OtherPortal >
VTKM_EXEC_CONT
ArrayPortalReverse(const ArrayPortalReverse<OtherPortal> &src) : portal(src.GetPortal()) {}
VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const {
return this->portal.GetNumberOfValues();
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
ValueType Get(vtkm::Id index) const { ArrayPortalReverse(const PortalType& p)
: portal(p)
{
}
template <typename OtherPortal>
VTKM_EXEC_CONT ArrayPortalReverse(const ArrayPortalReverse<OtherPortal>& src)
: portal(src.GetPortal())
{
}
VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const { return this->portal.GetNumberOfValues(); }
VTKM_EXEC_CONT
ValueType Get(vtkm::Id index) const
{
return this->portal.Get(portal.GetNumberOfValues() - index - 1); return this->portal.Get(portal.GetNumberOfValues() - index - 1);
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set(vtkm::Id index, const ValueType &value) const { void Set(vtkm::Id index, const ValueType& value) const
{
this->portal1.Set(portal.GetNumberOfValues() - index - 1, value); this->portal1.Set(portal.GetNumberOfValues() - index - 1, value);
} }
private: private:
PortalType portal; PortalType portal;
}; };
} }
template< typename ArrayHandleType > template <typename ArrayHandleType>
class StorageTagReverse class StorageTagReverse
{ {
}; };
namespace internal { namespace internal
{
template< typename ArrayHandleType > template <typename ArrayHandleType>
class Storage< typename ArrayHandleType::ValueType, StorageTagReverse<ArrayHandleType > > class Storage<typename ArrayHandleType::ValueType, StorageTagReverse<ArrayHandleType>>
{ {
public: public:
typedef typename ArrayHandleType::ValueType ValueType; typedef typename ArrayHandleType::ValueType ValueType;
typedef ArrayPortalReverse< typename ArrayHandleType::PortalControl > PortalType; typedef ArrayPortalReverse<typename ArrayHandleType::PortalControl> PortalType;
typedef ArrayPortalReverse< typename ArrayHandleType::PortalConstControl > PortalConstType; typedef ArrayPortalReverse<typename ArrayHandleType::PortalConstControl> PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : valid( false ) { } Storage()
: valid(false)
{
}
VTKM_CONT VTKM_CONT
Storage( const ArrayHandleType &a1 ) Storage(const ArrayHandleType& a1)
: array( a1 ), valid( true ) {}; : array(a1)
, valid(true){};
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const PortalConstType GetPortalConst() const
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return PortalConstType( this->array.GetPortalConstControl() ); return PortalConstType(this->array.GetPortalConstControl());
} }
VTKM_CONT VTKM_CONT
PortalType GetPortal() PortalType GetPortal()
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return PortalType( this->array.GetPortalControl() ); return PortalType(this->array.GetPortalControl());
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return this->array.GetNumberOfValues(); return this->array.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
void Allocate( vtkm::Id vtkmNotUsed(numberOfValues) ) void Allocate(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
throw vtkm::cont::ErrorInternal( throw vtkm::cont::ErrorInternal("ArrayHandleReverse should not be allocated explicitly. ");
"ArrayHandleReverse should not be allocated explicitly. " );
} }
VTKM_CONT VTKM_CONT
void Shrink( vtkm::Id vtkmNotUsed(numberOfValues) ) void Shrink(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
// throw vtkm::cont::ErrorBadType( // throw vtkm::cont::ErrorBadType(
// "ArrayHandleReverse cannot shrink."); // "ArrayHandleReverse cannot shrink.");
} }
VTKM_CONT VTKM_CONT
void ReleaseResources( ) void ReleaseResources()
{ {
// This request is ignored since it is asking to release the resources // This request is ignored since it is asking to release the resources
// of the delegate array, which may be used elsewhere. Should the behavior // of the delegate array, which may be used elsewhere. Should the behavior
@ -134,80 +147,78 @@ public:
} }
VTKM_CONT VTKM_CONT
const ArrayHandleType &GetArray() const const ArrayHandleType& GetArray() const
{ {
VTKM_ASSERT( this->valid ); VTKM_ASSERT(this->valid);
return this->array; return this->array;
} }
private: private:
ArrayHandleType array; ArrayHandleType array;
bool valid; bool valid;
}; // class storage }; // class storage
template< typename ArrayHandleType, typename Device > template <typename ArrayHandleType, typename Device>
class ArrayTransfer< typename ArrayHandleType::ValueType, StorageTagReverse< ArrayHandleType >, Device > class ArrayTransfer<typename ArrayHandleType::ValueType, StorageTagReverse<ArrayHandleType>, Device>
{ {
public: public:
typedef typename ArrayHandleType::ValueType ValueType; typedef typename ArrayHandleType::ValueType ValueType;
private: private:
typedef StorageTagReverse< ArrayHandleType > StorageTag; typedef StorageTagReverse<ArrayHandleType> StorageTag;
typedef vtkm::cont::internal::Storage< ValueType, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
typedef typename StorageType::PortalType PortalControl; typedef typename StorageType::PortalType PortalControl;
typedef typename StorageType::PortalConstType PortalConstControl; typedef typename StorageType::PortalConstType PortalConstControl;
typedef ArrayPortalReverse<typename ArrayHandleType::template ExecutionTypes< Device >::Portal> PortalExecution; typedef ArrayPortalReverse<typename ArrayHandleType::template ExecutionTypes<Device>::Portal>
typedef ArrayPortalReverse<typename ArrayHandleType::template ExecutionTypes< Device >::PortalConst> PortalConstExecution; PortalExecution;
typedef ArrayPortalReverse<typename ArrayHandleType::template ExecutionTypes<Device>::PortalConst>
PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer( StorageType* storage ) ArrayTransfer(StorageType* storage)
: array( storage->GetArray() ) {} : array(storage->GetArray())
VTKM_CONT
vtkm::Id GetNumberOfValues() const
{ {
return this->array.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput( bool vtkmNotUsed( updateData ) ) vtkm::Id GetNumberOfValues() const { return this->array.GetNumberOfValues(); }
VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{ {
return PortalConstExecution( this->array.PrepareForInput( Device() )); return PortalConstExecution(this->array.PrepareForInput(Device()));
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForInPlace( bool vtkmNotUsed( updateData ) ) PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData))
{ {
return PortalExecution( this->array.PrepareForInPlace( Device() )); return PortalExecution(this->array.PrepareForInPlace(Device()));
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForOutput( vtkm::Id vtkmNotUsed(numberOfValues) ) PortalExecution PrepareForOutput(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
return PortalExecution( this->array.PrepareForOutput( Device() )); return PortalExecution(this->array.PrepareForOutput(Device()));
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData( StorageType* vtkmNotUsed(storage) ) const void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{ {
// not need to implement // not need to implement
} }
VTKM_CONT VTKM_CONT
void Shrink( vtkm::Id vtkmNotUsed(numberOfValues) ) void Shrink(vtkm::Id vtkmNotUsed(numberOfValues))
{ {
// throw vtkm::cont::ErrorBadType( // throw vtkm::cont::ErrorBadType(
// "ArrayHandleReverse cannot shrink."); // "ArrayHandleReverse cannot shrink.");
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() void ReleaseResources() { this->array.ReleaseResourcesExecution(); }
{
this->array.ReleaseResourcesExecution();
}
private: private:
ArrayHandleType array; ArrayHandleType array;
@ -221,33 +232,34 @@ private:
/// it creates a new handle that returns the elements of the array in reverse /// it creates a new handle that returns the elements of the array in reverse
/// order (i.e. from end to beginning). /// order (i.e. from end to beginning).
/// ///
template< typename ArrayHandleType > template <typename ArrayHandleType>
class ArrayHandleReverse : public vtkm::cont::ArrayHandle<typename ArrayHandleType::ValueType, class ArrayHandleReverse : public vtkm::cont::ArrayHandle<typename ArrayHandleType::ValueType,
StorageTagReverse<ArrayHandleType> > StorageTagReverse<ArrayHandleType>>
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS(ArrayHandleReverse, VTKM_ARRAY_HANDLE_SUBCLASS(ArrayHandleReverse, (ArrayHandleReverse<ArrayHandleType>),
(ArrayHandleReverse<ArrayHandleType>), (vtkm::cont::ArrayHandle<typename ArrayHandleType::ValueType,
(vtkm::cont::ArrayHandle<typename ArrayHandleType::ValueType, StorageTagReverse<ArrayHandleType> >)); StorageTagReverse<ArrayHandleType>>));
protected: protected:
typedef vtkm::cont::internal::Storage< ValueType, StorageTag > StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
ArrayHandleReverse(const ArrayHandleType &handle) ArrayHandleReverse(const ArrayHandleType& handle)
: Superclass(handle) {} : Superclass(handle)
{
}
}; };
/// make_ArrayHandleReverse is convenience function to generate an /// make_ArrayHandleReverse is convenience function to generate an
/// ArrayHandleReverse. /// ArrayHandleReverse.
/// ///
template< typename HandleType > template <typename HandleType>
VTKM_CONT VTKM_CONT ArrayHandleReverse<HandleType> make_ArrayHandleReverse(const HandleType& handle)
ArrayHandleReverse<HandleType> make_ArrayHandleReverse(const HandleType &handle) { {
return ArrayHandleReverse<HandleType>(handle); return ArrayHandleReverse<HandleType>(handle);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -23,11 +23,14 @@
#include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandle.h>
#include <vtkm/cont/ArrayPortal.h> #include <vtkm/cont/ArrayPortal.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace internal { namespace cont
{
namespace internal
{
template<typename P> template <typename P>
class VTKM_ALWAYS_EXPORT ArrayPortalStreaming class VTKM_ALWAYS_EXPORT ArrayPortalStreaming
{ {
public: public:
@ -35,39 +38,50 @@ public:
typedef typename PortalType::ValueType ValueType; typedef typename PortalType::ValueType ValueType;
VTKM_CONT VTKM_CONT
ArrayPortalStreaming() : InputPortal(), BlockIndex(0), BlockSize(0), CurBlockSize(0) { } ArrayPortalStreaming()
: InputPortal()
VTKM_CONT , BlockIndex(0)
ArrayPortalStreaming(const PortalType &inputPortal, vtkm::Id blockIndex, , BlockSize(0)
vtkm::Id blockSize, vtkm::Id curBlockSize) : , CurBlockSize(0)
InputPortal(inputPortal), BlockIndex(blockIndex), {
BlockSize(blockSize), CurBlockSize(curBlockSize) { }
template<typename OtherP>
VTKM_CONT
ArrayPortalStreaming(const ArrayPortalStreaming<OtherP> &src) :
InputPortal(src.GetPortal()),
BlockIndex(src.GetBlockIndex()),
BlockSize(src.GetBlockSize()),
CurBlockSize(src.GetCurBlockSize()) { }
VTKM_CONT
vtkm::Id GetNumberOfValues() const {
return this->CurBlockSize;
} }
VTKM_CONT VTKM_CONT
ValueType Get(vtkm::Id index) const { ArrayPortalStreaming(const PortalType& inputPortal, vtkm::Id blockIndex, vtkm::Id blockSize,
return this->InputPortal.Get(this->BlockIndex*this->BlockSize + index); vtkm::Id curBlockSize)
: InputPortal(inputPortal)
, BlockIndex(blockIndex)
, BlockSize(blockSize)
, CurBlockSize(curBlockSize)
{
}
template <typename OtherP>
VTKM_CONT ArrayPortalStreaming(const ArrayPortalStreaming<OtherP>& src)
: InputPortal(src.GetPortal())
, BlockIndex(src.GetBlockIndex())
, BlockSize(src.GetBlockSize())
, CurBlockSize(src.GetCurBlockSize())
{
} }
VTKM_CONT VTKM_CONT
void Set(vtkm::Id index, const ValueType &value) const { vtkm::Id GetNumberOfValues() const { return this->CurBlockSize; }
this->InputPortal.Set(this->BlockIndex*this->BlockSize + index, value);
VTKM_CONT
ValueType Get(vtkm::Id index) const
{
return this->InputPortal.Get(this->BlockIndex * this->BlockSize + index);
} }
VTKM_CONT VTKM_CONT
const PortalType &GetPortal() const { return this->InputPortal; } void Set(vtkm::Id index, const ValueType& value) const
{
this->InputPortal.Set(this->BlockIndex * this->BlockSize + index, value);
}
VTKM_CONT
const PortalType& GetPortal() const { return this->InputPortal; }
VTKM_CONT VTKM_CONT
void SetBlockSize(vtkm::Id blockSize) { this->BlockSize = blockSize; } void SetBlockSize(vtkm::Id blockSize) { this->BlockSize = blockSize; }
@ -96,79 +110,96 @@ private:
} // internal } // internal
template<typename ArrayHandleInputType> template <typename ArrayHandleInputType>
struct VTKM_ALWAYS_EXPORT StorageTagStreaming { }; struct VTKM_ALWAYS_EXPORT StorageTagStreaming
{
};
namespace internal { namespace internal
{
template<typename ArrayHandleInputType> template <typename ArrayHandleInputType>
class Storage< class Storage<typename ArrayHandleInputType::ValueType, StorageTagStreaming<ArrayHandleInputType>>
typename ArrayHandleInputType::ValueType,
StorageTagStreaming<ArrayHandleInputType> >
{ {
public: public:
typedef typename ArrayHandleInputType::ValueType ValueType; typedef typename ArrayHandleInputType::ValueType ValueType;
typedef vtkm::cont::internal::ArrayPortalStreaming<typename ArrayHandleInputType::PortalControl>
PortalType;
typedef vtkm::cont::internal::ArrayPortalStreaming< typedef vtkm::cont::internal::ArrayPortalStreaming<
typename ArrayHandleInputType::PortalControl> PortalType; typename ArrayHandleInputType::PortalConstControl>
typedef vtkm::cont::internal::ArrayPortalStreaming< PortalConstType;
typename ArrayHandleInputType::PortalConstControl> PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : Valid(false) { } Storage()
: Valid(false)
VTKM_CONT {
Storage(const ArrayHandleInputType inputArray, vtkm::Id blockSize,
vtkm::Id blockIndex, vtkm::Id curBlockSize) :
InputArray(inputArray), BlockSize(blockSize),
BlockIndex(blockIndex), CurBlockSize(curBlockSize), Valid(true) { }
VTKM_CONT
PortalType GetPortal() {
VTKM_ASSERT(this->Valid);
return PortalType(this->InputArray.GetPortalControl(),
BlockSize, BlockIndex, CurBlockSize);
} }
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const { Storage(const ArrayHandleInputType inputArray, vtkm::Id blockSize, vtkm::Id blockIndex,
VTKM_ASSERT(this->Valid); vtkm::Id curBlockSize)
return PortalConstType(this->InputArray.GetPortalConstControl(), : InputArray(inputArray)
BlockSize, BlockIndex, CurBlockSize); , BlockSize(blockSize)
, BlockIndex(blockIndex)
, CurBlockSize(curBlockSize)
, Valid(true)
{
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const { PortalType GetPortal()
{
VTKM_ASSERT(this->Valid);
return PortalType(this->InputArray.GetPortalControl(), BlockSize, BlockIndex, CurBlockSize);
}
VTKM_CONT
PortalConstType GetPortalConst() const
{
VTKM_ASSERT(this->Valid);
return PortalConstType(this->InputArray.GetPortalConstControl(), BlockSize, BlockIndex,
CurBlockSize);
}
VTKM_CONT
vtkm::Id GetNumberOfValues() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return CurBlockSize; return CurBlockSize;
} }
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id numberOfValues) const { void Allocate(vtkm::Id numberOfValues) const
{
(void)numberOfValues; (void)numberOfValues;
// Do nothing, since we only allocate a streaming array once at the beginning // Do nothing, since we only allocate a streaming array once at the beginning
} }
VTKM_CONT VTKM_CONT
void AllocateFullArray(vtkm::Id numberOfValues) { void AllocateFullArray(vtkm::Id numberOfValues)
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
this->InputArray.Allocate(numberOfValues); this->InputArray.Allocate(numberOfValues);
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numberOfValues) { void Shrink(vtkm::Id numberOfValues)
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
this->InputArray.Shrink(numberOfValues); this->InputArray.Shrink(numberOfValues);
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources()
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
this->InputArray.ReleaseResources(); this->InputArray.ReleaseResources();
} }
VTKM_CONT VTKM_CONT
const ArrayHandleInputType &GetArray() const { const ArrayHandleInputType& GetArray() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->InputArray; return this->InputArray;
} }
@ -180,37 +211,33 @@ private:
vtkm::Id CurBlockSize; vtkm::Id CurBlockSize;
bool Valid; bool Valid;
}; };
} }
} }
} }
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
template<typename ArrayHandleInputType> template <typename ArrayHandleInputType>
class ArrayHandleStreaming class ArrayHandleStreaming
: public vtkm::cont::ArrayHandle< : public vtkm::cont::ArrayHandle<typename ArrayHandleInputType::ValueType,
typename ArrayHandleInputType::ValueType, StorageTagStreaming<ArrayHandleInputType>>
StorageTagStreaming<ArrayHandleInputType> >
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(ArrayHandleStreaming, (ArrayHandleStreaming<ArrayHandleInputType>),
ArrayHandleStreaming, (vtkm::cont::ArrayHandle<typename ArrayHandleInputType::ValueType,
(ArrayHandleStreaming<ArrayHandleInputType>), StorageTagStreaming<ArrayHandleInputType>>));
(vtkm::cont::ArrayHandle<
typename ArrayHandleInputType::ValueType,
StorageTagStreaming<ArrayHandleInputType> >));
private: private:
typedef vtkm::cont::internal::Storage<ValueType,StorageTag> StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
VTKM_CONT VTKM_CONT
ArrayHandleStreaming(const ArrayHandleInputType &inputArray, ArrayHandleStreaming(const ArrayHandleInputType& inputArray, const vtkm::Id blockIndex,
const vtkm::Id blockIndex, const vtkm::Id blockSize, const vtkm::Id blockSize, const vtkm::Id curBlockSize)
const vtkm::Id curBlockSize) : Superclass(StorageType(inputArray, blockIndex, blockSize, curBlockSize))
: Superclass(StorageType(inputArray, blockIndex, blockSize, curBlockSize))
{ {
this->GetPortalConstControl().SetBlockIndex(blockIndex); this->GetPortalConstControl().SetBlockIndex(blockIndex);
this->GetPortalConstControl().SetBlockSize(blockSize); this->GetPortalConstControl().SetBlockSize(blockSize);
@ -218,14 +245,13 @@ public:
} }
VTKM_CONT VTKM_CONT
void AllocateFullArray(vtkm::Id numberOfValues) { void AllocateFullArray(vtkm::Id numberOfValues)
{
this->ReleaseResourcesExecutionInternal(); this->ReleaseResourcesExecutionInternal();
this->Internals->ControlArray.AllocateFullArray(numberOfValues); this->Internals->ControlArray.AllocateFullArray(numberOfValues);
this->Internals->ControlArrayValid = true; this->Internals->ControlArrayValid = true;
} }
}; };
} }
} }

@ -26,31 +26,39 @@
#include <vtkm/cont/ErrorBadType.h> #include <vtkm/cont/ErrorBadType.h>
#include <vtkm/cont/ErrorInternal.h> #include <vtkm/cont/ErrorInternal.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace internal { namespace cont
{
namespace internal
{
/// Tag used in place of an inverse functor. /// Tag used in place of an inverse functor.
struct NullFunctorType {}; struct NullFunctorType
{
};
} }
} }
} // namespace vtkm::cont::internal } // namespace vtkm::cont::internal
namespace vtkm { namespace vtkm
namespace exec { {
namespace internal { namespace exec
{
namespace internal
{
typedef vtkm::cont::internal::NullFunctorType NullFunctorType; typedef vtkm::cont::internal::NullFunctorType NullFunctorType;
/// \brief An array portal that transforms a value from another portal. /// \brief An array portal that transforms a value from another portal.
/// ///
template<typename ValueType_, typename PortalType_, typename FunctorType_, template <typename ValueType_, typename PortalType_, typename FunctorType_,
typename InverseFunctorType_=NullFunctorType> typename InverseFunctorType_ = NullFunctorType>
class VTKM_ALWAYS_EXPORT ArrayPortalTransform; class VTKM_ALWAYS_EXPORT ArrayPortalTransform;
template<typename ValueType_, typename PortalType_, typename FunctorType_> template <typename ValueType_, typename PortalType_, typename FunctorType_>
class VTKM_ALWAYS_EXPORT ArrayPortalTransform<ValueType_,PortalType_,FunctorType_,NullFunctorType> class VTKM_ALWAYS_EXPORT
ArrayPortalTransform<ValueType_, PortalType_, FunctorType_, NullFunctorType>
{ {
public: public:
typedef PortalType_ PortalType; typedef PortalType_ PortalType;
@ -59,64 +67,63 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalTransform(const PortalType &portal = PortalType(), ArrayPortalTransform(const PortalType& portal = PortalType(),
const FunctorType &functor = FunctorType()) const FunctorType& functor = FunctorType())
: Portal(portal), Functor(functor) : Portal(portal)
{ } , Functor(functor)
{
}
/// Copy constructor for any other ArrayPortalTransform with an iterator /// Copy constructor for any other ArrayPortalTransform with an iterator
/// type that can be copied to this iterator type. This allows us to do any /// type that can be copied to this iterator type. This allows us to do any
/// type casting that the iterators do (like the non-const to const cast). /// type casting that the iterators do (like the non-const to const cast).
/// ///
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<class OtherV, class OtherP, class OtherF> template <class OtherV, class OtherP, class OtherF>
VTKM_EXEC_CONT VTKM_EXEC_CONT ArrayPortalTransform(const ArrayPortalTransform<OtherV, OtherP, OtherF>& src)
ArrayPortalTransform(const ArrayPortalTransform<OtherV,OtherP,OtherF> &src) : Portal(src.GetPortal())
: Portal(src.GetPortal()), , Functor(src.GetFunctor())
Functor(src.GetFunctor()) {
{ }
VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const {
return this->Portal.GetNumberOfValues();
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ValueType Get(vtkm::Id index) const { vtkm::Id GetNumberOfValues() const { return this->Portal.GetNumberOfValues(); }
return this->Functor(this->Portal.Get(index));
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
void Set(vtkm::Id vtkmNotUsed(index), ValueType Get(vtkm::Id index) const { return this->Functor(this->Portal.Get(index)); }
const ValueType &vtkmNotUsed(value)) const
VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT
void Set(vtkm::Id vtkmNotUsed(index), const ValueType& vtkmNotUsed(value)) const
{ {
#if !(defined(VTKM_MSVC) && defined(VTKM_CUDA)) #if !(defined(VTKM_MSVC) && defined(VTKM_CUDA))
VTKM_ASSERT(false && "Cannot write to read-only transform array. (No inverse transform given.)"); VTKM_ASSERT(false &&
"Cannot write to read-only transform array. (No inverse transform given.)");
#endif #endif
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const PortalType &GetPortal() const { return this->Portal; } const PortalType& GetPortal() const { return this->Portal; }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const FunctorType &GetFunctor() const { return this->Functor; } const FunctorType& GetFunctor() const { return this->Functor; }
protected: protected:
PortalType Portal; PortalType Portal;
FunctorType Functor; FunctorType Functor;
}; };
template<typename ValueType_, typename PortalType_, template <typename ValueType_, typename PortalType_, typename FunctorType_,
typename FunctorType_, typename InverseFunctorType_> typename InverseFunctorType_>
class VTKM_ALWAYS_EXPORT ArrayPortalTransform : public ArrayPortalTransform<ValueType_,PortalType_,FunctorType_,NullFunctorType> class VTKM_ALWAYS_EXPORT ArrayPortalTransform
: public ArrayPortalTransform<ValueType_, PortalType_, FunctorType_, NullFunctorType>
{ {
public: public:
typedef ArrayPortalTransform<ValueType_,PortalType_,FunctorType_,NullFunctorType> Superclass; typedef ArrayPortalTransform<ValueType_, PortalType_, FunctorType_, NullFunctorType> Superclass;
typedef PortalType_ PortalType; typedef PortalType_ PortalType;
typedef ValueType_ ValueType; typedef ValueType_ ValueType;
typedef FunctorType_ FunctorType; typedef FunctorType_ FunctorType;
@ -124,51 +131,57 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalTransform(const PortalType &portal = PortalType(), ArrayPortalTransform(const PortalType& portal = PortalType(),
const FunctorType &functor = FunctorType(), const FunctorType& functor = FunctorType(),
const InverseFunctorType& inverseFunctor = InverseFunctorType()) const InverseFunctorType& inverseFunctor = InverseFunctorType())
: Superclass(portal,functor), InverseFunctor(inverseFunctor) : Superclass(portal, functor)
{ } , InverseFunctor(inverseFunctor)
{
}
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<class OtherV, class OtherP, class OtherF, class OtherInvF> template <class OtherV, class OtherP, class OtherF, class OtherInvF>
VTKM_EXEC_CONT VTKM_EXEC_CONT ArrayPortalTransform(
ArrayPortalTransform(const ArrayPortalTransform<OtherV,OtherP,OtherF,OtherInvF> &src) const ArrayPortalTransform<OtherV, OtherP, OtherF, OtherInvF>& src)
: Superclass(src), InverseFunctor(src.GetInverseFunctor()) : Superclass(src)
{ } , InverseFunctor(src.GetInverseFunctor())
{
VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT
void Set(vtkm::Id index, const ValueType& value) const {
return this->Portal.Set(index,this->InverseFunctor(value));
} }
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
const InverseFunctorType &GetInverseFunctor() const { void Set(vtkm::Id index, const ValueType& value) const
return this->InverseFunctor; } {
return this->Portal.Set(index, this->InverseFunctor(value));
}
VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT
const InverseFunctorType& GetInverseFunctor() const { return this->InverseFunctor; }
private: private:
InverseFunctorType InverseFunctor; InverseFunctorType InverseFunctor;
}; };
} }
} }
} // namespace vtkm::exec::internal } // namespace vtkm::exec::internal
namespace vtkm
{
namespace cont
{
namespace vtkm { namespace internal
namespace cont { {
namespace internal { template <typename ValueType, typename ArrayHandleType, typename FunctorType,
typename InverseFunctorType = NullFunctorType>
struct VTKM_ALWAYS_EXPORT StorageTagTransform
{
};
template<typename ValueType, typename ArrayHandleType, typename FunctorType, template <typename T, typename ArrayHandleType, typename FunctorType>
typename InverseFunctorType=NullFunctorType> class Storage<T, StorageTagTransform<T, ArrayHandleType, FunctorType, NullFunctorType>>
struct VTKM_ALWAYS_EXPORT StorageTagTransform {};
template<typename T, typename ArrayHandleType, typename FunctorType>
class Storage<T, StorageTagTransform<T, ArrayHandleType, FunctorType, NullFunctorType > >
{ {
public: public:
typedef T ValueType; typedef T ValueType;
@ -177,71 +190,78 @@ public:
// should only be able to use the const version. // should only be able to use the const version.
struct PortalType struct PortalType
{ {
typedef void *ValueType; typedef void* ValueType;
typedef void *IteratorType; typedef void* IteratorType;
}; };
typedef vtkm::exec::internal::ArrayPortalTransform< typedef vtkm::exec::internal::ArrayPortalTransform<
ValueType, typename ArrayHandleType::PortalConstControl, FunctorType> ValueType, typename ArrayHandleType::PortalConstControl, FunctorType>
PortalConstType; PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : Valid(false) { } Storage()
: Valid(false)
VTKM_CONT {
Storage(const ArrayHandleType &array,
const FunctorType &functor = FunctorType())
: Array(array), Functor(functor), Valid(true) { }
VTKM_CONT
PortalType GetPortal() {
VTKM_ASSERT(this->Valid);
return PortalType(this->Array.GetPortalControl(),
this->Functor);
} }
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const { Storage(const ArrayHandleType& array, const FunctorType& functor = FunctorType())
VTKM_ASSERT(this->Valid); : Array(array)
return PortalConstType(this->Array.GetPortalConstControl(), , Functor(functor)
this->Functor); , Valid(true)
{
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const { PortalType GetPortal()
{
VTKM_ASSERT(this->Valid);
return PortalType(this->Array.GetPortalControl(), this->Functor);
}
VTKM_CONT
PortalConstType GetPortalConst() const
{
VTKM_ASSERT(this->Valid);
return PortalConstType(this->Array.GetPortalConstControl(), this->Functor);
}
VTKM_CONT
vtkm::Id GetNumberOfValues() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->Array.GetNumberOfValues(); return this->Array.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id vtkmNotUsed(numberOfValues)) { void Allocate(vtkm::Id vtkmNotUsed(numberOfValues))
throw vtkm::cont::ErrorBadType( {
"ArrayHandleTransform is read only. It cannot be allocated."); throw vtkm::cont::ErrorBadType("ArrayHandleTransform is read only. It cannot be allocated.");
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id vtkmNotUsed(numberOfValues)) { void Shrink(vtkm::Id vtkmNotUsed(numberOfValues))
throw vtkm::cont::ErrorBadType( {
"ArrayHandleTransform is read only. It cannot shrink."); throw vtkm::cont::ErrorBadType("ArrayHandleTransform is read only. It cannot shrink.");
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources()
{
// This request is ignored since it is asking to release the resources // This request is ignored since it is asking to release the resources
// of the delegate array, which may be used elsewhere. Should the behavior // of the delegate array, which may be used elsewhere. Should the behavior
// be different? // be different?
} }
VTKM_CONT VTKM_CONT
const ArrayHandleType &GetArray() const { const ArrayHandleType& GetArray() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->Array; return this->Array;
} }
VTKM_CONT VTKM_CONT
const FunctorType &GetFunctor() const { const FunctorType& GetFunctor() const { return this->Functor; }
return this->Functor;
}
private: private:
ArrayHandleType Array; ArrayHandleType Array;
@ -249,84 +269,86 @@ private:
bool Valid; bool Valid;
}; };
template<typename T, typename ArrayHandleType, typename FunctorType, template <typename T, typename ArrayHandleType, typename FunctorType, typename InverseFunctorType>
typename InverseFunctorType> class Storage<T, StorageTagTransform<T, ArrayHandleType, FunctorType, InverseFunctorType>>
class Storage<T,
StorageTagTransform<T, ArrayHandleType, FunctorType, InverseFunctorType> >
{ {
public: public:
typedef T ValueType; typedef T ValueType;
typedef vtkm::exec::internal::ArrayPortalTransform<ValueType, typedef vtkm::exec::internal::ArrayPortalTransform<
typename ArrayHandleType::PortalControl, FunctorType, InverseFunctorType> ValueType, typename ArrayHandleType::PortalControl, FunctorType, InverseFunctorType>
PortalType; PortalType;
typedef vtkm::exec::internal::ArrayPortalTransform<ValueType, typedef vtkm::exec::internal::ArrayPortalTransform<
typename ArrayHandleType::PortalConstControl,FunctorType,InverseFunctorType> ValueType, typename ArrayHandleType::PortalConstControl, FunctorType, InverseFunctorType>
PortalConstType; PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : Valid(false) { } Storage()
: Valid(false)
VTKM_CONT {
Storage(const ArrayHandleType &array,
const FunctorType &functor,
const InverseFunctorType &inverseFunctor)
: Array(array), Functor(functor), InverseFunctor(inverseFunctor), Valid(true) { }
VTKM_CONT
PortalType GetPortal() {
VTKM_ASSERT(this->Valid);
return PortalType(this->Array.GetPortalControl(),
this->Functor,
this->InverseFunctor);
} }
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const { Storage(const ArrayHandleType& array, const FunctorType& functor,
const InverseFunctorType& inverseFunctor)
: Array(array)
, Functor(functor)
, InverseFunctor(inverseFunctor)
, Valid(true)
{
}
VTKM_CONT
PortalType GetPortal()
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return PortalConstType(this->Array.GetPortalConstControl(), return PortalType(this->Array.GetPortalControl(), this->Functor, this->InverseFunctor);
this->Functor, }
VTKM_CONT
PortalConstType GetPortalConst() const
{
VTKM_ASSERT(this->Valid);
return PortalConstType(this->Array.GetPortalConstControl(), this->Functor,
this->InverseFunctor); this->InverseFunctor);
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const { vtkm::Id GetNumberOfValues() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->Array.GetNumberOfValues(); return this->Array.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id numberOfValues) { void Allocate(vtkm::Id numberOfValues)
{
this->Array.Allocate(numberOfValues); this->Array.Allocate(numberOfValues);
this->Valid = true; this->Valid = true;
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numberOfValues) { void Shrink(vtkm::Id numberOfValues) { this->Array.Shrink(numberOfValues); }
this->Array.Shrink(numberOfValues);
}
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources()
{
this->Array.ReleaseResources(); this->Array.ReleaseResources();
this->Valid = false; this->Valid = false;
} }
VTKM_CONT VTKM_CONT
const ArrayHandleType &GetArray() const { const ArrayHandleType& GetArray() const
{
VTKM_ASSERT(this->Valid); VTKM_ASSERT(this->Valid);
return this->Array; return this->Array;
} }
VTKM_CONT VTKM_CONT
const FunctorType &GetFunctor() const { const FunctorType& GetFunctor() const { return this->Functor; }
return this->Functor;
}
VTKM_CONT VTKM_CONT
const InverseFunctorType &GetInverseFunctor() const { const InverseFunctorType& GetInverseFunctor() const { return this->InverseFunctor; }
return this->InverseFunctor;
}
private: private:
ArrayHandleType Array; ArrayHandleType Array;
@ -335,14 +357,10 @@ private:
bool Valid; bool Valid;
}; };
template<typename T, template <typename T, typename ArrayHandleType, typename FunctorType, typename Device>
typename ArrayHandleType, class ArrayTransfer<T, StorageTagTransform<T, ArrayHandleType, FunctorType>, Device>
typename FunctorType,
typename Device>
class ArrayTransfer<
T, StorageTagTransform<T,ArrayHandleType,FunctorType>, Device>
{ {
typedef StorageTagTransform<T,ArrayHandleType,FunctorType> StorageTag; typedef StorageTagTransform<T, ArrayHandleType, FunctorType> StorageTag;
typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType;
public: public:
@ -354,72 +372,67 @@ public:
//meant to be an invalid writeable execution portal //meant to be an invalid writeable execution portal
typedef typename StorageType::PortalType PortalExecution; typedef typename StorageType::PortalType PortalExecution;
typedef vtkm::exec::internal::ArrayPortalTransform< typedef vtkm::exec::internal::ArrayPortalTransform<
ValueType, ValueType, typename ArrayHandleType::template ExecutionTypes<Device>::PortalConst, FunctorType>
typename ArrayHandleType::template ExecutionTypes<Device>::PortalConst, PortalConstExecution;
FunctorType> PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) ArrayTransfer(StorageType* storage)
: Array(storage->GetArray()), Functor(storage->GetFunctor()) { } : Array(storage->GetArray())
, Functor(storage->GetFunctor())
VTKM_CONT {
vtkm::Id GetNumberOfValues() const {
return this->Array.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) { vtkm::Id GetNumberOfValues() const { return this->Array.GetNumberOfValues(); }
VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{
return PortalConstExecution(this->Array.PrepareForInput(Device()), this->Functor); return PortalConstExecution(this->Array.PrepareForInput(Device()), this->Functor);
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForInPlace(bool &vtkmNotUsed(updateData)) { PortalExecution PrepareForInPlace(bool& vtkmNotUsed(updateData))
throw vtkm::cont::ErrorBadType( {
"ArrayHandleTransform read only. " throw vtkm::cont::ErrorBadType("ArrayHandleTransform read only. "
"Cannot be used for in-place operations."); "Cannot be used for in-place operations.");
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForOutput(vtkm::Id vtkmNotUsed(numberOfValues)) { PortalExecution PrepareForOutput(vtkm::Id vtkmNotUsed(numberOfValues))
throw vtkm::cont::ErrorBadType( {
"ArrayHandleTransform read only. Cannot be used as output."); throw vtkm::cont::ErrorBadType("ArrayHandleTransform read only. Cannot be used as output.");
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *vtkmNotUsed(storage)) const { void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{
throw vtkm::cont::ErrorInternal( throw vtkm::cont::ErrorInternal(
"ArrayHandleTransform read only. " "ArrayHandleTransform read only. "
"There should be no occurance of the ArrayHandle trying to pull " "There should be no occurance of the ArrayHandle trying to pull "
"data from the execution environment."); "data from the execution environment.");
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id vtkmNotUsed(numberOfValues)) { void Shrink(vtkm::Id vtkmNotUsed(numberOfValues))
throw vtkm::cont::ErrorBadType( {
"ArrayHandleTransform read only. Cannot shrink."); throw vtkm::cont::ErrorBadType("ArrayHandleTransform read only. Cannot shrink.");
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources() { this->Array.ReleaseResourcesExecution(); }
this->Array.ReleaseResourcesExecution();
}
private: private:
ArrayHandleType Array; ArrayHandleType Array;
FunctorType Functor; FunctorType Functor;
}; };
template<typename T, template <typename T, typename ArrayHandleType, typename FunctorType, typename InverseFunctorType,
typename ArrayHandleType, typename Device>
typename FunctorType, class ArrayTransfer<T, StorageTagTransform<T, ArrayHandleType, FunctorType, InverseFunctorType>,
typename InverseFunctorType, Device>
typename Device>
class ArrayTransfer<
T, StorageTagTransform<T,ArrayHandleType,FunctorType,InverseFunctorType>,
Device>
{ {
typedef StorageTagTransform<T,ArrayHandleType, typedef StorageTagTransform<T, ArrayHandleType, FunctorType, InverseFunctorType> StorageTag;
FunctorType,InverseFunctorType> StorageTag;
typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType;
public: public:
@ -429,56 +442,58 @@ public:
typedef typename StorageType::PortalConstType PortalConstControl; typedef typename StorageType::PortalConstType PortalConstControl;
typedef vtkm::exec::internal::ArrayPortalTransform< typedef vtkm::exec::internal::ArrayPortalTransform<
ValueType, ValueType, typename ArrayHandleType::template ExecutionTypes<Device>::Portal, FunctorType,
typename ArrayHandleType::template ExecutionTypes<Device>::Portal, InverseFunctorType>
FunctorType, InverseFunctorType> PortalExecution; PortalExecution;
typedef vtkm::exec::internal::ArrayPortalTransform< typedef vtkm::exec::internal::ArrayPortalTransform<
ValueType, ValueType, typename ArrayHandleType::template ExecutionTypes<Device>::PortalConst, FunctorType,
typename ArrayHandleType::template ExecutionTypes<Device>::PortalConst, InverseFunctorType>
FunctorType, InverseFunctorType> PortalConstExecution; PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) ArrayTransfer(StorageType* storage)
: Array(storage->GetArray()), : Array(storage->GetArray())
Functor(storage->GetFunctor()), , Functor(storage->GetFunctor())
InverseFunctor(storage->GetInverseFunctor()) { } , InverseFunctor(storage->GetInverseFunctor())
{
VTKM_CONT
vtkm::Id GetNumberOfValues() const {
return this->Array.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) { vtkm::Id GetNumberOfValues() const { return this->Array.GetNumberOfValues(); }
return PortalConstExecution(this->Array.PrepareForInput(Device()),this->Functor,this->InverseFunctor);
VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{
return PortalConstExecution(this->Array.PrepareForInput(Device()), this->Functor,
this->InverseFunctor);
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForInPlace(bool &vtkmNotUsed(updateData)) { PortalExecution PrepareForInPlace(bool& vtkmNotUsed(updateData))
return PortalExecution(this->Array.PrepareForInPlace(Device()),this->Functor,this->InverseFunctor); {
return PortalExecution(this->Array.PrepareForInPlace(Device()), this->Functor,
this->InverseFunctor);
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForOutput(vtkm::Id numberOfValues) { PortalExecution PrepareForOutput(vtkm::Id numberOfValues)
return PortalExecution(this->Array.PrepareForOutput(numberOfValues, {
Device()),this->Functor,this->InverseFunctor); return PortalExecution(this->Array.PrepareForOutput(numberOfValues, Device()), this->Functor,
this->InverseFunctor);
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *vtkmNotUsed(storage)) const { void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{
// Implementation of this method should be unnecessary. The internal // Implementation of this method should be unnecessary. The internal
// array handle should automatically retrieve the output data as necessary. // array handle should automatically retrieve the output data as necessary.
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numberOfValues) { void Shrink(vtkm::Id numberOfValues) { this->Array.Shrink(numberOfValues); }
this->Array.Shrink(numberOfValues);
}
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources() { this->Array.ReleaseResourcesExecution(); }
this->Array.ReleaseResourcesExecution();
}
private: private:
ArrayHandleType Array; ArrayHandleType Array;
@ -499,18 +514,14 @@ private:
/// the functor operator should work in both the control and execution /// the functor operator should work in both the control and execution
/// environments. /// environments.
/// ///
template <typename T, template <typename T, typename ArrayHandleType, typename FunctorType,
typename ArrayHandleType, typename InverseFunctorType = internal::NullFunctorType>
typename FunctorType,
typename InverseFunctorType=internal::NullFunctorType>
class ArrayHandleTransform; class ArrayHandleTransform;
template <typename T, template <typename T, typename ArrayHandleType, typename FunctorType>
typename ArrayHandleType, class ArrayHandleTransform<T, ArrayHandleType, FunctorType, internal::NullFunctorType>
typename FunctorType> : public vtkm::cont::ArrayHandle<T,
class ArrayHandleTransform<T,ArrayHandleType,FunctorType,internal::NullFunctorType> internal::StorageTagTransform<T, ArrayHandleType, FunctorType>>
: public vtkm::cont::ArrayHandle<
T, internal::StorageTagTransform<T, ArrayHandleType, FunctorType> >
{ {
// If the following line gives a compile error, then the ArrayHandleType // If the following line gives a compile error, then the ArrayHandleType
// template argument is not a valid ArrayHandle type. // template argument is not a valid ArrayHandle type.
@ -518,19 +529,18 @@ class ArrayHandleTransform<T,ArrayHandleType,FunctorType,internal::NullFunctorTy
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleTransform, ArrayHandleTransform, (ArrayHandleTransform<T, ArrayHandleType, FunctorType>),
(ArrayHandleTransform<T,ArrayHandleType,FunctorType>), (vtkm::cont::ArrayHandle<T, internal::StorageTagTransform<T, ArrayHandleType, FunctorType>>));
(vtkm::cont::ArrayHandle<
T, internal::StorageTagTransform<T, ArrayHandleType, FunctorType> >));
private: private:
typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType;
public: public:
VTKM_CONT VTKM_CONT
ArrayHandleTransform(const ArrayHandleType &handle, ArrayHandleTransform(const ArrayHandleType& handle, const FunctorType& functor = FunctorType())
const FunctorType &functor = FunctorType()) : Superclass(StorageType(handle, functor))
: Superclass(StorageType(handle, functor)) { } {
}
}; };
/// make_ArrayHandleTransform is convenience function to generate an /// make_ArrayHandleTransform is convenience function to generate an
@ -538,53 +548,46 @@ public:
/// to apply to each element of the Handle. /// to apply to each element of the Handle.
template <typename T, typename HandleType, typename FunctorType> template <typename T, typename HandleType, typename FunctorType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandleTransform<T, HandleType, FunctorType> make_ArrayHandleTransform(
vtkm::cont::ArrayHandleTransform<T, HandleType, FunctorType> HandleType handle, FunctorType functor)
make_ArrayHandleTransform(HandleType handle, FunctorType functor)
{ {
return ArrayHandleTransform<T,HandleType,FunctorType>(handle,functor); return ArrayHandleTransform<T, HandleType, FunctorType>(handle, functor);
} }
// ArrayHandleTransform with inverse functors enabled (no need to subclass from // ArrayHandleTransform with inverse functors enabled (no need to subclass from
// ArrayHandleTransform without inverse functors: nothing to inherit). // ArrayHandleTransform without inverse functors: nothing to inherit).
template <typename T, template <typename T, typename ArrayHandleType, typename FunctorType, typename InverseFunctorType>
typename ArrayHandleType,
typename FunctorType,
typename InverseFunctorType>
class ArrayHandleTransform class ArrayHandleTransform
: public vtkm::cont::ArrayHandle< : public vtkm::cont::ArrayHandle<
T, T, internal::StorageTagTransform<T, ArrayHandleType, FunctorType, InverseFunctorType>>
internal::StorageTagTransform<T, ArrayHandleType, FunctorType,
InverseFunctorType> >
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType); VTKM_IS_ARRAY_HANDLE(ArrayHandleType);
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleTransform, ArrayHandleTransform,
(ArrayHandleTransform<T,ArrayHandleType,FunctorType,InverseFunctorType>), (ArrayHandleTransform<T, ArrayHandleType, FunctorType, InverseFunctorType>),
(vtkm::cont::ArrayHandle< (vtkm::cont::ArrayHandle<
T, internal::StorageTagTransform<T, ArrayHandleType, FunctorType, T, internal::StorageTagTransform<T, ArrayHandleType, FunctorType, InverseFunctorType>>));
InverseFunctorType> >));
private: private:
typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType;
public: public:
ArrayHandleTransform(const ArrayHandleType &handle, ArrayHandleTransform(const ArrayHandleType& handle, const FunctorType& functor = FunctorType(),
const FunctorType &functor = FunctorType(), const InverseFunctorType& inverseFunctor = InverseFunctorType())
const InverseFunctorType &inverseFunctor = InverseFunctorType()) : Superclass(StorageType(handle, functor, inverseFunctor))
: Superclass(StorageType(handle, functor, inverseFunctor)) { } {
}
}; };
template <typename T, typename HandleType, typename FunctorType, typename InverseFunctorType> template <typename T, typename HandleType, typename FunctorType, typename InverseFunctorType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandleTransform<T, HandleType, FunctorType, InverseFunctorType>
vtkm::cont::ArrayHandleTransform<T, HandleType, FunctorType, InverseFunctorType>
make_ArrayHandleTransform(HandleType handle, FunctorType functor, InverseFunctorType inverseFunctor) make_ArrayHandleTransform(HandleType handle, FunctorType functor, InverseFunctorType inverseFunctor)
{ {
return ArrayHandleTransform<T,HandleType,FunctorType,InverseFunctorType>(handle,functor,inverseFunctor); return ArrayHandleTransform<T, HandleType, FunctorType, InverseFunctorType>(handle, functor,
inverseFunctor);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -24,8 +24,10 @@
#include <vtkm/cont/StorageImplicit.h> #include <vtkm/cont/StorageImplicit.h>
#include <vtkm/internal/ArrayPortalUniformPointCoordinates.h> #include <vtkm/internal/ArrayPortalUniformPointCoordinates.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
/// ArrayHandleUniformPointCoordinates is a specialization of ArrayHandle. It /// ArrayHandleUniformPointCoordinates is a specialization of ArrayHandle. It
/// contains the information necessary to compute the point coordinates in a /// contains the information necessary to compute the point coordinates in a
@ -33,34 +35,30 @@ namespace cont {
/// computes these coordinates in its array portal. /// computes these coordinates in its array portal.
/// ///
class ArrayHandleUniformPointCoordinates class ArrayHandleUniformPointCoordinates
: public vtkm::cont::ArrayHandle< : public vtkm::cont::ArrayHandle<
vtkm::Vec<vtkm::FloatDefault,3>, vtkm::Vec<vtkm::FloatDefault, 3>,
vtkm::cont::StorageTagImplicit< vtkm::cont::StorageTagImplicit<vtkm::internal::ArrayPortalUniformPointCoordinates>>
vtkm::internal::ArrayPortalUniformPointCoordinates> >
{ {
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS_NT( VTKM_ARRAY_HANDLE_SUBCLASS_NT(
ArrayHandleUniformPointCoordinates, ArrayHandleUniformPointCoordinates,
(vtkm::cont::ArrayHandle< (vtkm::cont::ArrayHandle<
vtkm::Vec<vtkm::FloatDefault,3>, vtkm::Vec<vtkm::FloatDefault, 3>,
vtkm::cont::StorageTagImplicit< vtkm::cont::StorageTagImplicit<vtkm::internal::ArrayPortalUniformPointCoordinates>>));
vtkm::internal::ArrayPortalUniformPointCoordinates> >));
private: private:
typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
VTKM_CONT VTKM_CONT
ArrayHandleUniformPointCoordinates( ArrayHandleUniformPointCoordinates(vtkm::Id3 dimensions,
vtkm::Id3 dimensions, ValueType origin = ValueType(0.0f, 0.0f, 0.0f),
ValueType origin = ValueType(0.0f, 0.0f, 0.0f), ValueType spacing = ValueType(1.0f, 1.0f, 1.0f))
ValueType spacing = ValueType(1.0f, 1.0f, 1.0f)) : Superclass(StorageType(
: Superclass( vtkm::internal::ArrayPortalUniformPointCoordinates(dimensions, origin, spacing)))
StorageType(vtkm::internal::ArrayPortalUniformPointCoordinates( {
dimensions, origin, spacing))) }
{ }
}; };
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -23,15 +23,16 @@
#include <vtkm/Pair.h> #include <vtkm/Pair.h>
#include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandle.h>
namespace vtkm { namespace vtkm
namespace exec { {
namespace internal { namespace exec
{
namespace internal
{
/// \brief An array portal that zips two portals together into a single value /// \brief An array portal that zips two portals together into a single value
/// for the execution environment /// for the execution environment
template<typename ValueType_, template <typename ValueType_, typename PortalTypeFirst_, typename PortalTypeSecond_>
typename PortalTypeFirst_,
typename PortalTypeSecond_>
class ArrayPortalZip class ArrayPortalZip
{ {
public: public:
@ -43,88 +44,94 @@ public:
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalZip() ArrayPortalZip()
: PortalFirst(), PortalSecond() : PortalFirst()
{ } //needs to be host and device so that cuda can create lvalue of these , PortalSecond()
{
} //needs to be host and device so that cuda can create lvalue of these
VTKM_CONT VTKM_CONT
ArrayPortalZip(const PortalTypeFirst &portalfirst, ArrayPortalZip(const PortalTypeFirst& portalfirst, const PortalTypeSecond& portalsecond)
const PortalTypeSecond &portalsecond) : PortalFirst(portalfirst)
: PortalFirst(portalfirst), PortalSecond(portalsecond) , PortalSecond(portalsecond)
{ } {
}
/// Copy constructor for any other ArrayPortalZip with an iterator /// Copy constructor for any other ArrayPortalZip with an iterator
/// type that can be copied to this iterator type. This allows us to do any /// type that can be copied to this iterator type. This allows us to do any
/// type casting that the iterators do (like the non-const to const cast). /// type casting that the iterators do (like the non-const to const cast).
/// ///
template<class OtherV, class OtherF, class OtherS> template <class OtherV, class OtherF, class OtherS>
VTKM_CONT VTKM_CONT ArrayPortalZip(const ArrayPortalZip<OtherV, OtherF, OtherS>& src)
ArrayPortalZip(const ArrayPortalZip<OtherV,OtherF,OtherS> &src) : PortalFirst(src.GetFirstPortal())
: PortalFirst(src.GetFirstPortal()), , PortalSecond(src.GetSecondPortal())
PortalSecond(src.GetSecondPortal()) {
{ } }
VTKM_EXEC_CONT VTKM_EXEC_CONT
vtkm::Id GetNumberOfValues() const { return this->PortalFirst.GetNumberOfValues(); } vtkm::Id GetNumberOfValues() const { return this->PortalFirst.GetNumberOfValues(); }
VTKM_EXEC VTKM_EXEC
ValueType Get(vtkm::Id index) const { ValueType Get(vtkm::Id index) const
return vtkm::make_Pair(this->PortalFirst.Get(index), {
this->PortalSecond.Get(index)); return vtkm::make_Pair(this->PortalFirst.Get(index), this->PortalSecond.Get(index));
} }
VTKM_EXEC VTKM_EXEC
void Set(vtkm::Id index, const ValueType &value) const { void Set(vtkm::Id index, const ValueType& value) const
{
this->PortalFirst.Set(index, value.first); this->PortalFirst.Set(index, value.first);
this->PortalSecond.Set(index, value.second); this->PortalSecond.Set(index, value.second);
} }
VTKM_EXEC_CONT VTKM_EXEC_CONT
const PortalTypeFirst &GetFirstPortal() const { return this->PortalFirst; } const PortalTypeFirst& GetFirstPortal() const { return this->PortalFirst; }
VTKM_EXEC_CONT VTKM_EXEC_CONT
const PortalTypeSecond &GetSecondPortal() const { return this->PortalSecond; } const PortalTypeSecond& GetSecondPortal() const { return this->PortalSecond; }
private: private:
PortalTypeFirst PortalFirst; PortalTypeFirst PortalFirst;
PortalTypeSecond PortalSecond; PortalTypeSecond PortalSecond;
}; };
} }
} }
} // namespace vtkm::exec::internal } // namespace vtkm::exec::internal
namespace vtkm
{
namespace cont
{
namespace vtkm { namespace internal
namespace cont { {
namespace internal { template <typename FirstHandleType, typename SecondHandleType>
struct VTKM_ALWAYS_EXPORT StorageTagZip
template<typename FirstHandleType, typename SecondHandleType> {
struct VTKM_ALWAYS_EXPORT StorageTagZip { }; };
/// This helper struct defines the value type for a zip container containing /// This helper struct defines the value type for a zip container containing
/// the given two array handles. /// the given two array handles.
/// ///
template<typename FirstHandleType, typename SecondHandleType> template <typename FirstHandleType, typename SecondHandleType>
struct ArrayHandleZipTraits { struct ArrayHandleZipTraits
{
/// The ValueType (a pair containing the value types of the two arrays). /// The ValueType (a pair containing the value types of the two arrays).
/// ///
typedef vtkm::Pair<typename FirstHandleType::ValueType, typedef vtkm::Pair<typename FirstHandleType::ValueType, typename SecondHandleType::ValueType>
typename SecondHandleType::ValueType> ValueType; ValueType;
/// The appropriately templated tag. /// The appropriately templated tag.
/// ///
typedef StorageTagZip<FirstHandleType,SecondHandleType> Tag; typedef StorageTagZip<FirstHandleType, SecondHandleType> Tag;
/// The superclass for ArrayHandleZip. /// The superclass for ArrayHandleZip.
/// ///
typedef vtkm::cont::ArrayHandle<ValueType,Tag> Superclass; typedef vtkm::cont::ArrayHandle<ValueType, Tag> Superclass;
}; };
template <typename T, typename FirstHandleType, typename SecondHandleType>
template<typename T, typename FirstHandleType, typename SecondHandleType> class Storage<T, StorageTagZip<FirstHandleType, SecondHandleType>>
class Storage<T, StorageTagZip<FirstHandleType, SecondHandleType > >
{ {
VTKM_IS_ARRAY_HANDLE(FirstHandleType); VTKM_IS_ARRAY_HANDLE(FirstHandleType);
VTKM_IS_ARRAY_HANDLE(SecondHandleType); VTKM_IS_ARRAY_HANDLE(SecondHandleType);
@ -132,84 +139,84 @@ class Storage<T, StorageTagZip<FirstHandleType, SecondHandleType > >
public: public:
typedef T ValueType; typedef T ValueType;
typedef vtkm::exec::internal::ArrayPortalZip< ValueType, typedef vtkm::exec::internal::ArrayPortalZip<ValueType, typename FirstHandleType::PortalControl,
typename FirstHandleType::PortalControl, typename SecondHandleType::PortalControl>
typename SecondHandleType::PortalControl> PortalType; PortalType;
typedef vtkm::exec::internal::ArrayPortalZip< ValueType, typedef vtkm::exec::internal::ArrayPortalZip<ValueType,
typename FirstHandleType::PortalConstControl, typename FirstHandleType::PortalConstControl,
typename SecondHandleType::PortalConstControl> typename SecondHandleType::PortalConstControl>
PortalConstType; PortalConstType;
VTKM_CONT VTKM_CONT
Storage() : FirstArray(), SecondArray() { } Storage()
: FirstArray()
VTKM_CONT , SecondArray()
Storage(const FirstHandleType &farray, const SecondHandleType &sarray)
: FirstArray(farray), SecondArray(sarray)
{ {
} }
VTKM_CONT VTKM_CONT
PortalType GetPortal() { Storage(const FirstHandleType& farray, const SecondHandleType& sarray)
return PortalType(this->FirstArray.GetPortalControl(), : FirstArray(farray)
this->SecondArray.GetPortalControl()); , SecondArray(sarray)
{
} }
VTKM_CONT VTKM_CONT
PortalConstType GetPortalConst() const { PortalType GetPortal()
{
return PortalType(this->FirstArray.GetPortalControl(), this->SecondArray.GetPortalControl());
}
VTKM_CONT
PortalConstType GetPortalConst() const
{
return PortalConstType(this->FirstArray.GetPortalConstControl(), return PortalConstType(this->FirstArray.GetPortalConstControl(),
this->SecondArray.GetPortalConstControl()); this->SecondArray.GetPortalConstControl());
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const { vtkm::Id GetNumberOfValues() const
VTKM_ASSERT(this->FirstArray.GetNumberOfValues() {
== this->SecondArray.GetNumberOfValues()); VTKM_ASSERT(this->FirstArray.GetNumberOfValues() == this->SecondArray.GetNumberOfValues());
return this->FirstArray.GetNumberOfValues(); return this->FirstArray.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
void Allocate(vtkm::Id numberOfValues) { void Allocate(vtkm::Id numberOfValues)
{
this->FirstArray.Allocate(numberOfValues); this->FirstArray.Allocate(numberOfValues);
this->SecondArray.Allocate(numberOfValues); this->SecondArray.Allocate(numberOfValues);
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numberOfValues) { void Shrink(vtkm::Id numberOfValues)
{
this->FirstArray.Shrink(numberOfValues); this->FirstArray.Shrink(numberOfValues);
this->SecondArray.Shrink(numberOfValues); this->SecondArray.Shrink(numberOfValues);
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources()
{
// This request is ignored since it is asking to release the resources // This request is ignored since it is asking to release the resources
// of the two zipped array, which may be used elsewhere. // of the two zipped array, which may be used elsewhere.
} }
VTKM_CONT VTKM_CONT
const FirstHandleType &GetFirstArray() const { const FirstHandleType& GetFirstArray() const { return this->FirstArray; }
return this->FirstArray;
}
VTKM_CONT VTKM_CONT
const SecondHandleType &GetSecondArray() const { const SecondHandleType& GetSecondArray() const { return this->SecondArray; }
return this->SecondArray;
}
private: private:
FirstHandleType FirstArray; FirstHandleType FirstArray;
SecondHandleType SecondArray; SecondHandleType SecondArray;
}; };
template<typename T, template <typename T, typename FirstHandleType, typename SecondHandleType, typename Device>
typename FirstHandleType, class ArrayTransfer<T, StorageTagZip<FirstHandleType, SecondHandleType>, Device>
typename SecondHandleType,
typename Device>
class ArrayTransfer<
T, StorageTagZip<FirstHandleType,SecondHandleType>, Device>
{ {
typedef StorageTagZip<FirstHandleType,SecondHandleType> StorageTag; typedef StorageTagZip<FirstHandleType, SecondHandleType> StorageTag;
typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<T, StorageTag> StorageType;
public: public:
@ -219,40 +226,39 @@ public:
typedef typename StorageType::PortalConstType PortalConstControl; typedef typename StorageType::PortalConstType PortalConstControl;
typedef vtkm::exec::internal::ArrayPortalZip< typedef vtkm::exec::internal::ArrayPortalZip<
ValueType, ValueType, typename FirstHandleType::template ExecutionTypes<Device>::Portal,
typename FirstHandleType::template ExecutionTypes<Device>::Portal, typename SecondHandleType::template ExecutionTypes<Device>::Portal>
typename SecondHandleType::template ExecutionTypes<Device>::Portal PortalExecution;
> PortalExecution;
typedef vtkm::exec::internal::ArrayPortalZip< typedef vtkm::exec::internal::ArrayPortalZip<
ValueType, ValueType, typename FirstHandleType::template ExecutionTypes<Device>::PortalConst,
typename FirstHandleType::template ExecutionTypes<Device>::PortalConst, typename SecondHandleType::template ExecutionTypes<Device>::PortalConst>
typename SecondHandleType::template ExecutionTypes<Device>::PortalConst PortalConstExecution;
> PortalConstExecution;
VTKM_CONT VTKM_CONT
ArrayTransfer(StorageType *storage) ArrayTransfer(StorageType* storage)
: FirstArray(storage->GetFirstArray()), : FirstArray(storage->GetFirstArray())
SecondArray(storage->GetSecondArray()) , SecondArray(storage->GetSecondArray())
{ } {
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const
{ {
VTKM_ASSERT( this->FirstArray.GetNumberOfValues() VTKM_ASSERT(this->FirstArray.GetNumberOfValues() == this->SecondArray.GetNumberOfValues());
== this->SecondArray.GetNumberOfValues() );
return this->FirstArray.GetNumberOfValues(); return this->FirstArray.GetNumberOfValues();
} }
VTKM_CONT VTKM_CONT
PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData)) { PortalConstExecution PrepareForInput(bool vtkmNotUsed(updateData))
{
return PortalConstExecution(this->FirstArray.PrepareForInput(Device()), return PortalConstExecution(this->FirstArray.PrepareForInput(Device()),
this->SecondArray.PrepareForInput(Device())); this->SecondArray.PrepareForInput(Device()));
} }
VTKM_CONT VTKM_CONT
PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData)) { PortalExecution PrepareForInPlace(bool vtkmNotUsed(updateData))
{
return PortalExecution(this->FirstArray.PrepareForInPlace(Device()), return PortalExecution(this->FirstArray.PrepareForInPlace(Device()),
this->SecondArray.PrepareForInPlace(Device())); this->SecondArray.PrepareForInPlace(Device()));
} }
@ -260,30 +266,32 @@ public:
VTKM_CONT VTKM_CONT
PortalExecution PrepareForOutput(vtkm::Id numberOfValues) PortalExecution PrepareForOutput(vtkm::Id numberOfValues)
{ {
return PortalExecution( this->FirstArray.PrepareForOutput(numberOfValues, Device()), return PortalExecution(this->FirstArray.PrepareForOutput(numberOfValues, Device()),
this->SecondArray.PrepareForOutput(numberOfValues, Device()) ); this->SecondArray.PrepareForOutput(numberOfValues, Device()));
} }
VTKM_CONT VTKM_CONT
void RetrieveOutputData(StorageType *vtkmNotUsed(storage)) const { void RetrieveOutputData(StorageType* vtkmNotUsed(storage)) const
{
// Implementation of this method should be unnecessary. The internal // Implementation of this method should be unnecessary. The internal
// first and second array handles should automatically retrieve the // first and second array handles should automatically retrieve the
// output data as necessary. // output data as necessary.
} }
VTKM_CONT VTKM_CONT
void Shrink(vtkm::Id numberOfValues) { void Shrink(vtkm::Id numberOfValues)
{
this->FirstArray.Shrink(numberOfValues); this->FirstArray.Shrink(numberOfValues);
this->SecondArray.Shrink(numberOfValues); this->SecondArray.Shrink(numberOfValues);
} }
VTKM_CONT VTKM_CONT
void ReleaseResources() { void ReleaseResources()
{
this->FirstArray.ReleaseResourcesExecution(); this->FirstArray.ReleaseResourcesExecution();
this->SecondArray.ReleaseResourcesExecution(); this->SecondArray.ReleaseResourcesExecution();
} }
private: private:
FirstHandleType FirstArray; FirstHandleType FirstArray;
SecondHandleType SecondArray; SecondHandleType SecondArray;
@ -294,10 +302,9 @@ private:
/// array handle and makes a new handle that access the corresponding entries /// array handle and makes a new handle that access the corresponding entries
/// in these arrays as a pair. /// in these arrays as a pair.
/// ///
template<typename FirstHandleType, template <typename FirstHandleType, typename SecondHandleType>
typename SecondHandleType>
class ArrayHandleZip class ArrayHandleZip
: public internal::ArrayHandleZipTraits<FirstHandleType,SecondHandleType>::Superclass : public internal::ArrayHandleZipTraits<FirstHandleType, SecondHandleType>::Superclass
{ {
// If the following line gives a compile error, then the FirstHandleType // If the following line gives a compile error, then the FirstHandleType
// template argument is not a valid ArrayHandle type. // template argument is not a valid ArrayHandle type.
@ -309,33 +316,29 @@ class ArrayHandleZip
public: public:
VTKM_ARRAY_HANDLE_SUBCLASS( VTKM_ARRAY_HANDLE_SUBCLASS(
ArrayHandleZip, ArrayHandleZip, (ArrayHandleZip<FirstHandleType, SecondHandleType>),
(ArrayHandleZip<FirstHandleType,SecondHandleType>), (typename internal::ArrayHandleZipTraits<FirstHandleType, SecondHandleType>::Superclass));
(typename internal::ArrayHandleZipTraits<
FirstHandleType,SecondHandleType>::Superclass));
private: private:
typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType; typedef vtkm::cont::internal::Storage<ValueType, StorageTag> StorageType;
public: public:
VTKM_CONT VTKM_CONT
ArrayHandleZip(const FirstHandleType &firstArray, ArrayHandleZip(const FirstHandleType& firstArray, const SecondHandleType& secondArray)
const SecondHandleType &secondArray) : Superclass(StorageType(firstArray, secondArray))
: Superclass( StorageType( firstArray, secondArray ) ) { } {
}
}; };
/// A convenience function for creating an ArrayHandleZip. It takes the two /// A convenience function for creating an ArrayHandleZip. It takes the two
/// arrays to be zipped together. /// arrays to be zipped together.
/// ///
template<typename FirstHandleType, typename SecondHandleType> template <typename FirstHandleType, typename SecondHandleType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandleZip<FirstHandleType, SecondHandleType> make_ArrayHandleZip(
vtkm::cont::ArrayHandleZip<FirstHandleType,SecondHandleType> const FirstHandleType& first, const SecondHandleType& second)
make_ArrayHandleZip(const FirstHandleType &first,
const SecondHandleType &second)
{ {
return ArrayHandleZip<FirstHandleType,SecondHandleType>(first, second); return ArrayHandleZip<FirstHandleType, SecondHandleType>(first, second);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -22,8 +22,10 @@
#include <vtkm/Types.h> #include <vtkm/Types.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
#ifdef VTKM_DOXYGEN_ONLY #ifdef VTKM_DOXYGEN_ONLY
@ -53,7 +55,7 @@ namespace cont {
/// Although portals are defined in the execution environment, they are also /// Although portals are defined in the execution environment, they are also
/// used in the control environment for accessing data on the host. /// used in the control environment for accessing data on the host.
/// ///
template<typename T> template <typename T>
class ArrayPortal class ArrayPortal
{ {
public: public:
@ -77,11 +79,10 @@ public:
/// this case the behavior is undefined. /// this case the behavior is undefined.
/// ///
VTKM_CONT VTKM_CONT
void Set(vtkm::Id index, const ValueType &value) const; void Set(vtkm::Id index, const ValueType& value) const;
}; };
#endif // VTKM_DOXYGEN_ONLY #endif // VTKM_DOXYGEN_ONLY
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -23,8 +23,10 @@
#include <vtkm/cont/ArrayPortal.h> #include <vtkm/cont/ArrayPortal.h>
#include <vtkm/cont/internal/IteratorFromArrayPortal.h> #include <vtkm/cont/internal/IteratorFromArrayPortal.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
/// \brief Convert an \c ArrayPortal to STL iterators. /// \brief Convert an \c ArrayPortal to STL iterators.
/// ///
@ -39,7 +41,7 @@ namespace cont {
/// ArrayPortalFromIterator has a specialization to return the original /// ArrayPortalFromIterator has a specialization to return the original
/// iterators. /// iterators.
/// ///
template<typename PortalType> template <typename PortalType>
class ArrayPortalToIterators class ArrayPortalToIterators
{ {
public: public:
@ -48,28 +50,26 @@ public:
/// ///
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
ArrayPortalToIterators(const PortalType &portal) : Portal(portal) { } ArrayPortalToIterators(const PortalType& portal)
: Portal(portal)
{
}
/// The type of the iterator. /// The type of the iterator.
/// ///
typedef vtkm::cont::internal::IteratorFromArrayPortal<PortalType> typedef vtkm::cont::internal::IteratorFromArrayPortal<PortalType> IteratorType;
IteratorType;
/// Returns an iterator pointing to the beginning of the ArrayPortal. /// Returns an iterator pointing to the beginning of the ArrayPortal.
/// ///
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
IteratorType GetBegin() const { IteratorType GetBegin() const { return vtkm::cont::internal::make_IteratorBegin(this->Portal); }
return vtkm::cont::internal::make_IteratorBegin(this->Portal);
}
/// Returns an iterator pointing to one past the end of the ArrayPortal. /// Returns an iterator pointing to one past the end of the ArrayPortal.
/// ///
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
VTKM_EXEC_CONT VTKM_EXEC_CONT
IteratorType GetEnd() const { IteratorType GetEnd() const { return vtkm::cont::internal::make_IteratorEnd(this->Portal); }
return vtkm::cont::internal::make_IteratorEnd(this->Portal);
}
private: private:
PortalType Portal; PortalType Portal;
@ -78,10 +78,9 @@ private:
/// Convienience function for converting an ArrayPortal to a begin iterator. /// Convienience function for converting an ArrayPortal to a begin iterator.
/// ///
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<typename PortalType> template <typename PortalType>
VTKM_EXEC_CONT VTKM_EXEC_CONT typename vtkm::cont::ArrayPortalToIterators<PortalType>::IteratorType
typename vtkm::cont::ArrayPortalToIterators<PortalType>::IteratorType ArrayPortalToIteratorBegin(const PortalType& portal)
ArrayPortalToIteratorBegin(const PortalType &portal)
{ {
vtkm::cont::ArrayPortalToIterators<PortalType> iterators(portal); vtkm::cont::ArrayPortalToIterators<PortalType> iterators(portal);
return iterators.GetBegin(); return iterators.GetBegin();
@ -90,15 +89,13 @@ ArrayPortalToIteratorBegin(const PortalType &portal)
/// Convienience function for converting an ArrayPortal to an end iterator. /// Convienience function for converting an ArrayPortal to an end iterator.
/// ///
VTKM_SUPPRESS_EXEC_WARNINGS VTKM_SUPPRESS_EXEC_WARNINGS
template<typename PortalType> template <typename PortalType>
VTKM_EXEC_CONT VTKM_EXEC_CONT typename vtkm::cont::ArrayPortalToIterators<PortalType>::IteratorType
typename vtkm::cont::ArrayPortalToIterators<PortalType>::IteratorType ArrayPortalToIteratorEnd(const PortalType& portal)
ArrayPortalToIteratorEnd(const PortalType &portal)
{ {
vtkm::cont::ArrayPortalToIterators<PortalType> iterators(portal); vtkm::cont::ArrayPortalToIterators<PortalType> iterators(portal);
return iterators.GetEnd(); return iterators.GetEnd();
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -20,26 +20,27 @@
#include <vtkm/cont/ArrayRangeCompute.hxx> #include <vtkm/cont/ArrayRangeCompute.hxx>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
#define VTKM_ARRAY_RANGE_COMPUTE_IMPL_T(T, Storage) \ #define VTKM_ARRAY_RANGE_COMPUTE_IMPL_T(T, Storage) \
VTKM_CONT \ VTKM_CONT \
vtkm::cont::ArrayHandle<vtkm::Range> \ vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute( \
ArrayRangeCompute(const vtkm::cont::ArrayHandle<T, Storage> &input, \ const vtkm::cont::ArrayHandle<T, Storage>& input, vtkm::cont::RuntimeDeviceTracker tracker) \
vtkm::cont::RuntimeDeviceTracker tracker) \ { \
{ \ return detail::ArrayRangeComputeImpl(input, tracker); \
return detail::ArrayRangeComputeImpl(input,tracker); \ } \
} \
struct SwallowSemicolon struct SwallowSemicolon
#define VTKM_ARRAY_RANGE_COMPUTE_IMPL_VEC(T, N, Storage) \ #define VTKM_ARRAY_RANGE_COMPUTE_IMPL_VEC(T, N, Storage) \
VTKM_CONT \ VTKM_CONT \
vtkm::cont::ArrayHandle<vtkm::Range> \ vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute( \
ArrayRangeCompute(const vtkm::cont::ArrayHandle<vtkm::Vec<T,N>, Storage> &input, \ const vtkm::cont::ArrayHandle<vtkm::Vec<T, N>, Storage>& input, \
vtkm::cont::RuntimeDeviceTracker tracker) \ vtkm::cont::RuntimeDeviceTracker tracker) \
{ \ { \
return detail::ArrayRangeComputeImpl(input,tracker); \ return detail::ArrayRangeComputeImpl(input, tracker); \
} \ } \
struct SwallowSemicolon struct SwallowSemicolon
VTKM_ARRAY_RANGE_COMPUTE_IMPL_T(char, vtkm::cont::StorageTagBasic); VTKM_ARRAY_RANGE_COMPUTE_IMPL_T(char, vtkm::cont::StorageTagBasic);
@ -73,30 +74,24 @@ VTKM_ARRAY_RANGE_COMPUTE_IMPL_VEC(vtkm::Float64, 4, vtkm::cont::StorageTagBasic)
#undef VTKM_ARRAY_RANGE_COMPUTE_IMPL_T #undef VTKM_ARRAY_RANGE_COMPUTE_IMPL_T
#undef VTKM_ARRAY_RANGE_COMPUTE_IMPL_VEC #undef VTKM_ARRAY_RANGE_COMPUTE_IMPL_VEC
// Special implementation for regular point coordinates, which are easy // Special implementation for regular point coordinates, which are easy
// to determine. // to determine.
VTKM_CONT VTKM_CONT
vtkm::cont::ArrayHandle<vtkm::Range> vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute(
ArrayRangeCompute(const vtkm::cont::ArrayHandle< const vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::FloatDefault, 3>,
vtkm::Vec<vtkm::FloatDefault,3>, vtkm::cont::ArrayHandleUniformPointCoordinates::StorageTag>& array,
vtkm::cont::ArrayHandleUniformPointCoordinates::StorageTag> vtkm::cont::RuntimeDeviceTracker)
&array,
vtkm::cont::RuntimeDeviceTracker)
{ {
vtkm::internal::ArrayPortalUniformPointCoordinates portal = vtkm::internal::ArrayPortalUniformPointCoordinates portal = array.GetPortalConstControl();
array.GetPortalConstControl();
// In this portal we know that the min value is the first entry and the // In this portal we know that the min value is the first entry and the
// max value is the last entry. // max value is the last entry.
vtkm::Vec<vtkm::FloatDefault,3> minimum = portal.Get(0); vtkm::Vec<vtkm::FloatDefault, 3> minimum = portal.Get(0);
vtkm::Vec<vtkm::FloatDefault,3> maximum = vtkm::Vec<vtkm::FloatDefault, 3> maximum = portal.Get(portal.GetNumberOfValues() - 1);
portal.Get(portal.GetNumberOfValues()-1);
vtkm::cont::ArrayHandle<vtkm::Range> rangeArray; vtkm::cont::ArrayHandle<vtkm::Range> rangeArray;
rangeArray.Allocate(3); rangeArray.Allocate(3);
vtkm::cont::ArrayHandle<vtkm::Range>::PortalControl outPortal = vtkm::cont::ArrayHandle<vtkm::Range>::PortalControl outPortal = rangeArray.GetPortalControl();
rangeArray.GetPortalControl();
outPortal.Set(0, vtkm::Range(minimum[0], maximum[0])); outPortal.Set(0, vtkm::Range(minimum[0], maximum[0]));
outPortal.Set(1, vtkm::Range(minimum[1], maximum[1])); outPortal.Set(1, vtkm::Range(minimum[1], maximum[1]));
outPortal.Set(2, vtkm::Range(minimum[2], maximum[2])); outPortal.Set(2, vtkm::Range(minimum[2], maximum[2]));
@ -106,36 +101,27 @@ ArrayRangeCompute(const vtkm::cont::ArrayHandle<
// Special implementation for composite vectors. // Special implementation for composite vectors.
VTKM_CONT VTKM_CONT
vtkm::cont::ArrayHandle<vtkm::Range> vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute(
ArrayRangeCompute(const vtkm::cont::ArrayHandle< const vtkm::cont::ArrayHandle<
vtkm::Vec<vtkm::Float32,3>, vtkm::Vec<vtkm::Float32, 3>,
typename vtkm::cont::ArrayHandleCompositeVector< typename vtkm::cont::ArrayHandleCompositeVector<vtkm::Vec<vtkm::Float32, 3>(
vtkm::Vec<vtkm::Float32,3>( vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::ArrayHandle<vtkm::Float32>,
vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::ArrayHandle<vtkm::Float32>)>::StorageTag>& input,
vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::RuntimeDeviceTracker tracker)
vtkm::cont::ArrayHandle<vtkm::Float32>)
>::StorageTag
> &input,
vtkm::cont::RuntimeDeviceTracker tracker)
{ {
return detail::ArrayRangeComputeImpl(input,tracker); return detail::ArrayRangeComputeImpl(input, tracker);
} }
VTKM_CONT VTKM_CONT
vtkm::cont::ArrayHandle<vtkm::Range> vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute(
ArrayRangeCompute(const vtkm::cont::ArrayHandle< const vtkm::cont::ArrayHandle<
vtkm::Vec<vtkm::Float64,3>, vtkm::Vec<vtkm::Float64, 3>,
typename vtkm::cont::ArrayHandleCompositeVector< typename vtkm::cont::ArrayHandleCompositeVector<vtkm::Vec<vtkm::Float64, 3>(
vtkm::Vec<vtkm::Float64,3>( vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::ArrayHandle<vtkm::Float64>,
vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::ArrayHandle<vtkm::Float64>)>::StorageTag>& input,
vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::RuntimeDeviceTracker tracker)
vtkm::cont::ArrayHandle<vtkm::Float64>)
>::StorageTag
> &input,
vtkm::cont::RuntimeDeviceTracker tracker)
{ {
return detail::ArrayRangeComputeImpl(input,tracker); return detail::ArrayRangeComputeImpl(input, tracker);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -28,8 +28,10 @@
#include <vtkm/cont/ArrayHandleUniformPointCoordinates.h> #include <vtkm/cont/ArrayHandleUniformPointCoordinates.h>
#include <vtkm/cont/RuntimeDeviceTracker.h> #include <vtkm/cont/RuntimeDeviceTracker.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
/// \brief Compute the range of the data in an array handle. /// \brief Compute the range of the data in an array handle.
/// ///
@ -44,28 +46,24 @@ namespace cont {
/// one value in the returned array for every component of the input's value /// one value in the returned array for every component of the input's value
/// type. /// type.
/// ///
template<typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute(
vtkm::cont::ArrayHandle<vtkm::Range> const ArrayHandleType& input,
ArrayRangeCompute(const ArrayHandleType &input, vtkm::cont::RuntimeDeviceTracker tracker = vtkm::cont::GetGlobalRuntimeDeviceTracker());
vtkm::cont::RuntimeDeviceTracker tracker =
vtkm::cont::GetGlobalRuntimeDeviceTracker());
// Precompiled versions of ArrayRangeCompute // Precompiled versions of ArrayRangeCompute
#define VTKM_ARRAY_RANGE_COMPUTE_EXPORT_T(T, Storage) \ #define VTKM_ARRAY_RANGE_COMPUTE_EXPORT_T(T, Storage) \
VTKM_CONT_EXPORT \ VTKM_CONT_EXPORT \
VTKM_CONT \ VTKM_CONT \
vtkm::cont::ArrayHandle<vtkm::Range> \ vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute( \
ArrayRangeCompute(const vtkm::cont::ArrayHandle<T, Storage> &input, \ const vtkm::cont::ArrayHandle<T, Storage>& input, \
vtkm::cont::RuntimeDeviceTracker tracker = \ vtkm::cont::RuntimeDeviceTracker tracker = vtkm::cont::GetGlobalRuntimeDeviceTracker())
vtkm::cont::GetGlobalRuntimeDeviceTracker()) #define VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(T, N, Storage) \
#define VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(T, N, Storage) \ VTKM_CONT_EXPORT \
VTKM_CONT_EXPORT \ VTKM_CONT \
VTKM_CONT \ vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute( \
vtkm::cont::ArrayHandle<vtkm::Range> \ const vtkm::cont::ArrayHandle<vtkm::Vec<T, N>, Storage>& input, \
ArrayRangeCompute(const vtkm::cont::ArrayHandle<vtkm::Vec<T,N>, Storage> &input, \ vtkm::cont::RuntimeDeviceTracker tracker = vtkm::cont::GetGlobalRuntimeDeviceTracker())
vtkm::cont::RuntimeDeviceTracker tracker = \
vtkm::cont::GetGlobalRuntimeDeviceTracker())
VTKM_ARRAY_RANGE_COMPUTE_EXPORT_T(char, vtkm::cont::StorageTagBasic); VTKM_ARRAY_RANGE_COMPUTE_EXPORT_T(char, vtkm::cont::StorageTagBasic);
VTKM_ARRAY_RANGE_COMPUTE_EXPORT_T(vtkm::Int8, vtkm::cont::StorageTagBasic); VTKM_ARRAY_RANGE_COMPUTE_EXPORT_T(vtkm::Int8, vtkm::cont::StorageTagBasic);
@ -95,9 +93,8 @@ VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(vtkm::UInt8, 4, vtkm::cont::StorageTagBasic)
VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(vtkm::Float32, 4, vtkm::cont::StorageTagBasic); VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(vtkm::Float32, 4, vtkm::cont::StorageTagBasic);
VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(vtkm::Float64, 4, vtkm::cont::StorageTagBasic); VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(vtkm::Float64, 4, vtkm::cont::StorageTagBasic);
VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC( VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(vtkm::FloatDefault, 3,
vtkm::FloatDefault, 3, vtkm::cont::ArrayHandleUniformPointCoordinates::StorageTag);
vtkm::cont::ArrayHandleUniformPointCoordinates::StorageTag);
#undef VTKM_ARRAY_RANGE_COMPUTE_EXPORT_T #undef VTKM_ARRAY_RANGE_COMPUTE_EXPORT_T
#undef VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC #undef VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC
@ -105,48 +102,30 @@ VTKM_ARRAY_RANGE_COMPUTE_EXPORT_VEC(
// Implementation of composite vectors // Implementation of composite vectors
VTKM_CONT_EXPORT VTKM_CONT_EXPORT
VTKM_CONT VTKM_CONT
vtkm::cont::ArrayHandle<vtkm::Range> vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute(
ArrayRangeCompute(const vtkm::cont::ArrayHandle< const vtkm::cont::ArrayHandle<
vtkm::Vec<vtkm::Float32,3>, vtkm::Vec<vtkm::Float32, 3>,
typename vtkm::cont::ArrayHandleCompositeVector< typename vtkm::cont::ArrayHandleCompositeVector<vtkm::Vec<vtkm::Float32, 3>(
vtkm::Vec<vtkm::Float32,3>( vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::ArrayHandle<vtkm::Float32>,
vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::ArrayHandle<vtkm::Float32>)>::StorageTag>& input,
vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::RuntimeDeviceTracker tracker = vtkm::cont::GetGlobalRuntimeDeviceTracker());
vtkm::cont::ArrayHandle<vtkm::Float32>)
>::StorageTag
> &input,
vtkm::cont::RuntimeDeviceTracker tracker =
vtkm::cont::GetGlobalRuntimeDeviceTracker());
VTKM_CONT_EXPORT VTKM_CONT_EXPORT
VTKM_CONT VTKM_CONT
vtkm::cont::ArrayHandle<vtkm::Range> vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute(
ArrayRangeCompute(const vtkm::cont::ArrayHandle< const vtkm::cont::ArrayHandle<
vtkm::Vec<vtkm::Float64,3>, vtkm::Vec<vtkm::Float64, 3>,
typename vtkm::cont::ArrayHandleCompositeVector< typename vtkm::cont::ArrayHandleCompositeVector<vtkm::Vec<vtkm::Float64, 3>(
vtkm::Vec<vtkm::Float64,3>( vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::ArrayHandle<vtkm::Float64>,
vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::ArrayHandle<vtkm::Float64>)>::StorageTag>& input,
vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::RuntimeDeviceTracker tracker = vtkm::cont::GetGlobalRuntimeDeviceTracker());
vtkm::cont::ArrayHandle<vtkm::Float64>)
>::StorageTag
> &input,
vtkm::cont::RuntimeDeviceTracker tracker =
vtkm::cont::GetGlobalRuntimeDeviceTracker());
// Implementation of cartesian products // Implementation of cartesian products
template<typename T, template <typename T, typename ArrayType1, typename ArrayType2, typename ArrayType3>
typename ArrayType1, VTKM_CONT inline vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute(
typename ArrayType2, const vtkm::cont::ArrayHandle<
typename ArrayType3> T, vtkm::cont::internal::StorageTagCartesianProduct<ArrayType1, ArrayType2, ArrayType3>>& input,
VTKM_CONT vtkm::cont::RuntimeDeviceTracker tracker = vtkm::cont::GetGlobalRuntimeDeviceTracker())
inline
vtkm::cont::ArrayHandle<vtkm::Range>
ArrayRangeCompute(const vtkm::cont::ArrayHandle<T,
vtkm::cont::internal::StorageTagCartesianProduct<
ArrayType1,ArrayType2,ArrayType3
> > &input,
vtkm::cont::RuntimeDeviceTracker tracker =
vtkm::cont::GetGlobalRuntimeDeviceTracker())
{ {
vtkm::cont::ArrayHandle<vtkm::Range> result; vtkm::cont::ArrayHandle<vtkm::Range> result;
result.Allocate(3); result.Allocate(3);
@ -171,7 +150,6 @@ ArrayRangeCompute(const vtkm::cont::ArrayHandle<T,
return result; return result;
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -28,12 +28,15 @@
#include <vtkm/cont/DeviceAdapterAlgorithm.h> #include <vtkm/cont/DeviceAdapterAlgorithm.h>
#include <vtkm/cont/TryExecute.h> #include <vtkm/cont/TryExecute.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace detail { namespace detail
{
template<typename ArrayHandleType> template <typename ArrayHandleType>
struct ArrayRangeComputeFunctor struct ArrayRangeComputeFunctor
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType); VTKM_IS_ARRAY_HANDLE(ArrayHandleType);
@ -42,13 +45,13 @@ struct ArrayRangeComputeFunctor
vtkm::cont::ArrayHandle<vtkm::Range> RangeArray; vtkm::cont::ArrayHandle<vtkm::Range> RangeArray;
VTKM_CONT VTKM_CONT
ArrayRangeComputeFunctor(const ArrayHandleType &input) ArrayRangeComputeFunctor(const ArrayHandleType& input)
: InputArray(input) : InputArray(input)
{ } {
}
template<typename Device> template <typename Device>
VTKM_CONT VTKM_CONT bool operator()(Device)
bool operator()(Device)
{ {
VTKM_IS_DEVICE_ADAPTER_TAG(Device); VTKM_IS_DEVICE_ADAPTER_TAG(Device);
@ -69,31 +72,25 @@ struct ArrayRangeComputeFunctor
return true; return true;
} }
vtkm::Vec<ValueType,2> initial( vtkm::Vec<ValueType, 2> initial(this->InputArray.GetPortalConstControl().Get(0));
this->InputArray.GetPortalConstControl().Get(0));
vtkm::Vec<ValueType, 2> result = vtkm::Vec<ValueType, 2> result =
Algorithm::Reduce(this->InputArray, Algorithm::Reduce(this->InputArray, initial, vtkm::MinAndMax<ValueType>());
initial,
vtkm::MinAndMax<ValueType>());
for (vtkm::IdComponent i = 0; i < NumberOfComponents; ++i) for (vtkm::IdComponent i = 0; i < NumberOfComponents; ++i)
{ {
this->RangeArray.GetPortalControl().Set( this->RangeArray.GetPortalControl().Set(
i, vtkm::Range(VecTraits::GetComponent(result[0], i), i,
VecTraits::GetComponent(result[1], i))); vtkm::Range(VecTraits::GetComponent(result[0], i), VecTraits::GetComponent(result[1], i)));
} }
return true; return true;
} }
}; };
template <typename ArrayHandleType>
template<typename ArrayHandleType> inline vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeComputeImpl(
inline const ArrayHandleType& input, vtkm::cont::RuntimeDeviceTracker tracker)
vtkm::cont::ArrayHandle<vtkm::Range>
ArrayRangeComputeImpl(const ArrayHandleType &input,
vtkm::cont::RuntimeDeviceTracker tracker)
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType); VTKM_IS_ARRAY_HANDLE(ArrayHandleType);
@ -101,8 +98,7 @@ ArrayRangeComputeImpl(const ArrayHandleType &input,
if (!vtkm::cont::TryExecute(functor, tracker)) if (!vtkm::cont::TryExecute(functor, tracker))
{ {
throw vtkm::cont::ErrorExecution( throw vtkm::cont::ErrorExecution("Failed to run ArrayRangeComputation on any device.");
"Failed to run ArrayRangeComputation on any device.");
} }
return functor.RangeArray; return functor.RangeArray;
@ -110,18 +106,14 @@ ArrayRangeComputeImpl(const ArrayHandleType &input,
} // namespace detail } // namespace detail
template<typename ArrayHandleType> template <typename ArrayHandleType>
inline inline vtkm::cont::ArrayHandle<vtkm::Range> ArrayRangeCompute(
vtkm::cont::ArrayHandle<vtkm::Range> const ArrayHandleType& input, vtkm::cont::RuntimeDeviceTracker tracker)
ArrayRangeCompute(const ArrayHandleType &input,
vtkm::cont::RuntimeDeviceTracker tracker)
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType); VTKM_IS_ARRAY_HANDLE(ArrayHandleType);
return detail::ArrayRangeComputeImpl(input, tracker); return detail::ArrayRangeComputeImpl(input, tracker);
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -20,14 +20,13 @@
#include <vtkm/cont/CellSet.h> #include <vtkm/cont/CellSet.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
CellSet::~CellSet() CellSet::~CellSet()
{ {
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -29,25 +29,28 @@
#include <vtkm/cont/DynamicArrayHandle.h> #include <vtkm/cont/DynamicArrayHandle.h>
#include <vtkm/cont/Field.h> #include <vtkm/cont/Field.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
class VTKM_CONT_EXPORT CellSet class VTKM_CONT_EXPORT CellSet
{ {
public: public:
VTKM_CONT VTKM_CONT
CellSet(const std::string &name) CellSet(const std::string& name)
: Name(name) : Name(name)
{ {
} }
VTKM_CONT VTKM_CONT
CellSet(const vtkm::cont::CellSet &src) CellSet(const vtkm::cont::CellSet& src)
: Name(src.Name) : Name(src.Name)
{ } {
}
VTKM_CONT VTKM_CONT
CellSet &operator=(const vtkm::cont::CellSet &src) CellSet& operator=(const vtkm::cont::CellSet& src)
{ {
this->Name = src.Name; this->Name = src.Name;
return *this; return *this;
@ -55,10 +58,7 @@ public:
virtual ~CellSet(); virtual ~CellSet();
std::string GetName() const std::string GetName() const { return this->Name; }
{
return this->Name;
}
virtual vtkm::Id GetNumberOfCells() const = 0; virtual vtkm::Id GetNumberOfCells() const = 0;
@ -71,27 +71,26 @@ public:
virtual void PrintSummary(std::ostream&) const = 0; virtual void PrintSummary(std::ostream&) const = 0;
protected: protected:
std::string Name; std::string Name;
}; };
namespace internal { namespace internal
{
/// Checks to see if the given object is a cell set. It contains a /// Checks to see if the given object is a cell set. It contains a
/// typedef named \c type that is either std::true_type or /// typedef named \c type that is either std::true_type or
/// std::false_type. Both of these have a typedef named value with the /// std::false_type. Both of these have a typedef named value with the
/// respective boolean value. /// respective boolean value.
/// ///
template<typename T> template <typename T>
struct CellSetCheck struct CellSetCheck
{ {
using type = typename std::is_base_of<vtkm::cont::CellSet, T>; using type = typename std::is_base_of<vtkm::cont::CellSet, T>;
}; };
#define VTKM_IS_CELL_SET(T) \ #define VTKM_IS_CELL_SET(T) VTKM_STATIC_ASSERT(::vtkm::cont::internal::CellSetCheck<T>::type::value)
VTKM_STATIC_ASSERT(::vtkm::cont::internal::CellSetCheck<T>::type::value)
} // namespace internal } // namespace internal
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -35,21 +35,22 @@
#include <map> #include <map>
#include <utility> #include <utility>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace detail { namespace detail
{
template<typename CellSetType, typename FromTopology, typename ToTopology> template <typename CellSetType, typename FromTopology, typename ToTopology>
struct CellSetExplicitConnectivityChooser struct CellSetExplicitConnectivityChooser
{ {
typedef vtkm::cont::internal::ConnectivityExplicitInternals<> typedef vtkm::cont::internal::ConnectivityExplicitInternals<> ConnectivityType;
ConnectivityType;
}; };
} // namespace detail } // namespace detail
#ifndef VTKM_DEFAULT_SHAPE_STORAGE_TAG #ifndef VTKM_DEFAULT_SHAPE_STORAGE_TAG
#define VTKM_DEFAULT_SHAPE_STORAGE_TAG VTKM_DEFAULT_STORAGE_TAG #define VTKM_DEFAULT_SHAPE_STORAGE_TAG VTKM_DEFAULT_STORAGE_TAG
#endif #endif
@ -66,39 +67,34 @@ struct CellSetExplicitConnectivityChooser
#define VTKM_DEFAULT_OFFSETS_STORAGE_TAG VTKM_DEFAULT_STORAGE_TAG #define VTKM_DEFAULT_OFFSETS_STORAGE_TAG VTKM_DEFAULT_STORAGE_TAG
#endif #endif
template<typename ShapeStorageTag = VTKM_DEFAULT_SHAPE_STORAGE_TAG, template <typename ShapeStorageTag = VTKM_DEFAULT_SHAPE_STORAGE_TAG,
typename NumIndicesStorageTag = VTKM_DEFAULT_NUM_INDICES_STORAGE_TAG, typename NumIndicesStorageTag = VTKM_DEFAULT_NUM_INDICES_STORAGE_TAG,
typename ConnectivityStorageTag = VTKM_DEFAULT_CONNECTIVITY_STORAGE_TAG, typename ConnectivityStorageTag = VTKM_DEFAULT_CONNECTIVITY_STORAGE_TAG,
typename OffsetsStorageTag = VTKM_DEFAULT_OFFSETS_STORAGE_TAG > typename OffsetsStorageTag = VTKM_DEFAULT_OFFSETS_STORAGE_TAG>
class VTKM_ALWAYS_EXPORT CellSetExplicit : public CellSet class VTKM_ALWAYS_EXPORT CellSetExplicit : public CellSet
{ {
typedef CellSetExplicit< ShapeStorageTag, typedef CellSetExplicit<ShapeStorageTag, NumIndicesStorageTag, ConnectivityStorageTag,
NumIndicesStorageTag, OffsetsStorageTag>
ConnectivityStorageTag, Thisclass;
OffsetsStorageTag > Thisclass;
template<typename FromTopology, typename ToTopology> template <typename FromTopology, typename ToTopology>
struct ConnectivityChooser struct ConnectivityChooser
{ {
typedef typename detail::CellSetExplicitConnectivityChooser< typedef typename detail::CellSetExplicitConnectivityChooser<
Thisclass, Thisclass, FromTopology, ToTopology>::ConnectivityType ConnectivityType;
FromTopology,
ToTopology>::ConnectivityType ConnectivityType;
typedef typename ConnectivityType::ShapeArrayType ShapeArrayType; typedef typename ConnectivityType::ShapeArrayType ShapeArrayType;
typedef typename ConnectivityType::NumIndicesArrayType NumIndicesArrayType; typedef typename ConnectivityType::NumIndicesArrayType NumIndicesArrayType;
typedef typename ConnectivityType::ConnectivityArrayType ConnectivityArrayType; typedef typename ConnectivityType::ConnectivityArrayType ConnectivityArrayType;
typedef typename ConnectivityType::IndexOffsetArrayType IndexOffsetArrayType; typedef typename ConnectivityType::IndexOffsetArrayType IndexOffsetArrayType;
}; };
public: public:
typedef vtkm::Id SchedulingRangeType; typedef vtkm::Id SchedulingRangeType;
//point to cell is used when iterating cells and asking for point properties //point to cell is used when iterating cells and asking for point properties
typedef ConnectivityChooser< vtkm::TopologyElementTagPoint, typedef ConnectivityChooser<vtkm::TopologyElementTagPoint, vtkm::TopologyElementTagCell>
vtkm::TopologyElementTagCell > PointToCellConnectivityType; PointToCellConnectivityType;
typedef typename PointToCellConnectivityType::ShapeArrayType ShapeArrayType; typedef typename PointToCellConnectivityType::ShapeArrayType ShapeArrayType;
typedef typename PointToCellConnectivityType::NumIndicesArrayType NumIndicesArrayType; typedef typename PointToCellConnectivityType::NumIndicesArrayType NumIndicesArrayType;
@ -106,26 +102,27 @@ public:
typedef typename PointToCellConnectivityType::IndexOffsetArrayType IndexOffsetArrayType; typedef typename PointToCellConnectivityType::IndexOffsetArrayType IndexOffsetArrayType;
VTKM_CONT VTKM_CONT
CellSetExplicit(const std::string &name = std::string()) CellSetExplicit(const std::string& name = std::string())
: CellSet(name), : CellSet(name)
ConnectivityAdded(-1), , ConnectivityAdded(-1)
NumberOfCellsAdded(-1), , NumberOfCellsAdded(-1)
NumberOfPoints(0) , NumberOfPoints(0)
{ {
} }
VTKM_CONT VTKM_CONT
CellSetExplicit(const Thisclass &src) CellSetExplicit(const Thisclass& src)
: CellSet(src), : CellSet(src)
PointToCell(src.PointToCell), , PointToCell(src.PointToCell)
CellToPoint(src.CellToPoint), , CellToPoint(src.CellToPoint)
ConnectivityAdded(src.ConnectivityAdded), , ConnectivityAdded(src.ConnectivityAdded)
NumberOfCellsAdded(src.NumberOfCellsAdded), , NumberOfCellsAdded(src.NumberOfCellsAdded)
NumberOfPoints(src.NumberOfPoints) , NumberOfPoints(src.NumberOfPoints)
{ } {
}
VTKM_CONT VTKM_CONT
Thisclass &operator=(const Thisclass &src) Thisclass& operator=(const Thisclass& src)
{ {
this->CellSet::operator=(src); this->CellSet::operator=(src);
this->PointToCell = src.PointToCell; this->PointToCell = src.PointToCell;
@ -136,17 +133,14 @@ public:
return *this; return *this;
} }
virtual ~CellSetExplicit() { } virtual ~CellSetExplicit() {}
vtkm::Id GetNumberOfCells() const VTKM_OVERRIDE vtkm::Id GetNumberOfCells() const VTKM_OVERRIDE
{ {
return this->PointToCell.GetNumberOfElements(); return this->PointToCell.GetNumberOfElements();
} }
vtkm::Id GetNumberOfPoints() const VTKM_OVERRIDE vtkm::Id GetNumberOfPoints() const VTKM_OVERRIDE { return this->NumberOfPoints; }
{
return this->NumberOfPoints;
}
vtkm::Id GetNumberOfFaces() const VTKM_OVERRIDE { return -1; } vtkm::Id GetNumberOfFaces() const VTKM_OVERRIDE { return -1; }
@ -177,16 +171,13 @@ public:
} }
template <vtkm::IdComponent ItemTupleLength> template <vtkm::IdComponent ItemTupleLength>
VTKM_CONT VTKM_CONT void GetIndices(vtkm::Id index, vtkm::Vec<vtkm::Id, ItemTupleLength>& ids) const
void GetIndices(vtkm::Id index,
vtkm::Vec<vtkm::Id,ItemTupleLength> &ids) const
{ {
this->PointToCell.BuildIndexOffsets(VTKM_DEFAULT_DEVICE_ADAPTER_TAG()); this->PointToCell.BuildIndexOffsets(VTKM_DEFAULT_DEVICE_ADAPTER_TAG());
vtkm::IdComponent numIndices = this->GetNumberOfPointsInCell(index); vtkm::IdComponent numIndices = this->GetNumberOfPointsInCell(index);
vtkm::Id start = vtkm::Id start = this->PointToCell.IndexOffsets.GetPortalConstControl().Get(index);
this->PointToCell.IndexOffsets.GetPortalConstControl().Get(index); for (vtkm::IdComponent i = 0; i < numIndices && i < ItemTupleLength; i++)
for (vtkm::IdComponent i=0; i<numIndices && i<ItemTupleLength; i++) ids[i] = this->PointToCell.Connectivity.GetPortalConstControl().Get(start + i);
ids[i] = this->PointToCell.Connectivity.GetPortalConstControl().Get(start+i);
} }
/// First method to add cells -- one at a time. /// First method to add cells -- one at a time.
@ -202,43 +193,36 @@ public:
} }
template <typename IdVecType> template <typename IdVecType>
VTKM_CONT VTKM_CONT void AddCell(vtkm::UInt8 cellType, vtkm::IdComponent numVertices, const IdVecType& ids)
void AddCell(vtkm::UInt8 cellType,
vtkm::IdComponent numVertices,
const IdVecType &ids)
{ {
using Traits = vtkm::VecTraits<IdVecType>; using Traits = vtkm::VecTraits<IdVecType>;
VTKM_STATIC_ASSERT_MSG( VTKM_STATIC_ASSERT_MSG((std::is_same<typename Traits::ComponentType, vtkm::Id>::value),
(std::is_same<typename Traits::ComponentType,vtkm::Id>::value), "CellSetSingleType::AddCell requires vtkm::Id for indices.");
"CellSetSingleType::AddCell requires vtkm::Id for indices.");
if (Traits::GetNumberOfComponents(ids) < numVertices) if (Traits::GetNumberOfComponents(ids) < numVertices)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Not enough indices given to CellSetSingleType::AddCell.");
"Not enough indices given to CellSetSingleType::AddCell.");
} }
if (this->NumberOfCellsAdded >= this->PointToCell.Shapes.GetNumberOfValues()) if (this->NumberOfCellsAdded >= this->PointToCell.Shapes.GetNumberOfValues())
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Added more cells then expected.");
"Added more cells then expected.");
} }
if (this->ConnectivityAdded+numVertices > if (this->ConnectivityAdded + numVertices > this->PointToCell.Connectivity.GetNumberOfValues())
this->PointToCell.Connectivity.GetNumberOfValues())
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"Connectivity increased passed estimated maximum connectivity."); "Connectivity increased passed estimated maximum connectivity.");
} }
this->PointToCell.Shapes.GetPortalControl().Set(this->NumberOfCellsAdded, cellType); this->PointToCell.Shapes.GetPortalControl().Set(this->NumberOfCellsAdded, cellType);
this->PointToCell.NumIndices.GetPortalControl().Set(this->NumberOfCellsAdded, numVertices); this->PointToCell.NumIndices.GetPortalControl().Set(this->NumberOfCellsAdded, numVertices);
for (vtkm::IdComponent iVec=0; iVec < numVertices; ++iVec) for (vtkm::IdComponent iVec = 0; iVec < numVertices; ++iVec)
{ {
this->PointToCell.Connectivity.GetPortalControl().Set( this->PointToCell.Connectivity.GetPortalControl().Set(this->ConnectivityAdded + iVec,
this->ConnectivityAdded+iVec, Traits::GetComponent(ids,iVec)); Traits::GetComponent(ids, iVec));
} }
this->PointToCell.IndexOffsets.GetPortalControl().Set( this->PointToCell.IndexOffsets.GetPortalControl().Set(this->NumberOfCellsAdded,
this->NumberOfCellsAdded, this->ConnectivityAdded); this->ConnectivityAdded);
this->NumberOfCellsAdded++; this->NumberOfCellsAdded++;
this->ConnectivityAdded += numVertices; this->ConnectivityAdded += numVertices;
} }
@ -253,8 +237,7 @@ public:
if (this->NumberOfCellsAdded != this->GetNumberOfCells()) if (this->NumberOfCellsAdded != this->GetNumberOfCells())
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Did not add as many cells as expected.");
"Did not add as many cells as expected.");
} }
this->NumberOfCellsAdded = -1; this->NumberOfCellsAdded = -1;
@ -266,11 +249,11 @@ public:
/// the way you can fill the memory from another system without copying /// the way you can fill the memory from another system without copying
VTKM_CONT VTKM_CONT
void Fill(vtkm::Id numPoints, void Fill(vtkm::Id numPoints,
const vtkm::cont::ArrayHandle<vtkm::UInt8, ShapeStorageTag> &cellTypes, const vtkm::cont::ArrayHandle<vtkm::UInt8, ShapeStorageTag>& cellTypes,
const vtkm::cont::ArrayHandle<vtkm::IdComponent, NumIndicesStorageTag> &numIndices, const vtkm::cont::ArrayHandle<vtkm::IdComponent, NumIndicesStorageTag>& numIndices,
const vtkm::cont::ArrayHandle<vtkm::Id, ConnectivityStorageTag> &connectivity, const vtkm::cont::ArrayHandle<vtkm::Id, ConnectivityStorageTag>& connectivity,
const vtkm::cont::ArrayHandle<vtkm::Id, OffsetsStorageTag> &offsets const vtkm::cont::ArrayHandle<vtkm::Id, OffsetsStorageTag>& offsets =
= vtkm::cont::ArrayHandle<vtkm::Id, OffsetsStorageTag>() ) vtkm::cont::ArrayHandle<vtkm::Id, OffsetsStorageTag>())
{ {
this->NumberOfPoints = numPoints; this->NumberOfPoints = numPoints;
this->PointToCell.Shapes = cellTypes; this->PointToCell.Shapes = cellTypes;
@ -279,7 +262,7 @@ public:
this->PointToCell.ElementsValid = true; this->PointToCell.ElementsValid = true;
if(offsets.GetNumberOfValues() == cellTypes.GetNumberOfValues()) if (offsets.GetNumberOfValues() == cellTypes.GetNumberOfValues())
{ {
this->PointToCell.IndexOffsets = offsets; this->PointToCell.IndexOffsets = offsets;
this->PointToCell.IndexOffsetsValid = true; this->PointToCell.IndexOffsetsValid = true;
@ -289,9 +272,8 @@ public:
this->PointToCell.IndexOffsetsValid = false; this->PointToCell.IndexOffsetsValid = false;
if (offsets.GetNumberOfValues() != 0) if (offsets.GetNumberOfValues() != 0)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Explicit cell offsets array unexpected size. "
"Explicit cell offsets array unexpected size. " "Use an empty array to automatically generate.");
"Use an empty array to automatically generate.");
} }
} }
} }
@ -303,63 +285,57 @@ public:
VTKM_IS_TOPOLOGY_ELEMENT_TAG(FromTopology); VTKM_IS_TOPOLOGY_ELEMENT_TAG(FromTopology);
VTKM_IS_TOPOLOGY_ELEMENT_TAG(ToTopology); VTKM_IS_TOPOLOGY_ELEMENT_TAG(ToTopology);
typedef ConnectivityChooser<FromTopology,ToTopology> ConnectivityTypes; typedef ConnectivityChooser<FromTopology, ToTopology> ConnectivityTypes;
typedef typename ConnectivityTypes::ShapeArrayType::template ExecutionTypes<DeviceAdapter>::PortalConst ShapePortalType; typedef typename ConnectivityTypes::ShapeArrayType::template ExecutionTypes<
typedef typename ConnectivityTypes::NumIndicesArrayType::template ExecutionTypes<DeviceAdapter>::PortalConst IndicePortalType; DeviceAdapter>::PortalConst ShapePortalType;
typedef typename ConnectivityTypes::ConnectivityArrayType::template ExecutionTypes<DeviceAdapter>::PortalConst ConnectivityPortalType; typedef typename ConnectivityTypes::NumIndicesArrayType::template ExecutionTypes<
typedef typename ConnectivityTypes::IndexOffsetArrayType::template ExecutionTypes<DeviceAdapter>::PortalConst IndexOffsetPortalType; DeviceAdapter>::PortalConst IndicePortalType;
typedef typename ConnectivityTypes::ConnectivityArrayType::template ExecutionTypes<
DeviceAdapter>::PortalConst ConnectivityPortalType;
typedef typename ConnectivityTypes::IndexOffsetArrayType::template ExecutionTypes<
DeviceAdapter>::PortalConst IndexOffsetPortalType;
typedef vtkm::exec::ConnectivityExplicit<ShapePortalType, typedef vtkm::exec::ConnectivityExplicit<ShapePortalType, IndicePortalType,
IndicePortalType, ConnectivityPortalType, IndexOffsetPortalType>
ConnectivityPortalType, ExecObjectType;
IndexOffsetPortalType
> ExecObjectType;
}; };
template<typename Device, typename FromTopology, typename ToTopology> template <typename Device, typename FromTopology, typename ToTopology>
typename ExecutionTypes<Device,FromTopology,ToTopology>::ExecObjectType typename ExecutionTypes<Device, FromTopology, ToTopology>::ExecObjectType PrepareForInput(
PrepareForInput(Device, FromTopology, ToTopology) const Device, FromTopology, ToTopology) const
{ {
this->BuildConnectivity(Device(), FromTopology(), ToTopology()); this->BuildConnectivity(Device(), FromTopology(), ToTopology());
const typename const typename ConnectivityChooser<FromTopology, ToTopology>::ConnectivityType& connectivity =
ConnectivityChooser<FromTopology,ToTopology>::ConnectivityType this->GetConnectivity(FromTopology(), ToTopology());
&connectivity = this->GetConnectivity(FromTopology(), ToTopology());
VTKM_ASSERT(connectivity.ElementsValid); VTKM_ASSERT(connectivity.ElementsValid);
typedef typename typedef typename ExecutionTypes<Device, FromTopology, ToTopology>::ExecObjectType ExecObjType;
ExecutionTypes<Device,FromTopology,ToTopology>::ExecObjectType
ExecObjType;
return ExecObjType(connectivity.Shapes.PrepareForInput(Device()), return ExecObjType(connectivity.Shapes.PrepareForInput(Device()),
connectivity.NumIndices.PrepareForInput(Device()), connectivity.NumIndices.PrepareForInput(Device()),
connectivity.Connectivity.PrepareForInput(Device()), connectivity.Connectivity.PrepareForInput(Device()),
connectivity.IndexOffsets.PrepareForInput(Device())); connectivity.IndexOffsets.PrepareForInput(Device()));
} }
template<typename Device, typename FromTopology, typename ToTopology> template <typename Device, typename FromTopology, typename ToTopology>
VTKM_CONT VTKM_CONT void BuildConnectivity(Device, FromTopology, ToTopology) const
void BuildConnectivity(Device, FromTopology, ToTopology) const
{ {
typedef CellSetExplicit<ShapeStorageTag, typedef CellSetExplicit<ShapeStorageTag, NumIndicesStorageTag, ConnectivityStorageTag,
NumIndicesStorageTag, OffsetsStorageTag>
ConnectivityStorageTag, CSE;
OffsetsStorageTag> CSE;
CSE *self = const_cast<CSE*>(this); CSE* self = const_cast<CSE*>(this);
self->CreateConnectivity(Device(), FromTopology(), ToTopology()); self->CreateConnectivity(Device(), FromTopology(), ToTopology());
self->GetConnectivity(FromTopology(), ToTopology()). self->GetConnectivity(FromTopology(), ToTopology()).BuildIndexOffsets(Device());
BuildIndexOffsets(Device());
} }
template<typename Device> template <typename Device>
VTKM_CONT VTKM_CONT void CreateConnectivity(Device, vtkm::TopologyElementTagPoint,
void CreateConnectivity(Device, vtkm::TopologyElementTagCell)
vtkm::TopologyElementTagPoint,
vtkm::TopologyElementTagCell)
{ {
// nothing to do // nothing to do
} }
@ -368,22 +344,17 @@ public:
class ExpandIndices : public vtkm::worklet::WorkletMapField class ExpandIndices : public vtkm::worklet::WorkletMapField
{ {
public: public:
typedef void ControlSignature(FieldIn<> cellIndex, typedef void ControlSignature(FieldIn<> cellIndex, FieldIn<> offset, FieldIn<> numIndices,
FieldIn<> offset,
FieldIn<> numIndices,
WholeArrayOut<> cellIndices); WholeArrayOut<> cellIndices);
typedef void ExecutionSignature(_1,_2,_3,_4); typedef void ExecutionSignature(_1, _2, _3, _4);
typedef _1 InputDomain; typedef _1 InputDomain;
VTKM_CONT VTKM_CONT
ExpandIndices() {} ExpandIndices() {}
template<typename PortalType> template <typename PortalType>
VTKM_EXEC VTKM_EXEC void operator()(const vtkm::Id& cellIndex, const vtkm::Id& offset,
void operator()(const vtkm::Id &cellIndex, const vtkm::Id& numIndices, const PortalType& cellIndices) const
const vtkm::Id &offset,
const vtkm::Id &numIndices,
const PortalType &cellIndices) const
{ {
VTKM_ASSERT(cellIndices.GetNumberOfValues() >= offset + numIndices); VTKM_ASSERT(cellIndices.GetNumberOfValues() >= offset + numIndices);
vtkm::Id startIndex = offset; vtkm::Id startIndex = offset;
@ -394,11 +365,9 @@ public:
} }
}; };
template<typename Device> template <typename Device>
VTKM_CONT VTKM_CONT void CreateConnectivity(Device, vtkm::TopologyElementTagCell,
void CreateConnectivity(Device, vtkm::TopologyElementTagPoint)
vtkm::TopologyElementTagCell,
vtkm::TopologyElementTagPoint)
{ {
// PointToCell connectivity array (point indices) will be // PointToCell connectivity array (point indices) will be
// transformed into the CellToPoint numIndices array using reduction // transformed into the CellToPoint numIndices array using reduction
@ -428,15 +397,13 @@ public:
this->PointToCell.BuildIndexOffsets(Device()); this->PointToCell.BuildIndexOffsets(Device());
vtkm::worklet::DispatcherMapField<ExpandIndices, Device> expandDispatcher; vtkm::worklet::DispatcherMapField<ExpandIndices, Device> expandDispatcher;
expandDispatcher.Invoke(index, expandDispatcher.Invoke(index, this->PointToCell.IndexOffsets, this->PointToCell.NumIndices,
this->PointToCell.IndexOffsets,
this->PointToCell.NumIndices,
this->CellToPoint.Connectivity); this->CellToPoint.Connectivity);
// SortByKey where key is PointToCell connectivity and value is the expanded cellIndex // SortByKey where key is PointToCell connectivity and value is the expanded cellIndex
Algorithm::SortByKey(pointIndices, this->CellToPoint.Connectivity); Algorithm::SortByKey(pointIndices, this->CellToPoint.Connectivity);
if(this->GetNumberOfPoints() <= 0) if (this->GetNumberOfPoints() <= 0)
{ {
this->NumberOfPoints = pointIndices.GetPortalControl().Get(connectivityLength - 1) + 1; this->NumberOfPoints = pointIndices.GetPortalControl().Get(connectivityLength - 1) + 1;
} }
@ -449,9 +416,7 @@ public:
uniquePoints.Allocate(numberOfPoints); uniquePoints.Allocate(numberOfPoints);
numIndices.Allocate(numberOfPoints); numIndices.Allocate(numberOfPoints);
Algorithm::ReduceByKey(pointIndices, numArray, Algorithm::ReduceByKey(pointIndices, numArray, uniquePoints, numIndices, vtkm::Add());
uniquePoints, numIndices,
vtkm::Add());
// Set the CellToPoint information // Set the CellToPoint information
this->CellToPoint.Shapes = vtkm::cont::make_ArrayHandleConstant( this->CellToPoint.Shapes = vtkm::cont::make_ArrayHandleConstant(
@ -462,7 +427,7 @@ public:
this->CellToPoint.IndexOffsetsValid = false; this->CellToPoint.IndexOffsetsValid = false;
} }
void PrintSummary(std::ostream &out) const VTKM_OVERRIDE void PrintSummary(std::ostream& out) const VTKM_OVERRIDE
{ {
out << " ExplicitCellSet: " << this->Name << std::endl; out << " ExplicitCellSet: " << this->Name << std::endl;
out << " PointToCell: " << std::endl; out << " PointToCell: " << std::endl;
@ -471,73 +436,63 @@ public:
this->CellToPoint.PrintSummary(out); this->CellToPoint.PrintSummary(out);
} }
template<typename FromTopology, typename ToTopology> template <typename FromTopology, typename ToTopology>
VTKM_CONT VTKM_CONT const typename ConnectivityChooser<FromTopology, ToTopology>::ShapeArrayType&
const typename ConnectivityChooser<FromTopology,ToTopology>::ShapeArrayType & GetShapesArray(FromTopology, ToTopology) const
GetShapesArray(FromTopology,ToTopology) const
{ {
return this->GetConnectivity(FromTopology(), ToTopology()).Shapes; return this->GetConnectivity(FromTopology(), ToTopology()).Shapes;
} }
template<typename FromTopology, typename ToTopology> template <typename FromTopology, typename ToTopology>
VTKM_CONT VTKM_CONT const typename ConnectivityChooser<FromTopology, ToTopology>::NumIndicesArrayType&
const typename ConnectivityChooser<FromTopology,ToTopology>::NumIndicesArrayType & GetNumIndicesArray(FromTopology, ToTopology) const
GetNumIndicesArray(FromTopology,ToTopology) const
{ {
return this->GetConnectivity(FromTopology(), ToTopology()).NumIndices; return this->GetConnectivity(FromTopology(), ToTopology()).NumIndices;
} }
template<typename FromTopology, typename ToTopology> template <typename FromTopology, typename ToTopology>
VTKM_CONT VTKM_CONT const typename ConnectivityChooser<FromTopology, ToTopology>::ConnectivityArrayType&
const typename ConnectivityChooser<FromTopology,ToTopology>::ConnectivityArrayType & GetConnectivityArray(FromTopology, ToTopology) const
GetConnectivityArray(FromTopology,ToTopology) const
{ {
return this->GetConnectivity(FromTopology(), ToTopology()).Connectivity; return this->GetConnectivity(FromTopology(), ToTopology()).Connectivity;
} }
template<typename FromTopology, typename ToTopology> template <typename FromTopology, typename ToTopology>
VTKM_CONT VTKM_CONT const typename ConnectivityChooser<FromTopology, ToTopology>::IndexOffsetArrayType&
const typename ConnectivityChooser<FromTopology,ToTopology>::IndexOffsetArrayType & GetIndexOffsetArray(FromTopology, ToTopology) const
GetIndexOffsetArray(FromTopology,ToTopology) const
{ {
return this->GetConnectivity(FromTopology(), ToTopology()).IndexOffsets; return this->GetConnectivity(FromTopology(), ToTopology()).IndexOffsets;
} }
protected: protected:
typename ConnectivityChooser< typename ConnectivityChooser<vtkm::TopologyElementTagPoint,
vtkm::TopologyElementTagPoint,vtkm::TopologyElementTagCell>:: vtkm::TopologyElementTagCell>::ConnectivityType PointToCell;
ConnectivityType PointToCell;
// TODO: Actually implement CellToPoint and other connectivity. (That is, // TODO: Actually implement CellToPoint and other connectivity. (That is,
// derive the connectivity from PointToCell. // derive the connectivity from PointToCell.
typename ConnectivityChooser< typename ConnectivityChooser<vtkm::TopologyElementTagCell,
vtkm::TopologyElementTagCell,vtkm::TopologyElementTagPoint>:: vtkm::TopologyElementTagPoint>::ConnectivityType CellToPoint;
ConnectivityType CellToPoint;
private:
// A set of overloaded methods to get the connectivity from a pair of private:
// topology element types. // A set of overloaded methods to get the connectivity from a pair of
#define VTKM_GET_CONNECTIVITY_METHOD(FromTopology,ToTopology,Ivar) \ // topology element types.
VTKM_CONT \ #define VTKM_GET_CONNECTIVITY_METHOD(FromTopology, ToTopology, Ivar) \
const typename ConnectivityChooser< \ VTKM_CONT \
FromTopology,ToTopology>::ConnectivityType & \ const typename ConnectivityChooser<FromTopology, ToTopology>::ConnectivityType& GetConnectivity( \
GetConnectivity(FromTopology, ToTopology) const \ FromTopology, ToTopology) const \
{ \ { \
return this->Ivar; \ return this->Ivar; \
} \ } \
VTKM_CONT \ VTKM_CONT \
typename ConnectivityChooser< \ typename ConnectivityChooser<FromTopology, ToTopology>::ConnectivityType& GetConnectivity( \
FromTopology,ToTopology>::ConnectivityType & \ FromTopology, ToTopology) \
GetConnectivity(FromTopology, ToTopology) \ { \
{ \ return this->Ivar; \
return this->Ivar; \
} }
VTKM_GET_CONNECTIVITY_METHOD(vtkm::TopologyElementTagPoint, VTKM_GET_CONNECTIVITY_METHOD(vtkm::TopologyElementTagPoint, vtkm::TopologyElementTagCell,
vtkm::TopologyElementTagCell,
PointToCell) PointToCell)
VTKM_GET_CONNECTIVITY_METHOD(vtkm::TopologyElementTagCell, VTKM_GET_CONNECTIVITY_METHOD(vtkm::TopologyElementTagCell, vtkm::TopologyElementTagPoint,
vtkm::TopologyElementTagPoint,
CellToPoint) CellToPoint)
#undef VTKM_GET_CONNECTIVITY_METHOD #undef VTKM_GET_CONNECTIVITY_METHOD
@ -551,33 +506,31 @@ protected:
vtkm::Id NumberOfPoints; vtkm::Id NumberOfPoints;
}; };
namespace detail { namespace detail
template<typename Storage1, typename Storage2, typename Storage3, typename Storage4>
struct CellSetExplicitConnectivityChooser<
vtkm::cont::CellSetExplicit<Storage1,Storage2,Storage3,Storage4>,
vtkm::TopologyElementTagPoint,
vtkm::TopologyElementTagCell>
{ {
typedef vtkm::cont::internal::ConnectivityExplicitInternals<
Storage1,Storage2,Storage3,Storage4> ConnectivityType; template <typename Storage1, typename Storage2, typename Storage3, typename Storage4>
struct CellSetExplicitConnectivityChooser<
vtkm::cont::CellSetExplicit<Storage1, Storage2, Storage3, Storage4>,
vtkm::TopologyElementTagPoint, vtkm::TopologyElementTagCell>
{
typedef vtkm::cont::internal::ConnectivityExplicitInternals<Storage1, Storage2, Storage3,
Storage4>
ConnectivityType;
}; };
template <typename CellSetType>
template<typename CellSetType> struct CellSetExplicitConnectivityChooser<CellSetType, vtkm::TopologyElementTagCell,
struct CellSetExplicitConnectivityChooser< vtkm::TopologyElementTagPoint>
CellSetType,
vtkm::TopologyElementTagCell,
vtkm::TopologyElementTagPoint>
{ {
//only specify the shape type as it will be constant as everything //only specify the shape type as it will be constant as everything
//is a vertex. otherwise use the defaults. //is a vertex. otherwise use the defaults.
typedef vtkm::cont::internal::ConnectivityExplicitInternals< typedef vtkm::cont::internal::ConnectivityExplicitInternals<
typename ArrayHandleConstant<vtkm::UInt8>::StorageTag > ConnectivityType; typename ArrayHandleConstant<vtkm::UInt8>::StorageTag>
ConnectivityType;
}; };
} // namespace detail } // namespace detail
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -30,54 +30,55 @@
#include <vtkm/cont/CellSetSingleType.h> #include <vtkm/cont/CellSetSingleType.h>
#include <vtkm/cont/CellSetStructured.h> #include <vtkm/cont/CellSetStructured.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
struct VTKM_ALWAYS_EXPORT CellSetListTagStructured1D struct VTKM_ALWAYS_EXPORT CellSetListTagStructured1D
: vtkm::ListTagBase<vtkm::cont::CellSetStructured<1> > { }; : vtkm::ListTagBase<vtkm::cont::CellSetStructured<1>>
{
};
struct VTKM_ALWAYS_EXPORT CellSetListTagStructured2D struct VTKM_ALWAYS_EXPORT CellSetListTagStructured2D
: vtkm::ListTagBase<vtkm::cont::CellSetStructured<2> > { }; : vtkm::ListTagBase<vtkm::cont::CellSetStructured<2>>
{
};
struct VTKM_ALWAYS_EXPORT CellSetListTagStructured3D struct VTKM_ALWAYS_EXPORT CellSetListTagStructured3D
: vtkm::ListTagBase<vtkm::cont::CellSetStructured<3> > { }; : vtkm::ListTagBase<vtkm::cont::CellSetStructured<3>>
{
};
template<typename ShapeStorageTag = VTKM_DEFAULT_SHAPE_STORAGE_TAG, template <typename ShapeStorageTag = VTKM_DEFAULT_SHAPE_STORAGE_TAG,
typename NumIndicesStorageTag = VTKM_DEFAULT_NUM_INDICES_STORAGE_TAG, typename NumIndicesStorageTag = VTKM_DEFAULT_NUM_INDICES_STORAGE_TAG,
typename ConnectivityStorageTag = VTKM_DEFAULT_CONNECTIVITY_STORAGE_TAG, typename ConnectivityStorageTag = VTKM_DEFAULT_CONNECTIVITY_STORAGE_TAG,
typename OffsetsStorageTag = VTKM_DEFAULT_OFFSETS_STORAGE_TAG > typename OffsetsStorageTag = VTKM_DEFAULT_OFFSETS_STORAGE_TAG>
struct VTKM_ALWAYS_EXPORT CellSetListTagExplicit struct VTKM_ALWAYS_EXPORT CellSetListTagExplicit
: vtkm::ListTagBase< : vtkm::ListTagBase<vtkm::cont::CellSetExplicit<ShapeStorageTag, NumIndicesStorageTag,
vtkm::cont::CellSetExplicit< ConnectivityStorageTag, OffsetsStorageTag>>
ShapeStorageTag, {
NumIndicesStorageTag, };
ConnectivityStorageTag,
OffsetsStorageTag> > { };
struct VTKM_ALWAYS_EXPORT CellSetListTagExplicitDefault
: CellSetListTagExplicit<> { };
struct VTKM_ALWAYS_EXPORT CellSetListTagExplicitDefault : CellSetListTagExplicit<>
{
};
struct VTKM_ALWAYS_EXPORT CellSetListTagCommon struct VTKM_ALWAYS_EXPORT CellSetListTagCommon
: vtkm::ListTagBase< : vtkm::ListTagBase<vtkm::cont::CellSetStructured<2>, vtkm::cont::CellSetStructured<3>,
vtkm::cont::CellSetStructured<2>, vtkm::cont::CellSetExplicit<>, vtkm::cont::CellSetSingleType<>>
vtkm::cont::CellSetStructured<3>, {
vtkm::cont::CellSetExplicit<>, };
vtkm::cont::CellSetSingleType<>
> { };
struct VTKM_ALWAYS_EXPORT CellSetListTagStructured struct VTKM_ALWAYS_EXPORT CellSetListTagStructured
: vtkm::ListTagBase< : vtkm::ListTagBase<vtkm::cont::CellSetStructured<2>, vtkm::cont::CellSetStructured<3>>
vtkm::cont::CellSetStructured<2>, {
vtkm::cont::CellSetStructured<3> };
> { };
struct VTKM_ALWAYS_EXPORT CellSetListTagUnstructured struct VTKM_ALWAYS_EXPORT CellSetListTagUnstructured
: vtkm::ListTagBase< : vtkm::ListTagBase<vtkm::cont::CellSetExplicit<>, vtkm::cont::CellSetSingleType<>>
vtkm::cont::CellSetExplicit<>, {
vtkm::cont::CellSetSingleType<> };
> { };
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -27,46 +27,43 @@
#include <vtkm/exec/ConnectivityPermuted.h> #include <vtkm/exec/ConnectivityPermuted.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
template< typename OriginalCellSet, typename ValidCellArrayHandleType> class CellSetPermutation; template <typename OriginalCellSet, typename ValidCellArrayHandleType>
class CellSetPermutation;
namespace internal { namespace internal
{
template< typename OriginalCellSet, typename PermutationArrayHandleType > template <typename OriginalCellSet, typename PermutationArrayHandleType>
class CellSetGeneralPermutation : public CellSet class CellSetGeneralPermutation : public CellSet
{ {
public: public:
VTKM_CONT VTKM_CONT
CellSetGeneralPermutation(const PermutationArrayHandleType& validCellIds, CellSetGeneralPermutation(const PermutationArrayHandleType& validCellIds,
const OriginalCellSet& cellset, const OriginalCellSet& cellset, const std::string& name)
const std::string &name) : CellSet(name)
: CellSet(name), , ValidCellIds(validCellIds)
ValidCellIds(validCellIds), , FullCellSet(cellset)
FullCellSet(cellset)
{ {
} }
VTKM_CONT VTKM_CONT
CellSetGeneralPermutation(const std::string &name) CellSetGeneralPermutation(const std::string& name)
: CellSet(name), : CellSet(name)
ValidCellIds(), , ValidCellIds()
FullCellSet() , FullCellSet()
{ {
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfCells() const VTKM_OVERRIDE vtkm::Id GetNumberOfCells() const VTKM_OVERRIDE { return this->ValidCellIds.GetNumberOfValues(); }
{
return this->ValidCellIds.GetNumberOfValues();
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfPoints() const VTKM_OVERRIDE vtkm::Id GetNumberOfPoints() const VTKM_OVERRIDE { return this->FullCellSet.GetNumberOfPoints(); }
{
return this->FullCellSet.GetNumberOfPoints();
}
vtkm::Id GetNumberOfFaces() const VTKM_OVERRIDE { return -1; } vtkm::Id GetNumberOfFaces() const VTKM_OVERRIDE { return -1; }
@ -74,50 +71,48 @@ public:
//This is the way you can fill the memory from another system without copying //This is the way you can fill the memory from another system without copying
VTKM_CONT VTKM_CONT
void Fill(const PermutationArrayHandleType &validCellIds, void Fill(const PermutationArrayHandleType& validCellIds, const OriginalCellSet& cellset)
const OriginalCellSet& cellset)
{ {
ValidCellIds = validCellIds; ValidCellIds = validCellIds;
FullCellSet = cellset; FullCellSet = cellset;
} }
template<typename TopologyElement> template <typename TopologyElement>
VTKM_CONT VTKM_CONT vtkm::Id GetSchedulingRange(TopologyElement) const
vtkm::Id GetSchedulingRange(TopologyElement) const { {
VTKM_IS_TOPOLOGY_ELEMENT_TAG(TopologyElement); VTKM_IS_TOPOLOGY_ELEMENT_TAG(TopologyElement);
return this->ValidCellIds.GetNumberOfValues(); return this->ValidCellIds.GetNumberOfValues();
} }
template<typename Device, typename FromTopology, typename ToTopology> template <typename Device, typename FromTopology, typename ToTopology>
struct ExecutionTypes { struct ExecutionTypes
{
VTKM_IS_DEVICE_ADAPTER_TAG(Device); VTKM_IS_DEVICE_ADAPTER_TAG(Device);
VTKM_IS_TOPOLOGY_ELEMENT_TAG(FromTopology); VTKM_IS_TOPOLOGY_ELEMENT_TAG(FromTopology);
VTKM_IS_TOPOLOGY_ELEMENT_TAG(ToTopology); VTKM_IS_TOPOLOGY_ELEMENT_TAG(ToTopology);
typedef typename PermutationArrayHandleType::template ExecutionTypes<Device>::PortalConst ExecPortalType; typedef typename PermutationArrayHandleType::template ExecutionTypes<Device>::PortalConst
ExecPortalType;
typedef typename OriginalCellSet::template ExecutionTypes< typedef typename OriginalCellSet::template ExecutionTypes<
Device, Device, FromTopology, ToTopology>::ExecObjectType OrigExecObjectType;
FromTopology,
ToTopology>::ExecObjectType OrigExecObjectType;
typedef vtkm::exec::ConnectivityPermuted< ExecPortalType, OrigExecObjectType> ExecObjectType; typedef vtkm::exec::ConnectivityPermuted<ExecPortalType, OrigExecObjectType> ExecObjectType;
}; };
template<typename Device, typename FromTopology, typename ToTopology> template <typename Device, typename FromTopology, typename ToTopology>
typename ExecutionTypes<Device,FromTopology,ToTopology>::ExecObjectType typename ExecutionTypes<Device, FromTopology, ToTopology>::ExecObjectType PrepareForInput(
PrepareForInput(Device d, FromTopology f, ToTopology t) const Device d, FromTopology f, ToTopology t) const
{ {
typedef typename typedef
ExecutionTypes<Device,FromTopology,ToTopology>::ExecObjectType typename ExecutionTypes<Device, FromTopology, ToTopology>::ExecObjectType ConnectivityType;
ConnectivityType;
return ConnectivityType(this->ValidCellIds.PrepareForInput(d), return ConnectivityType(this->ValidCellIds.PrepareForInput(d),
this->FullCellSet.PrepareForInput(d,f,t) ); this->FullCellSet.PrepareForInput(d, f, t));
} }
void PrintSummary(std::ostream &out) const VTKM_OVERRIDE void PrintSummary(std::ostream& out) const VTKM_OVERRIDE
{ {
out << " CellSetGeneralPermutation of: "<< std::endl; out << " CellSetGeneralPermutation of: " << std::endl;
this->FullCellSet.PrintSummary(out); this->FullCellSet.PrintSummary(out);
} }
@ -132,67 +127,64 @@ private:
#define VTKM_DEFAULT_CELLSET_PERMUTATION_STORAGE_TAG VTKM_DEFAULT_STORAGE_TAG #define VTKM_DEFAULT_CELLSET_PERMUTATION_STORAGE_TAG VTKM_DEFAULT_STORAGE_TAG
#endif #endif
template< typename OriginalCellSet, template <typename OriginalCellSet,
typename PermutationArrayHandleType = vtkm::cont::ArrayHandle< vtkm::Id, VTKM_DEFAULT_CELLSET_PERMUTATION_STORAGE_TAG > > typename PermutationArrayHandleType =
class CellSetPermutation : public vtkm::cont::internal::CellSetGeneralPermutation<OriginalCellSet, PermutationArrayHandleType> vtkm::cont::ArrayHandle<vtkm::Id, VTKM_DEFAULT_CELLSET_PERMUTATION_STORAGE_TAG>>
class CellSetPermutation
: public vtkm::cont::internal::CellSetGeneralPermutation<OriginalCellSet,
PermutationArrayHandleType>
{ {
VTKM_IS_CELL_SET(OriginalCellSet); VTKM_IS_CELL_SET(OriginalCellSet);
VTKM_IS_ARRAY_HANDLE(PermutationArrayHandleType); VTKM_IS_ARRAY_HANDLE(PermutationArrayHandleType);
typedef typename vtkm::cont::internal::CellSetGeneralPermutation< typedef typename vtkm::cont::internal::CellSetGeneralPermutation<OriginalCellSet,
OriginalCellSet, PermutationArrayHandleType> ParentType; PermutationArrayHandleType>
public: ParentType;
public:
VTKM_CONT VTKM_CONT
CellSetPermutation(const PermutationArrayHandleType& validCellIds, CellSetPermutation(const PermutationArrayHandleType& validCellIds, const OriginalCellSet& cellset,
const OriginalCellSet& cellset, const std::string& name = std::string())
const std::string &name = std::string())
: ParentType(validCellIds, cellset, name) : ParentType(validCellIds, cellset, name)
{ {
} }
VTKM_CONT VTKM_CONT
CellSetPermutation(const std::string &name = std::string()) CellSetPermutation(const std::string& name = std::string())
: ParentType(name) : ParentType(name)
{ {
} }
VTKM_CONT VTKM_CONT
CellSetPermutation<OriginalCellSet,PermutationArrayHandleType>& CellSetPermutation<OriginalCellSet, PermutationArrayHandleType>& operator=(
operator=(const CellSetPermutation<OriginalCellSet,PermutationArrayHandleType> &src) const CellSetPermutation<OriginalCellSet, PermutationArrayHandleType>& src)
{ {
ParentType::operator=(src); ParentType::operator=(src);
return *this; return *this;
} }
}; };
template<typename OriginalCellSet, typename PermutationArrayHandleType> template <typename OriginalCellSet, typename PermutationArrayHandleType>
vtkm::cont::CellSetPermutation<OriginalCellSet,PermutationArrayHandleType> vtkm::cont::CellSetPermutation<OriginalCellSet, PermutationArrayHandleType> make_CellSetPermutation(
make_CellSetPermutation(const PermutationArrayHandleType &cellIndexMap, const PermutationArrayHandleType& cellIndexMap, const OriginalCellSet& cellSet,
const OriginalCellSet &cellSet, const std::string& name)
const std::string &name)
{ {
VTKM_IS_CELL_SET(OriginalCellSet); VTKM_IS_CELL_SET(OriginalCellSet);
VTKM_IS_ARRAY_HANDLE(PermutationArrayHandleType); VTKM_IS_ARRAY_HANDLE(PermutationArrayHandleType);
return vtkm::cont::CellSetPermutation< return vtkm::cont::CellSetPermutation<OriginalCellSet, PermutationArrayHandleType>(cellIndexMap,
OriginalCellSet,PermutationArrayHandleType>( cellSet, name);
cellIndexMap, cellSet, name);
} }
template<typename OriginalCellSet, typename PermutationArrayHandleType> template <typename OriginalCellSet, typename PermutationArrayHandleType>
vtkm::cont::CellSetPermutation<OriginalCellSet,PermutationArrayHandleType> vtkm::cont::CellSetPermutation<OriginalCellSet, PermutationArrayHandleType> make_CellSetPermutation(
make_CellSetPermutation(const PermutationArrayHandleType &cellIndexMap, const PermutationArrayHandleType& cellIndexMap, const OriginalCellSet& cellSet)
const OriginalCellSet &cellSet)
{ {
VTKM_IS_CELL_SET(OriginalCellSet); VTKM_IS_CELL_SET(OriginalCellSet);
VTKM_IS_ARRAY_HANDLE(PermutationArrayHandleType); VTKM_IS_ARRAY_HANDLE(PermutationArrayHandleType);
return vtkm::cont::make_CellSetPermutation( return vtkm::cont::make_CellSetPermutation(cellIndexMap, cellSet, cellSet.GetName());
cellIndexMap, cellSet, cellSet.GetName());
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -30,49 +30,51 @@
#include <map> #include <map>
#include <utility> #include <utility>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
//Only works with fixed sized cell sets //Only works with fixed sized cell sets
template< typename ConnectivityStorageTag = VTKM_DEFAULT_CONNECTIVITY_STORAGE_TAG > template <typename ConnectivityStorageTag = VTKM_DEFAULT_CONNECTIVITY_STORAGE_TAG>
class VTKM_ALWAYS_EXPORT CellSetSingleType : class VTKM_ALWAYS_EXPORT CellSetSingleType
public vtkm::cont::CellSetExplicit< : public vtkm::cont::CellSetExplicit<
typename vtkm::cont::ArrayHandleConstant<vtkm::UInt8>::StorageTag, //ShapeStorageTag typename vtkm::cont::ArrayHandleConstant<vtkm::UInt8>::StorageTag, //ShapeStorageTag
typename vtkm::cont::ArrayHandleConstant<vtkm::IdComponent>::StorageTag, //NumIndicesStorageTag typename vtkm::cont::ArrayHandleConstant<
ConnectivityStorageTag, vtkm::IdComponent>::StorageTag, //NumIndicesStorageTag
typename vtkm::cont::ArrayHandleCounting<vtkm::Id>::StorageTag //IndexOffsetStorageTag ConnectivityStorageTag,
> typename vtkm::cont::ArrayHandleCounting<vtkm::Id>::StorageTag //IndexOffsetStorageTag
>
{ {
typedef vtkm::cont::CellSetSingleType<ConnectivityStorageTag> Thisclass; typedef vtkm::cont::CellSetSingleType<ConnectivityStorageTag> Thisclass;
typedef vtkm::cont::CellSetExplicit< typedef vtkm::cont::CellSetExplicit<
typename vtkm::cont::ArrayHandleConstant<vtkm::UInt8>::StorageTag, typename vtkm::cont::ArrayHandleConstant<vtkm::UInt8>::StorageTag,
typename vtkm::cont::ArrayHandleConstant<vtkm::IdComponent>::StorageTag, typename vtkm::cont::ArrayHandleConstant<vtkm::IdComponent>::StorageTag, ConnectivityStorageTag,
ConnectivityStorageTag, typename vtkm::cont::ArrayHandleCounting<vtkm::Id>::StorageTag>
typename vtkm::cont::ArrayHandleCounting<vtkm::Id>::StorageTag > Superclass; Superclass;
public: public:
VTKM_CONT VTKM_CONT
CellSetSingleType(const std::string &name = std::string()) CellSetSingleType(const std::string& name = std::string())
: Superclass(name), : Superclass(name)
ExpectedNumberOfCellsAdded(-1), , ExpectedNumberOfCellsAdded(-1)
CellShapeAsId(CellShapeTagEmpty::Id), , CellShapeAsId(CellShapeTagEmpty::Id)
NumberOfPointsPerCell(0) , NumberOfPointsPerCell(0)
{ {
} }
VTKM_CONT VTKM_CONT
CellSetSingleType(const Thisclass &src) CellSetSingleType(const Thisclass& src)
: Superclass(src), : Superclass(src)
ExpectedNumberOfCellsAdded(-1), , ExpectedNumberOfCellsAdded(-1)
CellShapeAsId(src.CellShapeAsId), , CellShapeAsId(src.CellShapeAsId)
NumberOfPointsPerCell(src.NumberOfPointsPerCell) , NumberOfPointsPerCell(src.NumberOfPointsPerCell)
{ } {
}
VTKM_CONT VTKM_CONT
Thisclass &operator=(const Thisclass &src) Thisclass& operator=(const Thisclass& src)
{ {
this->Superclass::operator=(src); this->Superclass::operator=(src);
this->CellShapeAsId = src.CellShapeAsId; this->CellShapeAsId = src.CellShapeAsId;
@ -80,12 +82,11 @@ public:
return *this; return *this;
} }
virtual ~CellSetSingleType() { } virtual ~CellSetSingleType() {}
/// First method to add cells -- one at a time. /// First method to add cells -- one at a time.
VTKM_CONT VTKM_CONT
void PrepareToAddCells(vtkm::Id numCells, void PrepareToAddCells(vtkm::Id numCells, vtkm::Id connectivityMaxLen)
vtkm::Id connectivityMaxLen)
{ {
this->CellShapeAsId = vtkm::CELL_SHAPE_EMPTY; this->CellShapeAsId = vtkm::CELL_SHAPE_EMPTY;
@ -98,35 +99,28 @@ public:
/// Second method to add cells -- one at a time. /// Second method to add cells -- one at a time.
template <typename IdVecType> template <typename IdVecType>
VTKM_CONT VTKM_CONT void AddCell(vtkm::UInt8 shapeId, vtkm::IdComponent numVertices, const IdVecType& ids)
void AddCell(vtkm::UInt8 shapeId,
vtkm::IdComponent numVertices,
const IdVecType &ids)
{ {
using Traits = vtkm::VecTraits<IdVecType>; using Traits = vtkm::VecTraits<IdVecType>;
VTKM_STATIC_ASSERT_MSG( VTKM_STATIC_ASSERT_MSG((std::is_same<typename Traits::ComponentType, vtkm::Id>::value),
(std::is_same<typename Traits::ComponentType,vtkm::Id>::value), "CellSetSingleType::AddCell requires vtkm::Id for indices.");
"CellSetSingleType::AddCell requires vtkm::Id for indices.");
if (Traits::GetNumberOfComponents(ids) < numVertices) if (Traits::GetNumberOfComponents(ids) < numVertices)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Not enough indices given to CellSetSingleType::AddCell.");
"Not enough indices given to CellSetSingleType::AddCell.");
} }
if (this->ConnectivityAdded+numVertices > if (this->ConnectivityAdded + numVertices > this->PointToCell.Connectivity.GetNumberOfValues())
this->PointToCell.Connectivity.GetNumberOfValues())
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"Connectivity increased passed estimated maximum connectivity."); "Connectivity increased passed estimated maximum connectivity.");
} }
if (this->CellShapeAsId == vtkm::CELL_SHAPE_EMPTY) if (this->CellShapeAsId == vtkm::CELL_SHAPE_EMPTY)
{ {
if (shapeId == vtkm::CELL_SHAPE_EMPTY) if (shapeId == vtkm::CELL_SHAPE_EMPTY)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Cannot create cells of type empty.");
"Cannot create cells of type empty.");
} }
this->CellShapeAsId = shapeId; this->CellShapeAsId = shapeId;
this->CheckNumberOfPointsPerCell(numVertices); this->CheckNumberOfPointsPerCell(numVertices);
@ -136,19 +130,18 @@ public:
{ {
if (shapeId != this->GetCellShape(0)) if (shapeId != this->GetCellShape(0))
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Cannot have differing shapes in CellSetSingleType.");
"Cannot have differing shapes in CellSetSingleType.");
} }
if (numVertices != this->NumberOfPointsPerCell) if (numVertices != this->NumberOfPointsPerCell)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue(
"Inconsistent number of points in cells for CellSetSingleType."); "Inconsistent number of points in cells for CellSetSingleType.");
} }
} }
for (vtkm::IdComponent iVert=0; iVert < numVertices; ++iVert) for (vtkm::IdComponent iVert = 0; iVert < numVertices; ++iVert)
{ {
this->PointToCell.Connectivity.GetPortalControl().Set( this->PointToCell.Connectivity.GetPortalControl().Set(this->ConnectivityAdded + iVert,
this->ConnectivityAdded+iVert, Traits::GetComponent(ids,iVert)); Traits::GetComponent(ids, iVert));
} }
this->NumberOfCellsAdded++; this->NumberOfCellsAdded++;
this->ConnectivityAdded += numVertices; this->ConnectivityAdded += numVertices;
@ -164,23 +157,18 @@ public:
vtkm::Id numCells = this->NumberOfCellsAdded; vtkm::Id numCells = this->NumberOfCellsAdded;
this->PointToCell.Shapes = this->PointToCell.Shapes =
vtkm::cont::make_ArrayHandleConstant(this->GetCellShape(0), numCells); vtkm::cont::make_ArrayHandleConstant(this->GetCellShape(0), numCells);
this->PointToCell.NumIndices = this->PointToCell.NumIndices =
vtkm::cont::make_ArrayHandleConstant(this->NumberOfPointsPerCell, vtkm::cont::make_ArrayHandleConstant(this->NumberOfPointsPerCell, numCells);
numCells); this->PointToCell.IndexOffsets = vtkm::cont::make_ArrayHandleCounting(
this->PointToCell.IndexOffsets = vtkm::Id(0), static_cast<vtkm::Id>(this->NumberOfPointsPerCell), numCells);
vtkm::cont::make_ArrayHandleCounting(
vtkm::Id(0),
static_cast<vtkm::Id>(this->NumberOfPointsPerCell),
numCells);
this->PointToCell.ElementsValid = true; this->PointToCell.ElementsValid = true;
this->PointToCell.IndexOffsetsValid = true; this->PointToCell.IndexOffsetsValid = true;
if (this->ExpectedNumberOfCellsAdded != this->GetNumberOfCells()) if (this->ExpectedNumberOfCellsAdded != this->GetNumberOfCells())
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Did not add the expected number of cells.");
"Did not add the expected number of cells.");
} }
this->NumberOfCellsAdded = -1; this->NumberOfCellsAdded = -1;
@ -190,27 +178,19 @@ public:
//This is the way you can fill the memory from another system without copying //This is the way you can fill the memory from another system without copying
VTKM_CONT VTKM_CONT
void Fill(vtkm::Id numPoints, void Fill(vtkm::Id numPoints, vtkm::UInt8 shapeId, vtkm::IdComponent numberOfPointsPerCell,
vtkm::UInt8 shapeId, const vtkm::cont::ArrayHandle<vtkm::Id, ConnectivityStorageTag>& connectivity)
vtkm::IdComponent numberOfPointsPerCell,
const vtkm::cont::ArrayHandle<vtkm::Id,ConnectivityStorageTag>
&connectivity)
{ {
this->NumberOfPoints = numPoints; this->NumberOfPoints = numPoints;
this->CellShapeAsId = shapeId; this->CellShapeAsId = shapeId;
this->CheckNumberOfPointsPerCell(numberOfPointsPerCell); this->CheckNumberOfPointsPerCell(numberOfPointsPerCell);
const vtkm::Id numCells = const vtkm::Id numCells = connectivity.GetNumberOfValues() / numberOfPointsPerCell;
connectivity.GetNumberOfValues() / numberOfPointsPerCell;
VTKM_ASSERT((connectivity.GetNumberOfValues() % numberOfPointsPerCell) == 0); VTKM_ASSERT((connectivity.GetNumberOfValues() % numberOfPointsPerCell) == 0);
this->PointToCell.Shapes = this->PointToCell.Shapes = vtkm::cont::make_ArrayHandleConstant(shapeId, numCells);
vtkm::cont::make_ArrayHandleConstant(shapeId, numCells);
this->PointToCell.NumIndices = this->PointToCell.NumIndices =
vtkm::cont::make_ArrayHandleConstant(numberOfPointsPerCell, vtkm::cont::make_ArrayHandleConstant(numberOfPointsPerCell, numCells);
numCells); this->PointToCell.IndexOffsets = vtkm::cont::make_ArrayHandleCounting(
this->PointToCell.IndexOffsets = vtkm::Id(0), static_cast<vtkm::Id>(numberOfPointsPerCell), numCells);
vtkm::cont::make_ArrayHandleCounting(vtkm::Id(0),
static_cast<vtkm::Id>(numberOfPointsPerCell),
numCells );
this->PointToCell.Connectivity = connectivity; this->PointToCell.Connectivity = connectivity;
this->PointToCell.ElementsValid = true; this->PointToCell.ElementsValid = true;
@ -218,10 +198,7 @@ public:
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetCellShapeAsId() const vtkm::Id GetCellShapeAsId() const { return this->CellShapeAsId; }
{
return this->CellShapeAsId;
}
VTKM_CONT VTKM_CONT
vtkm::UInt8 GetCellShape(vtkm::Id vtkmNotUsed(cellIndex)) const vtkm::UInt8 GetCellShape(vtkm::Id vtkmNotUsed(cellIndex)) const
@ -229,9 +206,10 @@ public:
return static_cast<vtkm::UInt8>(this->CellShapeAsId); return static_cast<vtkm::UInt8>(this->CellShapeAsId);
} }
virtual void PrintSummary(std::ostream &out) const virtual void PrintSummary(std::ostream& out) const
{ {
out << " ExplicitSingleCellSet: " << this->Name << " Type "<<this->CellShapeAsId<<std::endl; out << " ExplicitSingleCellSet: " << this->Name << " Type " << this->CellShapeAsId
<< std::endl;
out << " PointToCell: " << std::endl; out << " PointToCell: " << std::endl;
this->PointToCell.PrintSummary(out); this->PointToCell.PrintSummary(out);
out << " CellToPoint: " << std::endl; out << " CellToPoint: " << std::endl;
@ -239,21 +217,18 @@ public:
} }
private: private:
template< typename CellShapeTag> template <typename CellShapeTag>
void CheckNumberOfPointsPerCell(CellShapeTag, void CheckNumberOfPointsPerCell(CellShapeTag, vtkm::CellTraitsTagSizeFixed,
vtkm::CellTraitsTagSizeFixed,
vtkm::IdComponent numVertices) const vtkm::IdComponent numVertices) const
{ {
if (numVertices != vtkm::CellTraits<CellShapeTag>::NUM_POINTS) if (numVertices != vtkm::CellTraits<CellShapeTag>::NUM_POINTS)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Passed invalid number of points for cell shape.");
"Passed invalid number of points for cell shape.");
} }
} }
template< typename CellShapeTag> template <typename CellShapeTag>
void CheckNumberOfPointsPerCell(CellShapeTag, void CheckNumberOfPointsPerCell(CellShapeTag, vtkm::CellTraitsTagSizeVariable,
vtkm::CellTraitsTagSizeVariable,
vtkm::IdComponent vtkmNotUsed(numVertices)) const vtkm::IdComponent vtkmNotUsed(numVertices)) const
{ {
// Technically, a shape with a variable number of points probably has a // Technically, a shape with a variable number of points probably has a
@ -261,18 +236,14 @@ private:
// check that. Instead, just pass the check by returning without error. // check that. Instead, just pass the check by returning without error.
} }
void CheckNumberOfPointsPerCell(vtkm::IdComponent numVertices) const void CheckNumberOfPointsPerCell(vtkm::IdComponent numVertices) const
{ {
switch (this->CellShapeAsId) switch (this->CellShapeAsId)
{ {
vtkmGenericCellShapeMacro( vtkmGenericCellShapeMacro(this->CheckNumberOfPointsPerCell(
this->CheckNumberOfPointsPerCell(CellShapeTag(), CellShapeTag(), vtkm::CellTraits<CellShapeTag>::IsSizeFixed(), numVertices));
vtkm::CellTraits<CellShapeTag>::IsSizeFixed(),
numVertices) );
default: default:
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("CellSetSingleType unable to determine the cell type");
"CellSetSingleType unable to determine the cell type");
} }
} }
@ -280,7 +251,6 @@ private:
vtkm::Id CellShapeAsId; vtkm::Id CellShapeAsId;
vtkm::IdComponent NumberOfPointsPerCell; vtkm::IdComponent NumberOfPointsPerCell;
}; };
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -21,12 +21,13 @@
#define vtkm_cont_CellSetStructured_cxx #define vtkm_cont_CellSetStructured_cxx
#include <vtkm/cont/CellSetStructured.h> #include <vtkm/cont/CellSetStructured.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
template class VTKM_CONT_EXPORT CellSetStructured<1>; template class VTKM_CONT_EXPORT CellSetStructured<1>;
template class VTKM_CONT_EXPORT CellSetStructured<2>; template class VTKM_CONT_EXPORT CellSetStructured<2>;
template class VTKM_CONT_EXPORT CellSetStructured<3>; template class VTKM_CONT_EXPORT CellSetStructured<3>;
} }
} }

@ -28,40 +28,36 @@
#include <vtkm/exec/ConnectivityStructured.h> #include <vtkm/exec/ConnectivityStructured.h>
#include <vtkm/internal/ConnectivityStructuredInternals.h> #include <vtkm/internal/ConnectivityStructuredInternals.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
template<vtkm::IdComponent DIMENSION> template <vtkm::IdComponent DIMENSION>
class VTKM_ALWAYS_EXPORT CellSetStructured : public CellSet class VTKM_ALWAYS_EXPORT CellSetStructured : public CellSet
{ {
private: private:
typedef vtkm::cont::CellSetStructured<DIMENSION> Thisclass; typedef vtkm::cont::CellSetStructured<DIMENSION> Thisclass;
typedef vtkm::internal::ConnectivityStructuredInternals<DIMENSION> typedef vtkm::internal::ConnectivityStructuredInternals<DIMENSION> InternalsType;
InternalsType;
public: public:
static const vtkm::IdComponent Dimension=DIMENSION; static const vtkm::IdComponent Dimension = DIMENSION;
typedef typename InternalsType::SchedulingRangeType SchedulingRangeType; typedef typename InternalsType::SchedulingRangeType SchedulingRangeType;
CellSetStructured(const std::string &name = std::string()) CellSetStructured(const std::string& name = std::string())
: CellSet(name), Structure() : CellSet(name)
, Structure()
{ {
} }
CellSetStructured(const Thisclass &src); CellSetStructured(const Thisclass& src);
Thisclass &operator=(const Thisclass &src); Thisclass& operator=(const Thisclass& src);
virtual vtkm::Id GetNumberOfCells() const virtual vtkm::Id GetNumberOfCells() const { return this->Structure.GetNumberOfCells(); }
{
return this->Structure.GetNumberOfCells();
}
virtual vtkm::Id GetNumberOfPoints() const virtual vtkm::Id GetNumberOfPoints() const { return this->Structure.GetNumberOfPoints(); }
{
return this->Structure.GetNumberOfPoints();
}
virtual vtkm::Id GetNumberOfFaces() const { return -1; } virtual vtkm::Id GetNumberOfFaces() const { return -1; }
@ -72,43 +68,34 @@ public:
this->Structure.SetPointDimensions(dimensions); this->Structure.SetPointDimensions(dimensions);
} }
SchedulingRangeType GetPointDimensions() SchedulingRangeType GetPointDimensions() { return this->Structure.GetPointDimensions(); }
{
return this->Structure.GetPointDimensions();
}
SchedulingRangeType GetCellDimensions() SchedulingRangeType GetCellDimensions() { return this->Structure.GetCellDimensions(); }
{
return this->Structure.GetCellDimensions();
}
vtkm::IdComponent vtkm::IdComponent GetNumberOfPointsInCell(vtkm::Id vtkmNotUsed(cellIndex) = 0) const
GetNumberOfPointsInCell(vtkm::Id vtkmNotUsed(cellIndex)=0) const
{ {
return this->Structure.GetNumberOfPointsInCell(); return this->Structure.GetNumberOfPointsInCell();
} }
vtkm::IdComponent GetCellShape() const vtkm::IdComponent GetCellShape() const { return this->Structure.GetCellShape(); }
{
return this->Structure.GetCellShape();
}
template<typename TopologyElement> template <typename TopologyElement>
SchedulingRangeType GetSchedulingRange(TopologyElement) const; SchedulingRangeType GetSchedulingRange(TopologyElement) const;
template<typename DeviceAdapter, typename FromTopology, typename ToTopology> template <typename DeviceAdapter, typename FromTopology, typename ToTopology>
struct ExecutionTypes { struct ExecutionTypes
{
VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapter); VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapter);
VTKM_IS_TOPOLOGY_ELEMENT_TAG(FromTopology); VTKM_IS_TOPOLOGY_ELEMENT_TAG(FromTopology);
VTKM_IS_TOPOLOGY_ELEMENT_TAG(ToTopology); VTKM_IS_TOPOLOGY_ELEMENT_TAG(ToTopology);
typedef vtkm::exec::ConnectivityStructured<FromTopology,ToTopology,Dimension> ExecObjectType; typedef vtkm::exec::ConnectivityStructured<FromTopology, ToTopology, Dimension> ExecObjectType;
}; };
template<typename DeviceAdapter, typename FromTopology, typename ToTopology> template <typename DeviceAdapter, typename FromTopology, typename ToTopology>
typename ExecutionTypes<DeviceAdapter,FromTopology,ToTopology>::ExecObjectType typename ExecutionTypes<DeviceAdapter, FromTopology, ToTopology>::ExecObjectType PrepareForInput(
PrepareForInput(DeviceAdapter, FromTopology, ToTopology) const; DeviceAdapter, FromTopology, ToTopology) const;
virtual void PrintSummary(std::ostream &out) const; virtual void PrintSummary(std::ostream& out) const;
private: private:
InternalsType Structure; InternalsType Structure;
@ -119,7 +106,6 @@ extern template class VTKM_CONT_TEMPLATE_EXPORT CellSetStructured<1>;
extern template class VTKM_CONT_TEMPLATE_EXPORT CellSetStructured<2>; extern template class VTKM_CONT_TEMPLATE_EXPORT CellSetStructured<2>;
extern template class VTKM_CONT_TEMPLATE_EXPORT CellSetStructured<3>; extern template class VTKM_CONT_TEMPLATE_EXPORT CellSetStructured<3>;
#endif #endif
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -18,52 +18,52 @@
// this software. // this software.
//============================================================================ //============================================================================
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
template<vtkm::IdComponent DIMENSION>
CellSetStructured<DIMENSION>::CellSetStructured(const CellSetStructured<DIMENSION> &src)
: CellSet(src), Structure(src.Structure)
{ {
template <vtkm::IdComponent DIMENSION>
CellSetStructured<DIMENSION>::CellSetStructured(const CellSetStructured<DIMENSION>& src)
: CellSet(src)
, Structure(src.Structure)
{
} }
template<vtkm::IdComponent DIMENSION> template <vtkm::IdComponent DIMENSION>
CellSetStructured<DIMENSION>& CellSetStructured<DIMENSION>& CellSetStructured<DIMENSION>::operator=(
CellSetStructured<DIMENSION>::operator=(const CellSetStructured<DIMENSION> &src) const CellSetStructured<DIMENSION>& src)
{ {
this->CellSet::operator=(src); this->CellSet::operator=(src);
this->Structure = src.Structure; this->Structure = src.Structure;
return *this; return *this;
} }
template<vtkm::IdComponent DIMENSION> template <vtkm::IdComponent DIMENSION>
template<typename TopologyElement> template <typename TopologyElement>
typename CellSetStructured<DIMENSION>::SchedulingRangeType typename CellSetStructured<DIMENSION>::SchedulingRangeType
CellSetStructured<DIMENSION>::GetSchedulingRange(TopologyElement) const CellSetStructured<DIMENSION>::GetSchedulingRange(TopologyElement) const
{ {
VTKM_IS_TOPOLOGY_ELEMENT_TAG(TopologyElement); VTKM_IS_TOPOLOGY_ELEMENT_TAG(TopologyElement);
return this->Structure.GetSchedulingRange(TopologyElement()); return this->Structure.GetSchedulingRange(TopologyElement());
} }
template<vtkm::IdComponent DIMENSION> template <vtkm::IdComponent DIMENSION>
template<typename DeviceAdapter, typename FromTopology, typename ToTopology> template <typename DeviceAdapter, typename FromTopology, typename ToTopology>
typename CellSetStructured<DIMENSION>::template ExecutionTypes<DeviceAdapter,FromTopology,ToTopology>::ExecObjectType typename CellSetStructured<DIMENSION>::template ExecutionTypes<DeviceAdapter, FromTopology,
CellSetStructured<DIMENSION>::PrepareForInput(DeviceAdapter, FromTopology, ToTopology) const ToTopology>::ExecObjectType
CellSetStructured<DIMENSION>::PrepareForInput(DeviceAdapter, FromTopology, ToTopology) const
{ {
typedef typename typedef typename ExecutionTypes<DeviceAdapter, FromTopology, ToTopology>::ExecObjectType
ExecutionTypes<DeviceAdapter,FromTopology,ToTopology>::ExecObjectType ConnectivityType;
ConnectivityType;
return ConnectivityType(this->Structure); return ConnectivityType(this->Structure);
} }
template<vtkm::IdComponent DIMENSION> template <vtkm::IdComponent DIMENSION>
void CellSetStructured<DIMENSION>::PrintSummary(std::ostream &out) const void CellSetStructured<DIMENSION>::PrintSummary(std::ostream& out) const
{ {
out << " StructuredCellSet: " << this->GetName() << std::endl; out << " StructuredCellSet: " << this->GetName() << std::endl;
this->Structure.PrintSummary(out); this->Structure.PrintSummary(out);
} }
} }
} }

@ -20,32 +20,30 @@
#include <vtkm/cont/CoordinateSystem.h> #include <vtkm/cont/CoordinateSystem.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
VTKM_CONT VTKM_CONT
void CoordinateSystem::PrintSummary(std::ostream &out) const void CoordinateSystem::PrintSummary(std::ostream& out) const
{ {
out << " Coordinate System "; out << " Coordinate System ";
this->Superclass::PrintSummary(out); this->Superclass::PrintSummary(out);
} }
VTKM_CONT VTKM_CONT
void CoordinateSystem::GetRange(vtkm::Range *range) const void CoordinateSystem::GetRange(vtkm::Range* range) const
{ {
this->Superclass::GetRange( this->Superclass::GetRange(range, VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG(),
range, VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG(),
VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
} }
VTKM_CONT VTKM_CONT
const vtkm::cont::ArrayHandle<vtkm::Range>& const vtkm::cont::ArrayHandle<vtkm::Range>& CoordinateSystem::GetRange() const
CoordinateSystem::GetRange() const
{ {
return this->Superclass::GetRange( return this->Superclass::GetRange(VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG(),
VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG(), VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
} }
VTKM_CONT VTKM_CONT
@ -54,6 +52,5 @@ vtkm::Bounds CoordinateSystem::GetBounds() const
return this->GetBounds(VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG(), return this->GetBounds(VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG(),
VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG()); VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
} }
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -28,31 +28,29 @@
#include <vtkm/cont/Field.h> #include <vtkm/cont/Field.h>
#ifndef VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG #ifndef VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG
#define VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG \ #define VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG ::vtkm::TypeListTagFieldVec3
::vtkm::TypeListTagFieldVec3
#endif #endif
#ifndef VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG #ifndef VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG
#define VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG \ #define VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG \
::vtkm::cont::StorageListTagCoordinateSystemDefault ::vtkm::cont::StorageListTagCoordinateSystemDefault
#endif #endif
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
namespace detail { namespace detail
{
typedef vtkm::cont::ArrayHandleCompositeVectorType< typedef vtkm::cont::ArrayHandleCompositeVectorType<
vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::ArrayHandle<vtkm::Float32>,
vtkm::cont::ArrayHandle<vtkm::Float32>, vtkm::cont::ArrayHandle<vtkm::Float32>>::type ArrayHandleCompositeVectorFloat32_3Default;
vtkm::cont::ArrayHandle<vtkm::Float32> >::type
ArrayHandleCompositeVectorFloat32_3Default;
typedef vtkm::cont::ArrayHandleCompositeVectorType< typedef vtkm::cont::ArrayHandleCompositeVectorType<
vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::ArrayHandle<vtkm::Float64>,
vtkm::cont::ArrayHandle<vtkm::Float64>, vtkm::cont::ArrayHandle<vtkm::Float64>>::type ArrayHandleCompositeVectorFloat64_3Default;
vtkm::cont::ArrayHandle<vtkm::Float64> >::type
ArrayHandleCompositeVectorFloat64_3Default;
} // namespace detail } // namespace detail
@ -62,20 +60,18 @@ typedef vtkm::cont::ArrayHandleCompositeVectorType<
/// by default (unless it is defined before including VTK-m headers. /// by default (unless it is defined before including VTK-m headers.
/// ///
struct StorageListTagCoordinateSystemDefault struct StorageListTagCoordinateSystemDefault
: vtkm::ListTagBase< : vtkm::ListTagBase<
vtkm::cont::StorageTagBasic, vtkm::cont::StorageTagBasic, vtkm::cont::ArrayHandleUniformPointCoordinates::StorageTag,
vtkm::cont::ArrayHandleUniformPointCoordinates::StorageTag, detail::ArrayHandleCompositeVectorFloat32_3Default::StorageTag,
detail::ArrayHandleCompositeVectorFloat32_3Default::StorageTag, detail::ArrayHandleCompositeVectorFloat64_3Default::StorageTag,
detail::ArrayHandleCompositeVectorFloat64_3Default::StorageTag, vtkm::cont::ArrayHandleCartesianProduct<
vtkm::cont::ArrayHandleCartesianProduct< vtkm::cont::ArrayHandle<vtkm::FloatDefault>, vtkm::cont::ArrayHandle<vtkm::FloatDefault>,
vtkm::cont::ArrayHandle<vtkm::FloatDefault>, vtkm::cont::ArrayHandle<vtkm::FloatDefault>>::StorageTag>
vtkm::cont::ArrayHandle<vtkm::FloatDefault>, {
vtkm::cont::ArrayHandle<vtkm::FloatDefault> >::StorageTag > };
{ };
typedef vtkm::cont::DynamicArrayHandleBase< typedef vtkm::cont::DynamicArrayHandleBase<VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG,
VTKM_DEFAULT_COORDINATE_SYSTEM_TYPE_LIST_TAG, VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG>
VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG>
DynamicArrayHandleCoordinateSystem; DynamicArrayHandleCoordinateSystem;
class VTKM_CONT_EXPORT CoordinateSystem : public vtkm::cont::Field class VTKM_CONT_EXPORT CoordinateSystem : public vtkm::cont::Field
@ -84,164 +80,145 @@ class VTKM_CONT_EXPORT CoordinateSystem : public vtkm::cont::Field
public: public:
VTKM_CONT VTKM_CONT
CoordinateSystem() : Superclass() { } CoordinateSystem()
: Superclass()
{
}
VTKM_CONT VTKM_CONT
CoordinateSystem(std::string name, CoordinateSystem(std::string name, const vtkm::cont::DynamicArrayHandle& data)
const vtkm::cont::DynamicArrayHandle &data) : Superclass(name, ASSOC_POINTS, data)
: Superclass(name, ASSOC_POINTS, data) { } {
}
template<typename T, typename Storage> template <typename T, typename Storage>
VTKM_CONT VTKM_CONT CoordinateSystem(std::string name, const ArrayHandle<T, Storage>& data)
CoordinateSystem(std::string name, : Superclass(name, ASSOC_POINTS, data)
const ArrayHandle<T, Storage> &data) {
: Superclass(name, ASSOC_POINTS, data) { } }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT CoordinateSystem(std::string name, const std::vector<T>& data)
CoordinateSystem(std::string name, : Superclass(name, ASSOC_POINTS, data)
const std::vector<T> &data) {
: Superclass(name, ASSOC_POINTS, data) { } }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT CoordinateSystem(std::string name, const T* data, vtkm::Id numberOfValues)
CoordinateSystem(std::string name, : Superclass(name, ASSOC_POINTS, data, numberOfValues)
const T *data, {
vtkm::Id numberOfValues) }
: Superclass(name, ASSOC_POINTS, data, numberOfValues) { }
/// This constructor of coordinate system sets up a regular grid of points. /// This constructor of coordinate system sets up a regular grid of points.
/// ///
VTKM_CONT VTKM_CONT
CoordinateSystem(std::string name, CoordinateSystem(
vtkm::Id3 dimensions, std::string name, vtkm::Id3 dimensions,
vtkm::Vec<vtkm::FloatDefault,3> origin vtkm::Vec<vtkm::FloatDefault, 3> origin = vtkm::Vec<vtkm::FloatDefault, 3>(0.0f, 0.0f, 0.0f),
= vtkm::Vec<vtkm::FloatDefault,3>(0.0f, 0.0f, 0.0f), vtkm::Vec<vtkm::FloatDefault, 3> spacing = vtkm::Vec<vtkm::FloatDefault, 3>(1.0f, 1.0f, 1.0f))
vtkm::Vec<vtkm::FloatDefault,3> spacing : Superclass(name, ASSOC_POINTS,
= vtkm::Vec<vtkm::FloatDefault,3>(1.0f, 1.0f, 1.0f))
: Superclass(name,
ASSOC_POINTS,
vtkm::cont::DynamicArrayHandle( vtkm::cont::DynamicArrayHandle(
vtkm::cont::ArrayHandleUniformPointCoordinates(dimensions, origin, spacing))) vtkm::cont::ArrayHandleUniformPointCoordinates(dimensions, origin, spacing)))
{ } {
}
VTKM_CONT VTKM_CONT
CoordinateSystem &operator=(const vtkm::cont::CoordinateSystem &src) = default; CoordinateSystem& operator=(const vtkm::cont::CoordinateSystem& src) = default;
VTKM_CONT VTKM_CONT
vtkm::cont::DynamicArrayHandleCoordinateSystem GetData() const vtkm::cont::DynamicArrayHandleCoordinateSystem GetData() const
{ {
return vtkm::cont::DynamicArrayHandleCoordinateSystem( return vtkm::cont::DynamicArrayHandleCoordinateSystem(this->Superclass::GetData());
this->Superclass::GetData());
} }
VTKM_CONT VTKM_CONT
vtkm::cont::DynamicArrayHandleCoordinateSystem GetData() vtkm::cont::DynamicArrayHandleCoordinateSystem GetData()
{ {
return vtkm::cont::DynamicArrayHandleCoordinateSystem( return vtkm::cont::DynamicArrayHandleCoordinateSystem(this->Superclass::GetData());
this->Superclass::GetData());
} }
VTKM_CONT VTKM_CONT
void GetRange(vtkm::Range *range) const; void GetRange(vtkm::Range* range) const;
template<typename TypeList> template <typename TypeList>
VTKM_CONT VTKM_CONT void GetRange(vtkm::Range* range, TypeList) const
void GetRange(vtkm::Range *range, TypeList) const
{ {
VTKM_IS_LIST_TAG(TypeList); VTKM_IS_LIST_TAG(TypeList);
this->Superclass::GetRange( this->Superclass::GetRange(range, TypeList(),
range, VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
TypeList(),
VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
} }
template<typename TypeList, typename StorageList> template <typename TypeList, typename StorageList>
VTKM_CONT VTKM_CONT void GetRange(vtkm::Range* range, TypeList, StorageList) const
void GetRange(vtkm::Range *range, TypeList, StorageList) const
{ {
VTKM_IS_LIST_TAG(TypeList); VTKM_IS_LIST_TAG(TypeList);
VTKM_IS_LIST_TAG(StorageList); VTKM_IS_LIST_TAG(StorageList);
this->Superclass::GetRange( this->Superclass::GetRange(range, TypeList(), StorageList());
range,
TypeList(),
StorageList());
} }
VTKM_CONT VTKM_CONT
const vtkm::cont::ArrayHandle<vtkm::Range>& GetRange() const; const vtkm::cont::ArrayHandle<vtkm::Range>& GetRange() const;
template<typename TypeList> template <typename TypeList>
VTKM_CONT VTKM_CONT const vtkm::cont::ArrayHandle<vtkm::Range>& GetRange(TypeList) const
const vtkm::cont::ArrayHandle<vtkm::Range>& GetRange(TypeList) const
{ {
VTKM_IS_LIST_TAG(TypeList); VTKM_IS_LIST_TAG(TypeList);
return this->Superclass::GetRange( return this->Superclass::GetRange(TypeList(),
TypeList(), VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
} }
template<typename TypeList, typename StorageList> template <typename TypeList, typename StorageList>
VTKM_CONT VTKM_CONT const vtkm::cont::ArrayHandle<vtkm::Range>& GetRange(TypeList, StorageList) const
const vtkm::cont::ArrayHandle<vtkm::Range>& GetRange(TypeList,
StorageList) const
{ {
VTKM_IS_LIST_TAG(TypeList); VTKM_IS_LIST_TAG(TypeList);
VTKM_IS_LIST_TAG(StorageList); VTKM_IS_LIST_TAG(StorageList);
return this->Superclass::GetRange( return this->Superclass::GetRange(TypeList(), StorageList());
TypeList(),
StorageList());
} }
VTKM_CONT VTKM_CONT
vtkm::Bounds GetBounds() const; vtkm::Bounds GetBounds() const;
template<typename TypeList> template <typename TypeList>
VTKM_CONT VTKM_CONT vtkm::Bounds GetBounds(TypeList) const
vtkm::Bounds GetBounds(TypeList) const
{ {
VTKM_IS_LIST_TAG(TypeList); VTKM_IS_LIST_TAG(TypeList);
return this->GetBounds(TypeList(), return this->GetBounds(TypeList(), VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
VTKM_DEFAULT_COORDINATE_SYSTEM_STORAGE_LIST_TAG());
} }
template<typename TypeList, typename StorageList> template <typename TypeList, typename StorageList>
VTKM_CONT VTKM_CONT vtkm::Bounds GetBounds(TypeList, StorageList) const
vtkm::Bounds GetBounds(TypeList, StorageList) const
{ {
VTKM_IS_LIST_TAG(TypeList); VTKM_IS_LIST_TAG(TypeList);
VTKM_IS_LIST_TAG(StorageList); VTKM_IS_LIST_TAG(StorageList);
vtkm::cont::ArrayHandle<vtkm::Range> ranges = vtkm::cont::ArrayHandle<vtkm::Range> ranges = this->GetRange(TypeList(), StorageList());
this->GetRange(TypeList(), StorageList());
VTKM_ASSERT(ranges.GetNumberOfValues() == 3); VTKM_ASSERT(ranges.GetNumberOfValues() == 3);
vtkm::cont::ArrayHandle<vtkm::Range>::PortalConstControl rangePortal = vtkm::cont::ArrayHandle<vtkm::Range>::PortalConstControl rangePortal =
ranges.GetPortalConstControl(); ranges.GetPortalConstControl();
return vtkm::Bounds(rangePortal.Get(0), return vtkm::Bounds(rangePortal.Get(0), rangePortal.Get(1), rangePortal.Get(2));
rangePortal.Get(1),
rangePortal.Get(2));
} }
virtual void PrintSummary(std::ostream &out) const; virtual void PrintSummary(std::ostream& out) const;
}; };
template<typename Functor> template <typename Functor>
void CastAndCall(const vtkm::cont::CoordinateSystem& coords, const Functor &f) void CastAndCall(const vtkm::cont::CoordinateSystem& coords, const Functor& f)
{ {
coords.GetData().CastAndCall(f); coords.GetData().CastAndCall(f);
} }
namespace internal { namespace internal
{
template<> template <>
struct DynamicTransformTraits<vtkm::cont::CoordinateSystem> struct DynamicTransformTraits<vtkm::cont::CoordinateSystem>
{ {
typedef vtkm::cont::internal::DynamicTransformTagCastAndCall DynamicTag; typedef vtkm::cont::internal::DynamicTransformTagCastAndCall DynamicTag;
@ -251,5 +228,4 @@ struct DynamicTransformTraits<vtkm::cont::CoordinateSystem>
} // namespace cont } // namespace cont
} // namespace vtkm } // namespace vtkm
#endif //vtk_m_cont_CoordinateSystem_h #endif //vtk_m_cont_CoordinateSystem_h

@ -28,16 +28,16 @@
#include <vtkm/cont/ErrorBadValue.h> #include <vtkm/cont/ErrorBadValue.h>
#include <vtkm/cont/Field.h> #include <vtkm/cont/Field.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
class DataSet class DataSet
{ {
public: public:
VTKM_CONT VTKM_CONT
DataSet() DataSet() {}
{
}
VTKM_CONT VTKM_CONT
void Clear() void Clear()
@ -48,24 +48,18 @@ public:
} }
VTKM_CONT VTKM_CONT
void AddField(Field field) void AddField(Field field) { this->Fields.push_back(field); }
{
this->Fields.push_back(field);
}
VTKM_CONT VTKM_CONT
const vtkm::cont::Field &GetField(vtkm::Id index) const const vtkm::cont::Field& GetField(vtkm::Id index) const
{ {
VTKM_ASSERT((index >= 0) && VTKM_ASSERT((index >= 0) && (index < this->GetNumberOfFields()));
(index < this->GetNumberOfFields()));
return this->Fields[static_cast<std::size_t>(index)]; return this->Fields[static_cast<std::size_t>(index)];
} }
VTKM_CONT VTKM_CONT
bool HasField( bool HasField(const std::string& name,
const std::string &name, vtkm::cont::Field::AssociationEnum assoc = vtkm::cont::Field::ASSOC_ANY) const
vtkm::cont::Field::AssociationEnum assoc = vtkm::cont::Field::ASSOC_ANY)
const
{ {
bool found; bool found;
this->FindFieldIndex(name, assoc, found); this->FindFieldIndex(name, assoc, found);
@ -73,10 +67,8 @@ public:
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetFieldIndex( vtkm::Id GetFieldIndex(const std::string& name, vtkm::cont::Field::AssociationEnum assoc =
const std::string &name, vtkm::cont::Field::ASSOC_ANY) const
vtkm::cont::Field::AssociationEnum assoc = vtkm::cont::Field::ASSOC_ANY)
const
{ {
bool found; bool found;
vtkm::Id index = this->FindFieldIndex(name, assoc, found); vtkm::Id index = this->FindFieldIndex(name, assoc, found);
@ -86,48 +78,42 @@ public:
} }
else else
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("No field with requested name: " + name);
"No field with requested name: " + name);
} }
} }
VTKM_CONT VTKM_CONT
const vtkm::cont::Field &GetField(const std::string &name, const vtkm::cont::Field& GetField(
vtkm::cont::Field::AssociationEnum assoc = vtkm::cont::Field::ASSOC_ANY) const std::string& name,
const vtkm::cont::Field::AssociationEnum assoc = vtkm::cont::Field::ASSOC_ANY) const
{ {
return this->GetField(this->GetFieldIndex(name, assoc)); return this->GetField(this->GetFieldIndex(name, assoc));
} }
VTKM_CONT VTKM_CONT
const vtkm::cont::Field &GetCellField(const std::string &name) const const vtkm::cont::Field& GetCellField(const std::string& name) const
{ {
return this->GetField(name, vtkm::cont::Field::ASSOC_CELL_SET); return this->GetField(name, vtkm::cont::Field::ASSOC_CELL_SET);
} }
VTKM_CONT VTKM_CONT
const vtkm::cont::Field &GetPointField(const std::string &name) const const vtkm::cont::Field& GetPointField(const std::string& name) const
{ {
return this->GetField(name, vtkm::cont::Field::ASSOC_POINTS); return this->GetField(name, vtkm::cont::Field::ASSOC_POINTS);
} }
VTKM_CONT VTKM_CONT
void AddCoordinateSystem(vtkm::cont::CoordinateSystem cs) void AddCoordinateSystem(vtkm::cont::CoordinateSystem cs) { this->CoordSystems.push_back(cs); }
{
this->CoordSystems.push_back(cs);
}
VTKM_CONT VTKM_CONT
const vtkm::cont::CoordinateSystem & const vtkm::cont::CoordinateSystem& GetCoordinateSystem(vtkm::Id index = 0) const
GetCoordinateSystem(vtkm::Id index=0) const
{ {
VTKM_ASSERT((index >= 0) && VTKM_ASSERT((index >= 0) && (index < this->GetNumberOfCoordinateSystems()));
(index < this->GetNumberOfCoordinateSystems()));
return this->CoordSystems[static_cast<std::size_t>(index)]; return this->CoordSystems[static_cast<std::size_t>(index)];
} }
VTKM_CONT VTKM_CONT
bool HasCoordinateSystem(const std::string &name) const bool HasCoordinateSystem(const std::string& name) const
{ {
bool found; bool found;
this->FindCoordinateSystemIndex(name, found); this->FindCoordinateSystemIndex(name, found);
@ -135,7 +121,7 @@ public:
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetCoordinateSystemIndex(const std::string &name) const vtkm::Id GetCoordinateSystemIndex(const std::string& name) const
{ {
bool found; bool found;
vtkm::Id index = this->FindCoordinateSystemIndex(name, found); vtkm::Id index = this->FindCoordinateSystemIndex(name, found);
@ -145,42 +131,35 @@ public:
} }
else else
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("No coordinate system with requested name");
"No coordinate system with requested name");
} }
} }
VTKM_CONT VTKM_CONT
const vtkm::cont::CoordinateSystem & const vtkm::cont::CoordinateSystem& GetCoordinateSystem(const std::string& name) const
GetCoordinateSystem(const std::string &name) const
{ {
return this->GetCoordinateSystem(this->GetCoordinateSystemIndex(name)); return this->GetCoordinateSystem(this->GetCoordinateSystemIndex(name));
} }
VTKM_CONT VTKM_CONT
void AddCellSet(vtkm::cont::DynamicCellSet cellSet) void AddCellSet(vtkm::cont::DynamicCellSet cellSet) { this->CellSets.push_back(cellSet); }
{
this->CellSets.push_back(cellSet);
}
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT void AddCellSet(const CellSetType& cellSet)
void AddCellSet(const CellSetType &cellSet)
{ {
VTKM_IS_CELL_SET(CellSetType); VTKM_IS_CELL_SET(CellSetType);
this->CellSets.push_back(vtkm::cont::DynamicCellSet(cellSet)); this->CellSets.push_back(vtkm::cont::DynamicCellSet(cellSet));
} }
VTKM_CONT VTKM_CONT
vtkm::cont::DynamicCellSet GetCellSet(vtkm::Id index=0) const vtkm::cont::DynamicCellSet GetCellSet(vtkm::Id index = 0) const
{ {
VTKM_ASSERT((index >= 0) && VTKM_ASSERT((index >= 0) && (index < this->GetNumberOfCellSets()));
(index < this->GetNumberOfCellSets()));
return this->CellSets[static_cast<std::size_t>(index)]; return this->CellSets[static_cast<std::size_t>(index)];
} }
VTKM_CONT VTKM_CONT
bool HasCellSet(const std::string &name) const bool HasCellSet(const std::string& name) const
{ {
bool found; bool found;
this->FindCellSetIndex(name, found); this->FindCellSetIndex(name, found);
@ -188,7 +167,7 @@ public:
} }
VTKM_CONT VTKM_CONT
vtkm::Id GetCellSetIndex(const std::string &name) const vtkm::Id GetCellSetIndex(const std::string& name) const
{ {
bool found; bool found;
vtkm::Id index = this->FindCellSetIndex(name, found); vtkm::Id index = this->FindCellSetIndex(name, found);
@ -203,7 +182,7 @@ public:
} }
VTKM_CONT VTKM_CONT
vtkm::cont::DynamicCellSet GetCellSet(const std::string &name) const vtkm::cont::DynamicCellSet GetCellSet(const std::string& name) const
{ {
return this->GetCellSet(this->GetCellSetIndex(name)); return this->GetCellSet(this->GetCellSetIndex(name));
} }
@ -227,26 +206,26 @@ public:
} }
VTKM_CONT VTKM_CONT
void PrintSummary(std::ostream &out) const void PrintSummary(std::ostream& out) const
{ {
out<<"DataSet:\n"; out << "DataSet:\n";
out<<" CoordSystems["<<this->CoordSystems.size()<<"]\n"; out << " CoordSystems[" << this->CoordSystems.size() << "]\n";
for (std::size_t index = 0; index < this->CoordSystems.size(); index++) for (std::size_t index = 0; index < this->CoordSystems.size(); index++)
{ {
this->CoordSystems[index].PrintSummary(out); this->CoordSystems[index].PrintSummary(out);
} }
out<<" CellSets["<<this->GetNumberOfCellSets()<<"]\n"; out << " CellSets[" << this->GetNumberOfCellSets() << "]\n";
for (vtkm::Id index = 0; index < this->GetNumberOfCellSets(); index++) for (vtkm::Id index = 0; index < this->GetNumberOfCellSets(); index++)
{ {
this->GetCellSet(index).PrintSummary(out); this->GetCellSet(index).PrintSummary(out);
} }
out<<" Fields["<<this->GetNumberOfFields()<<"]\n"; out << " Fields[" << this->GetNumberOfFields() << "]\n";
for (vtkm::Id index = 0; index < this->GetNumberOfFields(); index++) for (vtkm::Id index = 0; index < this->GetNumberOfFields(); index++)
{ {
this->GetField(index).PrintSummary(out); this->GetField(index).PrintSummary(out);
} }
} }
private: private:
@ -255,17 +234,16 @@ private:
std::vector<vtkm::cont::DynamicCellSet> CellSets; std::vector<vtkm::cont::DynamicCellSet> CellSets;
VTKM_CONT VTKM_CONT
vtkm::Id FindFieldIndex(const std::string &name, vtkm::Id FindFieldIndex(const std::string& name, vtkm::cont::Field::AssociationEnum association,
vtkm::cont::Field::AssociationEnum association, bool& found) const
bool &found) const
{ {
for (std::size_t index=0; index < this->Fields.size(); ++index) for (std::size_t index = 0; index < this->Fields.size(); ++index)
{ {
if ((association == vtkm::cont::Field::ASSOC_ANY || if ((association == vtkm::cont::Field::ASSOC_ANY ||
association == this->Fields[index].GetAssociation()) && association == this->Fields[index].GetAssociation()) &&
this->Fields[index].GetName() == name) this->Fields[index].GetName() == name)
{ {
found= true; found = true;
return static_cast<vtkm::Id>(index); return static_cast<vtkm::Id>(index);
} }
} }
@ -274,9 +252,9 @@ private:
} }
VTKM_CONT VTKM_CONT
vtkm::Id FindCoordinateSystemIndex(const std::string &name, bool &found) const vtkm::Id FindCoordinateSystemIndex(const std::string& name, bool& found) const
{ {
for (std::size_t index=0; index < this->CoordSystems.size(); ++index) for (std::size_t index = 0; index < this->CoordSystems.size(); ++index)
{ {
if (this->CoordSystems[index].GetName() == name) if (this->CoordSystems[index].GetName() == name)
{ {
@ -289,9 +267,9 @@ private:
} }
VTKM_CONT VTKM_CONT
vtkm::Id FindCellSetIndex(const std::string &name, bool &found) const vtkm::Id FindCellSetIndex(const std::string& name, bool& found) const
{ {
for (std::size_t index=0; index < static_cast<size_t>(this->GetNumberOfCellSets()); ++index) for (std::size_t index = 0; index < static_cast<size_t>(this->GetNumberOfCellSets()); ++index)
{ {
if (this->CellSets[index].GetName() == name) if (this->CellSets[index].GetName() == name)
{ {
@ -307,5 +285,4 @@ private:
} // namespace cont } // namespace cont
} // namespace vtkm } // namespace vtkm
#endif //vtk_m_cont_DataSet_h #endif //vtk_m_cont_DataSet_h

@ -25,24 +25,23 @@
#include <vtkm/cont/CoordinateSystem.h> #include <vtkm/cont/CoordinateSystem.h>
#include <vtkm/cont/DataSet.h> #include <vtkm/cont/DataSet.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
//Coordinates builder?? //Coordinates builder??
//Need a singlecellset handler. //Need a singlecellset handler.
class DataSetBuilderExplicit class DataSetBuilderExplicit
{ {
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static void CopyInto(const std::vector<T>& input, vtkm::cont::ArrayHandle<T>& output)
static
void CopyInto(const std::vector<T>& input,
vtkm::cont::ArrayHandle<T>& output )
{ {
output.Allocate( static_cast<vtkm::Id>(input.size()) ); output.Allocate(static_cast<vtkm::Id>(input.size()));
std::copy( input.begin(), input.end(), std::copy(input.begin(), input.end(), ArrayPortalToIteratorBegin(output.GetPortalControl()));
ArrayPortalToIteratorBegin(output.GetPortalControl()) );
} }
public: public:
VTKM_CONT VTKM_CONT
DataSetBuilderExplicit() {} DataSetBuilderExplicit() {}
@ -51,185 +50,121 @@ public:
//TODO //TODO
//Zoo explicit cell //Zoo explicit cell
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const std::vector<T>& xVals,
static const std::vector<vtkm::UInt8>& shapes,
vtkm::cont::DataSet const std::vector<vtkm::IdComponent>& numIndices,
Create(const std::vector<T> &xVals, const std::vector<vtkm::Id>& connectivity,
const std::vector<vtkm::UInt8> &shapes, const std::string& coordsNm = "coords",
const std::vector<vtkm::IdComponent> &numIndices, const std::string& cellNm = "cells")
const std::vector<vtkm::Id> &connectivity,
const std::string &coordsNm="coords",
const std::string &cellNm="cells")
{ {
std::vector<T> yVals(xVals.size(),0), zVals(xVals.size(),0); std::vector<T> yVals(xVals.size(), 0), zVals(xVals.size(), 0);
return DataSetBuilderExplicit::Create(xVals,yVals,zVals, return DataSetBuilderExplicit::Create(xVals, yVals, zVals, shapes, numIndices, connectivity,
shapes,numIndices,connectivity, coordsNm, cellNm);
coordsNm,cellNm);
}
template<typename T>
VTKM_CONT
static
vtkm::cont::DataSet
Create(const std::vector<T> &xVals,
const std::vector<T> &yVals,
const std::vector<vtkm::UInt8> &shapes,
const std::vector<vtkm::IdComponent> &numIndices,
const std::vector<vtkm::Id> &connectivity,
const std::string &coordsNm="coords",
const std::string &cellNm="cells")
{
std::vector<T> zVals(xVals.size(),0);
return DataSetBuilderExplicit::Create(xVals,yVals,zVals,
shapes,numIndices,connectivity,
coordsNm,cellNm);
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const std::vector<T>& xVals,
static const std::vector<T>& yVals,
vtkm::cont::DataSet const std::vector<vtkm::UInt8>& shapes,
Create(const std::vector<T> &xVals, const std::vector<vtkm::IdComponent>& numIndices,
const std::vector<T> &yVals, const std::vector<vtkm::Id>& connectivity,
const std::vector<T> &zVals, const std::string& coordsNm = "coords",
const std::vector<vtkm::UInt8> &shapes, const std::string& cellNm = "cells")
const std::vector<vtkm::IdComponent> &numIndices,
const std::vector<vtkm::Id> &connectivity,
const std::string &coordsNm="coords",
const std::string &cellNm="cells");
template<typename T>
VTKM_CONT
static
vtkm::cont::DataSet
Create(const vtkm::cont::ArrayHandle<T> &xVals,
const vtkm::cont::ArrayHandle<T> &yVals,
const vtkm::cont::ArrayHandle<T> &zVals,
const vtkm::cont::ArrayHandle<vtkm::UInt8> &shapes,
const vtkm::cont::ArrayHandle<vtkm::IdComponent> &numIndices,
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity,
const std::string &coordsNm="coords",
const std::string &cellNm="cells")
{ {
return DataSetBuilderExplicit::BuildDataSet( std::vector<T> zVals(xVals.size(), 0);
xVals,yVals,zVals, return DataSetBuilderExplicit::Create(xVals, yVals, zVals, shapes, numIndices, connectivity,
shapes,numIndices,connectivity, coordsNm, cellNm);
coordsNm,cellNm);
} }
template <typename T>
VTKM_CONT static vtkm::cont::DataSet Create(
const std::vector<T>& xVals, const std::vector<T>& yVals, const std::vector<T>& zVals,
const std::vector<vtkm::UInt8>& shapes, const std::vector<vtkm::IdComponent>& numIndices,
const std::vector<vtkm::Id>& connectivity, const std::string& coordsNm = "coords",
const std::string& cellNm = "cells");
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(
static const vtkm::cont::ArrayHandle<T>& xVals, const vtkm::cont::ArrayHandle<T>& yVals,
vtkm::cont::DataSet const vtkm::cont::ArrayHandle<T>& zVals, const vtkm::cont::ArrayHandle<vtkm::UInt8>& shapes,
Create(const std::vector<vtkm::Vec<T,3> > &coords, const vtkm::cont::ArrayHandle<vtkm::IdComponent>& numIndices,
const std::vector<vtkm::UInt8> &shapes, const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity, const std::string& coordsNm = "coords",
const std::vector<vtkm::IdComponent> &numIndices, const std::string& cellNm = "cells")
const std::vector<vtkm::Id> &connectivity,
const std::string &coordsNm="coords",
const std::string &cellNm="cells");
template<typename T>
VTKM_CONT
static
vtkm::cont::DataSet
Create(const vtkm::cont::ArrayHandle<vtkm::Vec<T,3> > &coords,
const vtkm::cont::ArrayHandle<vtkm::UInt8> &shapes,
const vtkm::cont::ArrayHandle<vtkm::IdComponent> &numIndices,
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity,
const std::string &coordsNm="coords",
const std::string &cellNm="cells")
{ {
return DataSetBuilderExplicit::BuildDataSet(coords, return DataSetBuilderExplicit::BuildDataSet(xVals, yVals, zVals, shapes, numIndices,
shapes, connectivity, coordsNm, cellNm);
numIndices, }
connectivity,
coordsNm, template <typename T>
VTKM_CONT static vtkm::cont::DataSet Create(const std::vector<vtkm::Vec<T, 3>>& coords,
const std::vector<vtkm::UInt8>& shapes,
const std::vector<vtkm::IdComponent>& numIndices,
const std::vector<vtkm::Id>& connectivity,
const std::string& coordsNm = "coords",
const std::string& cellNm = "cells");
template <typename T>
VTKM_CONT static vtkm::cont::DataSet Create(
const vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>>& coords,
const vtkm::cont::ArrayHandle<vtkm::UInt8>& shapes,
const vtkm::cont::ArrayHandle<vtkm::IdComponent>& numIndices,
const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity, const std::string& coordsNm = "coords",
const std::string& cellNm = "cells")
{
return DataSetBuilderExplicit::BuildDataSet(coords, shapes, numIndices, connectivity, coordsNm,
cellNm); cellNm);
} }
template<typename T, typename CellShapeTag> template <typename T, typename CellShapeTag>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const std::vector<vtkm::Vec<T, 3>>& coords,
static CellShapeTag tag,
vtkm::cont::DataSet vtkm::IdComponent numberOfPointsPerCell,
Create(const std::vector<vtkm::Vec<T,3> > &coords, const std::vector<vtkm::Id>& connectivity,
CellShapeTag tag, const std::string& coordsNm = "coords",
vtkm::IdComponent numberOfPointsPerCell, const std::string& cellNm = "cells");
const std::vector<vtkm::Id> &connectivity,
const std::string &coordsNm="coords",
const std::string &cellNm="cells");
template<typename T, typename CellShapeTag> template <typename T, typename CellShapeTag>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(
static const vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>>& coords, CellShapeTag tag,
vtkm::cont::DataSet vtkm::IdComponent numberOfPointsPerCell, const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity,
Create(const vtkm::cont::ArrayHandle<vtkm::Vec<T,3> > &coords, const std::string& coordsNm = "coords", const std::string& cellNm = "cells")
CellShapeTag tag,
vtkm::IdComponent numberOfPointsPerCell,
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity,
const std::string &coordsNm="coords",
const std::string &cellNm="cells")
{ {
return DataSetBuilderExplicit::BuildDataSet(coords, return DataSetBuilderExplicit::BuildDataSet(coords, tag, numberOfPointsPerCell, connectivity,
tag, coordsNm, cellNm);
numberOfPointsPerCell,
connectivity,
coordsNm,
cellNm);
} }
private: private:
template<typename T> template <typename T>
static static vtkm::cont::DataSet BuildDataSet(
vtkm::cont::DataSet const vtkm::cont::ArrayHandle<T>& X, const vtkm::cont::ArrayHandle<T>& Y,
BuildDataSet(const vtkm::cont::ArrayHandle<T> &X, const vtkm::cont::ArrayHandle<T>& Z, const vtkm::cont::ArrayHandle<vtkm::UInt8>& shapes,
const vtkm::cont::ArrayHandle<T> &Y, const vtkm::cont::ArrayHandle<vtkm::IdComponent>& numIndices,
const vtkm::cont::ArrayHandle<T> &Z, const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity, const std::string& coordsNm,
const vtkm::cont::ArrayHandle<vtkm::UInt8> &shapes, const std::string& cellNm);
const vtkm::cont::ArrayHandle<vtkm::IdComponent> &numIndices,
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity,
const std::string &coordsNm,
const std::string &cellNm);
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet BuildDataSet(
static const vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>>& coords,
vtkm::cont::DataSet const vtkm::cont::ArrayHandle<vtkm::UInt8>& shapes,
BuildDataSet(const vtkm::cont::ArrayHandle<vtkm::Vec<T,3> > &coords, const vtkm::cont::ArrayHandle<vtkm::IdComponent>& numIndices,
const vtkm::cont::ArrayHandle<vtkm::UInt8> &shapes, const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity, const std::string& coordsNm,
const vtkm::cont::ArrayHandle<vtkm::IdComponent> &numIndices, const std::string& cellNm);
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity,
const std::string &coordsNm,
const std::string &cellNm);
template<typename T, typename CellShapeTag> template <typename T, typename CellShapeTag>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet BuildDataSet(
static const vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>>& coords, CellShapeTag tag,
vtkm::cont::DataSet vtkm::IdComponent numberOfPointsPerCell, const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity,
BuildDataSet(const vtkm::cont::ArrayHandle<vtkm::Vec<T,3> > &coords, const std::string& coordsNm, const std::string& cellNm);
CellShapeTag tag,
vtkm::IdComponent numberOfPointsPerCell,
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity,
const std::string &coordsNm,
const std::string &cellNm);
}; };
template<typename T> template <typename T>
inline VTKM_CONT inline VTKM_CONT vtkm::cont::DataSet DataSetBuilderExplicit::Create(
vtkm::cont::DataSet const std::vector<T>& xVals, const std::vector<T>& yVals, const std::vector<T>& zVals,
DataSetBuilderExplicit::Create(const std::vector<T> &xVals, const std::vector<vtkm::UInt8>& shapes, const std::vector<vtkm::IdComponent>& numIndices,
const std::vector<T> &yVals, const std::vector<vtkm::Id>& connectivity, const std::string& coordsNm, const std::string& cellNm)
const std::vector<T> &zVals,
const std::vector<vtkm::UInt8> &shapes,
const std::vector<vtkm::IdComponent> &numIndices,
const std::vector<vtkm::Id> &connectivity,
const std::string &coordsNm,
const std::string &cellNm)
{ {
VTKM_ASSERT(xVals.size() == yVals.size() && VTKM_ASSERT(xVals.size() == yVals.size() && yVals.size() == zVals.size() && xVals.size() > 0);
yVals.size() == zVals.size() &&
xVals.size() > 0);
vtkm::cont::ArrayHandle<T> Xc, Yc, Zc; vtkm::cont::ArrayHandle<T> Xc, Yc, Zc;
DataSetBuilderExplicit::CopyInto(xVals, Xc); DataSetBuilderExplicit::CopyInto(xVals, Xc);
@ -243,32 +178,24 @@ DataSetBuilderExplicit::Create(const std::vector<T> &xVals,
DataSetBuilderExplicit::CopyInto(numIndices, Nc); DataSetBuilderExplicit::CopyInto(numIndices, Nc);
DataSetBuilderExplicit::CopyInto(connectivity, Cc); DataSetBuilderExplicit::CopyInto(connectivity, Cc);
return DataSetBuilderExplicit::BuildDataSet( return DataSetBuilderExplicit::BuildDataSet(Xc, Yc, Zc, Sc, Nc, Cc, coordsNm, cellNm);
Xc,Yc,Zc, Sc,Nc,Cc, coordsNm, cellNm);
} }
template<typename T> template <typename T>
inline VTKM_CONT inline VTKM_CONT vtkm::cont::DataSet DataSetBuilderExplicit::BuildDataSet(
vtkm::cont::DataSet const vtkm::cont::ArrayHandle<T>& X, const vtkm::cont::ArrayHandle<T>& Y,
DataSetBuilderExplicit::BuildDataSet( const vtkm::cont::ArrayHandle<T>& Z, const vtkm::cont::ArrayHandle<vtkm::UInt8>& shapes,
const vtkm::cont::ArrayHandle<T> &X, const vtkm::cont::ArrayHandle<vtkm::IdComponent>& numIndices,
const vtkm::cont::ArrayHandle<T> &Y, const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity, const std::string& coordsNm,
const vtkm::cont::ArrayHandle<T> &Z, const std::string& cellNm)
const vtkm::cont::ArrayHandle<vtkm::UInt8> &shapes,
const vtkm::cont::ArrayHandle<vtkm::IdComponent> &numIndices,
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity,
const std::string &coordsNm,
const std::string &cellNm)
{ {
VTKM_ASSERT(X.GetNumberOfValues() == Y.GetNumberOfValues() && VTKM_ASSERT(X.GetNumberOfValues() == Y.GetNumberOfValues() &&
Y.GetNumberOfValues() == Z.GetNumberOfValues() && Y.GetNumberOfValues() == Z.GetNumberOfValues() && X.GetNumberOfValues() > 0 &&
X.GetNumberOfValues() > 0 && shapes.GetNumberOfValues() == numIndices.GetNumberOfValues());
shapes.GetNumberOfValues() == numIndices.GetNumberOfValues());
vtkm::cont::DataSet dataSet; vtkm::cont::DataSet dataSet;
dataSet.AddCoordinateSystem( dataSet.AddCoordinateSystem(
vtkm::cont::CoordinateSystem(coordsNm, vtkm::cont::CoordinateSystem(coordsNm, make_ArrayHandleCompositeVector(X, 0, Y, 0, Z, 0)));
make_ArrayHandleCompositeVector(X,0, Y,0, Z,0)));
vtkm::Id nPts = X.GetNumberOfValues(); vtkm::Id nPts = X.GetNumberOfValues();
vtkm::cont::CellSetExplicit<> cellSet(cellNm); vtkm::cont::CellSetExplicit<> cellSet(cellNm);
@ -278,17 +205,13 @@ DataSetBuilderExplicit::BuildDataSet(
return dataSet; return dataSet;
} }
template<typename T> template <typename T>
inline VTKM_CONT inline VTKM_CONT vtkm::cont::DataSet DataSetBuilderExplicit::Create(
vtkm::cont::DataSet const std::vector<vtkm::Vec<T, 3>>& coords, const std::vector<vtkm::UInt8>& shapes,
DataSetBuilderExplicit::Create(const std::vector<vtkm::Vec<T,3> > &coords, const std::vector<vtkm::IdComponent>& numIndices, const std::vector<vtkm::Id>& connectivity,
const std::vector<vtkm::UInt8> &shapes, const std::string& coordsNm, const std::string& cellNm)
const std::vector<vtkm::IdComponent> &numIndices,
const std::vector<vtkm::Id> &connectivity,
const std::string &coordsNm,
const std::string &cellNm)
{ {
vtkm::cont::ArrayHandle<Vec<T,3> > coordsArray; vtkm::cont::ArrayHandle<Vec<T, 3>> coordsArray;
DataSetBuilderExplicit::CopyInto(coords, coordsArray); DataSetBuilderExplicit::CopyInto(coords, coordsArray);
vtkm::cont::ArrayHandle<vtkm::UInt8> Sc; vtkm::cont::ArrayHandle<vtkm::UInt8> Sc;
@ -298,24 +221,20 @@ DataSetBuilderExplicit::Create(const std::vector<vtkm::Vec<T,3> > &coords,
DataSetBuilderExplicit::CopyInto(numIndices, Nc); DataSetBuilderExplicit::CopyInto(numIndices, Nc);
DataSetBuilderExplicit::CopyInto(connectivity, Cc); DataSetBuilderExplicit::CopyInto(connectivity, Cc);
return DataSetBuilderExplicit::Create( return DataSetBuilderExplicit::Create(coordsArray, Sc, Nc, Cc, coordsNm, cellNm);
coordsArray, Sc, Nc, Cc, coordsNm, cellNm);
} }
template<typename T> template <typename T>
inline VTKM_CONT inline VTKM_CONT vtkm::cont::DataSet DataSetBuilderExplicit::BuildDataSet(
vtkm::cont::DataSet const vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>>& coords,
DataSetBuilderExplicit::BuildDataSet(const vtkm::cont::ArrayHandle<vtkm::Vec<T,3> > &coords, const vtkm::cont::ArrayHandle<vtkm::UInt8>& shapes,
const vtkm::cont::ArrayHandle<vtkm::UInt8> &shapes, const vtkm::cont::ArrayHandle<vtkm::IdComponent>& numIndices,
const vtkm::cont::ArrayHandle<vtkm::IdComponent> &numIndices, const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity, const std::string& coordsNm,
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity, const std::string& cellNm)
const std::string &coordsNm,
const std::string &cellNm)
{ {
vtkm::cont::DataSet dataSet; vtkm::cont::DataSet dataSet;
dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem(coordsNm, dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem(coordsNm, coords));
coords));
vtkm::Id nPts = static_cast<vtkm::Id>(coords.GetNumberOfValues()); vtkm::Id nPts = static_cast<vtkm::Id>(coords.GetNumberOfValues());
vtkm::cont::CellSetExplicit<> cellSet(cellNm); vtkm::cont::CellSetExplicit<> cellSet(cellNm);
@ -325,51 +244,39 @@ DataSetBuilderExplicit::BuildDataSet(const vtkm::cont::ArrayHandle<vtkm::Vec<T,3
return dataSet; return dataSet;
} }
template<typename T, typename CellShapeTag> template <typename T, typename CellShapeTag>
inline VTKM_CONT inline VTKM_CONT vtkm::cont::DataSet DataSetBuilderExplicit::Create(
vtkm::cont::DataSet const std::vector<vtkm::Vec<T, 3>>& coords, CellShapeTag tag,
DataSetBuilderExplicit::Create(const std::vector<vtkm::Vec<T,3> > &coords, vtkm::IdComponent numberOfPointsPerCell, const std::vector<vtkm::Id>& connectivity,
CellShapeTag tag, const std::string& coordsNm, const std::string& cellNm)
vtkm::IdComponent numberOfPointsPerCell,
const std::vector<vtkm::Id> &connectivity,
const std::string &coordsNm,
const std::string &cellNm)
{ {
vtkm::cont::ArrayHandle<Vec<T,3> > coordsArray; vtkm::cont::ArrayHandle<Vec<T, 3>> coordsArray;
DataSetBuilderExplicit::CopyInto(coords, coordsArray); DataSetBuilderExplicit::CopyInto(coords, coordsArray);
vtkm::cont::ArrayHandle<vtkm::Id> Cc; vtkm::cont::ArrayHandle<vtkm::Id> Cc;
DataSetBuilderExplicit::CopyInto(connectivity, Cc); DataSetBuilderExplicit::CopyInto(connectivity, Cc);
return DataSetBuilderExplicit::Create( return DataSetBuilderExplicit::Create(coordsArray, tag, numberOfPointsPerCell, Cc, coordsNm,
coordsArray, tag, numberOfPointsPerCell, Cc, coordsNm, cellNm); cellNm);
} }
template<typename T, typename CellShapeTag> template <typename T, typename CellShapeTag>
inline VTKM_CONT inline VTKM_CONT vtkm::cont::DataSet DataSetBuilderExplicit::BuildDataSet(
vtkm::cont::DataSet const vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>>& coords, CellShapeTag tag,
DataSetBuilderExplicit::BuildDataSet(const vtkm::cont::ArrayHandle<vtkm::Vec<T,3> > &coords, vtkm::IdComponent numberOfPointsPerCell, const vtkm::cont::ArrayHandle<vtkm::Id>& connectivity,
CellShapeTag tag, const std::string& coordsNm, const std::string& cellNm)
vtkm::IdComponent numberOfPointsPerCell,
const vtkm::cont::ArrayHandle<vtkm::Id> &connectivity,
const std::string &coordsNm,
const std::string &cellNm)
{ {
vtkm::cont::DataSet dataSet; vtkm::cont::DataSet dataSet;
dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem(coordsNm, coords)); dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem(coordsNm, coords));
vtkm::cont::CellSetSingleType<> cellSet(cellNm); vtkm::cont::CellSetSingleType<> cellSet(cellNm);
cellSet.Fill(coords.GetNumberOfValues(), cellSet.Fill(coords.GetNumberOfValues(), tag.Id, numberOfPointsPerCell, connectivity);
tag.Id,
numberOfPointsPerCell,
connectivity);
dataSet.AddCellSet(cellSet); dataSet.AddCellSet(cellSet);
return dataSet; return dataSet;
} }
class DataSetBuilderExplicitIterative class DataSetBuilderExplicitIterative
{ {
public: public:
@ -377,8 +284,7 @@ public:
DataSetBuilderExplicitIterative() {} DataSetBuilderExplicitIterative() {}
VTKM_CONT VTKM_CONT
void Begin(const std::string &coordName="coords", void Begin(const std::string& coordName = "coords", const std::string& cellName = "cells")
const std::string &cellName="cells")
{ {
this->coordNm = coordName; this->coordNm = coordName;
this->cellNm = cellName; this->cellNm = cellName;
@ -393,7 +299,7 @@ public:
vtkm::cont::DataSet Create(); vtkm::cont::DataSet Create();
VTKM_CONT VTKM_CONT
vtkm::Id AddPoint(const vtkm::Vec<vtkm::Float32, 3> &pt) vtkm::Id AddPoint(const vtkm::Vec<vtkm::Float32, 3>& pt)
{ {
points.push_back(pt); points.push_back(pt);
vtkm::Id id = static_cast<vtkm::Id>(points.size()); vtkm::Id id = static_cast<vtkm::Id>(points.size());
@ -401,29 +307,24 @@ public:
} }
VTKM_CONT VTKM_CONT
vtkm::Id AddPoint(const vtkm::Float32 &x, vtkm::Id AddPoint(const vtkm::Float32& x, const vtkm::Float32& y, const vtkm::Float32& z = 0)
const vtkm::Float32 &y,
const vtkm::Float32 &z=0)
{ {
points.push_back(vtkm::make_Vec(x,y,z)); points.push_back(vtkm::make_Vec(x, y, z));
vtkm::Id id = static_cast<vtkm::Id>(points.size()); vtkm::Id id = static_cast<vtkm::Id>(points.size());
return id; return id;
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT vtkm::Id AddPoint(const T& x, const T& y, const T& z = 0)
vtkm::Id AddPoint(const T &x, const T &y, const T &z=0)
{ {
return AddPoint(static_cast<vtkm::Float32>(x), return AddPoint(static_cast<vtkm::Float32>(x), static_cast<vtkm::Float32>(y),
static_cast<vtkm::Float32>(y), static_cast<vtkm::Float32>(z));
static_cast<vtkm::Float32>(z));
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT vtkm::Id AddPoint(const vtkm::Vec<T, 3>& pt)
vtkm::Id AddPoint(const vtkm::Vec<T,3> &pt)
{ {
return AddPoint(static_cast<vtkm::Vec<vtkm::Float32,3> >(pt)); return AddPoint(static_cast<vtkm::Vec<vtkm::Float32, 3>>(pt));
} }
//Define cells. //Define cells.
@ -435,7 +336,7 @@ public:
} }
VTKM_CONT VTKM_CONT
void AddCell(const vtkm::UInt8 &shape, const std::vector<vtkm::Id> &conn) void AddCell(const vtkm::UInt8& shape, const std::vector<vtkm::Id>& conn)
{ {
this->shapes.push_back(shape); this->shapes.push_back(shape);
this->numIdx.push_back(static_cast<vtkm::IdComponent>(conn.size())); this->numIdx.push_back(static_cast<vtkm::IdComponent>(conn.size()));
@ -443,14 +344,14 @@ public:
} }
VTKM_CONT VTKM_CONT
void AddCell(const vtkm::UInt8 &shape, const vtkm::Id *conn, const vtkm::IdComponent &n) void AddCell(const vtkm::UInt8& shape, const vtkm::Id* conn, const vtkm::IdComponent& n)
{ {
this->shapes.push_back(shape); this->shapes.push_back(shape);
this->numIdx.push_back(n); this->numIdx.push_back(n);
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
{ {
connectivity.push_back(conn[i]); connectivity.push_back(conn[i]);
} }
} }
VTKM_CONT VTKM_CONT
@ -464,21 +365,17 @@ public:
private: private:
std::string coordNm, cellNm; std::string coordNm, cellNm;
std::vector<vtkm::Vec<vtkm::Float32,3> > points; std::vector<vtkm::Vec<vtkm::Float32, 3>> points;
std::vector<vtkm::UInt8> shapes; std::vector<vtkm::UInt8> shapes;
std::vector<vtkm::IdComponent> numIdx; std::vector<vtkm::IdComponent> numIdx;
std::vector<vtkm::Id> connectivity; std::vector<vtkm::Id> connectivity;
}; };
inline VTKM_CONT inline VTKM_CONT vtkm::cont::DataSet DataSetBuilderExplicitIterative::Create()
vtkm::cont::DataSet
DataSetBuilderExplicitIterative::Create()
{ {
DataSetBuilderExplicit dsb; DataSetBuilderExplicit dsb;
return dsb.Create(points, shapes, numIdx, connectivity, coordNm, cellNm); return dsb.Create(points, shapes, numIdx, connectivity, coordNm, cellNm);
} }
} }
} }

@ -26,235 +26,188 @@
#include <vtkm/cont/DataSet.h> #include <vtkm/cont/DataSet.h>
#include <vtkm/cont/serial/DeviceAdapterSerial.h> #include <vtkm/cont/serial/DeviceAdapterSerial.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
class DataSetBuilderRectilinear class DataSetBuilderRectilinear
{ {
template<typename T, typename U> template <typename T, typename U>
VTKM_CONT VTKM_CONT static void CopyInto(const std::vector<T>& input, vtkm::cont::ArrayHandle<U>& output)
static
void CopyInto(const std::vector<T>& input,
vtkm::cont::ArrayHandle<U>& output )
{ {
DataSetBuilderRectilinear::CopyInto( DataSetBuilderRectilinear::CopyInto(vtkm::cont::make_ArrayHandle(input), output);
vtkm::cont::make_ArrayHandle(input), output);
} }
template<typename T, typename U> template <typename T, typename U>
VTKM_CONT VTKM_CONT static void CopyInto(const vtkm::cont::ArrayHandle<T>& input,
static vtkm::cont::ArrayHandle<U>& output)
void CopyInto(const vtkm::cont::ArrayHandle<T>& input,
vtkm::cont::ArrayHandle<U>& output )
{ {
typedef vtkm::cont::DeviceAdapterAlgorithm< typedef vtkm::cont::DeviceAdapterAlgorithm<vtkm::cont::DeviceAdapterTagSerial> Algorithm;
vtkm::cont::DeviceAdapterTagSerial> Algorithm;
Algorithm::Copy(input, output); Algorithm::Copy(input, output);
} }
template<typename T, typename U> template <typename T, typename U>
VTKM_CONT VTKM_CONT static void CopyInto(const T* input, vtkm::Id len, vtkm::cont::ArrayHandle<U>& output)
static
void CopyInto(const T* input, vtkm::Id len,
vtkm::cont::ArrayHandle<U>& output )
{ {
DataSetBuilderRectilinear::CopyInto( DataSetBuilderRectilinear::CopyInto(vtkm::cont::make_ArrayHandle(input, len), output);
vtkm::cont::make_ArrayHandle(input, len), output);
} }
public: public:
VTKM_CONT VTKM_CONT
DataSetBuilderRectilinear() {} DataSetBuilderRectilinear() {}
//1D grids. //1D grids.
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const std::vector<T>& xvals,
static std::string coordNm = "coords",
vtkm::cont::DataSet std::string cellNm = "cells")
Create(const std::vector<T> &xvals,
std::string coordNm="coords", std::string cellNm="cells")
{ {
std::vector<T> yvals(1,0), zvals(1,0); std::vector<T> yvals(1, 0), zvals(1, 0);
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(1, xvals, yvals, zvals, coordNm, cellNm);
1, xvals,yvals,zvals, coordNm,cellNm);
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(vtkm::Id nx, T* xvals, std::string coordNm = "coords",
static std::string cellNm = "cells")
vtkm::cont::DataSet
Create(vtkm::Id nx, T *xvals,
std::string coordNm="coords", std::string cellNm="cells")
{ {
T yvals = 0, zvals = 0; T yvals = 0, zvals = 0;
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(1, nx, 1, 1, xvals, &yvals, &zvals, coordNm,
1, nx,1, 1, xvals, &yvals, &zvals, coordNm, cellNm); cellNm);
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const vtkm::cont::ArrayHandle<T>& xvals,
static std::string coordNm = "coords",
vtkm::cont::DataSet std::string cellNm = "cells")
Create(const vtkm::cont::ArrayHandle<T> &xvals,
std::string coordNm="coords", std::string cellNm="cells")
{ {
vtkm::cont::ArrayHandle<T> yvals, zvals; vtkm::cont::ArrayHandle<T> yvals, zvals;
yvals.Allocate(1); yvals.Allocate(1);
yvals.GetPortalControl().Set(0,0.0); yvals.GetPortalControl().Set(0, 0.0);
zvals.Allocate(1); zvals.Allocate(1);
zvals.GetPortalControl().Set(0,0.0); zvals.GetPortalControl().Set(0, 0.0);
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(1, xvals, yvals, zvals, coordNm, cellNm);
1, xvals,yvals,zvals, coordNm, cellNm);
} }
//2D grids. //2D grids.
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const std::vector<T>& xvals,
static const std::vector<T>& yvals,
vtkm::cont::DataSet std::string coordNm = "coords",
Create(const std::vector<T> &xvals, const std::vector<T> &yvals, std::string cellNm = "cells")
std::string coordNm="coords", std::string cellNm="cells")
{ {
std::vector<T> zvals(1,0); std::vector<T> zvals(1, 0);
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(2, xvals, yvals, zvals, coordNm, cellNm);
2, xvals,yvals,zvals, coordNm,cellNm);
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(vtkm::Id nx, vtkm::Id ny, T* xvals, T* yvals,
static std::string coordNm = "coords",
vtkm::cont::DataSet std::string cellNm = "cells")
Create(vtkm::Id nx, vtkm::Id ny,
T *xvals, T *yvals,
std::string coordNm="coords", std::string cellNm="cells")
{ {
T zvals = 0; T zvals = 0;
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(2, nx, ny, 1, xvals, yvals, &zvals, coordNm,
2, nx,ny, 1, xvals, yvals, &zvals, coordNm, cellNm); cellNm);
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const vtkm::cont::ArrayHandle<T>& xvals,
static const vtkm::cont::ArrayHandle<T>& yvals,
vtkm::cont::DataSet std::string coordNm = "coords",
Create(const vtkm::cont::ArrayHandle<T> &xvals, std::string cellNm = "cells")
const vtkm::cont::ArrayHandle<T> &yvals,
std::string coordNm="coords", std::string cellNm="cells")
{ {
vtkm::cont::ArrayHandle<T> zvals; vtkm::cont::ArrayHandle<T> zvals;
zvals.Allocate(1); zvals.Allocate(1);
zvals.GetPortalControl().Set(0,0.0); zvals.GetPortalControl().Set(0, 0.0);
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(2, xvals, yvals, zvals, coordNm, cellNm);
2, xvals,yvals,zvals, coordNm, cellNm);
} }
//3D grids. //3D grids.
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(vtkm::Id nx, vtkm::Id ny, vtkm::Id nz, T* xvals,
static T* yvals, T* zvals, std::string coordNm = "coords",
vtkm::cont::DataSet std::string cellNm = "cells")
Create(vtkm::Id nx, vtkm::Id ny, vtkm::Id nz,
T *xvals, T *yvals, T *zvals,
std::string coordNm="coords", std::string cellNm="cells")
{ {
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(3, nx, ny, nz, xvals, yvals, zvals, coordNm,
3, nx,ny,nz, xvals, yvals, zvals, coordNm, cellNm); cellNm);
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const std::vector<T>& xvals,
static const std::vector<T>& yvals,
vtkm::cont::DataSet const std::vector<T>& zvals,
Create(const std::vector<T> &xvals, std::string coordNm = "coords",
const std::vector<T> &yvals, std::string cellNm = "cells")
const std::vector<T> &zvals,
std::string coordNm="coords", std::string cellNm="cells")
{ {
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(3, xvals, yvals, zvals, coordNm, cellNm);
3, xvals, yvals, zvals, coordNm, cellNm);
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const vtkm::cont::ArrayHandle<T>& xvals,
static const vtkm::cont::ArrayHandle<T>& yvals,
vtkm::cont::DataSet const vtkm::cont::ArrayHandle<T>& zvals,
Create(const vtkm::cont::ArrayHandle<T> &xvals, std::string coordNm = "coords",
const vtkm::cont::ArrayHandle<T> &yvals, std::string cellNm = "cells")
const vtkm::cont::ArrayHandle<T> &zvals,
std::string coordNm="coords", std::string cellNm="cells")
{ {
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(3, xvals, yvals, zvals, coordNm, cellNm);
3, xvals,yvals,zvals, coordNm, cellNm);
} }
private: private:
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet BuildDataSet(int dim, const std::vector<T>& xvals,
static const std::vector<T>& yvals,
vtkm::cont::DataSet const std::vector<T>& zvals,
BuildDataSet(int dim, std::string coordNm, std::string cellNm)
const std::vector<T> &xvals,
const std::vector<T> &yvals,
const std::vector<T> &zvals,
std::string coordNm, std::string cellNm)
{ {
VTKM_ASSERT((dim==1 && xvals.size()>1 && yvals.size()==1 && zvals.size()==1) || VTKM_ASSERT((dim == 1 && xvals.size() > 1 && yvals.size() == 1 && zvals.size() == 1) ||
(dim==2 && xvals.size()>1 && yvals.size()>1 && zvals.size()==1) || (dim == 2 && xvals.size() > 1 && yvals.size() > 1 && zvals.size() == 1) ||
(dim==3 && xvals.size()>1 && yvals.size()>1 && zvals.size()>1)); (dim == 3 && xvals.size() > 1 && yvals.size() > 1 && zvals.size() > 1));
vtkm::cont::ArrayHandle<vtkm::FloatDefault> Xc, Yc, Zc; vtkm::cont::ArrayHandle<vtkm::FloatDefault> Xc, Yc, Zc;
DataSetBuilderRectilinear::CopyInto(xvals, Xc); DataSetBuilderRectilinear::CopyInto(xvals, Xc);
DataSetBuilderRectilinear::CopyInto(yvals, Yc); DataSetBuilderRectilinear::CopyInto(yvals, Yc);
DataSetBuilderRectilinear::CopyInto(zvals, Zc); DataSetBuilderRectilinear::CopyInto(zvals, Zc);
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(dim, Xc, Yc, Zc, coordNm, cellNm);
dim, Xc,Yc,Zc, coordNm, cellNm);
} }
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet BuildDataSet(int dim, vtkm::Id nx, vtkm::Id ny, vtkm::Id nz,
static const T* xvals, const T* yvals, const T* zvals,
vtkm::cont::DataSet std::string coordNm, std::string cellNm)
BuildDataSet(int dim, vtkm::Id nx, vtkm::Id ny, vtkm::Id nz,
const T *xvals, const T *yvals, const T *zvals,
std::string coordNm, std::string cellNm)
{ {
VTKM_ASSERT((dim==1 && nx>1 && ny==1 && nz==1) || VTKM_ASSERT((dim == 1 && nx > 1 && ny == 1 && nz == 1) ||
(dim==2 && nx>1 && ny>1 && nz==1) || (dim == 2 && nx > 1 && ny > 1 && nz == 1) ||
(dim==3 && nx>1 && ny>1 && nz>1)); (dim == 3 && nx > 1 && ny > 1 && nz > 1));
vtkm::cont::ArrayHandle<vtkm::FloatDefault> Xc, Yc, Zc; vtkm::cont::ArrayHandle<vtkm::FloatDefault> Xc, Yc, Zc;
DataSetBuilderRectilinear::CopyInto(xvals, nx, Xc); DataSetBuilderRectilinear::CopyInto(xvals, nx, Xc);
DataSetBuilderRectilinear::CopyInto(yvals, ny, Yc); DataSetBuilderRectilinear::CopyInto(yvals, ny, Yc);
DataSetBuilderRectilinear::CopyInto(zvals, nz, Zc); DataSetBuilderRectilinear::CopyInto(zvals, nz, Zc);
return DataSetBuilderRectilinear::BuildDataSet( return DataSetBuilderRectilinear::BuildDataSet(dim, Xc, Yc, Zc, coordNm, cellNm);
dim, Xc,Yc,Zc, coordNm, cellNm); }
}
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet BuildDataSet(int dim, const vtkm::cont::ArrayHandle<T>& X,
static const vtkm::cont::ArrayHandle<T>& Y,
vtkm::cont::DataSet const vtkm::cont::ArrayHandle<T>& Z,
BuildDataSet(int dim, std::string coordNm, std::string cellNm)
const vtkm::cont::ArrayHandle<T> &X,
const vtkm::cont::ArrayHandle<T> &Y,
const vtkm::cont::ArrayHandle<T> &Z,
std::string coordNm, std::string cellNm)
{ {
vtkm::cont::DataSet dataSet; vtkm::cont::DataSet dataSet;
//Convert all coordinates to floatDefault. //Convert all coordinates to floatDefault.
vtkm::cont::ArrayHandleCartesianProduct< vtkm::cont::ArrayHandleCartesianProduct<vtkm::cont::ArrayHandle<vtkm::FloatDefault>,
vtkm::cont::ArrayHandle<vtkm::FloatDefault>, vtkm::cont::ArrayHandle<vtkm::FloatDefault>,
vtkm::cont::ArrayHandle<vtkm::FloatDefault>, vtkm::cont::ArrayHandle<vtkm::FloatDefault>>
vtkm::cont::ArrayHandle<vtkm::FloatDefault> > coords; coords;
vtkm::cont::ArrayHandle<vtkm::FloatDefault> Xc, Yc, Zc; vtkm::cont::ArrayHandle<vtkm::FloatDefault> Xc, Yc, Zc;
DataSetBuilderRectilinear::CopyInto(X, Xc); DataSetBuilderRectilinear::CopyInto(X, Xc);
DataSetBuilderRectilinear::CopyInto(Y, Yc); DataSetBuilderRectilinear::CopyInto(Y, Yc);
DataSetBuilderRectilinear::CopyInto(Z, Zc); DataSetBuilderRectilinear::CopyInto(Z, Zc);
coords = vtkm::cont::make_ArrayHandleCartesianProduct(Xc,Yc,Zc); coords = vtkm::cont::make_ArrayHandleCartesianProduct(Xc, Yc, Zc);
vtkm::cont::CoordinateSystem cs(coordNm, coords); vtkm::cont::CoordinateSystem cs(coordNm, coords);
dataSet.AddCoordinateSystem(cs); dataSet.AddCoordinateSystem(cs);
@ -262,25 +215,23 @@ private:
{ {
vtkm::cont::CellSetStructured<1> cellSet(cellNm); vtkm::cont::CellSetStructured<1> cellSet(cellNm);
cellSet.SetPointDimensions(Xc.GetNumberOfValues()); cellSet.SetPointDimensions(Xc.GetNumberOfValues());
dataSet.AddCellSet(cellSet); dataSet.AddCellSet(cellSet);
} }
else if (dim == 2) else if (dim == 2)
{ {
vtkm::cont::CellSetStructured<2> cellSet(cellNm); vtkm::cont::CellSetStructured<2> cellSet(cellNm);
cellSet.SetPointDimensions(vtkm::make_Vec(Xc.GetNumberOfValues(), cellSet.SetPointDimensions(vtkm::make_Vec(Xc.GetNumberOfValues(), Yc.GetNumberOfValues()));
Yc.GetNumberOfValues()));
dataSet.AddCellSet(cellSet); dataSet.AddCellSet(cellSet);
} }
else if (dim == 3) else if (dim == 3)
{ {
vtkm::cont::CellSetStructured<3> cellSet(cellNm); vtkm::cont::CellSetStructured<3> cellSet(cellNm);
cellSet.SetPointDimensions(vtkm::make_Vec(Xc.GetNumberOfValues(), cellSet.SetPointDimensions(
Yc.GetNumberOfValues(), vtkm::make_Vec(Xc.GetNumberOfValues(), Yc.GetNumberOfValues(), Zc.GetNumberOfValues()));
Zc.GetNumberOfValues()));
dataSet.AddCellSet(cellSet); dataSet.AddCellSet(cellSet);
} }
else else
throw vtkm::cont::ErrorBadValue("Invalid cell set dimension"); throw vtkm::cont::ErrorBadValue("Invalid cell set dimension");
return dataSet; return dataSet;
} }

@ -23,153 +23,131 @@
#include <vtkm/cont/CoordinateSystem.h> #include <vtkm/cont/CoordinateSystem.h>
#include <vtkm/cont/DataSet.h> #include <vtkm/cont/DataSet.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
class DataSetBuilderUniform class DataSetBuilderUniform
{ {
typedef vtkm::Vec<vtkm::FloatDefault,3> VecType; typedef vtkm::Vec<vtkm::FloatDefault, 3> VecType;
public: public:
VTKM_CONT VTKM_CONT
DataSetBuilderUniform() {} DataSetBuilderUniform() {}
//1D uniform grid //1D uniform grid
template <typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const vtkm::Id& dimension, const T& origin,
static const T& spacing, std::string coordNm = "coords",
vtkm::cont::DataSet std::string cellNm = "cells")
Create(const vtkm::Id &dimension, {
const T &origin, const T &spacing, return DataSetBuilderUniform::CreateDataSet(
std::string coordNm="coords", std::string cellNm="cells") 1, dimension, 1, 1, VecType(static_cast<vtkm::FloatDefault>(origin), 0, 0),
{ VecType(static_cast<vtkm::FloatDefault>(spacing), 1, 1), coordNm, cellNm);
return DataSetBuilderUniform::CreateDataSet(1, }
dimension,1,1,
VecType(static_cast<vtkm::FloatDefault>(origin),
0,0),
VecType(static_cast<vtkm::FloatDefault>(spacing),
1,1),
coordNm, cellNm);
}
VTKM_CONT
static
vtkm::cont::DataSet
Create(const vtkm::Id &dimension,
std::string coordNm="coords", std::string cellNm="cells")
{
return CreateDataSet(1, dimension, 1, 1,
VecType(0), VecType(1), coordNm, cellNm);
}
//2D uniform grids. VTKM_CONT
template <typename T> static vtkm::cont::DataSet Create(const vtkm::Id& dimension, std::string coordNm = "coords",
VTKM_CONT std::string cellNm = "cells")
static {
vtkm::cont::DataSet return CreateDataSet(1, dimension, 1, 1, VecType(0), VecType(1), coordNm, cellNm);
Create(const vtkm::Id2 &dimensions, }
const vtkm::Vec<T,2> &origin, const vtkm::Vec<T,2> &spacing,
std::string coordNm="coords", std::string cellNm="cells")
{
return DataSetBuilderUniform::CreateDataSet(2,
dimensions[0],dimensions[1],1,
VecType(static_cast<vtkm::FloatDefault>(origin[0]),
static_cast<vtkm::FloatDefault>(origin[1]),
0),
VecType(static_cast<vtkm::FloatDefault>(spacing[0]),
static_cast<vtkm::FloatDefault>(spacing[1]),
1),
coordNm, cellNm);
}
VTKM_CONT
static
vtkm::cont::DataSet
Create(const vtkm::Id2 &dimensions,
std::string coordNm="coords", std::string cellNm="cells")
{
return CreateDataSet(2, dimensions[0], dimensions[1], 1,
VecType(0), VecType(1), coordNm, cellNm);
}
//3D uniform grids. //2D uniform grids.
template <typename T> template <typename T>
VTKM_CONT VTKM_CONT static vtkm::cont::DataSet Create(const vtkm::Id2& dimensions,
static const vtkm::Vec<T, 2>& origin,
vtkm::cont::DataSet const vtkm::Vec<T, 2>& spacing,
Create(const vtkm::Id3 &dimensions, std::string coordNm = "coords",
const vtkm::Vec<T,3> &origin, const vtkm::Vec<T,3> &spacing, std::string cellNm = "cells")
std::string coordNm="coords", std::string cellNm="cells") {
{ return DataSetBuilderUniform::CreateDataSet(
return DataSetBuilderUniform::CreateDataSet(3, 2, dimensions[0], dimensions[1], 1, VecType(static_cast<vtkm::FloatDefault>(origin[0]),
dimensions[0],dimensions[1],dimensions[2], static_cast<vtkm::FloatDefault>(origin[1]), 0),
VecType(static_cast<vtkm::FloatDefault>(origin[0]), VecType(static_cast<vtkm::FloatDefault>(spacing[0]),
static_cast<vtkm::FloatDefault>(origin[1]), static_cast<vtkm::FloatDefault>(spacing[1]), 1),
static_cast<vtkm::FloatDefault>(origin[2])), coordNm, cellNm);
VecType(static_cast<vtkm::FloatDefault>(spacing[0]), }
static_cast<vtkm::FloatDefault>(spacing[1]),
static_cast<vtkm::FloatDefault>(spacing[2])), VTKM_CONT
coordNm, cellNm); static vtkm::cont::DataSet Create(const vtkm::Id2& dimensions, std::string coordNm = "coords",
} std::string cellNm = "cells")
{
VTKM_CONT return CreateDataSet(2, dimensions[0], dimensions[1], 1, VecType(0), VecType(1), coordNm,
static cellNm);
vtkm::cont::DataSet }
Create(const vtkm::Id3 &dimensions,
std::string coordNm="coords", std::string cellNm="cells") //3D uniform grids.
{ template <typename T>
return CreateDataSet(3, dimensions[0], dimensions[1], dimensions[2], VTKM_CONT static vtkm::cont::DataSet Create(const vtkm::Id3& dimensions,
VecType(0), VecType(1), coordNm, cellNm); const vtkm::Vec<T, 3>& origin,
} const vtkm::Vec<T, 3>& spacing,
std::string coordNm = "coords",
std::string cellNm = "cells")
{
return DataSetBuilderUniform::CreateDataSet(
3, dimensions[0], dimensions[1], dimensions[2],
VecType(static_cast<vtkm::FloatDefault>(origin[0]),
static_cast<vtkm::FloatDefault>(origin[1]),
static_cast<vtkm::FloatDefault>(origin[2])),
VecType(static_cast<vtkm::FloatDefault>(spacing[0]),
static_cast<vtkm::FloatDefault>(spacing[1]),
static_cast<vtkm::FloatDefault>(spacing[2])),
coordNm, cellNm);
}
VTKM_CONT
static vtkm::cont::DataSet Create(const vtkm::Id3& dimensions, std::string coordNm = "coords",
std::string cellNm = "cells")
{
return CreateDataSet(3, dimensions[0], dimensions[1], dimensions[2], VecType(0), VecType(1),
coordNm, cellNm);
}
private: private:
VTKM_CONT VTKM_CONT
static static vtkm::cont::DataSet CreateDataSet(int dim, vtkm::Id nx, vtkm::Id ny, vtkm::Id nz,
vtkm::cont::DataSet const vtkm::Vec<vtkm::FloatDefault, 3>& origin,
CreateDataSet(int dim, vtkm::Id nx, vtkm::Id ny, vtkm::Id nz, const vtkm::Vec<vtkm::FloatDefault, 3>& spacing,
const vtkm::Vec<vtkm::FloatDefault,3> &origin, std::string coordNm, std::string cellNm)
const vtkm::Vec<vtkm::FloatDefault,3> &spacing, {
std::string coordNm, std::string cellNm) VTKM_ASSERT((dim == 1 && nx > 1 && ny == 1 && nz == 1) ||
(dim == 2 && nx > 1 && ny > 1 && nz == 1) ||
(dim == 3 && nx > 1 && ny > 1 && nz > 1));
VTKM_ASSERT(spacing[0] > 0 && spacing[1] > 0 && spacing[2] > 0);
vtkm::cont::DataSet dataSet;
vtkm::cont::ArrayHandleUniformPointCoordinates coords(vtkm::Id3(nx, ny, nz), origin, spacing);
vtkm::cont::CoordinateSystem cs(coordNm, coords);
dataSet.AddCoordinateSystem(cs);
if (dim == 1)
{ {
VTKM_ASSERT((dim==1 && nx>1 && ny==1 && nz==1) || vtkm::cont::CellSetStructured<1> cellSet(cellNm);
(dim==2 && nx>1 && ny>1 && nz==1) || cellSet.SetPointDimensions(nx);
(dim==3 && nx>1 && ny>1 && nz>1)); dataSet.AddCellSet(cellSet);
VTKM_ASSERT(spacing[0]>0 && spacing[1]>0 && spacing[2]>0);
vtkm::cont::DataSet dataSet;
vtkm::cont::ArrayHandleUniformPointCoordinates
coords(vtkm::Id3(nx, ny, nz),
origin, spacing);
vtkm::cont::CoordinateSystem cs(coordNm, coords);
dataSet.AddCoordinateSystem(cs);
if (dim == 1)
{
vtkm::cont::CellSetStructured<1> cellSet(cellNm);
cellSet.SetPointDimensions(nx);
dataSet.AddCellSet(cellSet);
}
else if (dim == 2)
{
vtkm::cont::CellSetStructured<2> cellSet(cellNm);
cellSet.SetPointDimensions(vtkm::make_Vec(nx,ny));
dataSet.AddCellSet(cellSet);
}
else if (dim == 3)
{
vtkm::cont::CellSetStructured<3> cellSet(cellNm);
cellSet.SetPointDimensions(vtkm::make_Vec(nx,ny,nz));
dataSet.AddCellSet(cellSet);
}
else
throw vtkm::cont::ErrorBadValue("Invalid cell set dimension");
return dataSet;
} }
else if (dim == 2)
{
vtkm::cont::CellSetStructured<2> cellSet(cellNm);
cellSet.SetPointDimensions(vtkm::make_Vec(nx, ny));
dataSet.AddCellSet(cellSet);
}
else if (dim == 3)
{
vtkm::cont::CellSetStructured<3> cellSet(cellNm);
cellSet.SetPointDimensions(vtkm::make_Vec(nx, ny, nz));
dataSet.AddCellSet(cellSet);
}
else
throw vtkm::cont::ErrorBadValue("Invalid cell set dimension");
return dataSet;
}
}; };
} // namespace cont } // namespace cont
} // namespace vtkm } // namespace vtkm
#endif //vtk_m_cont_DataSetBuilderUniform_h #endif //vtk_m_cont_DataSetBuilderUniform_h

@ -24,161 +24,110 @@
#include <vtkm/cont/DataSet.h> #include <vtkm/cont/DataSet.h>
#include <vtkm/cont/Field.h> #include <vtkm/cont/Field.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
class DataSetFieldAdd class DataSetFieldAdd
{ {
public: public:
VTKM_CONT VTKM_CONT
DataSetFieldAdd() {} DataSetFieldAdd() {}
//Point centered fields. //Point centered fields.
VTKM_CONT VTKM_CONT
static static void AddPointField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
void AddPointField(vtkm::cont::DataSet &dataSet, const vtkm::cont::DynamicArrayHandle& field)
const std::string &fieldName, {
const vtkm::cont::DynamicArrayHandle &field) dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_POINTS, field));
{ }
dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_POINTS,
field));
}
template <typename T, typename Storage> template <typename T, typename Storage>
VTKM_CONT VTKM_CONT static void AddPointField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
static const vtkm::cont::ArrayHandle<T, Storage>& field)
void AddPointField(vtkm::cont::DataSet &dataSet, {
const std::string &fieldName, dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_POINTS, field));
const vtkm::cont::ArrayHandle<T, Storage> &field) }
{
dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_POINTS,
field));
}
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static void AddPointField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
static const std::vector<T>& field)
void AddPointField(vtkm::cont::DataSet &dataSet, {
const std::string &fieldName, dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_POINTS, field));
const std::vector<T> &field) }
{
dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_POINTS,
field));
}
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static void AddPointField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
static const T* field, const vtkm::Id& n)
void AddPointField(vtkm::cont::DataSet &dataSet, {
const std::string &fieldName, dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_POINTS, field, n));
const T *field, const vtkm::Id &n) }
{
dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_POINTS,
field, n));
}
//Cell centered field //Cell centered field
VTKM_CONT VTKM_CONT
static static void AddCellField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
void AddCellField(vtkm::cont::DataSet &dataSet, const vtkm::cont::DynamicArrayHandle& field,
const std::string &fieldName, const std::string& cellSetName)
const vtkm::cont::DynamicArrayHandle &field, {
const std::string &cellSetName) dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_CELL_SET, cellSetName, field));
{ }
dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_CELL_SET,
cellSetName, field));
}
template <typename T, typename Storage> template <typename T, typename Storage>
VTKM_CONT VTKM_CONT static void AddCellField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
static const vtkm::cont::ArrayHandle<T, Storage>& field,
void AddCellField(vtkm::cont::DataSet &dataSet, const std::string& cellSetName)
const std::string &fieldName, {
const vtkm::cont::ArrayHandle<T, Storage> &field, dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_CELL_SET, cellSetName, field));
const std::string &cellSetName) }
{
dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_CELL_SET,
cellSetName, field));
}
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static void AddCellField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
static const std::vector<T>& field, const std::string& cellSetName)
void AddCellField(vtkm::cont::DataSet &dataSet, {
const std::string &fieldName, dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_CELL_SET, cellSetName, field));
const std::vector<T> &field, }
const std::string &cellSetName)
{
dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_CELL_SET,
cellSetName, field));
}
template<typename T> template <typename T>
VTKM_CONT VTKM_CONT static void AddCellField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
static const T* field, const vtkm::Id& n,
void AddCellField(vtkm::cont::DataSet &dataSet, const std::string& cellSetName)
const std::string &fieldName, {
const T *field, const vtkm::Id &n, dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_CELL_SET, cellSetName, field, n));
const std::string &cellSetName) }
{
dataSet.AddField(Field(fieldName, vtkm::cont::Field::ASSOC_CELL_SET,
cellSetName, field, n));
}
VTKM_CONT
static
void AddCellField(vtkm::cont::DataSet &dataSet,
const std::string &fieldName,
const vtkm::cont::DynamicArrayHandle &field,
vtkm::Id cellSetIndex = 0)
{
std::string cellSetName =
dataSet.GetCellSet(cellSetIndex).GetName();
DataSetFieldAdd::AddCellField(dataSet, fieldName, field, cellSetName);
}
template <typename T, typename Storage>
VTKM_CONT
static
void AddCellField(vtkm::cont::DataSet &dataSet,
const std::string &fieldName,
const vtkm::cont::ArrayHandle<T, Storage> &field,
vtkm::Id cellSetIndex = 0)
{
std::string cellSetName =
dataSet.GetCellSet(cellSetIndex).GetName();
DataSetFieldAdd::AddCellField(dataSet, fieldName, field, cellSetName);
}
template<typename T>
VTKM_CONT
static
void AddCellField(vtkm::cont::DataSet &dataSet,
const std::string &fieldName,
const std::vector<T> &field,
vtkm::Id cellSetIndex = 0)
{
std::string cellSetName =
dataSet.GetCellSet(cellSetIndex).GetName();
DataSetFieldAdd::AddCellField(dataSet, fieldName, field, cellSetName);
}
template<typename T>
VTKM_CONT
static
void AddCellField(vtkm::cont::DataSet &dataSet,
const std::string &fieldName,
const T *field, const vtkm::Id &n,
vtkm::Id cellSetIndex = 0)
{
std::string cellSetName =
dataSet.GetCellSet(cellSetIndex).GetName();
DataSetFieldAdd::AddCellField(dataSet, fieldName, field, n, cellSetName);
}
VTKM_CONT
static void AddCellField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
const vtkm::cont::DynamicArrayHandle& field, vtkm::Id cellSetIndex = 0)
{
std::string cellSetName = dataSet.GetCellSet(cellSetIndex).GetName();
DataSetFieldAdd::AddCellField(dataSet, fieldName, field, cellSetName);
}
template <typename T, typename Storage>
VTKM_CONT static void AddCellField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
const vtkm::cont::ArrayHandle<T, Storage>& field,
vtkm::Id cellSetIndex = 0)
{
std::string cellSetName = dataSet.GetCellSet(cellSetIndex).GetName();
DataSetFieldAdd::AddCellField(dataSet, fieldName, field, cellSetName);
}
template <typename T>
VTKM_CONT static void AddCellField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
const std::vector<T>& field, vtkm::Id cellSetIndex = 0)
{
std::string cellSetName = dataSet.GetCellSet(cellSetIndex).GetName();
DataSetFieldAdd::AddCellField(dataSet, fieldName, field, cellSetName);
}
template <typename T>
VTKM_CONT static void AddCellField(vtkm::cont::DataSet& dataSet, const std::string& fieldName,
const T* field, const vtkm::Id& n, vtkm::Id cellSetIndex = 0)
{
std::string cellSetName = dataSet.GetCellSet(cellSetIndex).GetName();
DataSetFieldAdd::AddCellField(dataSet, fieldName, field, n, cellSetName);
}
}; };
} }
}//namespace vtkm::cont } //namespace vtkm::cont
#endif //vtk_m_cont_DataSetFieldAdd_h #endif //vtk_m_cont_DataSetFieldAdd_h

@ -31,8 +31,10 @@
#include <vtkm/cont/internal/ArrayManagerExecution.h> #include <vtkm/cont/internal/ArrayManagerExecution.h>
// clang-format on // clang-format on
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
#ifdef VTKM_DOXYGEN_ONLY #ifdef VTKM_DOXYGEN_ONLY
/// \brief A tag specifying the interface between the control and execution environments. /// \brief A tag specifying the interface between the control and execution environments.
@ -62,15 +64,16 @@ namespace cont {
/// documentation on all the functions and classes that must be /// documentation on all the functions and classes that must be
/// overloaded/specialized to create a new device adapter. /// overloaded/specialized to create a new device adapter.
/// ///
struct DeviceAdapterTag___ { }; struct DeviceAdapterTag___
{
};
#endif //VTKM_DOXYGEN_ONLY #endif //VTKM_DOXYGEN_ONLY
namespace internal { namespace internal
{
} // namespace internal } // namespace internal
} }
} // namespace vtkm::cont } // namespace vtkm::cont
#endif //vtk_m_cont_DeviceAdapter_h #endif //vtk_m_cont_DeviceAdapter_h

@ -34,8 +34,10 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
/// \brief Struct containing device adapter algorithms. /// \brief Struct containing device adapter algorithms.
/// ///
@ -44,7 +46,7 @@ namespace cont {
/// struct is not implemented. Device adapter implementations must specialize /// struct is not implemented. Device adapter implementations must specialize
/// the template. /// the template.
/// ///
template<class DeviceAdapterTag> template <class DeviceAdapterTag>
struct DeviceAdapterAlgorithm struct DeviceAdapterAlgorithm
#ifdef VTKM_DOXYGEN_ONLY #ifdef VTKM_DOXYGEN_ONLY
{ {
@ -54,9 +56,9 @@ struct DeviceAdapterAlgorithm
/// allocated to the same size of \c input. If output has already been /// allocated to the same size of \c input. If output has already been
/// allocated we will reallocate and clear any current values. /// allocated we will reallocate and clear any current values.
/// ///
template<typename T, typename U, class CIn, class COut> template <typename T, typename U, class CIn, class COut>
VTKM_CONT static void Copy(const vtkm::cont::ArrayHandle<T,CIn> &input, VTKM_CONT static void Copy(const vtkm::cont::ArrayHandle<T, CIn>& input,
vtkm::cont::ArrayHandle<U, COut> &output); vtkm::cont::ArrayHandle<U, COut>& output);
/// \brief Conditionally copy elements in the input array to the output array. /// \brief Conditionally copy elements in the input array to the output array.
/// ///
@ -69,11 +71,10 @@ struct DeviceAdapterAlgorithm
/// the number of elements that will be removed by the stream compaction /// the number of elements that will be removed by the stream compaction
/// algorithm. /// algorithm.
/// ///
template<typename T, typename U, class CIn, class CStencil, class COut> template <typename T, typename U, class CIn, class CStencil, class COut>
VTKM_CONT static void CopyIf( VTKM_CONT static void CopyIf(const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn> &input, const vtkm::cont::ArrayHandle<U, CStencil>& stencil,
const vtkm::cont::ArrayHandle<U,CStencil> &stencil, vtkm::cont::ArrayHandle<T, COut>& output);
vtkm::cont::ArrayHandle<T,COut> &output);
/// \brief Conditionally copy elements in the input array to the output array. /// \brief Conditionally copy elements in the input array to the output array.
/// ///
@ -86,13 +87,11 @@ struct DeviceAdapterAlgorithm
/// the number of elements that will be removed by the stream compaction /// the number of elements that will be removed by the stream compaction
/// algorithm. /// algorithm.
/// ///
template<typename T, typename U, class CIn, class CStencil, template <typename T, typename U, class CIn, class CStencil, class COut, class UnaryPredicate>
class COut, class UnaryPredicate> VTKM_CONT static void CopyIf(const vtkm::cont::ArrayHandle<T, CIn>& input,
VTKM_CONT static void CopyIf( const vtkm::cont::ArrayHandle<U, CStencil>& stencil,
const vtkm::cont::ArrayHandle<T,CIn> &input, vtkm::cont::ArrayHandle<T, COut>& output,
const vtkm::cont::ArrayHandle<U,CStencil> &stencil, UnaryPredicate unary_predicate);
vtkm::cont::ArrayHandle<T,COut> &output,
UnaryPredicate unary_predicate);
/// \brief Copy the contents of a section of one ArrayHandle to another /// \brief Copy the contents of a section of one ArrayHandle to another
/// ///
@ -111,12 +110,11 @@ struct DeviceAdapterAlgorithm
/// \par Requirements: /// \par Requirements:
/// \arg \c input must already be sorted /// \arg \c input must already be sorted
/// ///
template<typename T, typename U, class CIn, class COut> template <typename T, typename U, class CIn, class COut>
VTKM_CONT static bool CopySubRange(const vtkm::cont::ArrayHandle<T,CIn> &input, VTKM_CONT static bool CopySubRange(const vtkm::cont::ArrayHandle<T, CIn>& input,
vtkm::Id inputStartIndex, vtkm::Id inputStartIndex, vtkm::Id numberOfElementsToCopy,
vtkm::Id numberOfElementsToCopy, vtkm::cont::ArrayHandle<U, COut>& output,
vtkm::cont::ArrayHandle<U, COut> &output, vtkm::Id outputIndex = 0);
vtkm::Id outputIndex = 0);
/// \brief Output is the first index in input for each item in values that wouldn't alter the ordering of input /// \brief Output is the first index in input for each item in values that wouldn't alter the ordering of input
/// ///
@ -127,11 +125,10 @@ struct DeviceAdapterAlgorithm
/// \par Requirements: /// \par Requirements:
/// \arg \c input must already be sorted /// \arg \c input must already be sorted
/// ///
template<typename T, class CIn, class CVal, class COut> template <typename T, class CIn, class CVal, class COut>
VTKM_CONT static void LowerBounds( VTKM_CONT static void LowerBounds(const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn>& input, const vtkm::cont::ArrayHandle<T, CVal>& values,
const vtkm::cont::ArrayHandle<T,CVal>& values, vtkm::cont::ArrayHandle<vtkm::Id, COut>& output);
vtkm::cont::ArrayHandle<vtkm::Id,COut>& output);
/// \brief Output is the first index in input for each item in values that wouldn't alter the ordering of input /// \brief Output is the first index in input for each item in values that wouldn't alter the ordering of input
/// ///
@ -143,12 +140,11 @@ struct DeviceAdapterAlgorithm
/// \par Requirements: /// \par Requirements:
/// \arg \c input must already be sorted /// \arg \c input must already be sorted
/// ///
template<typename T, class CIn, class CVal, class COut, class BinaryCompare> template <typename T, class CIn, class CVal, class COut, class BinaryCompare>
VTKM_CONT static void LowerBounds( VTKM_CONT static void LowerBounds(const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn>& input, const vtkm::cont::ArrayHandle<T, CVal>& values,
const vtkm::cont::ArrayHandle<T,CVal>& values, vtkm::cont::ArrayHandle<vtkm::Id, COut>& output,
vtkm::cont::ArrayHandle<vtkm::Id,COut>& output, BinaryCompare binary_compare);
BinaryCompare binary_compare);
/// \brief A special version of LowerBounds that does an in place operation. /// \brief A special version of LowerBounds that does an in place operation.
/// ///
@ -157,10 +153,9 @@ struct DeviceAdapterAlgorithm
/// where it occurs. Because this is an in place operation, the type of the /// where it occurs. Because this is an in place operation, the type of the
/// arrays is limited to vtkm::Id. /// arrays is limited to vtkm::Id.
/// ///
template<class CIn, class COut> template <class CIn, class COut>
VTKM_CONT static void LowerBounds( VTKM_CONT static void LowerBounds(const vtkm::cont::ArrayHandle<vtkm::Id, CIn>& input,
const vtkm::cont::ArrayHandle<vtkm::Id,CIn>& input, vtkm::cont::ArrayHandle<vtkm::Id, COut>& values_output);
vtkm::cont::ArrayHandle<vtkm::Id,COut>& values_output);
/// \brief Compute a accumulated sum operation on the input ArrayHandle /// \brief Compute a accumulated sum operation on the input ArrayHandle
/// ///
@ -171,10 +166,8 @@ struct DeviceAdapterAlgorithm
/// or you will get inconsistent results. /// or you will get inconsistent results.
/// ///
/// \return The total sum. /// \return The total sum.
template<typename T, typename U, class CIn> template <typename T, typename U, class CIn>
VTKM_CONT static U Reduce( VTKM_CONT static U Reduce(const vtkm::cont::ArrayHandle<T, CIn>& input, U initialValue);
const vtkm::cont::ArrayHandle<T,CIn> &input,
U initialValue);
/// \brief Compute a accumulated sum operation on the input ArrayHandle /// \brief Compute a accumulated sum operation on the input ArrayHandle
/// ///
@ -186,11 +179,9 @@ struct DeviceAdapterAlgorithm
/// inconsistent results. /// inconsistent results.
/// ///
/// \return The total sum. /// \return The total sum.
template<typename T, typename U, class CIn, class BinaryFunctor> template <typename T, typename U, class CIn, class BinaryFunctor>
VTKM_CONT static U Reduce( VTKM_CONT static U Reduce(const vtkm::cont::ArrayHandle<T, CIn>& input, U initialValue,
const vtkm::cont::ArrayHandle<T,CIn> &input, BinaryFunctor binary_functor);
U initialValue,
BinaryFunctor binary_functor);
/// \brief Compute a accumulated sum operation on the input key value pairs /// \brief Compute a accumulated sum operation on the input key value pairs
/// ///
@ -200,16 +191,13 @@ struct DeviceAdapterAlgorithm
/// values inside that range. Once finished a single key and value is created /// values inside that range. Once finished a single key and value is created
/// for each segment. /// for each segment.
/// ///
template<typename T, typename U, template <typename T, typename U, class CKeyIn, class CValIn, class CKeyOut, class CValOut,
class CKeyIn, class CValIn, class BinaryFunctor>
class CKeyOut, class CValOut, VTKM_CONT static void ReduceByKey(const vtkm::cont::ArrayHandle<T, CKeyIn>& keys,
class BinaryFunctor > const vtkm::cont::ArrayHandle<U, CValIn>& values,
VTKM_CONT static void ReduceByKey( vtkm::cont::ArrayHandle<T, CKeyOut>& keys_output,
const vtkm::cont::ArrayHandle<T,CKeyIn> &keys, vtkm::cont::ArrayHandle<T, CValOut>& values_output,
const vtkm::cont::ArrayHandle<U,CValIn> &values, BinaryFunctor binary_functor);
vtkm::cont::ArrayHandle<T,CKeyOut>& keys_output,
vtkm::cont::ArrayHandle<T,CValOut>& values_output,
BinaryFunctor binary_functor);
/// \brief Compute an inclusive prefix sum operation on the input ArrayHandle. /// \brief Compute an inclusive prefix sum operation on the input ArrayHandle.
/// ///
@ -223,10 +211,9 @@ struct DeviceAdapterAlgorithm
/// ///
/// \return The total sum. /// \return The total sum.
/// ///
template<typename T, class CIn, class COut> template <typename T, class CIn, class COut>
VTKM_CONT static T ScanInclusive( VTKM_CONT static T ScanInclusive(const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn> &input, vtkm::cont::ArrayHandle<T, COut>& output);
vtkm::cont::ArrayHandle<T,COut>& output);
/// \brief Streaming version of scan inclusive /// \brief Streaming version of scan inclusive
/// ///
@ -234,11 +221,10 @@ struct DeviceAdapterAlgorithm
/// ///
/// \return The total sum. /// \return The total sum.
/// ///
template<typename T, class CIn, class COut> template <typename T, class CIn, class COut>
VTKM_CONT static T StreamingScanInclusive( VTKM_CONT static T StreamingScanInclusive(const vtkm::Id numBlocks,
const vtkm::Id numBlocks, const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn> &input, vtkm::cont::ArrayHandle<T, COut>& output);
vtkm::cont::ArrayHandle<T,COut>& output);
/// \brief Compute an inclusive prefix sum operation on the input ArrayHandle. /// \brief Compute an inclusive prefix sum operation on the input ArrayHandle.
/// ///
@ -252,11 +238,10 @@ struct DeviceAdapterAlgorithm
/// ///
/// \return The total sum. /// \return The total sum.
/// ///
template<typename T, class CIn, class COut, class BinaryFunctor> template <typename T, class CIn, class COut, class BinaryFunctor>
VTKM_CONT static T ScanInclusive( VTKM_CONT static T ScanInclusive(const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn> &input, vtkm::cont::ArrayHandle<T, COut>& output,
vtkm::cont::ArrayHandle<T,COut>& output, BinaryFunctor binary_functor);
BinaryFunctor binary_functor);
/// \brief Compute a segmented inclusive prefix sum operation on the input key value pairs. /// \brief Compute a segmented inclusive prefix sum operation on the input key value pairs.
/// ///
@ -266,14 +251,12 @@ struct DeviceAdapterAlgorithm
/// applied to all values inside that range. Once finished the result is /// applied to all values inside that range. Once finished the result is
/// stored in \c values_output ArrayHandle. /// stored in \c values_output ArrayHandle.
/// ///
template<typename T, typename U, template <typename T, typename U, typename KIn, typename VIn, typename VOut,
typename KIn, typename VIn, typename BinaryFunctor>
typename VOut, typename BinaryFunctor> VTKM_CONT static void ScanInclusiveByKey(const vtkm::cont::ArrayHandle<T, KIn>& keys,
VTKM_CONT static void ScanInclusiveByKey( const vtkm::cont::ArrayHandle<U, VIn>& values,
const vtkm::cont::ArrayHandle<T, KIn> &keys, vtkm::cont::ArrayHandle<U, VOut>& values_output,
const vtkm::cont::ArrayHandle<U, VIn> &values, BinaryFunctor binary_functor);
vtkm::cont::ArrayHandle<U, VOut> &values_output,
BinaryFunctor binary_functor);
/// \brief Compute a segmented inclusive prefix sum operation on the input key value pairs. /// \brief Compute a segmented inclusive prefix sum operation on the input key value pairs.
/// ///
@ -282,13 +265,10 @@ struct DeviceAdapterAlgorithm
/// equal keys with the binary operation vtkm::Add applied to all values inside /// equal keys with the binary operation vtkm::Add applied to all values inside
/// that range. Once finished the result is stored in \c values_output ArrayHandle. /// that range. Once finished the result is stored in \c values_output ArrayHandle.
/// ///
template<typename T, typename U, template <typename T, typename U, typename KIn, typename VIn, typename VOut>
typename KIn, typename VIn, VTKM_CONT static void ScanInclusiveByKey(const vtkm::cont::ArrayHandle<T, KIn>& keys,
typename VOut> const vtkm::cont::ArrayHandle<U, VIn>& values,
VTKM_CONT static void ScanInclusiveByKey( vtkm::cont::ArrayHandle<U, VOut>& values_output);
const vtkm::cont::ArrayHandle<T, KIn> &keys,
const vtkm::cont::ArrayHandle<U, VIn> &values,
vtkm::cont::ArrayHandle<U, VOut> &values_output);
/// \brief Streaming version of scan inclusive /// \brief Streaming version of scan inclusive
/// ///
@ -296,12 +276,11 @@ struct DeviceAdapterAlgorithm
/// ///
/// \return The total sum. /// \return The total sum.
/// ///
template<typename T, class CIn, class COut, class BinaryFunctor> template <typename T, class CIn, class COut, class BinaryFunctor>
VTKM_CONT static T StreamingScanInclusive( VTKM_CONT static T StreamingScanInclusive(const vtkm::Id numBlocks,
const vtkm::Id numBlocks, const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn> &input, vtkm::cont::ArrayHandle<T, COut>& output,
vtkm::cont::ArrayHandle<T,COut>& output, BinaryFunctor binary_functor);
BinaryFunctor binary_functor);
/// \brief Compute an exclusive prefix sum operation on the input ArrayHandle. /// \brief Compute an exclusive prefix sum operation on the input ArrayHandle.
/// ///
@ -315,10 +294,9 @@ struct DeviceAdapterAlgorithm
/// ///
/// \return The total sum. /// \return The total sum.
/// ///
template<typename T, class CIn, class COut> template <typename T, class CIn, class COut>
VTKM_CONT static T ScanExclusive( VTKM_CONT static T ScanExclusive(const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn> &input, vtkm::cont::ArrayHandle<T, COut>& output);
vtkm::cont::ArrayHandle<T,COut>& output);
/// \brief Compute a segmented exclusive prefix sum operation on the input key value pairs. /// \brief Compute a segmented exclusive prefix sum operation on the input key value pairs.
/// ///
@ -328,15 +306,11 @@ struct DeviceAdapterAlgorithm
/// applied to all values inside that range. Once finished the result is /// applied to all values inside that range. Once finished the result is
/// stored in \c values_output ArrayHandle. /// stored in \c values_output ArrayHandle.
/// ///
template<typename T, typename U, template <typename T, typename U, typename KIn, typename VIn, typename VOut, class BinaryFunctor>
typename KIn, typename VIn, VTKM_CONT static void ScanExclusiveByKey(const vtkm::cont::ArrayHandle<T, KIn>& keys,
typename VOut, class BinaryFunctor> const vtkm::cont::ArrayHandle<U, VIn>& values,
VTKM_CONT static void ScanExclusiveByKey( vtkm::cont::ArrayHandle<U, VOut>& output,
const vtkm::cont::ArrayHandle<T, KIn>& keys, const U& initialValue, BinaryFunctor binaryFunctor);
const vtkm::cont::ArrayHandle<U, VIn>& values,
vtkm::cont::ArrayHandle<U ,VOut>& output,
const U& initialValue,
BinaryFunctor binaryFunctor);
/// \brief Compute a segmented exclusive prefix sum operation on the input key value pairs. /// \brief Compute a segmented exclusive prefix sum operation on the input key value pairs.
/// ///
@ -345,11 +319,10 @@ struct DeviceAdapterAlgorithm
/// equal keys with the binary operation vtkm::Add applied to all values inside /// equal keys with the binary operation vtkm::Add applied to all values inside
/// that range. Once finished the result is stored in \c values_output ArrayHandle. /// that range. Once finished the result is stored in \c values_output ArrayHandle.
/// ///
template<typename T, typename U, class KIn, typename VIn, typename VOut> template <typename T, typename U, class KIn, typename VIn, typename VOut>
VTKM_CONT static void ScanExclusiveByKey( VTKM_CONT static void ScanExclusiveByKey(const vtkm::cont::ArrayHandle<T, KIn>& keys,
const vtkm::cont::ArrayHandle<T, KIn>& keys, const vtkm::cont::ArrayHandle<U, VIn>& values,
const vtkm::cont::ArrayHandle<U, VIn>& values, vtkm::cont::ArrayHandle<U, VOut>& output);
vtkm::cont::ArrayHandle<U, VOut>& output);
/// \brief Schedule many instances of a function to run on concurrent threads. /// \brief Schedule many instances of a function to run on concurrent threads.
/// ///
@ -368,9 +341,8 @@ struct DeviceAdapterAlgorithm
/// instance of the invocation. There should be one invocation for each index /// instance of the invocation. There should be one invocation for each index
/// in the range [0, \c numInstances]. /// in the range [0, \c numInstances].
/// ///
template<class Functor> template <class Functor>
VTKM_CONT static void Schedule(Functor functor, VTKM_CONT static void Schedule(Functor functor, vtkm::Id numInstances);
vtkm::Id numInstances);
/// \brief Schedule many instances of a function to run on concurrent threads. /// \brief Schedule many instances of a function to run on concurrent threads.
/// ///
@ -394,17 +366,16 @@ struct DeviceAdapterAlgorithm
/// If 1D indices are used, this Schedule behaves as if <tt>Schedule(functor, /// If 1D indices are used, this Schedule behaves as if <tt>Schedule(functor,
/// rangeMax[0]*rangeMax[1]*rangeMax[2])</tt> were called. /// rangeMax[0]*rangeMax[1]*rangeMax[2])</tt> were called.
/// ///
template<class Functor, class IndiceType> template <class Functor, class IndiceType>
VTKM_CONT static void Schedule(Functor functor, VTKM_CONT static void Schedule(Functor functor, vtkm::Id3 rangeMax);
vtkm::Id3 rangeMax);
/// \brief Unstable ascending sort of input array. /// \brief Unstable ascending sort of input array.
/// ///
/// Sorts the contents of \c values so that they in ascending value. Doesn't /// Sorts the contents of \c values so that they in ascending value. Doesn't
/// guarantee stability /// guarantee stability
/// ///
template<typename T, class Storage> template <typename T, class Storage>
VTKM_CONT static void Sort(vtkm::cont::ArrayHandle<T,Storage> &values); VTKM_CONT static void Sort(vtkm::cont::ArrayHandle<T, Storage>& values);
/// \brief Unstable ascending sort of input array. /// \brief Unstable ascending sort of input array.
/// ///
@ -413,19 +384,18 @@ struct DeviceAdapterAlgorithm
/// ///
/// BinaryCompare should be a strict weak ordering comparison operator /// BinaryCompare should be a strict weak ordering comparison operator
/// ///
template<typename T, class Storage, class BinaryCompare> template <typename T, class Storage, class BinaryCompare>
VTKM_CONT static void Sort(vtkm::cont::ArrayHandle<T,Storage> &values, VTKM_CONT static void Sort(vtkm::cont::ArrayHandle<T, Storage>& values,
BinaryCompare binary_compare); BinaryCompare binary_compare);
/// \brief Unstable ascending sort of keys and values. /// \brief Unstable ascending sort of keys and values.
/// ///
/// Sorts the contents of \c keys and \c values so that they in ascending value based /// Sorts the contents of \c keys and \c values so that they in ascending value based
/// on the values of keys. /// on the values of keys.
/// ///
template<typename T, typename U, class StorageT, class StorageU> template <typename T, typename U, class StorageT, class StorageU>
VTKM_CONT static void SortByKey( VTKM_CONT static void SortByKey(vtkm::cont::ArrayHandle<T, StorageT>& keys,
vtkm::cont::ArrayHandle<T,StorageT> &keys, vtkm::cont::ArrayHandle<U, StorageU>& values);
vtkm::cont::ArrayHandle<U,StorageU> &values);
/// \brief Unstable ascending sort of keys and values. /// \brief Unstable ascending sort of keys and values.
/// ///
@ -434,17 +404,16 @@ struct DeviceAdapterAlgorithm
/// ///
/// BinaryCompare should be a strict weak ordering comparison operator /// BinaryCompare should be a strict weak ordering comparison operator
/// ///
template<typename T, typename U, class StorageT, class StorageU, class BinaryCompare> template <typename T, typename U, class StorageT, class StorageU, class BinaryCompare>
VTKM_CONT static void SortByKey( VTKM_CONT static void SortByKey(vtkm::cont::ArrayHandle<T, StorageT>& keys,
vtkm::cont::ArrayHandle<T,StorageT> &keys, vtkm::cont::ArrayHandle<U, StorageU>& values,
vtkm::cont::ArrayHandle<U,StorageU> &values, BinaryCompare binary_compare)
BinaryCompare binary_compare)
/// \brief Completes any asynchronous operations running on the device. /// \brief Completes any asynchronous operations running on the device.
/// ///
/// Waits for any asynchronous operations running on the device to complete. /// Waits for any asynchronous operations running on the device to complete.
/// ///
VTKM_CONT static void Synchronize(); VTKM_CONT static void Synchronize();
/// \brief Reduce an array to only the unique values it contains /// \brief Reduce an array to only the unique values it contains
/// ///
@ -453,9 +422,8 @@ struct DeviceAdapterAlgorithm
/// duplicate values that aren't adjacent. Note the values array size might /// duplicate values that aren't adjacent. Note the values array size might
/// be modified by this operation. /// be modified by this operation.
/// ///
template<typename T, class Storage> template <typename T, class Storage>
VTKM_CONT static void Unique( VTKM_CONT static void Unique(vtkm::cont::ArrayHandle<T, Storage>& values);
vtkm::cont::ArrayHandle<T,Storage>& values);
/// \brief Reduce an array to only the unique values it contains /// \brief Reduce an array to only the unique values it contains
/// ///
@ -467,10 +435,9 @@ struct DeviceAdapterAlgorithm
/// Uses the custom binary predicate Comparison to determine if something /// Uses the custom binary predicate Comparison to determine if something
/// is unique. The predicate must return true if the two items are the same. /// is unique. The predicate must return true if the two items are the same.
/// ///
template<typename T, class Storage, class BinaryCompare> template <typename T, class Storage, class BinaryCompare>
VTKM_CONT static void Unique( VTKM_CONT static void Unique(vtkm::cont::ArrayHandle<T, Storage>& values,
vtkm::cont::ArrayHandle<T,Storage>& values, BinaryCompare binary_compare);
BinaryCompare binary_compare);
/// \brief Output is the last index in input for each item in values that wouldn't alter the ordering of input /// \brief Output is the last index in input for each item in values that wouldn't alter the ordering of input
/// ///
@ -481,11 +448,10 @@ struct DeviceAdapterAlgorithm
/// \par Requirements: /// \par Requirements:
/// \arg \c input must already be sorted /// \arg \c input must already be sorted
/// ///
template<typename T, class CIn, class CVal, class COut> template <typename T, class CIn, class CVal, class COut>
VTKM_CONT static void UpperBounds( VTKM_CONT static void UpperBounds(const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn>& input, const vtkm::cont::ArrayHandle<T, CVal>& values,
const vtkm::cont::ArrayHandle<T,CVal>& values, vtkm::cont::ArrayHandle<vtkm::Id, COut>& output);
vtkm::cont::ArrayHandle<vtkm::Id,COut>& output);
/// \brief Output is the last index in input for each item in values that wouldn't alter the ordering of input /// \brief Output is the last index in input for each item in values that wouldn't alter the ordering of input
/// ///
@ -497,12 +463,11 @@ struct DeviceAdapterAlgorithm
/// \par Requirements: /// \par Requirements:
/// \arg \c input must already be sorted /// \arg \c input must already be sorted
/// ///
template<typename T, class CIn, class CVal, class COut, class BinaryCompare> template <typename T, class CIn, class CVal, class COut, class BinaryCompare>
VTKM_CONT static void UpperBounds( VTKM_CONT static void UpperBounds(const vtkm::cont::ArrayHandle<T, CIn>& input,
const vtkm::cont::ArrayHandle<T,CIn>& input, const vtkm::cont::ArrayHandle<T, CVal>& values,
const vtkm::cont::ArrayHandle<T,CVal>& values, vtkm::cont::ArrayHandle<vtkm::Id, COut>& output,
vtkm::cont::ArrayHandle<vtkm::Id,COut>& output, BinaryCompare binary_compare);
BinaryCompare binary_compare);
/// \brief A special version of UpperBounds that does an in place operation. /// \brief A special version of UpperBounds that does an in place operation.
/// ///
@ -511,13 +476,12 @@ struct DeviceAdapterAlgorithm
/// \c input where it occurs. Because this is an in place operation, the type /// \c input where it occurs. Because this is an in place operation, the type
/// of the arrays is limited to vtkm::Id. /// of the arrays is limited to vtkm::Id.
/// ///
template<class CIn, class COut> template <class CIn, class COut>
VTKM_CONT static void UpperBounds( VTKM_CONT static void UpperBounds(const vtkm::cont::ArrayHandle<vtkm::Id, CIn>& input,
const vtkm::cont::ArrayHandle<vtkm::Id,CIn>& input, vtkm::cont::ArrayHandle<vtkm::Id, COut>& values_output);
vtkm::cont::ArrayHandle<vtkm::Id,COut>& values_output);
}; };
#else // VTKM_DOXYGEN_ONLY #else // VTKM_DOXYGEN_ONLY
; ;
#endif //VTKM_DOXYGEN_ONLY #endif //VTKM_DOXYGEN_ONLY
/// \brief Class providing a device-specific timer. /// \brief Class providing a device-specific timer.
@ -527,26 +491,20 @@ struct DeviceAdapterAlgorithm
/// one (in conjunction with DeviceAdapterAlgorithm) where appropriate. The /// one (in conjunction with DeviceAdapterAlgorithm) where appropriate. The
/// interface for this class is exactly the same as vtkm::cont::Timer. /// interface for this class is exactly the same as vtkm::cont::Timer.
/// ///
template<class DeviceAdapterTag> template <class DeviceAdapterTag>
class DeviceAdapterTimerImplementation class DeviceAdapterTimerImplementation
{ {
public: public:
/// When a timer is constructed, all threads are synchronized and the /// When a timer is constructed, all threads are synchronized and the
/// current time is marked so that GetElapsedTime returns the number of /// current time is marked so that GetElapsedTime returns the number of
/// seconds elapsed since the construction. /// seconds elapsed since the construction.
VTKM_CONT DeviceAdapterTimerImplementation() VTKM_CONT DeviceAdapterTimerImplementation() { this->Reset(); }
{
this->Reset();
}
/// Resets the timer. All further calls to GetElapsedTime will report the /// Resets the timer. All further calls to GetElapsedTime will report the
/// number of seconds elapsed since the call to this. This method /// number of seconds elapsed since the call to this. This method
/// synchronizes all asynchronous operations. /// synchronizes all asynchronous operations.
/// ///
VTKM_CONT void Reset() VTKM_CONT void Reset() { this->StartTime = this->GetCurrentTime(); }
{
this->StartTime = this->GetCurrentTime();
}
/// Returns the elapsed time in seconds between the construction of this /// Returns the elapsed time in seconds between the construction of this
/// class or the last call to Reset and the time this function is called. The /// class or the last call to Reset and the time this function is called. The
@ -560,9 +518,8 @@ public:
vtkm::Float64 elapsedTime; vtkm::Float64 elapsedTime;
elapsedTime = vtkm::Float64(currentTime.Seconds - this->StartTime.Seconds); elapsedTime = vtkm::Float64(currentTime.Seconds - this->StartTime.Seconds);
elapsedTime += elapsedTime += (vtkm::Float64(currentTime.Microseconds - this->StartTime.Microseconds) /
(vtkm::Float64(currentTime.Microseconds - this->StartTime.Microseconds) vtkm::Float64(1000000));
/vtkm::Float64(1000000));
return elapsedTime; return elapsedTime;
} }
@ -575,15 +532,14 @@ public:
VTKM_CONT TimeStamp GetCurrentTime() VTKM_CONT TimeStamp GetCurrentTime()
{ {
vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag> vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapterTag>::Synchronize();
::Synchronize();
TimeStamp retval; TimeStamp retval;
#ifdef _WIN32 #ifdef _WIN32
timeb currentTime; timeb currentTime;
::ftime(&currentTime); ::ftime(&currentTime);
retval.Seconds = currentTime.time; retval.Seconds = currentTime.time;
retval.Microseconds = 1000*currentTime.millitm; retval.Microseconds = 1000 * currentTime.millitm;
#else #else
timeval currentTime; timeval currentTime;
gettimeofday(&currentTime, nullptr); gettimeofday(&currentTime, nullptr);
@ -603,11 +559,10 @@ public:
/// physical hardware or other special runtime requirements should provide /// physical hardware or other special runtime requirements should provide
/// one (in conjunction with DeviceAdapterAlgorithm) where appropriate. /// one (in conjunction with DeviceAdapterAlgorithm) where appropriate.
/// ///
template<class DeviceAdapterTag> template <class DeviceAdapterTag>
class DeviceAdapterRuntimeDetector class DeviceAdapterRuntimeDetector
{ {
public: public:
/// Returns true if the given device adapter is supported on the current /// Returns true if the given device adapter is supported on the current
/// machine. /// machine.
/// ///
@ -626,9 +581,8 @@ public:
/// The class provide the actual implementation used by /// The class provide the actual implementation used by
/// vtkm::cont::DeviceAdapterAtomicArrayImplementation. /// vtkm::cont::DeviceAdapterAtomicArrayImplementation.
/// ///
template<typename T, typename DeviceTag> template <typename T, typename DeviceTag>
class DeviceAdapterAtomicArrayImplementation; class DeviceAdapterAtomicArrayImplementation;
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -21,8 +21,7 @@
#define vtk_m_cont_DeviceAdapterListTag_h #define vtk_m_cont_DeviceAdapterListTag_h
#ifndef VTKM_DEFAULT_DEVICE_ADAPTER_LIST_TAG #ifndef VTKM_DEFAULT_DEVICE_ADAPTER_LIST_TAG
#define VTKM_DEFAULT_DEVICE_ADAPTER_LIST_TAG \ #define VTKM_DEFAULT_DEVICE_ADAPTER_LIST_TAG ::vtkm::cont::DeviceAdapterListTagCommon
::vtkm::cont::DeviceAdapterListTagCommon
#endif #endif
#include <vtkm/ListTag.h> #include <vtkm/ListTag.h>
@ -31,15 +30,16 @@
#include <vtkm/cont/serial/DeviceAdapterSerial.h> #include <vtkm/cont/serial/DeviceAdapterSerial.h>
#include <vtkm/cont/tbb/DeviceAdapterTBB.h> #include <vtkm/cont/tbb/DeviceAdapterTBB.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
struct DeviceAdapterListTagCommon struct DeviceAdapterListTagCommon
: vtkm::ListTagBase< : vtkm::ListTagBase<vtkm::cont::DeviceAdapterTagCuda, vtkm::cont::DeviceAdapterTagTBB,
vtkm::cont::DeviceAdapterTagCuda, vtkm::cont::DeviceAdapterTagSerial>
vtkm::cont::DeviceAdapterTagTBB, {
vtkm::cont::DeviceAdapterTagSerial> { }; };
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -20,20 +20,20 @@
#include <vtkm/cont/DynamicArrayHandle.h> #include <vtkm/cont/DynamicArrayHandle.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace detail { namespace cont
{
namespace detail
{
PolymorphicArrayHandleContainerBase::PolymorphicArrayHandleContainerBase() PolymorphicArrayHandleContainerBase::PolymorphicArrayHandleContainerBase()
{ {
} }
PolymorphicArrayHandleContainerBase::~PolymorphicArrayHandleContainerBase() PolymorphicArrayHandleContainerBase::~PolymorphicArrayHandleContainerBase()
{ {
} }
} }
} }
} // namespace vtkm::cont::detail } // namespace vtkm::cont::detail

@ -33,14 +33,17 @@
#include <sstream> #include <sstream>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
// Forward declaration // Forward declaration
template<typename TypeList, typename StorageList> template <typename TypeList, typename StorageList>
class DynamicArrayHandleBase; class DynamicArrayHandleBase;
namespace detail { namespace detail
{
/// \brief Base class for PolymorphicArrayHandleContainer /// \brief Base class for PolymorphicArrayHandleContainer
/// ///
@ -54,10 +57,9 @@ struct VTKM_CONT_EXPORT PolymorphicArrayHandleContainerBase
virtual vtkm::IdComponent GetNumberOfComponents() const = 0; virtual vtkm::IdComponent GetNumberOfComponents() const = 0;
virtual vtkm::Id GetNumberOfValues() const = 0; virtual vtkm::Id GetNumberOfValues() const = 0;
virtual void PrintSummary(std::ostream &out) const = 0; virtual void PrintSummary(std::ostream& out) const = 0;
virtual std::shared_ptr<PolymorphicArrayHandleContainerBase> virtual std::shared_ptr<PolymorphicArrayHandleContainerBase> NewInstance() const = 0;
NewInstance() const = 0;
}; };
/// \brief ArrayHandle container that can use C++ run-time type information. /// \brief ArrayHandle container that can use C++ run-time type information.
@ -68,41 +70,42 @@ struct VTKM_CONT_EXPORT PolymorphicArrayHandleContainerBase
/// (with different template parameters) so that it can polymorphically answer /// (with different template parameters) so that it can polymorphically answer
/// simple questions about the object. /// simple questions about the object.
/// ///
template<typename T, typename Storage> template <typename T, typename Storage>
struct VTKM_ALWAYS_EXPORT PolymorphicArrayHandleContainer struct VTKM_ALWAYS_EXPORT PolymorphicArrayHandleContainer
: public PolymorphicArrayHandleContainerBase : public PolymorphicArrayHandleContainerBase
{ {
typedef vtkm::cont::ArrayHandle<T, Storage> ArrayHandleType; typedef vtkm::cont::ArrayHandle<T, Storage> ArrayHandleType;
ArrayHandleType Array; ArrayHandleType Array;
VTKM_CONT VTKM_CONT
PolymorphicArrayHandleContainer() : Array() { } PolymorphicArrayHandleContainer()
: Array()
{
}
VTKM_CONT VTKM_CONT
PolymorphicArrayHandleContainer(const ArrayHandleType &array) PolymorphicArrayHandleContainer(const ArrayHandleType& array)
: Array(array) { } : Array(array)
{
}
virtual vtkm::IdComponent GetNumberOfComponents() const virtual vtkm::IdComponent GetNumberOfComponents() const
{ {
return vtkm::VecTraits<T>::NUM_COMPONENTS; return vtkm::VecTraits<T>::NUM_COMPONENTS;
} }
virtual vtkm::Id GetNumberOfValues() const virtual vtkm::Id GetNumberOfValues() const { return this->Array.GetNumberOfValues(); }
{
return this->Array.GetNumberOfValues();
}
virtual void PrintSummary(std::ostream &out) const virtual void PrintSummary(std::ostream& out) const
{ {
vtkm::cont::printSummary_ArrayHandle(this->Array, out); vtkm::cont::printSummary_ArrayHandle(this->Array, out);
} }
virtual std::shared_ptr<PolymorphicArrayHandleContainerBase> virtual std::shared_ptr<PolymorphicArrayHandleContainerBase> NewInstance() const
NewInstance() const
{ {
return std::shared_ptr<PolymorphicArrayHandleContainerBase>( return std::shared_ptr<PolymorphicArrayHandleContainerBase>(
new PolymorphicArrayHandleContainer<T,Storage>()); new PolymorphicArrayHandleContainer<T, Storage>());
} }
}; };
@ -111,12 +114,11 @@ struct VTKM_ALWAYS_EXPORT PolymorphicArrayHandleContainer
// construct a DynamicArrayHandle from another DynamicArrayHandle of any other // construct a DynamicArrayHandle from another DynamicArrayHandle of any other
// type. Since you cannot partially specialize friendship, use this accessor // type. Since you cannot partially specialize friendship, use this accessor
// class to get at the internals for the copy constructor. // class to get at the internals for the copy constructor.
struct DynamicArrayHandleCopyHelper { struct DynamicArrayHandleCopyHelper
template<typename TypeList, typename StorageList> {
VTKM_CONT template <typename TypeList, typename StorageList>
static VTKM_CONT static const std::shared_ptr<vtkm::cont::detail::PolymorphicArrayHandleContainerBase>&
const std::shared_ptr<vtkm::cont::detail::PolymorphicArrayHandleContainerBase>& GetArrayHandleContainer(const vtkm::cont::DynamicArrayHandleBase<TypeList, StorageList>& src)
GetArrayHandleContainer(const vtkm::cont::DynamicArrayHandleBase<TypeList,StorageList> &src)
{ {
return src.ArrayContainer; return src.ArrayContainer;
} }
@ -125,16 +127,13 @@ struct DynamicArrayHandleCopyHelper {
// A simple function to downcast an ArrayHandle encapsulated in a // A simple function to downcast an ArrayHandle encapsulated in a
// PolymorphicArrayHandleContainerBase to the given type of ArrayHandle. If the // PolymorphicArrayHandleContainerBase to the given type of ArrayHandle. If the
// conversion cannot be done, nullptr is returned. // conversion cannot be done, nullptr is returned.
template<typename Type, typename Storage> template <typename Type, typename Storage>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandle<Type, Storage>* DynamicArrayHandleTryCast(
vtkm::cont::ArrayHandle<Type,Storage> * vtkm::cont::detail::PolymorphicArrayHandleContainerBase* arrayContainer)
DynamicArrayHandleTryCast(
vtkm::cont::detail::PolymorphicArrayHandleContainerBase *arrayContainer)
{ {
vtkm::cont::detail::PolymorphicArrayHandleContainer<Type,Storage> * vtkm::cont::detail::PolymorphicArrayHandleContainer<Type, Storage>* downcastContainer =
downcastContainer = dynamic_cast< dynamic_cast<vtkm::cont::detail::PolymorphicArrayHandleContainer<Type, Storage>*>(
vtkm::cont::detail::PolymorphicArrayHandleContainer<Type,Storage> *>( arrayContainer);
arrayContainer);
if (downcastContainer != nullptr) if (downcastContainer != nullptr)
{ {
return &downcastContainer->Array; return &downcastContainer->Array;
@ -145,13 +144,11 @@ DynamicArrayHandleTryCast(
} }
} }
template<typename Type, typename Storage> template <typename Type, typename Storage>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandle<Type, Storage>* DynamicArrayHandleTryCast(
vtkm::cont::ArrayHandle<Type,Storage> *
DynamicArrayHandleTryCast(
const std::shared_ptr<vtkm::cont::detail::PolymorphicArrayHandleContainerBase>& arrayContainer) const std::shared_ptr<vtkm::cont::detail::PolymorphicArrayHandleContainerBase>& arrayContainer)
{ {
return detail::DynamicArrayHandleTryCast<Type,Storage>(arrayContainer.get()); return detail::DynamicArrayHandleTryCast<Type, Storage>(arrayContainer.get());
} }
} // namespace detail } // namespace detail
@ -189,39 +186,38 @@ DynamicArrayHandleTryCast(
/// typedef of \c DynamicArrayHandleBase with the default type and storage /// typedef of \c DynamicArrayHandleBase with the default type and storage
/// lists. /// lists.
/// ///
template<typename TypeList, typename StorageList> template <typename TypeList, typename StorageList>
class VTKM_ALWAYS_EXPORT DynamicArrayHandleBase class VTKM_ALWAYS_EXPORT DynamicArrayHandleBase
{ {
public: public:
VTKM_CONT VTKM_CONT
DynamicArrayHandleBase() { } DynamicArrayHandleBase() {}
template<typename Type, typename Storage> template <typename Type, typename Storage>
VTKM_CONT VTKM_CONT DynamicArrayHandleBase(const vtkm::cont::ArrayHandle<Type, Storage>& array)
DynamicArrayHandleBase(const vtkm::cont::ArrayHandle<Type,Storage> &array) : ArrayContainer(new vtkm::cont::detail::PolymorphicArrayHandleContainer<Type, Storage>(array))
: ArrayContainer(new vtkm::cont::detail::PolymorphicArrayHandleContainer< {
Type,Storage>(array)) }
{ }
VTKM_CONT VTKM_CONT
DynamicArrayHandleBase( DynamicArrayHandleBase(const DynamicArrayHandleBase<TypeList, StorageList>& src)
const DynamicArrayHandleBase<TypeList,StorageList> &src) : ArrayContainer(src.ArrayContainer)
: ArrayContainer(src.ArrayContainer) { } {
}
template<typename OtherTypeList, typename OtherStorageList> template <typename OtherTypeList, typename OtherStorageList>
VTKM_CONT VTKM_CONT explicit DynamicArrayHandleBase(
explicit DynamicArrayHandleBase( const DynamicArrayHandleBase<OtherTypeList, OtherStorageList>& src)
const DynamicArrayHandleBase<OtherTypeList,OtherStorageList> &src) : ArrayContainer(detail::DynamicArrayHandleCopyHelper::GetArrayHandleContainer(src))
: ArrayContainer( {
detail::DynamicArrayHandleCopyHelper::GetArrayHandleContainer(src)) }
{ }
VTKM_CONT VTKM_CONT
~DynamicArrayHandleBase() { } ~DynamicArrayHandleBase() {}
VTKM_CONT VTKM_CONT
vtkm::cont::DynamicArrayHandleBase<TypeList,StorageList> & vtkm::cont::DynamicArrayHandleBase<TypeList, StorageList>& operator=(
operator=(const vtkm::cont::DynamicArrayHandleBase<TypeList,StorageList> &src) const vtkm::cont::DynamicArrayHandleBase<TypeList, StorageList>& src)
{ {
this->ArrayContainer = src.ArrayContainer; this->ArrayContainer = src.ArrayContainer;
return *this; return *this;
@ -230,32 +226,28 @@ public:
/// Returns true if this array is of the provided type and uses the provided /// Returns true if this array is of the provided type and uses the provided
/// storage. /// storage.
/// ///
template<typename Type, typename Storage> template <typename Type, typename Storage>
VTKM_CONT VTKM_CONT bool IsTypeAndStorage() const
bool IsTypeAndStorage() const { {
return ( return (detail::DynamicArrayHandleTryCast<Type, Storage>(this->ArrayContainer) != nullptr);
detail::DynamicArrayHandleTryCast<Type,Storage>(this->ArrayContainer)
!= nullptr);
} }
/// Returns true if this array matches the array handle type passed in. /// Returns true if this array matches the array handle type passed in.
/// ///
template<typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT bool IsType()
bool IsType()
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType); VTKM_IS_ARRAY_HANDLE(ArrayHandleType);
typedef typename ArrayHandleType::ValueType ValueType; typedef typename ArrayHandleType::ValueType ValueType;
typedef typename ArrayHandleType::StorageTag StorageTag; typedef typename ArrayHandleType::StorageTag StorageTag;
return this->IsTypeAndStorage<ValueType,StorageTag>(); return this->IsTypeAndStorage<ValueType, StorageTag>();
} }
/// Returns true if the array held in this object is the same (or equivalent) /// Returns true if the array held in this object is the same (or equivalent)
/// type as the object given. /// type as the object given.
/// ///
template<typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT bool IsSameType(const ArrayHandleType&)
bool IsSameType(const ArrayHandleType &)
{ {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType); VTKM_IS_ARRAY_HANDLE(ArrayHandleType);
return this->IsType<ArrayHandleType>(); return this->IsType<ArrayHandleType>();
@ -266,12 +258,11 @@ public:
/// \c IsTypeAndStorage to check if the cast can happen. /// \c IsTypeAndStorage to check if the cast can happen.
/// ///
/// ///
template<typename Type, typename Storage> template <typename Type, typename Storage>
VTKM_CONT VTKM_CONT vtkm::cont::ArrayHandle<Type, Storage> CastToTypeStorage() const
vtkm::cont::ArrayHandle<Type, Storage> {
CastToTypeStorage() const { vtkm::cont::ArrayHandle<Type, Storage>* downcastArray =
vtkm::cont::ArrayHandle<Type, Storage> *downcastArray = detail::DynamicArrayHandleTryCast<Type, Storage>(this->ArrayContainer);
detail::DynamicArrayHandleTryCast<Type,Storage>(this->ArrayContainer);
if (downcastArray == nullptr) if (downcastArray == nullptr)
{ {
throw vtkm::cont::ErrorBadType("Bad cast of dynamic array."); throw vtkm::cont::ErrorBadType("Bad cast of dynamic array.");
@ -286,16 +277,16 @@ public:
/// ErrorBadType if the cast does not work. Use \c IsType /// ErrorBadType if the cast does not work. Use \c IsType
/// to check if the cast can happen. /// to check if the cast can happen.
/// ///
template<typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT ArrayHandleType Cast() const
ArrayHandleType Cast() const { {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType); VTKM_IS_ARRAY_HANDLE(ArrayHandleType);
typedef typename ArrayHandleType::ValueType ValueType; typedef typename ArrayHandleType::ValueType ValueType;
typedef typename ArrayHandleType::StorageTag StorageTag; typedef typename ArrayHandleType::StorageTag StorageTag;
// Technically, this method returns a copy of the \c ArrayHandle. But // Technically, this method returns a copy of the \c ArrayHandle. But
// because \c ArrayHandle acts like a shared pointer, it is valid to // because \c ArrayHandle acts like a shared pointer, it is valid to
// do the copy. // do the copy.
return this->CastToTypeStorage<ValueType,StorageTag>(); return this->CastToTypeStorage<ValueType, StorageTag>();
} }
/// Given a refernce to an ArrayHandle object, casts this array to the /// Given a refernce to an ArrayHandle object, casts this array to the
@ -306,9 +297,9 @@ public:
/// Note that this is a shallow copy. The data are not copied and a change /// Note that this is a shallow copy. The data are not copied and a change
/// in the data in one array will be reflected in the other. /// in the data in one array will be reflected in the other.
/// ///
template<typename ArrayHandleType> template <typename ArrayHandleType>
VTKM_CONT VTKM_CONT void CopyTo(ArrayHandleType& array) const
void CopyTo(ArrayHandleType &array) const { {
VTKM_IS_ARRAY_HANDLE(ArrayHandleType); VTKM_IS_ARRAY_HANDLE(ArrayHandleType);
array = this->Cast<ArrayHandleType>(); array = this->Cast<ArrayHandleType>();
} }
@ -320,12 +311,12 @@ public:
/// narrow down (or expand) the types when using an array of particular /// narrow down (or expand) the types when using an array of particular
/// constraints. /// constraints.
/// ///
template<typename NewTypeList> template <typename NewTypeList>
VTKM_CONT VTKM_CONT DynamicArrayHandleBase<NewTypeList, StorageList> ResetTypeList(
DynamicArrayHandleBase<NewTypeList,StorageList> NewTypeList = NewTypeList()) const
ResetTypeList(NewTypeList = NewTypeList()) const { {
VTKM_IS_LIST_TAG(NewTypeList); VTKM_IS_LIST_TAG(NewTypeList);
return DynamicArrayHandleBase<NewTypeList,StorageList>(*this); return DynamicArrayHandleBase<NewTypeList, StorageList>(*this);
} }
/// Changes the array storage types to try casting to when resolving this /// Changes the array storage types to try casting to when resolving this
@ -335,12 +326,12 @@ public:
/// method is particularly useful to narrow down (or expand) the types when /// method is particularly useful to narrow down (or expand) the types when
/// using an array of particular constraints. /// using an array of particular constraints.
/// ///
template<typename NewStorageList> template <typename NewStorageList>
VTKM_CONT VTKM_CONT DynamicArrayHandleBase<TypeList, NewStorageList> ResetStorageList(
DynamicArrayHandleBase<TypeList,NewStorageList> NewStorageList = NewStorageList()) const
ResetStorageList(NewStorageList = NewStorageList()) const { {
VTKM_IS_LIST_TAG(NewStorageList); VTKM_IS_LIST_TAG(NewStorageList);
return DynamicArrayHandleBase<TypeList,NewStorageList>(*this); return DynamicArrayHandleBase<TypeList, NewStorageList>(*this);
} }
/// Changes the value, and array storage types to try casting to when /// Changes the value, and array storage types to try casting to when
@ -349,14 +340,13 @@ public:
/// object. This method is particularly useful when you have both custom /// object. This method is particularly useful when you have both custom
/// types and traits. /// types and traits.
/// ///
template<typename NewTypeList, typename NewStorageList> template <typename NewTypeList, typename NewStorageList>
VTKM_CONT VTKM_CONT DynamicArrayHandleBase<NewTypeList, NewStorageList> ResetTypeAndStorageLists(
DynamicArrayHandleBase<NewTypeList,NewStorageList> NewTypeList = NewTypeList(), NewStorageList = NewStorageList()) const
ResetTypeAndStorageLists(NewTypeList = NewTypeList(), {
NewStorageList = NewStorageList()) const {
VTKM_IS_LIST_TAG(NewTypeList); VTKM_IS_LIST_TAG(NewTypeList);
VTKM_IS_LIST_TAG(NewStorageList); VTKM_IS_LIST_TAG(NewStorageList);
return DynamicArrayHandleBase<NewTypeList,NewStorageList>(*this); return DynamicArrayHandleBase<NewTypeList, NewStorageList>(*this);
} }
/// Attempts to cast the held array to a specific value type and storage, /// Attempts to cast the held array to a specific value type and storage,
@ -366,9 +356,8 @@ public:
/// two lists to VTKM_DEFAULT_TYPE_LIST_TAG and VTK_DEFAULT_STORAGE_LIST_TAG, /// two lists to VTKM_DEFAULT_TYPE_LIST_TAG and VTK_DEFAULT_STORAGE_LIST_TAG,
/// respectively. /// respectively.
/// ///
template<typename Functor> template <typename Functor>
VTKM_CONT VTKM_CONT void CastAndCall(const Functor& f) const;
void CastAndCall(const Functor &f) const;
/// \brief Create a new array of the same type as this array. /// \brief Create a new array of the same type as this array.
/// ///
@ -377,9 +366,9 @@ public:
/// creating output arrays that should be the same type as some input array. /// creating output arrays that should be the same type as some input array.
/// ///
VTKM_CONT VTKM_CONT
DynamicArrayHandleBase<TypeList,StorageList> NewInstance() const DynamicArrayHandleBase<TypeList, StorageList> NewInstance() const
{ {
DynamicArrayHandleBase<TypeList,StorageList> newArray; DynamicArrayHandleBase<TypeList, StorageList> newArray;
newArray.ArrayContainer = this->ArrayContainer->NewInstance(); newArray.ArrayContainer = this->ArrayContainer->NewInstance();
return newArray; return newArray;
} }
@ -399,86 +388,90 @@ public:
/// \brief Get the number of values in the array. /// \brief Get the number of values in the array.
/// ///
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfValues() const vtkm::Id GetNumberOfValues() const { return this->ArrayContainer->GetNumberOfValues(); }
{
return this->ArrayContainer->GetNumberOfValues();
}
VTKM_CONT VTKM_CONT
void PrintSummary(std::ostream &out) const void PrintSummary(std::ostream& out) const { this->ArrayContainer->PrintSummary(out); }
{
this->ArrayContainer->PrintSummary(out);
}
private: private:
std::shared_ptr<vtkm::cont::detail::PolymorphicArrayHandleContainerBase> std::shared_ptr<vtkm::cont::detail::PolymorphicArrayHandleContainerBase> ArrayContainer;
ArrayContainer;
friend struct detail::DynamicArrayHandleCopyHelper; friend struct detail::DynamicArrayHandleCopyHelper;
}; };
typedef vtkm::cont::DynamicArrayHandleBase< typedef vtkm::cont::DynamicArrayHandleBase<VTKM_DEFAULT_TYPE_LIST_TAG,
VTKM_DEFAULT_TYPE_LIST_TAG, VTKM_DEFAULT_STORAGE_LIST_TAG> VTKM_DEFAULT_STORAGE_LIST_TAG>
DynamicArrayHandle; DynamicArrayHandle;
namespace detail { namespace detail
{
template<typename Functor, typename Type> template <typename Functor, typename Type>
struct DynamicArrayHandleTryStorage { struct DynamicArrayHandleTryStorage
{
const DynamicArrayHandle* const Array; const DynamicArrayHandle* const Array;
const Functor &Function; const Functor& Function;
bool FoundCast; bool FoundCast;
VTKM_CONT VTKM_CONT
DynamicArrayHandleTryStorage(const DynamicArrayHandle &array, DynamicArrayHandleTryStorage(const DynamicArrayHandle& array, const Functor& f)
const Functor &f) : Array(&array)
: Array(&array), Function(f), FoundCast(false) { } , Function(f)
, FoundCast(false)
{
}
template<typename Storage> template <typename Storage>
VTKM_CONT VTKM_CONT void operator()(Storage)
void operator()(Storage) { {
this->DoCast(Storage(), this->DoCast(Storage(),
typename vtkm::cont::internal::IsValidArrayHandle<Type,Storage>::type()); typename vtkm::cont::internal::IsValidArrayHandle<Type, Storage>::type());
} }
private: private:
template<typename Storage> template <typename Storage>
void DoCast(Storage, std::true_type) void DoCast(Storage, std::true_type)
{ {
if (!this->FoundCast && if (!this->FoundCast && this->Array->template IsTypeAndStorage<Type, Storage>())
this->Array->template IsTypeAndStorage<Type,Storage>())
{ {
this->Function(this->Array->template CastToTypeStorage<Type,Storage>()); this->Function(this->Array->template CastToTypeStorage<Type, Storage>());
this->FoundCast = true; this->FoundCast = true;
} }
} }
template<typename Storage> template <typename Storage>
void DoCast(Storage, std::false_type) void DoCast(Storage, std::false_type)
{ {
// This type of array handle cannot exist, so do nothing. // This type of array handle cannot exist, so do nothing.
} }
void operator=(const DynamicArrayHandleTryStorage<Functor,Type> &) = delete; void operator=(const DynamicArrayHandleTryStorage<Functor, Type>&) = delete;
}; };
template<typename Functor, typename StorageList> template <typename Functor, typename StorageList>
struct DynamicArrayHandleTryType { struct DynamicArrayHandleTryType
{
const DynamicArrayHandle* const Array; const DynamicArrayHandle* const Array;
const Functor &Function; const Functor& Function;
bool FoundCast; bool FoundCast;
VTKM_CONT VTKM_CONT
DynamicArrayHandleTryType(const DynamicArrayHandle &array, const Functor &f) DynamicArrayHandleTryType(const DynamicArrayHandle& array, const Functor& f)
: Array(&array), Function(f), FoundCast(false) { } : Array(&array)
, Function(f)
, FoundCast(false)
{
}
template<typename Type> template <typename Type>
VTKM_CONT VTKM_CONT void operator()(Type)
void operator()(Type) { {
if (this->FoundCast) { return; } if (this->FoundCast)
{
return;
}
typedef DynamicArrayHandleTryStorage<Functor, Type> TryStorageType; typedef DynamicArrayHandleTryStorage<Functor, Type> TryStorageType;
TryStorageType tryStorage = TryStorageType tryStorage = TryStorageType(*this->Array, this->Function);
TryStorageType(*this->Array, this->Function);
vtkm::ListForEach(tryStorage, StorageList()); vtkm::ListForEach(tryStorage, StorageList());
if (tryStorage.FoundCast) if (tryStorage.FoundCast)
@ -488,16 +481,14 @@ struct DynamicArrayHandleTryType {
} }
private: private:
void operator=(const DynamicArrayHandleTryType<Functor,StorageList> &) = delete; void operator=(const DynamicArrayHandleTryType<Functor, StorageList>&) = delete;
}; };
} // namespace detail } // namespace detail
template<typename TypeList, typename StorageList> template <typename TypeList, typename StorageList>
template<typename Functor> template <typename Functor>
VTKM_CONT VTKM_CONT void DynamicArrayHandleBase<TypeList, StorageList>::CastAndCall(const Functor& f) const
void DynamicArrayHandleBase<TypeList,StorageList>::
CastAndCall(const Functor &f) const
{ {
VTKM_IS_LIST_TAG(TypeList); VTKM_IS_LIST_TAG(TypeList);
VTKM_IS_LIST_TAG(StorageList); VTKM_IS_LIST_TAG(StorageList);
@ -526,16 +517,13 @@ void DynamicArrayHandleBase<TypeList,StorageList>::
} }
} }
template<> template <>
template<typename Functor> template <typename Functor>
VTKM_CONT VTKM_CONT void DynamicArrayHandleBase<
void DynamicArrayHandleBase<VTKM_DEFAULT_TYPE_LIST_TAG, VTKM_DEFAULT_TYPE_LIST_TAG, VTKM_DEFAULT_STORAGE_LIST_TAG>::CastAndCall(const Functor& f) const
VTKM_DEFAULT_STORAGE_LIST_TAG>::
CastAndCall(const Functor &f) const
{ {
typedef detail::DynamicArrayHandleTryType<Functor, typedef detail::DynamicArrayHandleTryType<Functor, VTKM_DEFAULT_STORAGE_LIST_TAG> TryTypeType;
VTKM_DEFAULT_STORAGE_LIST_TAG> TryTypeType;
// We can remove the copy, as the current DynamicArrayHandle is already // We can remove the copy, as the current DynamicArrayHandle is already
// the default one, and no reason to do an atomic increment and increase // the default one, and no reason to do an atomic increment and increase
@ -545,22 +533,20 @@ void DynamicArrayHandleBase<VTKM_DEFAULT_TYPE_LIST_TAG,
vtkm::ListForEach(tryType, VTKM_DEFAULT_TYPE_LIST_TAG()); vtkm::ListForEach(tryType, VTKM_DEFAULT_TYPE_LIST_TAG());
if (!tryType.FoundCast) if (!tryType.FoundCast)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Could not find appropriate cast for array in CastAndCall2.");
"Could not find appropriate cast for array in CastAndCall2.");
} }
} }
namespace internal { namespace internal
{
template<typename TypeList, typename StorageList> template <typename TypeList, typename StorageList>
struct DynamicTransformTraits< struct DynamicTransformTraits<vtkm::cont::DynamicArrayHandleBase<TypeList, StorageList>>
vtkm::cont::DynamicArrayHandleBase<TypeList,StorageList> >
{ {
typedef vtkm::cont::internal::DynamicTransformTagCastAndCall DynamicTag; typedef vtkm::cont::internal::DynamicTransformTagCastAndCall DynamicTag;
}; };
} // namespace internal } // namespace internal
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -27,26 +27,28 @@
#include <vtkm/cont/internal/DynamicTransform.h> #include <vtkm/cont/internal/DynamicTransform.h>
#include <vtkm/cont/internal/SimplePolymorphicContainer.h> #include <vtkm/cont/internal/SimplePolymorphicContainer.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
// Forward declaration. // Forward declaration.
template<typename CellSetList> template <typename CellSetList>
class DynamicCellSetBase; class DynamicCellSetBase;
namespace detail { namespace detail
{
// One instance of a template class cannot access the private members of // One instance of a template class cannot access the private members of
// another instance of a template class. However, I want to be able to copy // another instance of a template class. However, I want to be able to copy
// construct a DynamicCellSet from another DynamicCellSet of any other type. // construct a DynamicCellSet from another DynamicCellSet of any other type.
// Since you cannot partially specialize friendship, use this accessor class to // Since you cannot partially specialize friendship, use this accessor class to
// get at the internals for the copy constructor. // get at the internals for the copy constructor.
struct DynamicCellSetCopyHelper { struct DynamicCellSetCopyHelper
template<typename CellSetList> {
VTKM_CONT template <typename CellSetList>
static VTKM_CONT static const std::shared_ptr<vtkm::cont::internal::SimplePolymorphicContainerBase>&
const std::shared_ptr<vtkm::cont::internal::SimplePolymorphicContainerBase>& GetCellSetContainer(const vtkm::cont::DynamicCellSetBase<CellSetList>& src)
GetCellSetContainer(const vtkm::cont::DynamicCellSetBase<CellSetList> &src)
{ {
return src.CellSetContainer; return src.CellSetContainer;
} }
@ -55,16 +57,12 @@ struct DynamicCellSetCopyHelper {
// A simple function to downcast a CellSet encapsulated in a // A simple function to downcast a CellSet encapsulated in a
// SimplePolymorphicContainerBase to the given subclass of CellSet. If the // SimplePolymorphicContainerBase to the given subclass of CellSet. If the
// conversion cannot be done, nullptr is returned. // conversion cannot be done, nullptr is returned.
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT CellSetType* DynamicCellSetTryCast(
CellSetType * vtkm::cont::internal::SimplePolymorphicContainerBase* cellSetContainer)
DynamicCellSetTryCast(
vtkm::cont::internal::SimplePolymorphicContainerBase *cellSetContainer)
{ {
vtkm::cont::internal::SimplePolymorphicContainer<CellSetType> * vtkm::cont::internal::SimplePolymorphicContainer<CellSetType>* downcastContainer =
downcastContainer = dynamic_cast< dynamic_cast<vtkm::cont::internal::SimplePolymorphicContainer<CellSetType>*>(cellSetContainer);
vtkm::cont::internal::SimplePolymorphicContainer<CellSetType> *>(
cellSetContainer);
if (downcastContainer != nullptr) if (downcastContainer != nullptr)
{ {
return &downcastContainer->Item; return &downcastContainer->Item;
@ -75,10 +73,8 @@ DynamicCellSetTryCast(
} }
} }
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT CellSetType* DynamicCellSetTryCast(
CellSetType *
DynamicCellSetTryCast(
const std::shared_ptr<vtkm::cont::internal::SimplePolymorphicContainerBase>& cellSetContainer) const std::shared_ptr<vtkm::cont::internal::SimplePolymorphicContainerBase>& cellSetContainer)
{ {
return detail::DynamicCellSetTryCast<CellSetType>(cellSetContainer.get()); return detail::DynamicCellSetTryCast<CellSetType>(cellSetContainer.get());
@ -115,42 +111,40 @@ DynamicCellSetTryCast(
/// types. \c DynamicCellSet is really just a typedef of \c DynamicCellSetBase /// types. \c DynamicCellSet is really just a typedef of \c DynamicCellSetBase
/// with the default cell set list. /// with the default cell set list.
/// ///
template<typename CellSetList> template <typename CellSetList>
class VTKM_ALWAYS_EXPORT DynamicCellSetBase class VTKM_ALWAYS_EXPORT DynamicCellSetBase
{ {
VTKM_IS_LIST_TAG(CellSetList); VTKM_IS_LIST_TAG(CellSetList);
public: public:
VTKM_CONT VTKM_CONT
DynamicCellSetBase() { } DynamicCellSetBase() {}
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT DynamicCellSetBase(const CellSetType& cellSet)
DynamicCellSetBase(const CellSetType &cellSet) : CellSetContainer(new vtkm::cont::internal::SimplePolymorphicContainer<CellSetType>(cellSet))
: CellSetContainer(
new vtkm::cont::internal::SimplePolymorphicContainer<CellSetType>(
cellSet))
{ {
VTKM_IS_CELL_SET(CellSetType); VTKM_IS_CELL_SET(CellSetType);
} }
VTKM_CONT VTKM_CONT
DynamicCellSetBase(const DynamicCellSetBase<CellSetList> &src) DynamicCellSetBase(const DynamicCellSetBase<CellSetList>& src)
: CellSetContainer(src.CellSetContainer) { } : CellSetContainer(src.CellSetContainer)
{
}
template<typename OtherCellSetList> template <typename OtherCellSetList>
VTKM_CONT VTKM_CONT explicit DynamicCellSetBase(const DynamicCellSetBase<OtherCellSetList>& src)
explicit : CellSetContainer(detail::DynamicCellSetCopyHelper::GetCellSetContainer(src))
DynamicCellSetBase(const DynamicCellSetBase<OtherCellSetList> &src) {
: CellSetContainer( }
detail::DynamicCellSetCopyHelper::GetCellSetContainer(src))
{ }
VTKM_CONT VTKM_CONT
~DynamicCellSetBase() { } ~DynamicCellSetBase() {}
VTKM_CONT VTKM_CONT
vtkm::cont::DynamicCellSetBase<CellSetList> & vtkm::cont::DynamicCellSetBase<CellSetList>& operator=(
operator=(const vtkm::cont::DynamicCellSetBase<CellSetList> &src) const vtkm::cont::DynamicCellSetBase<CellSetList>& src)
{ {
this->CellSetContainer = src.CellSetContainer; this->CellSetContainer = src.CellSetContainer;
return *this; return *this;
@ -158,39 +152,38 @@ public:
/// Returns true if this cell set is of the provided type. /// Returns true if this cell set is of the provided type.
/// ///
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT bool IsType() const
bool IsType() const { {
return (detail::DynamicCellSetTryCast<CellSetType>(this->CellSetContainer) return (detail::DynamicCellSetTryCast<CellSetType>(this->CellSetContainer) != nullptr);
!= nullptr);
} }
/// Returns true if this cell set is the same (or equivalent) type as the /// Returns true if this cell set is the same (or equivalent) type as the
/// object provided. /// object provided.
/// ///
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT bool IsSameType(const CellSetType&) const
bool IsSameType(const CellSetType &) const { {
return this->IsType<CellSetType>(); return this->IsType<CellSetType>();
} }
/// Returns the contained cell set as the abstract \c CellSet type. /// Returns the contained cell set as the abstract \c CellSet type.
/// ///
VTKM_CONT VTKM_CONT
const vtkm::cont::CellSet &CastToBase() const { const vtkm::cont::CellSet& CastToBase() const
return *reinterpret_cast<const vtkm::cont::CellSet *>( {
this->CellSetContainer->GetVoidPointer()); return *reinterpret_cast<const vtkm::cont::CellSet*>(this->CellSetContainer->GetVoidPointer());
} }
/// Returns this cell set cast to the given \c CellSet type. Throws \c /// Returns this cell set cast to the given \c CellSet type. Throws \c
/// ErrorBadType if the cast does not work. Use \c IsType to check if /// ErrorBadType if the cast does not work. Use \c IsType to check if
/// the cast can happen. /// the cast can happen.
/// ///
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT CellSetType& Cast() const
CellSetType &Cast() const { {
CellSetType *cellSetPointer = CellSetType* cellSetPointer =
detail::DynamicCellSetTryCast<CellSetType>(this->CellSetContainer); detail::DynamicCellSetTryCast<CellSetType>(this->CellSetContainer);
if (cellSetPointer == nullptr) if (cellSetPointer == nullptr)
{ {
throw vtkm::cont::ErrorBadType("Bad cast of dynamic cell set."); throw vtkm::cont::ErrorBadType("Bad cast of dynamic cell set.");
@ -206,9 +199,9 @@ public:
/// Note that this is a shallow copy. Any data in associated arrays are not /// Note that this is a shallow copy. Any data in associated arrays are not
/// copied. /// copied.
/// ///
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT void CopyTo(CellSetType& cellSet) const
void CopyTo(CellSetType &cellSet) const { {
cellSet = this->Cast<CellSetType>(); cellSet = this->Cast<CellSetType>();
} }
@ -219,10 +212,10 @@ public:
/// This method is particularly useful to narrow down (or expand) the types /// This method is particularly useful to narrow down (or expand) the types
/// when using a cell set of particular constraints. /// when using a cell set of particular constraints.
/// ///
template<typename NewCellSetList> template <typename NewCellSetList>
VTKM_CONT VTKM_CONT DynamicCellSetBase<NewCellSetList> ResetCellSetList(
DynamicCellSetBase<NewCellSetList> NewCellSetList = NewCellSetList()) const
ResetCellSetList(NewCellSetList = NewCellSetList()) const { {
VTKM_IS_LIST_TAG(NewCellSetList); VTKM_IS_LIST_TAG(NewCellSetList);
return DynamicCellSetBase<NewCellSetList>(*this); return DynamicCellSetBase<NewCellSetList>(*this);
} }
@ -234,9 +227,8 @@ public:
/// DynamicCellSet). You can use \c ResetCellSetList to get different /// DynamicCellSet). You can use \c ResetCellSetList to get different
/// behavior from \c CastAndCall. /// behavior from \c CastAndCall.
/// ///
template<typename Functor> template <typename Functor>
VTKM_CONT VTKM_CONT void CastAndCall(const Functor& f) const;
void CastAndCall(const Functor &f) const;
/// \brief Create a new cell set of the same type as this cell set. /// \brief Create a new cell set of the same type as this cell set.
/// ///
@ -254,71 +246,54 @@ public:
} }
VTKM_CONT VTKM_CONT
std::string GetName() const std::string GetName() const { return this->CastToBase().GetName(); }
{
return this->CastToBase().GetName();
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfCells() const vtkm::Id GetNumberOfCells() const { return this->CastToBase().GetNumberOfCells(); }
{
return this->CastToBase().GetNumberOfCells();
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfFaces() const vtkm::Id GetNumberOfFaces() const { return this->CastToBase().GetNumberOfFaces(); }
{
return this->CastToBase().GetNumberOfFaces();
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfEdges() const vtkm::Id GetNumberOfEdges() const { return this->CastToBase().GetNumberOfEdges(); }
{
return this->CastToBase().GetNumberOfEdges();
}
VTKM_CONT VTKM_CONT
vtkm::Id GetNumberOfPoints() const vtkm::Id GetNumberOfPoints() const { return this->CastToBase().GetNumberOfPoints(); }
{
return this->CastToBase().GetNumberOfPoints();
}
VTKM_CONT VTKM_CONT
void PrintSummary(std::ostream& stream) const void PrintSummary(std::ostream& stream) const { return this->CastToBase().PrintSummary(stream); }
{
return this->CastToBase().PrintSummary(stream);
}
private: private:
std::shared_ptr<vtkm::cont::internal::SimplePolymorphicContainerBase> std::shared_ptr<vtkm::cont::internal::SimplePolymorphicContainerBase> CellSetContainer;
CellSetContainer;
friend struct detail::DynamicCellSetCopyHelper; friend struct detail::DynamicCellSetCopyHelper;
}; };
namespace detail { namespace detail
{
template<typename Functor> template <typename Functor>
struct DynamicCellSetTryCellSet struct DynamicCellSetTryCellSet
{ {
vtkm::cont::internal::SimplePolymorphicContainerBase *CellSetContainer; vtkm::cont::internal::SimplePolymorphicContainerBase* CellSetContainer;
const Functor &Function; const Functor& Function;
bool FoundCast; bool FoundCast;
VTKM_CONT VTKM_CONT
DynamicCellSetTryCellSet( DynamicCellSetTryCellSet(vtkm::cont::internal::SimplePolymorphicContainerBase* cellSetContainer,
vtkm::cont::internal::SimplePolymorphicContainerBase *cellSetContainer, const Functor& f)
const Functor &f) : CellSetContainer(cellSetContainer)
: CellSetContainer(cellSetContainer), Function(f), FoundCast(false) { } , Function(f)
, FoundCast(false)
{
}
template<typename CellSetType> template <typename CellSetType>
VTKM_CONT VTKM_CONT void operator()(CellSetType)
void operator()(CellSetType) { {
if (!this->FoundCast) if (!this->FoundCast)
{ {
CellSetType *cellSet = CellSetType* cellSet = detail::DynamicCellSetTryCast<CellSetType>(this->CellSetContainer);
detail::DynamicCellSetTryCast<CellSetType>(this->CellSetContainer);
if (cellSet != nullptr) if (cellSet != nullptr)
{ {
this->Function(*cellSet); this->Function(*cellSet);
@ -328,15 +303,14 @@ struct DynamicCellSetTryCellSet
} }
private: private:
void operator=(const DynamicCellSetTryCellSet<Functor> &) = delete; void operator=(const DynamicCellSetTryCellSet<Functor>&) = delete;
}; };
} // namespace detail } // namespace detail
template<typename CellSetList> template <typename CellSetList>
template<typename Functor> template <typename Functor>
VTKM_CONT VTKM_CONT void DynamicCellSetBase<CellSetList>::CastAndCall(const Functor& f) const
void DynamicCellSetBase<CellSetList>::CastAndCall(const Functor &f) const
{ {
typedef detail::DynamicCellSetTryCellSet<Functor> TryCellSetType; typedef detail::DynamicCellSetTryCellSet<Functor> TryCellSetType;
TryCellSetType tryCellSet = TryCellSetType(this->CellSetContainer.get(), f); TryCellSetType tryCellSet = TryCellSetType(this->CellSetContainer.get(), f);
@ -344,52 +318,50 @@ void DynamicCellSetBase<CellSetList>::CastAndCall(const Functor &f) const
vtkm::ListForEach(tryCellSet, CellSetList()); vtkm::ListForEach(tryCellSet, CellSetList());
if (!tryCellSet.FoundCast) if (!tryCellSet.FoundCast)
{ {
throw vtkm::cont::ErrorBadValue( throw vtkm::cont::ErrorBadValue("Could not find appropriate cast for cell set.");
"Could not find appropriate cast for cell set.");
} }
} }
typedef DynamicCellSetBase< VTKM_DEFAULT_CELL_SET_LIST_TAG > DynamicCellSet; typedef DynamicCellSetBase<VTKM_DEFAULT_CELL_SET_LIST_TAG> DynamicCellSet;
namespace internal { namespace internal
{
template<typename CellSetList> template <typename CellSetList>
struct DynamicTransformTraits< struct DynamicTransformTraits<vtkm::cont::DynamicCellSetBase<CellSetList>>
vtkm::cont::DynamicCellSetBase<CellSetList> >
{ {
typedef vtkm::cont::internal::DynamicTransformTagCastAndCall DynamicTag; typedef vtkm::cont::internal::DynamicTransformTagCastAndCall DynamicTag;
}; };
} // namespace internal } // namespace internal
namespace internal { namespace internal
{
/// Checks to see if the given object is a dynamic cell set. It contains a /// Checks to see if the given object is a dynamic cell set. It contains a
/// typedef named \c type that is either std::true_type or std::false_type. /// typedef named \c type that is either std::true_type or std::false_type.
/// Both of these have a typedef named value with the respective boolean value. /// Both of these have a typedef named value with the respective boolean value.
/// ///
template<typename T> template <typename T>
struct DynamicCellSetCheck struct DynamicCellSetCheck
{ {
using type = std::false_type; using type = std::false_type;
}; };
template<typename CellSetList> template <typename CellSetList>
struct DynamicCellSetCheck<vtkm::cont::DynamicCellSetBase<CellSetList> > struct DynamicCellSetCheck<vtkm::cont::DynamicCellSetBase<CellSetList>>
{ {
using type = std::true_type; using type = std::true_type;
}; };
#define VTKM_IS_DYNAMIC_CELL_SET(T) \ #define VTKM_IS_DYNAMIC_CELL_SET(T) \
VTKM_STATIC_ASSERT(::vtkm::cont::internal::DynamicCellSetCheck<T>::type::value) VTKM_STATIC_ASSERT(::vtkm::cont::internal::DynamicCellSetCheck<T>::type::value)
#define VTKM_IS_DYNAMIC_OR_STATIC_CELL_SET(T) \ #define VTKM_IS_DYNAMIC_OR_STATIC_CELL_SET(T) \
VTKM_STATIC_ASSERT( \ VTKM_STATIC_ASSERT(::vtkm::cont::internal::CellSetCheck<T>::type::value || \
::vtkm::cont::internal::CellSetCheck<T>::type::value || \ ::vtkm::cont::internal::DynamicCellSetCheck<T>::type::value)
::vtkm::cont::internal::DynamicCellSetCheck<T>::type::value)
} // namespace internal } // namespace internal
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -29,8 +29,10 @@
#include <vtkm/internal/ExportMacros.h> // For VTKM_OVERRIDE #include <vtkm/internal/ExportMacros.h> // For VTKM_OVERRIDE
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
VTKM_SILENCE_WEAK_VTABLE_WARNING_START VTKM_SILENCE_WEAK_VTABLE_WARNING_START
@ -41,38 +43,34 @@ class VTKM_ALWAYS_EXPORT Error : public std::exception
public: public:
//See note about GetMessage macro below. //See note about GetMessage macro below.
#ifndef GetMessage #ifndef GetMessage
const std::string &GetMessage() const { return this->Message; } const std::string& GetMessage() const { return this->Message; }
#endif #endif
//GetMessage is a macro defined by <windows.h> to redirrect to //GetMessage is a macro defined by <windows.h> to redirrect to
//GetMessageA or W depending on if you are using ansi or unicode. //GetMessageA or W depending on if you are using ansi or unicode.
//To get around this we make our own A/W variants on windows. //To get around this we make our own A/W variants on windows.
#ifdef _WIN32 #ifdef _WIN32
const std::string &GetMessageA() const { return this->Message; } const std::string& GetMessageA() const { return this->Message; }
const std::string &GetMessageW() const { return this->Message; } const std::string& GetMessageW() const { return this->Message; }
#endif #endif
// For std::exception compatibility: // For std::exception compatibility:
const char* what() const VTKM_NOEXCEPT VTKM_OVERRIDE const char* what() const VTKM_NOEXCEPT VTKM_OVERRIDE { return this->Message.c_str(); }
{
return this->Message.c_str();
}
protected: protected:
Error() { } Error() {}
Error(const std::string message) : Message(message) { } Error(const std::string message)
: Message(message)
void SetMessage(const std::string &message)
{ {
this->Message = message;
} }
void SetMessage(const std::string& message) { this->Message = message; }
private: private:
std::string Message; std::string Message;
}; };
VTKM_SILENCE_WEAK_VTABLE_WARNING_END VTKM_SILENCE_WEAK_VTABLE_WARNING_END
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -22,8 +22,10 @@
#include <vtkm/cont/Error.h> #include <vtkm/cont/Error.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
VTKM_SILENCE_WEAK_VTABLE_WARNING_START VTKM_SILENCE_WEAK_VTABLE_WARNING_START
@ -33,12 +35,13 @@ VTKM_SILENCE_WEAK_VTABLE_WARNING_START
class VTKM_ALWAYS_EXPORT ErrorBadAllocation : public Error class VTKM_ALWAYS_EXPORT ErrorBadAllocation : public Error
{ {
public: public:
ErrorBadAllocation(const std::string &message) ErrorBadAllocation(const std::string& message)
: Error(message) { } : Error(message)
{
}
}; };
VTKM_SILENCE_WEAK_VTABLE_WARNING_END VTKM_SILENCE_WEAK_VTABLE_WARNING_END
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -22,8 +22,10 @@
#include <vtkm/cont/Error.h> #include <vtkm/cont/Error.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
VTKM_SILENCE_WEAK_VTABLE_WARNING_START VTKM_SILENCE_WEAK_VTABLE_WARNING_START
@ -33,12 +35,13 @@ VTKM_SILENCE_WEAK_VTABLE_WARNING_START
class VTKM_ALWAYS_EXPORT ErrorBadType : public Error class VTKM_ALWAYS_EXPORT ErrorBadType : public Error
{ {
public: public:
ErrorBadType(const std::string &message) ErrorBadType(const std::string& message)
: Error(message) { } : Error(message)
{
}
}; };
VTKM_SILENCE_WEAK_VTABLE_WARNING_END VTKM_SILENCE_WEAK_VTABLE_WARNING_END
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -22,8 +22,10 @@
#include <vtkm/cont/Error.h> #include <vtkm/cont/Error.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
VTKM_SILENCE_WEAK_VTABLE_WARNING_START VTKM_SILENCE_WEAK_VTABLE_WARNING_START
@ -33,12 +35,13 @@ VTKM_SILENCE_WEAK_VTABLE_WARNING_START
class VTKM_ALWAYS_EXPORT ErrorBadValue : public Error class VTKM_ALWAYS_EXPORT ErrorBadValue : public Error
{ {
public: public:
ErrorBadValue(const std::string &message) ErrorBadValue(const std::string& message)
: Error(message) { } : Error(message)
{
}
}; };
VTKM_SILENCE_WEAK_VTABLE_WARNING_END VTKM_SILENCE_WEAK_VTABLE_WARNING_END
} }
} // namespace vtkm::cont } // namespace vtkm::cont

@ -22,8 +22,10 @@
#include <vtkm/cont/Error.h> #include <vtkm/cont/Error.h>
namespace vtkm { namespace vtkm
namespace cont { {
namespace cont
{
VTKM_SILENCE_WEAK_VTABLE_WARNING_START VTKM_SILENCE_WEAK_VTABLE_WARNING_START
@ -33,13 +35,14 @@ VTKM_SILENCE_WEAK_VTABLE_WARNING_START
class VTKM_ALWAYS_EXPORT ErrorExecution : public vtkm::cont::Error class VTKM_ALWAYS_EXPORT ErrorExecution : public vtkm::cont::Error
{ {
public: public:
ErrorExecution(const std::string &message) ErrorExecution(const std::string& message)
: Error(message) { } : Error(message)
{
}
}; };
VTKM_SILENCE_WEAK_VTABLE_WARNING_END VTKM_SILENCE_WEAK_VTABLE_WARNING_END
} }
} // namespace vtkm::cont } // namespace vtkm::cont
#endif //vtk_m_cont_ErrorExecution_h #endif //vtk_m_cont_ErrorExecution_h

Some files were not shown because too many files have changed in this diff Show More