9 #ifndef OPENVDB_POINTS_POINT_CONVERSION_IMPL_HAS_BEEN_INCLUDED
10 #define OPENVDB_POINTS_POINT_CONVERSION_IMPL_HAS_BEEN_INCLUDED
19 namespace point_conversion_internal {
23 template <
typename T>
struct ConversionTraits
25 using Handle = AttributeHandle<T, UnknownCodec>;
26 using WriteHandle = AttributeWriteHandle<T, UnknownCodec>;
27 static T zero() {
return zeroVal<T>(); }
28 template <
typename LeafT>
29 static std::unique_ptr<Handle> handleFromLeaf(
const LeafT& leaf,
const Index
index) {
31 return std::make_unique<Handle>(array);
33 template <
typename LeafT>
34 static std::unique_ptr<WriteHandle> writeHandleFromLeaf(LeafT& leaf,
const Index index) {
36 return std::make_unique<WriteHandle>(array);
39 template <>
struct ConversionTraits<openvdb::
Name>
41 using Handle = StringAttributeHandle;
42 using WriteHandle = StringAttributeWriteHandle;
44 template <
typename LeafT>
45 static std::unique_ptr<Handle> handleFromLeaf(
const LeafT& leaf,
const Index index) {
48 return std::make_unique<Handle>(array, descriptor.getMetadata());
50 template <
typename LeafT>
51 static std::unique_ptr<WriteHandle> writeHandleFromLeaf(LeafT& leaf,
const Index index) {
54 return std::make_unique<WriteHandle>(array, descriptor.getMetadata());
58 template<
typename PointDataTreeType,
59 typename PointIndexTreeType,
60 typename AttributeListType>
61 struct PopulateAttributeOp {
63 using LeafManagerT =
typename tree::LeafManager<PointDataTreeType>;
64 using LeafRangeT =
typename LeafManagerT::LeafRange;
65 using PointIndexLeafNode =
typename PointIndexTreeType::LeafNodeType;
68 using HandleT =
typename ConversionTraits<ValueType>::WriteHandle;
70 PopulateAttributeOp(
const PointIndexTreeType& pointIndexTree,
71 const AttributeListType&
data,
74 : mPointIndexTree(pointIndexTree)
79 void operator()(
const typename LeafManagerT::LeafRange&
range)
const {
81 for (
auto leaf = range.begin(); leaf; ++leaf) {
85 const PointIndexLeafNode* pointIndexLeaf =
86 mPointIndexTree.probeConstLeaf(leaf->origin());
88 if (!pointIndexLeaf)
continue;
90 auto attributeWriteHandle =
91 ConversionTraits<ValueType>::writeHandleFromLeaf(*leaf, static_cast<Index>(mIndex));
97 for (
const Index64 leafIndex: indices)
100 for (Index i = 0; i < mStride; i++) {
101 mData.get(value, leafIndex, i);
102 attributeWriteHandle->set(static_cast<Index>(index), i, value);
109 attributeWriteHandle->compact();
115 const PointIndexTreeType& mPointIndexTree;
116 const AttributeListType& mData;
121 template<
typename Po
intDataTreeType,
typename Attribute,
typename FilterT>
122 struct ConvertPointDataGridPositionOp {
124 using LeafNode =
typename PointDataTreeType::LeafNodeType;
127 using SourceHandleT = AttributeHandle<ValueType>;
128 using LeafManagerT =
typename tree::LeafManager<const PointDataTreeType>;
129 using LeafRangeT =
typename LeafManagerT::LeafRange;
137 const bool inCoreOnly)
138 : mAttribute(attribute)
139 , mPointOffsets(pointOffsets)
140 , mStartOffset(startOffset)
141 , mTransform(transform)
144 , mInCoreOnly(inCoreOnly)
147 static_assert(VecTraits<ValueType>::Size == 3 &&
149 "ValueType is not Vec3f");
152 template <
typename IterT>
153 void convert(IterT& iter, HandleT& targetHandle,
156 for (; iter; ++iter) {
157 const Vec3d xyz = iter.getCoord().asVec3d();
158 const Vec3d pos = sourceHandle.get(*iter);
159 targetHandle.set(static_cast<Index>(offset++), 0,
160 mTransform.indexToWorld(pos + xyz));
164 void operator()(
const LeafRangeT& range)
const
166 HandleT pHandle(mAttribute);
168 for (
auto leaf = range.begin(); leaf; ++leaf) {
170 assert(leaf.pos() < mPointOffsets.size());
172 if (mInCoreOnly && leaf->buffer().isOutOfCore())
continue;
176 if (leaf.pos() > 0) offset += mPointOffsets[leaf.pos() - 1];
178 auto handle = SourceHandleT::create(leaf->constAttributeArray(mIndex));
181 auto iter = leaf->beginIndexOn();
185 auto iter = leaf->beginIndexOn(mFilter);
194 const std::vector<Index64>& mPointOffsets;
196 const math::Transform& mTransform;
198 const FilterT& mFilter;
199 const bool mInCoreOnly;
203 template<
typename Po
intDataTreeType,
typename Attribute,
typename FilterT>
204 struct ConvertPointDataGridAttributeOp {
206 using LeafNode =
typename PointDataTreeType::LeafNodeType;
210 using LeafManagerT =
typename tree::LeafManager<const PointDataTreeType>;
211 using LeafRangeT =
typename LeafManagerT::LeafRange;
219 const bool inCoreOnly)
220 : mAttribute(attribute)
221 , mPointOffsets(pointOffsets)
222 , mStartOffset(startOffset)
226 , mInCoreOnly(inCoreOnly) { }
228 template <
typename IterT>
229 void convert(IterT& iter, HandleT& targetHandle,
230 SourceHandleT& sourceHandle,
Index64& offset)
const
232 if (sourceHandle.isUniform()) {
233 const ValueType uniformValue(sourceHandle.get(0));
234 for (; iter; ++iter) {
235 for (Index i = 0; i < mStride; i++) {
236 targetHandle.set(static_cast<Index>(offset), i, uniformValue);
242 for (; iter; ++iter) {
243 for (Index i = 0; i < mStride; i++) {
244 targetHandle.set(static_cast<Index>(offset), i,
245 sourceHandle.get(*iter, i));
252 void operator()(
const LeafRangeT& range)
const
254 HandleT pHandle(mAttribute);
256 for (
auto leaf = range.begin(); leaf; ++leaf) {
258 assert(leaf.pos() < mPointOffsets.size());
260 if (mInCoreOnly && leaf->buffer().isOutOfCore())
continue;
264 if (leaf.pos() > 0) offset += mPointOffsets[leaf.pos() - 1];
266 auto handle = ConversionTraits<ValueType>::handleFromLeaf(
267 *leaf, static_cast<Index>(mIndex));
270 auto iter = leaf->beginIndexOn();
273 auto iter = leaf->beginIndexOn(mFilter);
282 const std::vector<Index64>& mPointOffsets;
286 const FilterT& mFilter;
287 const bool mInCoreOnly;
290 template<
typename Po
intDataTreeType,
typename Group,
typename FilterT>
291 struct ConvertPointDataGridGroupOp {
293 using LeafNode =
typename PointDataTreeType::LeafNodeType;
294 using GroupIndex = AttributeSet::Descriptor::GroupIndex;
295 using LeafManagerT =
typename tree::LeafManager<const PointDataTreeType>;
296 using LeafRangeT =
typename LeafManagerT::LeafRange;
298 ConvertPointDataGridGroupOp(Group& group,
301 const AttributeSet::Descriptor::GroupIndex index,
303 const bool inCoreOnly)
305 , mPointOffsets(pointOffsets)
306 , mStartOffset(startOffset)
309 , mInCoreOnly(inCoreOnly) { }
311 template <
typename IterT>
314 const auto bitmask =
static_cast<GroupType>(1 << mIndex.second);
316 if (groupArray.isUniform()) {
317 if (groupArray.get(0) & bitmask) {
318 for (; iter; ++iter) {
319 mGroup.setOffsetOn(static_cast<Index>(offset));
325 for (; iter; ++iter) {
326 if (groupArray.get(*iter) & bitmask) {
327 mGroup.setOffsetOn(static_cast<Index>(offset));
334 void operator()(
const LeafRangeT& range)
const
336 for (
auto leaf = range.begin(); leaf; ++leaf) {
338 assert(leaf.pos() < mPointOffsets.size());
340 if (mInCoreOnly && leaf->buffer().isOutOfCore())
continue;
344 if (leaf.pos() > 0) offset += mPointOffsets[leaf.pos() - 1];
346 const AttributeArray& array = leaf->constAttributeArray(mIndex.first);
351 auto iter = leaf->beginIndexOn();
352 convert(iter, groupArray, offset);
355 auto iter = leaf->beginIndexOn(mFilter);
356 convert(iter, groupArray, offset);
364 const std::vector<Index64>& mPointOffsets;
366 const GroupIndex mIndex;
367 const FilterT& mFilter;
368 const bool mInCoreOnly;
371 template<
typename PositionArrayT,
typename VecT = Vec3R>
372 struct CalculatePositionBounds
374 CalculatePositionBounds(
const PositionArrayT& positions,
376 : mPositions(positions)
377 , mInverseMat(inverse)
378 , mMin(std::numeric_limits<
Real>::
max())
379 , mMax(-std::numeric_limits<
Real>::
max()) {}
381 CalculatePositionBounds(
const CalculatePositionBounds& other,
tbb::split)
382 : mPositions(other.mPositions)
383 , mInverseMat(other.mInverseMat)
384 , mMin(std::numeric_limits<
Real>::
max())
385 , mMax(-std::numeric_limits<
Real>::
max()) {}
387 void operator()(
const tbb::blocked_range<size_t>& range) {
389 for (
size_t n = range.begin(),
N = range.
end();
n !=
N; ++
n) {
390 mPositions.getPos(
n, pos);
391 pos = mInverseMat.transform(pos);
397 void join(
const CalculatePositionBounds& other) {
402 BBoxd getBoundingBox()
const {
403 return BBoxd(mMin, mMax);
407 const PositionArrayT& mPositions;
419 template<
typename CompressionT,
typename Po
intDataGr
idT,
typename PositionArrayT,
typename Po
intIndexGr
idT>
420 inline typename PointDataGridT::Ptr
422 const PositionArrayT& positions,
424 const Metadata* positionDefaultValue)
426 using PointDataTreeT =
typename PointDataGridT::TreeType;
427 using LeafT =
typename PointDataTreeT::LeafNodeType;
428 using PointIndexLeafT =
typename PointIndexGridT::TreeType::LeafNodeType;
433 const NamePair positionType = PositionAttributeT::attributeType();
437 const auto& pointIndexTree = pointIndexGrid.tree();
438 typename PointDataTreeT::Ptr treePtr(
new PointDataTreeT(pointIndexTree));
442 auto descriptor = AttributeSet::Descriptor::create(positionType);
446 if (positionDefaultValue) descriptor->setDefaultValue(
"P", *positionDefaultValue);
450 const size_t positionIndex = descriptor->find(
"P");
459 LeafManagerT leafManager(*treePtr);
461 [&](LeafT& leaf,
size_t ) {
465 const auto* pointIndexLeaf = pointIndexTree.probeConstLeaf(leaf.origin());
466 assert(pointIndexLeaf);
470 Index pointCount(static_cast<Index>(pointIndexLeaf->indices().size()));
471 leaf.initializeAttributes(descriptor, pointCount, &lock);
476 leaf.attributeArray(positionIndex));
481 *
begin =
static_cast<PointIndexT*
>(
nullptr),
482 *
end = static_cast<PointIndexT*>(
nullptr);
486 for (
auto iter = pointIndexLeaf->cbeginValueOn(); iter; ++iter) {
490 const Coord& ijk = iter.getCoord();
491 const Vec3d& positionCellCenter(ijk.asVec3d());
495 pointIndexLeaf->getIndices(ijk, begin,
end);
497 while (begin <
end) {
500 positions.getPos(*begin, positionWorldSpace);
504 const Vec3d positionIndexSpace = xform.
worldToIndex(positionWorldSpace);
505 const Vec3f positionVoxelSpace(positionIndexSpace - positionCellCenter);
507 attributeWriteHandle->set(index++, positionVoxelSpace);
515 auto grid = PointDataGridT::create(treePtr);
516 grid->setTransform(xform.
copy());
524 template <
typename CompressionT,
typename Po
intDataGr
idT,
typename ValueT>
525 inline typename PointDataGridT::Ptr
528 const Metadata* positionDefaultValue)
533 tools::createPointIndexGrid<tools::PointIndexGrid>(pointList, xform);
534 return createPointDataGrid<CompressionT, PointDataGridT>(
535 *pointIndexGrid, pointList, xform, positionDefaultValue);
542 template <
typename Po
intDataTreeT,
typename Po
intIndexTreeT,
typename Po
intArrayT>
546 const bool insertMetadata)
548 using point_conversion_internal::PopulateAttributeOp;
551 auto iter = tree.cbeginLeaf();
555 const size_t index = iter->attributeSet().find(attributeName);
558 OPENVDB_THROW(KeyError,
"Attribute not found to populate - " << attributeName <<
".");
561 if (insertMetadata) {
569 PopulateAttributeOp<PointDataTreeT,
571 PointArrayT> populate(pointIndexTree, data, index, stride);
579 template <
typename PositionAttribute,
typename Po
intDataGr
idT,
typename FilterT>
582 const PointDataGridT& grid,
586 const bool inCoreOnly)
588 using TreeType =
typename PointDataGridT::TreeType;
591 using point_conversion_internal::ConvertPointDataGridPositionOp;
593 const TreeType& tree = grid.
tree();
594 auto iter = tree.cbeginLeaf();
598 const size_t positionIndex = iter->attributeSet().find(
"P");
600 positionAttribute.expand();
601 LeafManagerT leafManager(tree);
602 ConvertPointDataGridPositionOp<TreeType, PositionAttribute, FilterT>
convert(
603 positionAttribute, pointOffsets, startOffset, grid.transform(), positionIndex,
606 positionAttribute.compact();
613 template <
typename TypedAttribute,
typename Po
intDataTreeT,
typename FilterT>
616 const PointDataTreeT& tree,
619 const unsigned arrayIndex,
622 const bool inCoreOnly)
626 using point_conversion_internal::ConvertPointDataGridAttributeOp;
628 auto iter = tree.cbeginLeaf();
633 LeafManagerT leafManager(tree);
634 ConvertPointDataGridAttributeOp<PointDataTreeT, TypedAttribute, FilterT>
convert(
635 attribute, pointOffsets, startOffset, arrayIndex, stride,
645 template <
typename Group,
typename Po
intDataTreeT,
typename FilterT>
648 const PointDataTreeT& tree,
651 const AttributeSet::Descriptor::GroupIndex index,
653 const bool inCoreOnly)
657 using point_conversion_internal::ConvertPointDataGridGroupOp;
659 auto iter = tree.cbeginLeaf();
662 LeafManagerT leafManager(tree);
663 ConvertPointDataGridGroupOp<PointDataTreeT, Group, FilterT>
convert(
664 group, pointOffsets, startOffset, index,
673 template<
typename PositionWrapper,
typename InterrupterT,
typename VecT>
676 const uint32_t pointsPerVoxel,
678 const Index decimalPlaces,
679 InterrupterT*
const interrupter)
681 using namespace point_conversion_internal;
685 static bool voxelSizeFromVolume(
const double volume,
686 const size_t estimatedVoxelCount,
690 static const double minimumVoxelVolume(3e-15);
693 double voxelVolume = volume /
static_cast<double>(estimatedVoxelCount);
696 if (voxelVolume < minimumVoxelVolume) {
697 voxelVolume = minimumVoxelVolume;
700 else if (voxelVolume > maximumVoxelVolume) {
701 voxelVolume = maximumVoxelVolume;
705 voxelSize =
static_cast<float>(
math::Pow(voxelVolume, 1.0/3.0));
709 static float truncate(
const float voxelSize,
Index decPlaces)
711 float truncatedVoxelSize = voxelSize;
714 for (
int i = decPlaces; i < 11; i++) {
715 truncatedVoxelSize =
static_cast<float>(
math::Truncate(
double(voxelSize), i));
716 if (truncatedVoxelSize != 0.0
f)
break;
719 return truncatedVoxelSize;
723 if (pointsPerVoxel == 0)
OPENVDB_THROW(ValueError,
"Points per voxel cannot be zero.");
727 float voxelSize(0.1
f);
729 const size_t numPoints = positions.size();
733 if (numPoints <= 1)
return voxelSize;
735 size_t targetVoxelCount(numPoints /
size_t(pointsPerVoxel));
736 if (targetVoxelCount == 0) targetVoxelCount++;
741 inverseTransform =
math::unit(inverseTransform);
743 tbb::blocked_range<size_t>
range(0, numPoints);
744 CalculatePositionBounds<PositionWrapper, VecT>
calculateBounds(positions, inverseTransform);
745 tbb::parallel_reduce(range, calculateBounds);
747 BBoxd bbox = calculateBounds.getBoundingBox();
751 if (bbox.min() == bbox.max())
return voxelSize;
753 double volume = bbox.volume();
758 Vec3d extents = bbox.extents().sorted().reversed();
761 volume = extents[0]*extents[0]*extents[0];
765 volume = extents[0]*extents[1]*extents[1];
769 double previousVolume = volume;
771 if (!Local::voxelSizeFromVolume(volume, targetVoxelCount, voxelSize)) {
776 size_t previousVoxelCount(0);
777 size_t voxelCount(1);
779 if (interrupter) interrupter->start(
"Computing voxel size");
781 while (voxelCount > previousVoxelCount)
804 mask->setTransform(newTransform);
806 pointMaskOp.template addPoints<PositionWrapper, VecT>(positions);
810 previousVoxelCount = voxelCount;
811 voxelCount = mask->activeVoxelCount();
812 volume =
math::Pow3(voxelSize) *
static_cast<float>(voxelCount);
816 if (volume >= previousVolume)
break;
817 previousVolume = volume;
819 const float previousVoxelSize = voxelSize;
823 if (!Local::voxelSizeFromVolume(volume, targetVoxelCount, voxelSize)) {
824 voxelSize = previousVoxelSize;
831 if (voxelSize / previousVoxelSize > 0.9
f)
break;
834 if (interrupter) interrupter->end();
838 return Local::truncate(voxelSize, decimalPlaces);
849 #endif // OPENVDB_POINTS_POINT_CONVERSION_IMPL_HAS_BEEN_INCLUDED
Vec2< T > minComponent(const Vec2< T > &v1, const Vec2< T > &v2)
Return component-wise minimum of the two vectors.
void parallel_for(int64_t start, int64_t end, std::function< void(int64_t index)> &&task, parallel_options opt=parallel_options(0, Split_Y, 1))
Type Truncate(Type x, unsigned int digits)
Return x truncated to the given number of decimal digits.
GLsizei GLenum const void * indices
GLdouble GLdouble GLint GLint const GLdouble * points
Type Pow(Type x, int n)
Return xn.
LeafRange leafRange(size_t grainsize=1) const
Return a TBB-compatible LeafRange.
GLsizei const GLfloat * value
const TreeType & tree() const
Return a const reference to tree associated with this manager.
bool isIdentity(const MatType &m)
Determine if a matrix is an identity matrix.
#define OPENVDB_USE_VERSION_NAMESPACE
Tto convert(const Tfrom &source)
TypedAttributeArray< GroupType, GroupCodec > GroupAttributeArray
MatType unit(const MatType &mat, typename MatType::value_type eps=1.0e-8)
Return a copy of the given matrix with its upper 3×3 rows normalized.
static Ptr create(AttributeArray &array, const bool expand=true)
PointDataGridT::Ptr createPointDataGrid(const PointIndexGridT &pointIndexGrid, const PositionArrayT &positions, const math::Transform &xform, const Metadata *positionDefaultValue)
Localises points with position into a PointDataGrid into two stages: allocation of the leaf attribute...
bool isGroup(const AttributeArray &array)
SYS_FORCE_INLINE const_iterator end() const
void populateAttribute(PointDataTreeT &tree, const PointIndexTreeT &pointIndexTree, const openvdb::Name &attributeName, const PointArrayT &data, const Index stride, const bool insertMetadata)
Stores point attribute data in an existing PointDataGrid attribute.
std::vector< Index > IndexArray
SYS_FORCE_INLINE const X * cast(const InstancablePtr *o)
void preScale(const Vec3< T0 > &v)
GLint GLenum GLboolean GLsizei stride
OPENVDB_API void calculateBounds(const Transform &t, const Vec3d &minWS, const Vec3d &maxWS, Vec3d &minIS, Vec3d &maxIS)
Calculate an axis-aligned bounding box in index space from an axis-aligned bounding box in world spac...
This class manages a linear array of pointers to a given tree's leaf nodes, as well as optional auxil...
Type Pow3(Type x)
Return x3.
Index64 pointCount(const PointDataTreeT &tree, const FilterT &filter, const bool inCoreOnly, const bool threaded)
Count the total number of points in a PointDataTree.
std::pair< Name, Name > NamePair
bool isApproxZero(const Type &x)
Return true if x is equal to zero to within the default floating-point comparison tolerance...
GA_API const UT_StringHolder transform
#define OPENVDB_LOG_DEBUG(mesg)
Typed class for storing attribute data.
void convertPointDataGridAttribute(TypedAttribute &attribute, const PointDataTreeT &tree, const std::vector< Index64 > &pointOffsets, const Index64 startOffset, const unsigned arrayIndex, const Index stride, const FilterT &filter, const bool inCoreOnly)
Convert the attribute from a PointDataGrid.
math::BBox< Vec3d > BBoxd
ImageBuf OIIO_API max(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
Vec2< T > maxComponent(const Vec2< T > &v1, const Vec2< T > &v2)
Return component-wise maximum of the two vectors.
Vec3< typename MatType::value_type > getScale(const MatType &mat)
Return a Vec3 representing the lengths of the passed matrix's upper 3×3's rows.
Index64 pointOffsets(std::vector< Index64 > &pointOffsets, const PointDataTreeT &tree, const FilterT &filter, const bool inCoreOnly, const bool threaded)
Populate an array of cumulative point offsets per leaf node.
GA_API const UT_StringHolder N
OIIO_API bool attribute(string_view name, TypeDesc type, const void *val)
Point-partitioner compatible STL vector attribute wrapper for convenience.
void convertPointDataGridGroup(Group &group, const PointDataTreeT &tree, const std::vector< Index64 > &pointOffsets, const Index64 startOffset, const AttributeSet::Descriptor::GroupIndex index, const FilterT &filter, const bool inCoreOnly)
Convert the group from a PointDataGrid.
ImageBuf OIIO_API add(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
void OIIO_UTIL_API split(string_view str, std::vector< string_view > &result, string_view sep=string_view(), int maxsplit=-1)
bool wasInterrupted(T *i, int percent=-1)
ImageBuf OIIO_API zero(ROI roi, int nthreads=0)
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Mat4 inverse(T tolerance=0) const
void convertPointDataGridPosition(PositionAttribute &positionAttribute, const PointDataGridT &grid, const std::vector< Index64 > &pointOffsets, const Index64 startOffset, const FilterT &filter, const bool inCoreOnly)
Convert the position attribute from a Point Data Grid.
#define OPENVDB_THROW(exception, message)
float computeVoxelSize(const PositionWrapper &positions, const uint32_t pointsPerVoxel, const math::Mat4d transform, const Index decimalPlaces, InterrupterT *const interrupter)
GLint GLint GLint GLint GLint GLint GLint GLbitfield GLenum filter
PcpNodeRef_ChildrenIterator begin(const PcpNodeRef::child_const_range &r)
Support for range-based for loops for PcpNodeRef children ranges.