OpenVDB 13.0.1
Loading...
Searching...
No Matches
MeshToVolume.h
Go to the documentation of this file.
1// Copyright Contributors to the OpenVDB Project
2// SPDX-License-Identifier: Apache-2.0
3
4/// @file MeshToVolume.h
5///
6/// @brief Convert polygonal meshes that consist of quads and/or triangles
7/// into signed or unsigned distance field volumes.
8///
9/// @note The signed distance field conversion requires a closed surface
10/// but not necessarily a manifold surface. Supports surfaces with
11/// self intersections and degenerate faces and is independent of
12/// mesh surface normals / polygon orientation.
13///
14/// @author Mihai Alden
15
16#ifndef OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
17#define OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
18
19#include <openvdb/Platform.h>
20#include <openvdb/Types.h>
21#include <openvdb/math/FiniteDifference.h> // for GodunovsNormSqrd
22#include <openvdb/math/Proximity.h> // for closestPointOnTriangleToPoint
24#include <openvdb/util/Util.h>
25#include <openvdb/util/Assert.h>
27#include <openvdb/openvdb.h>
28
29#include "ChangeBackground.h"
30#include "Prune.h" // for pruneInactive and pruneLevelSet
31#include "SignedFloodFill.h" // for signedFloodFillWithValues
32
33#include <tbb/blocked_range.h>
34#include <tbb/enumerable_thread_specific.h>
35#include <tbb/parallel_for.h>
36#include <tbb/parallel_reduce.h>
37#include <tbb/partitioner.h>
38#include <tbb/task_group.h>
39#include <tbb/task_arena.h>
40
41#include <algorithm> // for std::sort()
42#include <cmath> // for std::isfinite(), std::isnan()
43#include <deque>
44#include <limits>
45#include <memory>
46#include <sstream>
47#include <type_traits>
48#include <vector>
49
50namespace openvdb {
52namespace OPENVDB_VERSION_NAME {
53namespace tools {
54
55
56////////////////////////////////////////
57
58
59/// @brief Mesh to volume conversion flags
61
62 /// Switch from the default signed distance field conversion that classifies
63 /// regions as either inside or outside the mesh boundary to a unsigned distance
64 /// field conversion that only computes distance values. This conversion type
65 /// does not require a closed watertight mesh.
67
68 /// Disable the cleanup step that removes voxels created by self intersecting
69 /// portions of the mesh.
71
72 /// Disable the distance renormalization step that smooths out bumps caused
73 /// by self intersecting or overlapping portions of the mesh
75
76 /// Disable the cleanup step that removes active voxels that exceed the
77 /// narrow band limits. (Only relevant for small limits)
79};
80
81
82/// @brief Different staregies how to determine sign of an SDF when using
83/// interior test.
85
86 /// Evaluates interior test at every voxel. This is usefull when we rebuild already
87 /// existing SDF where evaluating previous grid is cheap
89
90 /// Evaluates interior test at least once per tile and flood fills within the tile.
92};
93
94
95/// @brief Convert polygonal meshes that consist of quads and/or triangles into
96/// signed or unsigned distance field volumes.
97///
98/// @note Requires a closed surface but not necessarily a manifold surface.
99/// Supports surfaces with self intersections and degenerate faces
100/// and is independent of mesh surface normals.
101///
102/// @interface MeshDataAdapter
103/// Expected interface for the MeshDataAdapter class
104/// @code
105/// struct MeshDataAdapter {
106/// size_t polygonCount() const; // Total number of polygons
107/// size_t pointCount() const; // Total number of points
108/// size_t vertexCount(size_t n) const; // Vertex count for polygon n
109///
110/// // Return position pos in local grid index space for polygon n and vertex v
111/// void getIndexSpacePoint(size_t n, size_t v, openvdb::Vec3d& pos) const;
112/// };
113/// @endcode
114///
115/// @param mesh mesh data access class that conforms to the MeshDataAdapter
116/// interface
117/// @param transform world-to-index-space transform
118/// @param exteriorBandWidth exterior narrow band width in voxel units
119/// @param interiorBandWidth interior narrow band width in voxel units
120/// (set to std::numeric_limits<float>::max() to fill object
121/// interior with distance values)
122/// @param flags optional conversion flags defined in @c MeshToVolumeFlags
123/// @param polygonIndexGrid optional grid output that will contain the closest-polygon
124/// index for each voxel in the narrow band region
125/// @param interiorTest function `Coord -> Bool` that evaluates to true inside of the
126/// mesh and false outside, for more see evaluateInteriortest
127/// @param interiorTestStrat determines how the interiorTest is used, see InteriorTestStrategy
128template <typename GridType, typename MeshDataAdapter, typename InteriorTest = std::nullptr_t>
129typename GridType::Ptr
130meshToVolume(
131 const MeshDataAdapter& mesh,
132 const math::Transform& transform,
133 float exteriorBandWidth = 3.0f,
134 float interiorBandWidth = 3.0f,
135 int flags = 0,
136 typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid = nullptr,
137 InteriorTest interiorTest = nullptr,
138 InteriorTestStrategy interiorTestStrat = EVAL_EVERY_VOXEL);
139
140
141/// @brief Convert polygonal meshes that consist of quads and/or triangles into
142/// signed or unsigned distance field volumes.
143///
144/// @param interrupter a callback to interrupt the conversion process that conforms
145/// to the util::NullInterrupter interface
146/// @param mesh mesh data access class that conforms to the MeshDataAdapter
147/// interface
148/// @param transform world-to-index-space transform
149/// @param exteriorBandWidth exterior narrow band width in voxel units
150/// @param interiorBandWidth interior narrow band width in voxel units (set this value to
151/// std::numeric_limits<float>::max() to fill interior regions
152/// with distance values)
153/// @param flags optional conversion flags defined in @c MeshToVolumeFlags
154/// @param polygonIndexGrid optional grid output that will contain the closest-polygon
155/// index for each voxel in the active narrow band region
156/// @param interiorTest function `Coord -> Bool` that evaluates to true inside of the
157/// mesh and false outside, for more see evaluatInteriorTest
158/// @param interiorTestStrat determines how the interiorTest is used, see InteriorTestStrategy
159template <typename GridType, typename MeshDataAdapter, typename Interrupter, typename InteriorTest = std::nullptr_t>
160typename GridType::Ptr
161meshToVolume(
162 Interrupter& interrupter,
163 const MeshDataAdapter& mesh,
164 const math::Transform& transform,
165 float exteriorBandWidth = 3.0f,
166 float interiorBandWidth = 3.0f,
167 int flags = 0,
168 typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid = nullptr,
169 InteriorTest interiorTest = nullptr,
170 InteriorTestStrategy interiorTestStrat = EVAL_EVERY_VOXEL);
171
172
173////////////////////////////////////////
174
175
176/// @brief Contiguous quad and triangle data adapter class
177///
178/// @details PointType and PolygonType must provide element access
179/// through the square brackets operator.
180/// @details Points are assumed to be in local grid index space.
181/// @details The PolygonType tuple can have either three or four components
182/// this property must be specified in a static member variable
183/// named @c size, similar to the math::Tuple class.
184/// @details A four component tuple can represent a quads or a triangle
185/// if the fourth component set to @c util::INVALID_INDEX
186template<typename PointType, typename PolygonType>
188
189 QuadAndTriangleDataAdapter(const std::vector<PointType>& points,
190 const std::vector<PolygonType>& polygons)
191 : mPointArray(points.empty() ? nullptr : &points[0])
192 , mPointArraySize(points.size())
193 , mPolygonArray(polygons.empty() ? nullptr : &polygons[0])
194 , mPolygonArraySize(polygons.size())
195 {
196 }
197
198 QuadAndTriangleDataAdapter(const PointType * pointArray, size_t pointArraySize,
199 const PolygonType* polygonArray, size_t polygonArraySize)
200 : mPointArray(pointArray)
201 , mPointArraySize(pointArraySize)
202 , mPolygonArray(polygonArray)
203 , mPolygonArraySize(polygonArraySize)
204 {
205 }
206
207 size_t polygonCount() const { return mPolygonArraySize; }
208 size_t pointCount() const { return mPointArraySize; }
209
210 /// @brief Vertex count for polygon @a n
211 size_t vertexCount(size_t n) const {
212 return (PolygonType::size == 3 || mPolygonArray[n][3] == util::INVALID_IDX) ? 3 : 4;
213 }
214
215 /// @brief Returns position @a pos in local grid index space
216 /// for polygon @a n and vertex @a v
217 void getIndexSpacePoint(size_t n, size_t v, Vec3d& pos) const {
218 const PointType& p = mPointArray[mPolygonArray[n][int(v)]];
219 pos[0] = double(p[0]);
220 pos[1] = double(p[1]);
221 pos[2] = double(p[2]);
222 }
223
224private:
225 PointType const * const mPointArray;
226 size_t const mPointArraySize;
227 PolygonType const * const mPolygonArray;
228 size_t const mPolygonArraySize;
229}; // struct QuadAndTriangleDataAdapter
230
231
232////////////////////////////////////////
233
234
235// Convenience functions for the mesh to volume converter that wrap stl containers.
236//
237// Note the meshToVolume() method declared above is more flexible and better suited
238// for arbitrary data structures.
239
240
241/// @brief Convert a triangle mesh to a level set volume.
242///
243/// @return a grid of type @c GridType containing a narrow-band level set
244/// representation of the input mesh.
245///
246/// @throw TypeError if @c GridType is not scalar or not floating-point
247///
248/// @note Requires a closed surface but not necessarily a manifold surface.
249/// Supports surfaces with self intersections and degenerate faces
250/// and is independent of mesh surface normals.
251///
252/// @param xform transform for the output grid
253/// @param points list of world space point positions
254/// @param triangles triangle index list
255/// @param halfWidth half the width of the narrow band, in voxel units
256template<typename GridType>
257typename GridType::Ptr
258meshToLevelSet(
259 const openvdb::math::Transform& xform,
260 const std::vector<Vec3s>& points,
261 const std::vector<Vec3I>& triangles,
262 float halfWidth = float(LEVEL_SET_HALF_WIDTH));
263
264/// Adds support for a @a interrupter callback used to cancel the conversion.
265template<typename GridType, typename Interrupter>
266typename GridType::Ptr
267meshToLevelSet(
268 Interrupter& interrupter,
269 const openvdb::math::Transform& xform,
270 const std::vector<Vec3s>& points,
271 const std::vector<Vec3I>& triangles,
272 float halfWidth = float(LEVEL_SET_HALF_WIDTH));
273
274
275/// @brief Convert a quad mesh to a level set volume.
276///
277/// @return a grid of type @c GridType containing a narrow-band level set
278/// representation of the input mesh.
279///
280/// @throw TypeError if @c GridType is not scalar or not floating-point
281///
282/// @note Requires a closed surface but not necessarily a manifold surface.
283/// Supports surfaces with self intersections and degenerate faces
284/// and is independent of mesh surface normals.
285///
286/// @param xform transform for the output grid
287/// @param points list of world space point positions
288/// @param quads quad index list
289/// @param halfWidth half the width of the narrow band, in voxel units
290template<typename GridType>
291typename GridType::Ptr
292meshToLevelSet(
293 const openvdb::math::Transform& xform,
294 const std::vector<Vec3s>& points,
295 const std::vector<Vec4I>& quads,
296 float halfWidth = float(LEVEL_SET_HALF_WIDTH));
297
298/// Adds support for a @a interrupter callback used to cancel the conversion.
299template<typename GridType, typename Interrupter>
300typename GridType::Ptr
301meshToLevelSet(
302 Interrupter& interrupter,
303 const openvdb::math::Transform& xform,
304 const std::vector<Vec3s>& points,
305 const std::vector<Vec4I>& quads,
306 float halfWidth = float(LEVEL_SET_HALF_WIDTH));
307
308
309/// @brief Convert a triangle and quad mesh to a level set volume.
310///
311/// @return a grid of type @c GridType containing a narrow-band level set
312/// representation of the input mesh.
313///
314/// @throw TypeError if @c GridType is not scalar or not floating-point
315///
316/// @note Requires a closed surface but not necessarily a manifold surface.
317/// Supports surfaces with self intersections and degenerate faces
318/// and is independent of mesh surface normals.
319///
320/// @param xform transform for the output grid
321/// @param points list of world space point positions
322/// @param triangles triangle index list
323/// @param quads quad index list
324/// @param halfWidth half the width of the narrow band, in voxel units
325template<typename GridType>
326typename GridType::Ptr
327meshToLevelSet(
328 const openvdb::math::Transform& xform,
329 const std::vector<Vec3s>& points,
330 const std::vector<Vec3I>& triangles,
331 const std::vector<Vec4I>& quads,
332 float halfWidth = float(LEVEL_SET_HALF_WIDTH));
333
334/// Adds support for a @a interrupter callback used to cancel the conversion.
335template<typename GridType, typename Interrupter>
336typename GridType::Ptr
337meshToLevelSet(
338 Interrupter& interrupter,
339 const openvdb::math::Transform& xform,
340 const std::vector<Vec3s>& points,
341 const std::vector<Vec3I>& triangles,
342 const std::vector<Vec4I>& quads,
343 float halfWidth = float(LEVEL_SET_HALF_WIDTH));
344
345
346/// @brief Convert a triangle and quad mesh to a signed distance field
347/// with an asymmetrical narrow band.
348///
349/// @return a grid of type @c GridType containing a narrow-band signed
350/// distance field representation of the input mesh.
351///
352/// @throw TypeError if @c GridType is not scalar or not floating-point
353///
354/// @note Requires a closed surface but not necessarily a manifold surface.
355/// Supports surfaces with self intersections and degenerate faces
356/// and is independent of mesh surface normals.
357///
358/// @param xform transform for the output grid
359/// @param points list of world space point positions
360/// @param triangles triangle index list
361/// @param quads quad index list
362/// @param exBandWidth the exterior narrow-band width in voxel units
363/// @param inBandWidth the interior narrow-band width in voxel units
364template<typename GridType>
365typename GridType::Ptr
366meshToSignedDistanceField(
367 const openvdb::math::Transform& xform,
368 const std::vector<Vec3s>& points,
369 const std::vector<Vec3I>& triangles,
370 const std::vector<Vec4I>& quads,
371 float exBandWidth,
372 float inBandWidth);
373
374/// Adds support for a @a interrupter callback used to cancel the conversion.
375template<typename GridType, typename Interrupter>
376typename GridType::Ptr
377meshToSignedDistanceField(
378 Interrupter& interrupter,
379 const openvdb::math::Transform& xform,
380 const std::vector<Vec3s>& points,
381 const std::vector<Vec3I>& triangles,
382 const std::vector<Vec4I>& quads,
383 float exBandWidth,
384 float inBandWidth);
385
386
387/// @brief Convert a triangle and quad mesh to an unsigned distance field.
388///
389/// @return a grid of type @c GridType containing a narrow-band unsigned
390/// distance field representation of the input mesh.
391///
392/// @throw TypeError if @c GridType is not scalar or not floating-point
393///
394/// @note Does not requires a closed surface.
395///
396/// @param xform transform for the output grid
397/// @param points list of world space point positions
398/// @param triangles triangle index list
399/// @param quads quad index list
400/// @param bandWidth the width of the narrow band, in voxel units
401template<typename GridType>
402typename GridType::Ptr
403meshToUnsignedDistanceField(
404 const openvdb::math::Transform& xform,
405 const std::vector<Vec3s>& points,
406 const std::vector<Vec3I>& triangles,
407 const std::vector<Vec4I>& quads,
408 float bandWidth);
409
410/// Adds support for a @a interrupter callback used to cancel the conversion.
411template<typename GridType, typename Interrupter>
412typename GridType::Ptr
413meshToUnsignedDistanceField(
414 Interrupter& interrupter,
415 const openvdb::math::Transform& xform,
416 const std::vector<Vec3s>& points,
417 const std::vector<Vec3I>& triangles,
418 const std::vector<Vec4I>& quads,
419 float bandWidth);
420
421
422////////////////////////////////////////
423
424
425/// @brief Return a grid of type @c GridType containing a narrow-band level set
426/// representation of a box.
427///
428/// @param bbox a bounding box in world units
429/// @param xform world-to-index-space transform
430/// @param halfWidth half the width of the narrow band, in voxel units
431template<typename GridType, typename VecType>
432typename GridType::Ptr
433createLevelSetBox(const math::BBox<VecType>& bbox,
434 const openvdb::math::Transform& xform,
435 typename VecType::ValueType halfWidth = LEVEL_SET_HALF_WIDTH);
436
437
438////////////////////////////////////////
439
440
441/// @brief Traces the exterior voxel boundary of closed objects in the input
442/// volume @a tree. Exterior voxels are marked with a negative sign,
443/// voxels with a value below @c 0.75 are left unchanged and act as
444/// the boundary layer.
445///
446/// @note Does not propagate sign information into tile regions.
447template <typename FloatTreeT>
448void
449traceExteriorBoundaries(FloatTreeT& tree);
450
451
452////////////////////////////////////////
453
454
455/// @brief Extracts and stores voxel edge intersection data from a mesh.
457{
458public:
459
460 //////////
461
462 ///@brief Internal edge data type.
463 struct EdgeData {
464 EdgeData(float dist = 1.0)
465 : mXDist(dist), mYDist(dist), mZDist(dist)
466 , mXPrim(util::INVALID_IDX)
467 , mYPrim(util::INVALID_IDX)
468 , mZPrim(util::INVALID_IDX)
469 {
470 }
471
472 //@{
473 /// Required by several of the tree nodes
474 /// @note These methods don't perform meaningful operations.
475 bool operator< (const EdgeData&) const { return false; }
476 bool operator> (const EdgeData&) const { return false; }
477 template<class T> EdgeData operator+(const T&) const { return *this; }
478 template<class T> EdgeData operator-(const T&) const { return *this; }
479 EdgeData operator-() const { return *this; }
480 //@}
481
482 bool operator==(const EdgeData& rhs) const
483 {
484 return mXPrim == rhs.mXPrim && mYPrim == rhs.mYPrim && mZPrim == rhs.mZPrim;
485 }
486
489 };
490
493
494
495 //////////
496
497
499
500
501 /// @brief Threaded method to extract voxel edge data, the closest
502 /// intersection point and corresponding primitive index,
503 /// from the given mesh.
504 ///
505 /// @param pointList List of points in grid index space, preferably unique
506 /// and shared by different polygons.
507 /// @param polygonList List of triangles and/or quads.
508 void convert(const std::vector<Vec3s>& pointList, const std::vector<Vec4I>& polygonList);
509
510
511 /// @brief Returns intersection points with corresponding primitive
512 /// indices for the given @c ijk voxel.
513 void getEdgeData(Accessor& acc, const Coord& ijk,
514 std::vector<Vec3d>& points, std::vector<Index32>& primitives);
515
516 /// @return An accessor of @c MeshToVoxelEdgeData::Accessor type that
517 /// provides random read access to the internal tree.
518 Accessor getAccessor() { return Accessor(mTree); }
519
520private:
521 void operator=(const MeshToVoxelEdgeData&) {}
522 TreeType mTree;
523 class GenEdgeData;
524};
525
526
527////////////////////////////////////////////////////////////////////////////////
528////////////////////////////////////////////////////////////////////////////////
529
530
531// Internal utility objects and implementation details
532
533/// @cond OPENVDB_DOCS_INTERNAL
534
535namespace mesh_to_volume_internal {
536
537template<typename PointType>
538struct TransformPoints {
539
540 TransformPoints(const PointType* pointsIn, PointType* pointsOut,
541 const math::Transform& xform)
542 : mPointsIn(pointsIn), mPointsOut(pointsOut), mXform(&xform)
543 {
544 }
545
546 void operator()(const tbb::blocked_range<size_t>& range) const {
547
548 Vec3d pos;
549
550 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
551
552 const PointType& wsP = mPointsIn[n];
553 pos[0] = double(wsP[0]);
554 pos[1] = double(wsP[1]);
555 pos[2] = double(wsP[2]);
556
557 pos = mXform->worldToIndex(pos);
558
559 PointType& isP = mPointsOut[n];
560 isP[0] = typename PointType::value_type(pos[0]);
561 isP[1] = typename PointType::value_type(pos[1]);
562 isP[2] = typename PointType::value_type(pos[2]);
563 }
564 }
565
566 PointType const * const mPointsIn;
567 PointType * const mPointsOut;
568 math::Transform const * const mXform;
569}; // TransformPoints
570
571
572template<typename ValueType>
573struct Tolerance
574{
575 static ValueType epsilon() { return ValueType(1e-7); }
576 static ValueType minNarrowBandWidth() { return ValueType(1.0 + 1e-6); }
577};
578
579
580////////////////////////////////////////
581
582
583template<typename TreeType>
584class CombineLeafNodes
585{
586public:
587
588 using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
589
590 using LeafNodeType = typename TreeType::LeafNodeType;
591 using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
592
593 CombineLeafNodes(TreeType& lhsDistTree, Int32TreeType& lhsIdxTree,
594 LeafNodeType ** rhsDistNodes, Int32LeafNodeType ** rhsIdxNodes)
595 : mDistTree(&lhsDistTree)
596 , mIdxTree(&lhsIdxTree)
597 , mRhsDistNodes(rhsDistNodes)
598 , mRhsIdxNodes(rhsIdxNodes)
599 {
600 }
601
602 void operator()(const tbb::blocked_range<size_t>& range) const {
603
604 tree::ValueAccessor<TreeType> distAcc(*mDistTree);
605 tree::ValueAccessor<Int32TreeType> idxAcc(*mIdxTree);
606
607 using DistValueType = typename LeafNodeType::ValueType;
608 using IndexValueType = typename Int32LeafNodeType::ValueType;
609
610 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
611
612 const Coord& origin = mRhsDistNodes[n]->origin();
613
614 LeafNodeType* lhsDistNode = distAcc.probeLeaf(origin);
615 Int32LeafNodeType* lhsIdxNode = idxAcc.probeLeaf(origin);
616
617 DistValueType* lhsDistData = lhsDistNode->buffer().data();
618 IndexValueType* lhsIdxData = lhsIdxNode->buffer().data();
619
620 const DistValueType* rhsDistData = mRhsDistNodes[n]->buffer().data();
621 const IndexValueType* rhsIdxData = mRhsIdxNodes[n]->buffer().data();
622
623
624 for (Index32 offset = 0; offset < LeafNodeType::SIZE; ++offset) {
625
626 if (rhsIdxData[offset] != Int32(util::INVALID_IDX)) {
627
628 const DistValueType& lhsValue = lhsDistData[offset];
629 const DistValueType& rhsValue = rhsDistData[offset];
630
631 if (rhsValue < lhsValue) {
632 lhsDistNode->setValueOn(offset, rhsValue);
633 lhsIdxNode->setValueOn(offset, rhsIdxData[offset]);
634 } else if (math::isExactlyEqual(rhsValue, lhsValue)) {
635 lhsIdxNode->setValueOn(offset,
636 std::min(lhsIdxData[offset], rhsIdxData[offset]));
637 }
638 }
639 }
640
641 delete mRhsDistNodes[n];
642 delete mRhsIdxNodes[n];
643 }
644 }
645
646private:
647
648 TreeType * const mDistTree;
649 Int32TreeType * const mIdxTree;
650
651 LeafNodeType ** const mRhsDistNodes;
652 Int32LeafNodeType ** const mRhsIdxNodes;
653}; // class CombineLeafNodes
654
655
656////////////////////////////////////////
657
658
659template<typename TreeType>
660struct StashOriginAndStoreOffset
661{
662 using LeafNodeType = typename TreeType::LeafNodeType;
663
664 StashOriginAndStoreOffset(std::vector<LeafNodeType*>& nodes, Coord* coordinates)
665 : mNodes(nodes.empty() ? nullptr : &nodes[0]), mCoordinates(coordinates)
666 {
667 }
668
669 void operator()(const tbb::blocked_range<size_t>& range) const {
670 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
671 Coord& origin = const_cast<Coord&>(mNodes[n]->origin());
672 mCoordinates[n] = origin;
673 origin[0] = static_cast<int>(n);
674 }
675 }
676
677 LeafNodeType ** const mNodes;
678 Coord * const mCoordinates;
679};
680
681
682template<typename TreeType>
683struct RestoreOrigin
684{
685 using LeafNodeType = typename TreeType::LeafNodeType;
686
687 RestoreOrigin(std::vector<LeafNodeType*>& nodes, const Coord* coordinates)
688 : mNodes(nodes.empty() ? nullptr : &nodes[0]), mCoordinates(coordinates)
689 {
690 }
691
692 void operator()(const tbb::blocked_range<size_t>& range) const {
693 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
694 Coord& origin = const_cast<Coord&>(mNodes[n]->origin());
695 origin[0] = mCoordinates[n][0];
696 }
697 }
698
699 LeafNodeType ** const mNodes;
700 Coord const * const mCoordinates;
701};
702
703
704template<typename TreeType>
705class ComputeNodeConnectivity
706{
707public:
708 using LeafNodeType = typename TreeType::LeafNodeType;
709
710 ComputeNodeConnectivity(const TreeType& tree, const Coord* coordinates,
711 size_t* offsets, size_t numNodes, const CoordBBox& bbox)
712 : mTree(&tree)
713 , mCoordinates(coordinates)
714 , mOffsets(offsets)
715 , mNumNodes(numNodes)
716 , mBBox(bbox)
717 {
718 }
719
720 ComputeNodeConnectivity(const ComputeNodeConnectivity&) = default;
721
722 // Disallow assignment
723 ComputeNodeConnectivity& operator=(const ComputeNodeConnectivity&) = delete;
724
725 void operator()(const tbb::blocked_range<size_t>& range) const {
726
727 size_t* offsetsNextX = mOffsets;
728 size_t* offsetsPrevX = mOffsets + mNumNodes;
729 size_t* offsetsNextY = mOffsets + mNumNodes * 2;
730 size_t* offsetsPrevY = mOffsets + mNumNodes * 3;
731 size_t* offsetsNextZ = mOffsets + mNumNodes * 4;
732 size_t* offsetsPrevZ = mOffsets + mNumNodes * 5;
733
734 tree::ValueAccessor<const TreeType> acc(*mTree);
735 Coord ijk;
736 const Int32 DIM = static_cast<Int32>(LeafNodeType::DIM);
737
738 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
739 const Coord& origin = mCoordinates[n];
740 offsetsNextX[n] = findNeighbourNode(acc, origin, Coord(DIM, 0, 0));
741 offsetsPrevX[n] = findNeighbourNode(acc, origin, Coord(-DIM, 0, 0));
742 offsetsNextY[n] = findNeighbourNode(acc, origin, Coord(0, DIM, 0));
743 offsetsPrevY[n] = findNeighbourNode(acc, origin, Coord(0, -DIM, 0));
744 offsetsNextZ[n] = findNeighbourNode(acc, origin, Coord(0, 0, DIM));
745 offsetsPrevZ[n] = findNeighbourNode(acc, origin, Coord(0, 0, -DIM));
746 }
747 }
748
749 size_t findNeighbourNode(tree::ValueAccessor<const TreeType>& acc,
750 const Coord& start, const Coord& step) const
751 {
752 Coord ijk = start + step;
753 CoordBBox bbox(mBBox);
754
755 while (bbox.isInside(ijk)) {
756 const LeafNodeType* node = acc.probeConstLeaf(ijk);
757 if (node) return static_cast<size_t>(node->origin()[0]);
758 ijk += step;
759 }
760
761 return std::numeric_limits<size_t>::max();
762 }
763
764
765private:
766 TreeType const * const mTree;
767 Coord const * const mCoordinates;
768 size_t * const mOffsets;
769
770 const size_t mNumNodes;
771 const CoordBBox mBBox;
772}; // class ComputeNodeConnectivity
773
774
775template<typename TreeType>
776struct LeafNodeConnectivityTable
777{
778 enum { INVALID_OFFSET = std::numeric_limits<size_t>::max() };
779
780 using LeafNodeType = typename TreeType::LeafNodeType;
781
782 LeafNodeConnectivityTable(TreeType& tree)
783 {
784 mLeafNodes.reserve(tree.leafCount());
785 tree.getNodes(mLeafNodes);
786
787 if (mLeafNodes.empty()) return;
788
789 CoordBBox bbox;
790 tree.evalLeafBoundingBox(bbox);
791
792 const tbb::blocked_range<size_t> range(0, mLeafNodes.size());
793
794 // stash the leafnode origin coordinate and temporarily store the
795 // linear offset in the origin.x variable.
796 std::unique_ptr<Coord[]> coordinates{new Coord[mLeafNodes.size()]};
797 tbb::parallel_for(range,
798 StashOriginAndStoreOffset<TreeType>(mLeafNodes, coordinates.get()));
799
800 // build the leafnode offset table
801 mOffsets.reset(new size_t[mLeafNodes.size() * 6]);
802
803
804 tbb::parallel_for(range, ComputeNodeConnectivity<TreeType>(
805 tree, coordinates.get(), mOffsets.get(), mLeafNodes.size(), bbox));
806
807 // restore the leafnode origin coordinate
808 tbb::parallel_for(range, RestoreOrigin<TreeType>(mLeafNodes, coordinates.get()));
809 }
810
811 size_t size() const { return mLeafNodes.size(); }
812
813 std::vector<LeafNodeType*>& nodes() { return mLeafNodes; }
814 const std::vector<LeafNodeType*>& nodes() const { return mLeafNodes; }
815
816
817 const size_t* offsetsNextX() const { return mOffsets.get(); }
818 const size_t* offsetsPrevX() const { return mOffsets.get() + mLeafNodes.size(); }
819
820 const size_t* offsetsNextY() const { return mOffsets.get() + mLeafNodes.size() * 2; }
821 const size_t* offsetsPrevY() const { return mOffsets.get() + mLeafNodes.size() * 3; }
822
823 const size_t* offsetsNextZ() const { return mOffsets.get() + mLeafNodes.size() * 4; }
824 const size_t* offsetsPrevZ() const { return mOffsets.get() + mLeafNodes.size() * 5; }
825
826private:
827 std::vector<LeafNodeType*> mLeafNodes;
828 std::unique_ptr<size_t[]> mOffsets;
829}; // struct LeafNodeConnectivityTable
830
831
832template<typename TreeType>
833class SweepExteriorSign
834{
835public:
836
837 enum Axis { X_AXIS = 0, Y_AXIS = 1, Z_AXIS = 2 };
838
839 using ValueType = typename TreeType::ValueType;
840 using LeafNodeType = typename TreeType::LeafNodeType;
841 using ConnectivityTable = LeafNodeConnectivityTable<TreeType>;
842
843 SweepExteriorSign(Axis axis, const std::vector<size_t>& startNodeIndices,
844 ConnectivityTable& connectivity)
845 : mStartNodeIndices(startNodeIndices.empty() ? nullptr : &startNodeIndices[0])
846 , mConnectivity(&connectivity)
847 , mAxis(axis)
848 {
849 }
850
851 void operator()(const tbb::blocked_range<size_t>& range) const {
852
853 constexpr Int32 DIM = static_cast<Int32>(LeafNodeType::DIM);
854
855 std::vector<LeafNodeType*>& nodes = mConnectivity->nodes();
856
857 // Z Axis
858 size_t idxA = 0, idxB = 1;
859 Int32 step = 1;
860
861 const size_t* nextOffsets = mConnectivity->offsetsNextZ();
862 const size_t* prevOffsets = mConnectivity->offsetsPrevZ();
863
864 if (mAxis == Y_AXIS) {
865
866 idxA = 0;
867 idxB = 2;
868 step = DIM;
869
870 nextOffsets = mConnectivity->offsetsNextY();
871 prevOffsets = mConnectivity->offsetsPrevY();
872
873 } else if (mAxis == X_AXIS) {
874
875 idxA = 1;
876 idxB = 2;
877 step = DIM*DIM;
878
879 nextOffsets = mConnectivity->offsetsNextX();
880 prevOffsets = mConnectivity->offsetsPrevX();
881 }
882
883 Coord ijk(0, 0, 0);
884
885 Int32& a = ijk[idxA];
886 Int32& b = ijk[idxB];
887
888 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
889
890 size_t startOffset = mStartNodeIndices[n];
891 size_t lastOffset = startOffset;
892
893 Int32 pos(0);
894
895 for (a = 0; a < DIM; ++a) {
896 for (b = 0; b < DIM; ++b) {
897
898 pos = static_cast<Int32>(LeafNodeType::coordToOffset(ijk));
899 size_t offset = startOffset;
900
901 // sweep in +axis direction until a boundary voxel is hit.
902 while ( offset != ConnectivityTable::INVALID_OFFSET &&
903 traceVoxelLine(*nodes[offset], pos, step) ) {
904
905 lastOffset = offset;
906 offset = nextOffsets[offset];
907 }
908
909 // find last leafnode in +axis direction
910 offset = lastOffset;
911 while (offset != ConnectivityTable::INVALID_OFFSET) {
912 lastOffset = offset;
913 offset = nextOffsets[offset];
914 }
915
916 // sweep in -axis direction until a boundary voxel is hit.
917 offset = lastOffset;
918 pos += step * (DIM - 1);
919 while ( offset != ConnectivityTable::INVALID_OFFSET &&
920 traceVoxelLine(*nodes[offset], pos, -step)) {
921 offset = prevOffsets[offset];
922 }
923 }
924 }
925 }
926 }
927
928
929 bool traceVoxelLine(LeafNodeType& node, Int32 pos, const Int32 step) const {
930
931 ValueType* data = node.buffer().data();
932
933 bool isOutside = true;
934
935 for (Index i = 0; i < LeafNodeType::DIM; ++i) {
936
937 OPENVDB_ASSERT(pos >= 0);
938 ValueType& dist = data[pos];
939
940 if (dist < ValueType(0.0)) {
941 isOutside = true;
942 } else {
943 // Boundary voxel check. (Voxel that intersects the surface)
944 if (!(dist > ValueType(0.75))) isOutside = false;
945
946 if (isOutside) dist = ValueType(-dist);
947 }
948
949 pos += step;
950 }
951
952 return isOutside;
953 }
954
955
956private:
957 size_t const * const mStartNodeIndices;
958 ConnectivityTable * const mConnectivity;
959
960 const Axis mAxis;
961}; // class SweepExteriorSign
962
963
964template<typename LeafNodeType>
965inline void
966seedFill(LeafNodeType& node)
967{
968 using ValueType = typename LeafNodeType::ValueType;
969 using Queue = std::deque<Index>;
970
971
972 ValueType* data = node.buffer().data();
973
974 // find seed points
975 Queue seedPoints;
976 for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
977 if (data[pos] < 0.0) seedPoints.push_back(pos);
978 }
979
980 if (seedPoints.empty()) return;
981
982 // clear sign information
983 for (Queue::iterator it = seedPoints.begin(); it != seedPoints.end(); ++it) {
984 ValueType& dist = data[*it];
985 dist = -dist;
986 }
987
988 // flood fill
989
990 Coord ijk(0, 0, 0);
991 Index pos(0), nextPos(0);
992
993 while (!seedPoints.empty()) {
994
995 pos = seedPoints.back();
996 seedPoints.pop_back();
997
998 ValueType& dist = data[pos];
999
1000 if (!(dist < ValueType(0.0))) {
1001
1002 dist = -dist; // flip sign
1003
1004 ijk = LeafNodeType::offsetToLocalCoord(pos);
1005
1006 if (ijk[0] != 0) { // i - 1, j, k
1007 nextPos = pos - LeafNodeType::DIM * LeafNodeType::DIM;
1008 if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1009 }
1010
1011 if (ijk[0] != (LeafNodeType::DIM - 1)) { // i + 1, j, k
1012 nextPos = pos + LeafNodeType::DIM * LeafNodeType::DIM;
1013 if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1014 }
1015
1016 if (ijk[1] != 0) { // i, j - 1, k
1017 nextPos = pos - LeafNodeType::DIM;
1018 if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1019 }
1020
1021 if (ijk[1] != (LeafNodeType::DIM - 1)) { // i, j + 1, k
1022 nextPos = pos + LeafNodeType::DIM;
1023 if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1024 }
1025
1026 if (ijk[2] != 0) { // i, j, k - 1
1027 nextPos = pos - 1;
1028 if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1029 }
1030
1031 if (ijk[2] != (LeafNodeType::DIM - 1)) { // i, j, k + 1
1032 nextPos = pos + 1;
1033 if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1034 }
1035 }
1036 }
1037} // seedFill()
1038
1039
1040template<typename LeafNodeType>
1041inline bool
1042scanFill(LeafNodeType& node)
1043{
1044 bool updatedNode = false;
1045
1046 using ValueType = typename LeafNodeType::ValueType;
1047 ValueType* data = node.buffer().data();
1048
1049 Coord ijk(0, 0, 0);
1050
1051 bool updatedSign = true;
1052 while (updatedSign) {
1053
1054 updatedSign = false;
1055
1056 for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
1057
1058 ValueType& dist = data[pos];
1059
1060 if (!(dist < ValueType(0.0)) && dist > ValueType(0.75)) {
1061
1062 ijk = LeafNodeType::offsetToLocalCoord(pos);
1063
1064 // i, j, k - 1
1065 if (ijk[2] != 0 && data[pos - 1] < ValueType(0.0)) {
1066 updatedSign = true;
1067 dist = ValueType(-dist);
1068
1069 // i, j, k + 1
1070 } else if (ijk[2] != (LeafNodeType::DIM - 1) && data[pos + 1] < ValueType(0.0)) {
1071 updatedSign = true;
1072 dist = ValueType(-dist);
1073
1074 // i, j - 1, k
1075 } else if (ijk[1] != 0 && data[pos - LeafNodeType::DIM] < ValueType(0.0)) {
1076 updatedSign = true;
1077 dist = ValueType(-dist);
1078
1079 // i, j + 1, k
1080 } else if (ijk[1] != (LeafNodeType::DIM - 1)
1081 && data[pos + LeafNodeType::DIM] < ValueType(0.0))
1082 {
1083 updatedSign = true;
1084 dist = ValueType(-dist);
1085
1086 // i - 1, j, k
1087 } else if (ijk[0] != 0
1088 && data[pos - LeafNodeType::DIM * LeafNodeType::DIM] < ValueType(0.0))
1089 {
1090 updatedSign = true;
1091 dist = ValueType(-dist);
1092
1093 // i + 1, j, k
1094 } else if (ijk[0] != (LeafNodeType::DIM - 1)
1095 && data[pos + LeafNodeType::DIM * LeafNodeType::DIM] < ValueType(0.0))
1096 {
1097 updatedSign = true;
1098 dist = ValueType(-dist);
1099 }
1100 }
1101 } // end value loop
1102
1103 updatedNode |= updatedSign;
1104 } // end update loop
1105
1106 return updatedNode;
1107} // scanFill()
1108
1109
1110template<typename TreeType>
1111class SeedFillExteriorSign
1112{
1113public:
1114 using ValueType = typename TreeType::ValueType;
1115 using LeafNodeType = typename TreeType::LeafNodeType;
1116
1117 SeedFillExteriorSign(std::vector<LeafNodeType*>& nodes, const bool* changedNodeMask)
1118 : mNodes(nodes.empty() ? nullptr : &nodes[0])
1119 , mChangedNodeMask(changedNodeMask)
1120 {
1121 }
1122
1123 void operator()(const tbb::blocked_range<size_t>& range) const {
1124 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1125 if (mChangedNodeMask[n]) {
1126 //seedFill(*mNodes[n]);
1127 // Do not update the flag in mChangedNodeMask even if scanFill
1128 // returns false. mChangedNodeMask is queried by neighboring
1129 // accesses in ::SeedPoints which needs to know that this
1130 // node has values propagated on a previous iteration.
1131 scanFill(*mNodes[n]);
1132 }
1133 }
1134 }
1135
1136 LeafNodeType ** const mNodes;
1137 const bool * const mChangedNodeMask;
1138};
1139
1140
1141template<typename ValueType>
1142struct FillArray
1143{
1144 FillArray(ValueType* array, const ValueType v) : mArray(array), mValue(v) { }
1145
1146 void operator()(const tbb::blocked_range<size_t>& range) const {
1147 const ValueType v = mValue;
1148 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1149 mArray[n] = v;
1150 }
1151 }
1152
1153 ValueType * const mArray;
1154 const ValueType mValue;
1155};
1156
1157
1158template<typename ValueType>
1159inline void
1160fillArray(ValueType* array, const ValueType val, const size_t length)
1161{
1162 const auto grainSize = std::max<size_t>(
1163 length / tbb::this_task_arena::max_concurrency(), 1024);
1164 const tbb::blocked_range<size_t> range(0, length, grainSize);
1165 tbb::parallel_for(range, FillArray<ValueType>(array, val), tbb::simple_partitioner());
1166}
1167
1168
1169template<typename TreeType>
1170class SyncVoxelMask
1171{
1172public:
1173 using ValueType = typename TreeType::ValueType;
1174 using LeafNodeType = typename TreeType::LeafNodeType;
1175
1176 SyncVoxelMask(std::vector<LeafNodeType*>& nodes,
1177 const bool* changedNodeMask, bool* changedVoxelMask)
1178 : mNodes(nodes.empty() ? nullptr : &nodes[0])
1179 , mChangedNodeMask(changedNodeMask)
1180 , mChangedVoxelMask(changedVoxelMask)
1181 {
1182 }
1183
1184 void operator()(const tbb::blocked_range<size_t>& range) const {
1185 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1186
1187 if (mChangedNodeMask[n]) {
1188 bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
1189
1190 ValueType* data = mNodes[n]->buffer().data();
1191
1192 for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
1193 if (mask[pos]) {
1194 data[pos] = ValueType(-data[pos]);
1195 mask[pos] = false;
1196 }
1197 }
1198 }
1199 }
1200 }
1201
1202 LeafNodeType ** const mNodes;
1203 bool const * const mChangedNodeMask;
1204 bool * const mChangedVoxelMask;
1205};
1206
1207
1208template<typename TreeType>
1209class SeedPoints
1210{
1211public:
1212 using ValueType = typename TreeType::ValueType;
1213 using LeafNodeType = typename TreeType::LeafNodeType;
1214 using ConnectivityTable = LeafNodeConnectivityTable<TreeType>;
1215
1216 SeedPoints(ConnectivityTable& connectivity,
1217 bool* changedNodeMask, bool* nodeMask, bool* changedVoxelMask)
1218 : mConnectivity(&connectivity)
1219 , mChangedNodeMask(changedNodeMask)
1220 , mNodeMask(nodeMask)
1221 , mChangedVoxelMask(changedVoxelMask)
1222 {
1223 }
1224
1225 void operator()(const tbb::blocked_range<size_t>& range) const {
1226
1227 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1228 bool changedValue = false;
1229
1230 changedValue |= processZ(n, /*firstFace=*/true);
1231 changedValue |= processZ(n, /*firstFace=*/false);
1232
1233 changedValue |= processY(n, /*firstFace=*/true);
1234 changedValue |= processY(n, /*firstFace=*/false);
1235
1236 changedValue |= processX(n, /*firstFace=*/true);
1237 changedValue |= processX(n, /*firstFace=*/false);
1238
1239 mNodeMask[n] = changedValue;
1240 }
1241 }
1242
1243
1244 bool processZ(const size_t n, bool firstFace) const
1245 {
1246 const size_t offset =
1247 firstFace ? mConnectivity->offsetsPrevZ()[n] : mConnectivity->offsetsNextZ()[n];
1248 if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1249
1250 bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
1251
1252 const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1253 const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1254
1255 const Index lastOffset = LeafNodeType::DIM - 1;
1256 const Index lhsOffset =
1257 firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1258
1259 Index tmpPos(0), pos(0);
1260 bool changedValue = false;
1261
1262 for (Index x = 0; x < LeafNodeType::DIM; ++x) {
1263 tmpPos = x << (2 * LeafNodeType::LOG2DIM);
1264 for (Index y = 0; y < LeafNodeType::DIM; ++y) {
1265 pos = tmpPos + (y << LeafNodeType::LOG2DIM);
1266
1267 if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1268 if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1269 changedValue = true;
1270 mask[pos + lhsOffset] = true;
1271 }
1272 }
1273 }
1274 }
1275
1276 return changedValue;
1277 }
1278
1279 return false;
1280 }
1281
1282 bool processY(const size_t n, bool firstFace) const
1283 {
1284 const size_t offset =
1285 firstFace ? mConnectivity->offsetsPrevY()[n] : mConnectivity->offsetsNextY()[n];
1286 if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1287
1288 bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
1289
1290 const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1291 const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1292
1293 const Index lastOffset = LeafNodeType::DIM * (LeafNodeType::DIM - 1);
1294 const Index lhsOffset =
1295 firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1296
1297 Index tmpPos(0), pos(0);
1298 bool changedValue = false;
1299
1300 for (Index x = 0; x < LeafNodeType::DIM; ++x) {
1301 tmpPos = x << (2 * LeafNodeType::LOG2DIM);
1302 for (Index z = 0; z < LeafNodeType::DIM; ++z) {
1303 pos = tmpPos + z;
1304
1305 if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1306 if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1307 changedValue = true;
1308 mask[pos + lhsOffset] = true;
1309 }
1310 }
1311 }
1312 }
1313
1314 return changedValue;
1315 }
1316
1317 return false;
1318 }
1319
1320 bool processX(const size_t n, bool firstFace) const
1321 {
1322 const size_t offset =
1323 firstFace ? mConnectivity->offsetsPrevX()[n] : mConnectivity->offsetsNextX()[n];
1324 if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1325
1326 bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
1327
1328 const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1329 const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1330
1331 const Index lastOffset = LeafNodeType::DIM * LeafNodeType::DIM * (LeafNodeType::DIM-1);
1332 const Index lhsOffset =
1333 firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1334
1335 Index tmpPos(0), pos(0);
1336 bool changedValue = false;
1337
1338 for (Index y = 0; y < LeafNodeType::DIM; ++y) {
1339 tmpPos = y << LeafNodeType::LOG2DIM;
1340 for (Index z = 0; z < LeafNodeType::DIM; ++z) {
1341 pos = tmpPos + z;
1342
1343 if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1344 if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1345 changedValue = true;
1346 mask[pos + lhsOffset] = true;
1347 }
1348 }
1349 }
1350 }
1351
1352 return changedValue;
1353 }
1354
1355 return false;
1356 }
1357
1358 ConnectivityTable * const mConnectivity;
1359 bool * const mChangedNodeMask;
1360 bool * const mNodeMask;
1361 bool * const mChangedVoxelMask;
1362};
1363
1364
1365////////////////////////////////////////
1366
1367template<typename TreeType, typename MeshDataAdapter>
1368struct ComputeIntersectingVoxelSign
1369{
1370 using ValueType = typename TreeType::ValueType;
1371 using LeafNodeType = typename TreeType::LeafNodeType;
1372 using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1373 using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
1374
1375 using PointArray = std::unique_ptr<Vec3d[]>;
1376 using MaskArray = std::unique_ptr<bool[]>;
1377 using LocalData = std::pair<PointArray, MaskArray>;
1378 using LocalDataTable = tbb::enumerable_thread_specific<LocalData>;
1379
1380 ComputeIntersectingVoxelSign(
1381 std::vector<LeafNodeType*>& distNodes,
1382 const TreeType& distTree,
1383 const Int32TreeType& indexTree,
1384 const MeshDataAdapter& mesh)
1385 : mDistNodes(distNodes.empty() ? nullptr : &distNodes[0])
1386 , mDistTree(&distTree)
1387 , mIndexTree(&indexTree)
1388 , mMesh(&mesh)
1389 , mLocalDataTable(new LocalDataTable())
1390 {
1391 }
1392
1393
1394 void operator()(const tbb::blocked_range<size_t>& range) const {
1395
1396 tree::ValueAccessor<const TreeType> distAcc(*mDistTree);
1397 tree::ValueAccessor<const Int32TreeType> idxAcc(*mIndexTree);
1398
1399 ValueType nval;
1400 CoordBBox bbox;
1401 Index xPos(0), yPos(0);
1402 Coord ijk, nijk, nodeMin, nodeMax;
1403 Vec3d cp, xyz, nxyz, dir1, dir2;
1404
1405 LocalData& localData = mLocalDataTable->local();
1406
1407 PointArray& points = localData.first;
1408 if (!points) points.reset(new Vec3d[LeafNodeType::SIZE * 2]);
1409
1410 MaskArray& mask = localData.second;
1411 if (!mask) mask.reset(new bool[LeafNodeType::SIZE]);
1412
1413
1414 typename LeafNodeType::ValueOnCIter it;
1415
1416 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1417
1418 LeafNodeType& node = *mDistNodes[n];
1419 ValueType* data = node.buffer().data();
1420
1421 const Int32LeafNodeType* idxNode = idxAcc.probeConstLeaf(node.origin());
1422 const Int32* idxData = idxNode->buffer().data();
1423
1424 nodeMin = node.origin();
1425 nodeMax = nodeMin.offsetBy(LeafNodeType::DIM - 1);
1426
1427 // reset computed voxel mask.
1428 memset(mask.get(), 0, sizeof(bool) * LeafNodeType::SIZE);
1429
1430 for (it = node.cbeginValueOn(); it; ++it) {
1431 Index pos = it.pos();
1432
1433 ValueType& dist = data[pos];
1434 if (dist < 0.0 || dist > 0.75) continue;
1435
1436 ijk = node.offsetToGlobalCoord(pos);
1437
1438 xyz[0] = double(ijk[0]);
1439 xyz[1] = double(ijk[1]);
1440 xyz[2] = double(ijk[2]);
1441
1442
1443 bbox.min() = Coord::maxComponent(ijk.offsetBy(-1), nodeMin);
1444 bbox.max() = Coord::minComponent(ijk.offsetBy(1), nodeMax);
1445
1446 bool flipSign = false;
1447
1448 for (nijk[0] = bbox.min()[0]; nijk[0] <= bbox.max()[0] && !flipSign; ++nijk[0]) {
1449 xPos = (nijk[0] & (LeafNodeType::DIM - 1u)) << (2 * LeafNodeType::LOG2DIM);
1450 for (nijk[1]=bbox.min()[1]; nijk[1] <= bbox.max()[1] && !flipSign; ++nijk[1]) {
1451 yPos = xPos + ((nijk[1] & (LeafNodeType::DIM-1u)) << LeafNodeType::LOG2DIM);
1452 for (nijk[2] = bbox.min()[2]; nijk[2] <= bbox.max()[2]; ++nijk[2]) {
1453 pos = yPos + (nijk[2] & (LeafNodeType::DIM - 1u));
1454
1455 const Int32& polyIdx = idxData[pos];
1456
1457 if (polyIdx == Int32(util::INVALID_IDX) || !(data[pos] < -0.75))
1458 continue;
1459
1460 const Index pointIndex = pos * 2;
1461
1462 if (!mask[pos]) {
1463
1464 mask[pos] = true;
1465
1466 nxyz[0] = double(nijk[0]);
1467 nxyz[1] = double(nijk[1]);
1468 nxyz[2] = double(nijk[2]);
1469
1470 Vec3d& point = points[pointIndex];
1471
1472 point = closestPoint(nxyz, polyIdx);
1473
1474 Vec3d& direction = points[pointIndex + 1];
1475 direction = nxyz - point;
1476 direction.normalize();
1477 }
1478
1479 dir1 = xyz - points[pointIndex];
1480 dir1.normalize();
1481
1482 if (points[pointIndex + 1].dot(dir1) > 0.0) {
1483 flipSign = true;
1484 break;
1485 }
1486 }
1487 }
1488 }
1489
1490 if (flipSign) {
1491 dist = -dist;
1492 } else {
1493 for (Int32 m = 0; m < 26; ++m) {
1494 nijk = ijk + util::COORD_OFFSETS[m];
1495
1496 if (!bbox.isInside(nijk) && distAcc.probeValue(nijk, nval) && nval<-0.75) {
1497 nxyz[0] = double(nijk[0]);
1498 nxyz[1] = double(nijk[1]);
1499 nxyz[2] = double(nijk[2]);
1500
1501 cp = closestPoint(nxyz, idxAcc.getValue(nijk));
1502
1503 dir1 = xyz - cp;
1504 dir1.normalize();
1505
1506 dir2 = nxyz - cp;
1507 dir2.normalize();
1508
1509 if (dir2.dot(dir1) > 0.0) {
1510 dist = -dist;
1511 break;
1512 }
1513 }
1514 }
1515 }
1516
1517 } // active voxel loop
1518 } // leaf node loop
1519 }
1520
1521private:
1522
1523 Vec3d closestPoint(const Vec3d& center, Int32 polyIdx) const
1524 {
1525 Vec3d a, b, c, cp, uvw;
1526
1527 const size_t polygon = size_t(polyIdx);
1528 mMesh->getIndexSpacePoint(polygon, 0, a);
1529 mMesh->getIndexSpacePoint(polygon, 1, b);
1530 mMesh->getIndexSpacePoint(polygon, 2, c);
1531
1532 cp = closestPointOnTriangleToPoint(a, c, b, center, uvw);
1533
1534 if (4 == mMesh->vertexCount(polygon)) {
1535
1536 mMesh->getIndexSpacePoint(polygon, 3, b);
1537
1538 c = closestPointOnTriangleToPoint(a, b, c, center, uvw);
1539
1540 if ((center - c).lengthSqr() < (center - cp).lengthSqr()) {
1541 cp = c;
1542 }
1543 }
1544
1545 return cp;
1546 }
1547
1548
1549 LeafNodeType ** const mDistNodes;
1550 TreeType const * const mDistTree;
1551 Int32TreeType const * const mIndexTree;
1552 MeshDataAdapter const * const mMesh;
1553
1554 SharedPtr<LocalDataTable> mLocalDataTable;
1555}; // ComputeIntersectingVoxelSign
1556
1557
1558////////////////////////////////////////
1559
1560
1561template<typename LeafNodeType>
1562inline void
1563maskNodeInternalNeighbours(const Index pos, bool (&mask)[26])
1564{
1565 using NodeT = LeafNodeType;
1566
1567 const Coord ijk = NodeT::offsetToLocalCoord(pos);
1568
1569 // Face adjacent neighbours
1570 // i+1, j, k
1571 mask[0] = ijk[0] != (NodeT::DIM - 1);
1572 // i-1, j, k
1573 mask[1] = ijk[0] != 0;
1574 // i, j+1, k
1575 mask[2] = ijk[1] != (NodeT::DIM - 1);
1576 // i, j-1, k
1577 mask[3] = ijk[1] != 0;
1578 // i, j, k+1
1579 mask[4] = ijk[2] != (NodeT::DIM - 1);
1580 // i, j, k-1
1581 mask[5] = ijk[2] != 0;
1582
1583 // Edge adjacent neighbour
1584 // i+1, j, k-1
1585 mask[6] = mask[0] && mask[5];
1586 // i-1, j, k-1
1587 mask[7] = mask[1] && mask[5];
1588 // i+1, j, k+1
1589 mask[8] = mask[0] && mask[4];
1590 // i-1, j, k+1
1591 mask[9] = mask[1] && mask[4];
1592 // i+1, j+1, k
1593 mask[10] = mask[0] && mask[2];
1594 // i-1, j+1, k
1595 mask[11] = mask[1] && mask[2];
1596 // i+1, j-1, k
1597 mask[12] = mask[0] && mask[3];
1598 // i-1, j-1, k
1599 mask[13] = mask[1] && mask[3];
1600 // i, j-1, k+1
1601 mask[14] = mask[3] && mask[4];
1602 // i, j-1, k-1
1603 mask[15] = mask[3] && mask[5];
1604 // i, j+1, k+1
1605 mask[16] = mask[2] && mask[4];
1606 // i, j+1, k-1
1607 mask[17] = mask[2] && mask[5];
1608
1609 // Corner adjacent neighbours
1610 // i-1, j-1, k-1
1611 mask[18] = mask[1] && mask[3] && mask[5];
1612 // i-1, j-1, k+1
1613 mask[19] = mask[1] && mask[3] && mask[4];
1614 // i+1, j-1, k+1
1615 mask[20] = mask[0] && mask[3] && mask[4];
1616 // i+1, j-1, k-1
1617 mask[21] = mask[0] && mask[3] && mask[5];
1618 // i-1, j+1, k-1
1619 mask[22] = mask[1] && mask[2] && mask[5];
1620 // i-1, j+1, k+1
1621 mask[23] = mask[1] && mask[2] && mask[4];
1622 // i+1, j+1, k+1
1623 mask[24] = mask[0] && mask[2] && mask[4];
1624 // i+1, j+1, k-1
1625 mask[25] = mask[0] && mask[2] && mask[5];
1626}
1627
1628
1629template<typename Compare, typename LeafNodeType>
1630inline bool
1631checkNeighbours(const Index pos, const typename LeafNodeType::ValueType * data, bool (&mask)[26])
1632{
1633 using NodeT = LeafNodeType;
1634
1635 // i, j, k - 1
1636 if (mask[5] && Compare::check(data[pos - 1])) return true;
1637 // i, j, k + 1
1638 if (mask[4] && Compare::check(data[pos + 1])) return true;
1639 // i, j - 1, k
1640 if (mask[3] && Compare::check(data[pos - NodeT::DIM])) return true;
1641 // i, j + 1, k
1642 if (mask[2] && Compare::check(data[pos + NodeT::DIM])) return true;
1643 // i - 1, j, k
1644 if (mask[1] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM])) return true;
1645 // i + 1, j, k
1646 if (mask[0] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM])) return true;
1647 // i+1, j, k-1
1648 if (mask[6] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM])) return true;
1649 // i-1, j, k-1
1650 if (mask[7] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - 1])) return true;
1651 // i+1, j, k+1
1652 if (mask[8] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + 1])) return true;
1653 // i-1, j, k+1
1654 if (mask[9] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + 1])) return true;
1655 // i+1, j+1, k
1656 if (mask[10] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM])) return true;
1657 // i-1, j+1, k
1658 if (mask[11] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM])) return true;
1659 // i+1, j-1, k
1660 if (mask[12] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM])) return true;
1661 // i-1, j-1, k
1662 if (mask[13] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM])) return true;
1663 // i, j-1, k+1
1664 if (mask[14] && Compare::check(data[pos - NodeT::DIM + 1])) return true;
1665 // i, j-1, k-1
1666 if (mask[15] && Compare::check(data[pos - NodeT::DIM - 1])) return true;
1667 // i, j+1, k+1
1668 if (mask[16] && Compare::check(data[pos + NodeT::DIM + 1])) return true;
1669 // i, j+1, k-1
1670 if (mask[17] && Compare::check(data[pos + NodeT::DIM - 1])) return true;
1671 // i-1, j-1, k-1
1672 if (mask[18] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM - 1])) return true;
1673 // i-1, j-1, k+1
1674 if (mask[19] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM + 1])) return true;
1675 // i+1, j-1, k+1
1676 if (mask[20] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM + 1])) return true;
1677 // i+1, j-1, k-1
1678 if (mask[21] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM - 1])) return true;
1679 // i-1, j+1, k-1
1680 if (mask[22] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM - 1])) return true;
1681 // i-1, j+1, k+1
1682 if (mask[23] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM + 1])) return true;
1683 // i+1, j+1, k+1
1684 if (mask[24] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM + 1])) return true;
1685 // i+1, j+1, k-1
1686 if (mask[25] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM - 1])) return true;
1687
1688 return false;
1689}
1690
1691
1692template<typename Compare, typename AccessorType>
1693inline bool
1694checkNeighbours(const Coord& ijk, AccessorType& acc, bool (&mask)[26])
1695{
1696 for (Int32 m = 0; m < 26; ++m) {
1697 if (!mask[m] && Compare::check(acc.getValue(ijk + util::COORD_OFFSETS[m]))) {
1698 return true;
1699 }
1700 }
1701
1702 return false;
1703}
1704
1705
1706template<typename TreeType>
1707struct ValidateIntersectingVoxels
1708{
1709 using ValueType = typename TreeType::ValueType;
1710 using LeafNodeType = typename TreeType::LeafNodeType;
1711
1712 struct IsNegative { static bool check(const ValueType v) { return v < ValueType(0.0); } };
1713
1714 ValidateIntersectingVoxels(TreeType& tree, std::vector<LeafNodeType*>& nodes)
1715 : mTree(&tree)
1716 , mNodes(nodes.empty() ? nullptr : &nodes[0])
1717 {
1718 }
1719
1720 void operator()(const tbb::blocked_range<size_t>& range) const
1721 {
1722 tree::ValueAccessor<const TreeType> acc(*mTree);
1723 bool neighbourMask[26];
1724
1725 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1726
1727 LeafNodeType& node = *mNodes[n];
1728 ValueType* data = node.buffer().data();
1729
1730 typename LeafNodeType::ValueOnCIter it;
1731 for (it = node.cbeginValueOn(); it; ++it) {
1732
1733 const Index pos = it.pos();
1734
1735 ValueType& dist = data[pos];
1736 if (dist < 0.0 || dist > 0.75) continue;
1737
1738 // Mask node internal neighbours
1739 maskNodeInternalNeighbours<LeafNodeType>(pos, neighbourMask);
1740
1741 const bool hasNegativeNeighbour =
1742 checkNeighbours<IsNegative, LeafNodeType>(pos, data, neighbourMask) ||
1743 checkNeighbours<IsNegative>(node.offsetToGlobalCoord(pos), acc, neighbourMask);
1744
1745 if (!hasNegativeNeighbour) {
1746 // push over boundary voxel distance
1747 dist = ValueType(0.75) + Tolerance<ValueType>::epsilon();
1748 }
1749 }
1750 }
1751 }
1752
1753 TreeType * const mTree;
1754 LeafNodeType ** const mNodes;
1755}; // ValidateIntersectingVoxels
1756
1757
1758template<typename TreeType>
1759struct RemoveSelfIntersectingSurface
1760{
1761 using ValueType = typename TreeType::ValueType;
1762 using LeafNodeType = typename TreeType::LeafNodeType;
1763 using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1764
1765 struct Comp { static bool check(const ValueType v) { return !(v > ValueType(0.75)); } };
1766
1767 RemoveSelfIntersectingSurface(std::vector<LeafNodeType*>& nodes,
1768 TreeType& distTree, Int32TreeType& indexTree)
1769 : mNodes(nodes.empty() ? nullptr : &nodes[0])
1770 , mDistTree(&distTree)
1771 , mIndexTree(&indexTree)
1772 {
1773 }
1774
1775 void operator()(const tbb::blocked_range<size_t>& range) const
1776 {
1777 tree::ValueAccessor<const TreeType> distAcc(*mDistTree);
1778 tree::ValueAccessor<Int32TreeType> idxAcc(*mIndexTree);
1779 bool neighbourMask[26];
1780
1781 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1782
1783 LeafNodeType& distNode = *mNodes[n];
1784 ValueType* data = distNode.buffer().data();
1785
1786 typename Int32TreeType::LeafNodeType* idxNode =
1787 idxAcc.probeLeaf(distNode.origin());
1788
1789 typename LeafNodeType::ValueOnCIter it;
1790 for (it = distNode.cbeginValueOn(); it; ++it) {
1791
1792 const Index pos = it.pos();
1793
1794 if (!(data[pos] > 0.75)) continue;
1795
1796 // Mask node internal neighbours
1797 maskNodeInternalNeighbours<LeafNodeType>(pos, neighbourMask);
1798
1799 const bool hasBoundaryNeighbour =
1800 checkNeighbours<Comp, LeafNodeType>(pos, data, neighbourMask) ||
1801 checkNeighbours<Comp>(distNode.offsetToGlobalCoord(pos),distAcc,neighbourMask);
1802
1803 if (!hasBoundaryNeighbour) {
1804 distNode.setValueOff(pos);
1805 idxNode->setValueOff(pos);
1806 }
1807 }
1808 }
1809 }
1810
1811 LeafNodeType * * const mNodes;
1812 TreeType * const mDistTree;
1813 Int32TreeType * const mIndexTree;
1814}; // RemoveSelfIntersectingSurface
1815
1816
1817////////////////////////////////////////
1818
1819
1820template<typename NodeType>
1821struct ReleaseChildNodes
1822{
1823 ReleaseChildNodes(NodeType ** nodes) : mNodes(nodes) {}
1824
1825 void operator()(const tbb::blocked_range<size_t>& range) const {
1826
1827 using NodeMaskType = typename NodeType::NodeMaskType;
1828
1829 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1830 const_cast<NodeMaskType&>(mNodes[n]->getChildMask()).setOff();
1831 }
1832 }
1833
1834 NodeType ** const mNodes;
1835};
1836
1837
1838template<typename TreeType>
1839inline void
1840releaseLeafNodes(TreeType& tree)
1841{
1842 using RootNodeType = typename TreeType::RootNodeType;
1843 using NodeChainType = typename RootNodeType::NodeChainType;
1844 using InternalNodeType = typename NodeChainType::template Get<1>;
1845
1846 std::vector<InternalNodeType*> nodes;
1847 tree.getNodes(nodes);
1848
1849 tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
1850 ReleaseChildNodes<InternalNodeType>(nodes.empty() ? nullptr : &nodes[0]));
1851}
1852
1853
1854template<typename TreeType>
1855struct StealUniqueLeafNodes
1856{
1857 using LeafNodeType = typename TreeType::LeafNodeType;
1858
1859 StealUniqueLeafNodes(TreeType& lhsTree, TreeType& rhsTree,
1860 std::vector<LeafNodeType*>& overlappingNodes)
1861 : mLhsTree(&lhsTree)
1862 , mRhsTree(&rhsTree)
1863 , mNodes(&overlappingNodes)
1864 {
1865 }
1866
1867 void operator()() const {
1868
1869 std::vector<LeafNodeType*> rhsLeafNodes;
1870
1871 rhsLeafNodes.reserve(mRhsTree->leafCount());
1872 //mRhsTree->getNodes(rhsLeafNodes);
1873 //releaseLeafNodes(*mRhsTree);
1874 mRhsTree->stealNodes(rhsLeafNodes);
1875
1876 tree::ValueAccessor<TreeType> acc(*mLhsTree);
1877
1878 for (size_t n = 0, N = rhsLeafNodes.size(); n < N; ++n) {
1879 if (!acc.probeLeaf(rhsLeafNodes[n]->origin())) {
1880 acc.addLeaf(rhsLeafNodes[n]);
1881 } else {
1882 mNodes->push_back(rhsLeafNodes[n]);
1883 }
1884 }
1885 }
1886
1887private:
1888 TreeType * const mLhsTree;
1889 TreeType * const mRhsTree;
1890 std::vector<LeafNodeType*> * const mNodes;
1891};
1892
1893
1894template<typename DistTreeType, typename IndexTreeType>
1895inline void
1896combineData(DistTreeType& lhsDist, IndexTreeType& lhsIdx,
1897 DistTreeType& rhsDist, IndexTreeType& rhsIdx)
1898{
1899 using DistLeafNodeType = typename DistTreeType::LeafNodeType;
1900 using IndexLeafNodeType = typename IndexTreeType::LeafNodeType;
1901
1902 std::vector<DistLeafNodeType*> overlappingDistNodes;
1903 std::vector<IndexLeafNodeType*> overlappingIdxNodes;
1904
1905 // Steal unique leafnodes
1906 tbb::task_group tasks;
1907 tasks.run(StealUniqueLeafNodes<DistTreeType>(lhsDist, rhsDist, overlappingDistNodes));
1908 tasks.run(StealUniqueLeafNodes<IndexTreeType>(lhsIdx, rhsIdx, overlappingIdxNodes));
1909 tasks.wait();
1910
1911 // Combine overlapping leaf nodes
1912 if (!overlappingDistNodes.empty() && !overlappingIdxNodes.empty()) {
1913 tbb::parallel_for(tbb::blocked_range<size_t>(0, overlappingDistNodes.size()),
1914 CombineLeafNodes<DistTreeType>(lhsDist, lhsIdx,
1915 &overlappingDistNodes[0], &overlappingIdxNodes[0]));
1916 }
1917}
1918
1919/// @brief TBB body object to voxelize a mesh of triangles and/or quads into a collection
1920/// of VDB grids, namely a squared distance grid, a closest primitive grid and an
1921/// intersecting voxels grid (masks the mesh intersecting voxels)
1922/// @note Only the leaf nodes that intersect the mesh are allocated, and only voxels in
1923/// a narrow band (of two to three voxels in proximity to the mesh's surface) are activated.
1924/// They are populated with distance values and primitive indices.
1925template<typename TreeType>
1926struct VoxelizationData {
1927
1928 using Ptr = std::unique_ptr<VoxelizationData>;
1929 using ValueType = typename TreeType::ValueType;
1930
1931 using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1932 using UCharTreeType = typename TreeType::template ValueConverter<unsigned char>::Type;
1933
1934 using FloatTreeAcc = tree::ValueAccessor<TreeType>;
1935 using Int32TreeAcc = tree::ValueAccessor<Int32TreeType>;
1936 using UCharTreeAcc = tree::ValueAccessor<UCharTreeType>;
1937
1938
1939 VoxelizationData()
1940 : distTree(std::numeric_limits<ValueType>::max())
1941 , distAcc(distTree)
1942 , indexTree(Int32(util::INVALID_IDX))
1943 , indexAcc(indexTree)
1944 , primIdTree(MaxPrimId)
1945 , primIdAcc(primIdTree)
1946 , mPrimCount(0)
1947 {
1948 }
1949
1950 TreeType distTree;
1951 FloatTreeAcc distAcc;
1952
1953 Int32TreeType indexTree;
1954 Int32TreeAcc indexAcc;
1955
1956 UCharTreeType primIdTree;
1957 UCharTreeAcc primIdAcc;
1958
1959 unsigned char getNewPrimId() {
1960
1961 /// @warning Don't use parallel methods here!
1962 /// The primIdTree is used as a "scratch" pad to mark visits for a given polygon
1963 /// into voxels which it may contribute to. The tree is kept as lightweight as
1964 /// possible and is reset when a maximum count or size is reached. A previous
1965 /// bug here occurred due to the calling of tree methods with multi-threaded
1966 /// implementations, resulting in nested parallelization and re-use of the TLS
1967 /// from the initial task. This consequently resulted in non deterministic values
1968 /// of mPrimCount on the return of the initial task, and could potentially end up
1969 /// with a mPrimCount equal to that of the MaxPrimId. This is used as the background
1970 /// value of the scratch tree.
1971 /// @see jira.aswf.io/browse/OVDB-117, PR #564
1972 /// @todo Consider profiling this operator with tree.clear() and Investigate the
1973 /// chosen value of MaxPrimId
1974
1975 if (mPrimCount == MaxPrimId || primIdTree.leafCount() > 1000) {
1976 mPrimCount = 0;
1977 primIdTree.root().clear();
1978 primIdTree.clearAllAccessors();
1979 OPENVDB_ASSERT(mPrimCount == 0);
1980 }
1981
1982 return mPrimCount++;
1983 }
1984
1985private:
1986
1987 enum { MaxPrimId = 100 };
1988
1989 unsigned char mPrimCount;
1990};
1991
1992
1993template<typename TreeType, typename MeshDataAdapter, typename Interrupter = util::NullInterrupter>
1994class VoxelizePolygons
1995{
1996public:
1997
1998 using VoxelizationDataType = VoxelizationData<TreeType>;
1999 using DataTable = tbb::enumerable_thread_specific<typename VoxelizationDataType::Ptr>;
2000
2001 VoxelizePolygons(DataTable& dataTable,
2002 const MeshDataAdapter& mesh,
2003 Interrupter* interrupter = nullptr)
2004 : mDataTable(&dataTable)
2005 , mMesh(&mesh)
2006 , mInterrupter(interrupter)
2007 {
2008 }
2009
2010 void operator()(const tbb::blocked_range<size_t>& range) const {
2011
2012 typename VoxelizationDataType::Ptr& dataPtr = mDataTable->local();
2013 if (!dataPtr) dataPtr.reset(new VoxelizationDataType());
2014
2015 Triangle prim;
2016
2017 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2018
2019 if (this->wasInterrupted()) {
2020 thread::cancelGroupExecution();
2021 break;
2022 }
2023
2024 const size_t numVerts = mMesh->vertexCount(n);
2025
2026 // rasterize triangles and quads.
2027 if (numVerts == 3 || numVerts == 4) {
2028
2029 prim.index = Int32(n);
2030
2031 mMesh->getIndexSpacePoint(n, 0, prim.a);
2032 mMesh->getIndexSpacePoint(n, 1, prim.b);
2033 mMesh->getIndexSpacePoint(n, 2, prim.c);
2034
2035 evalTriangle(prim, *dataPtr);
2036
2037 if (numVerts == 4) {
2038 mMesh->getIndexSpacePoint(n, 3, prim.b);
2039 evalTriangle(prim, *dataPtr);
2040 }
2041 }
2042 }
2043 }
2044
2045private:
2046
2047 bool wasInterrupted() const { return mInterrupter && mInterrupter->wasInterrupted(); }
2048
2049 struct Triangle { Vec3d a, b, c; Int32 index; };
2050
2051 struct SubTask
2052 {
2053 enum { POLYGON_LIMIT = 1000 };
2054
2055 SubTask(const Triangle& prim, DataTable& dataTable,
2056 int subdivisionCount, size_t polygonCount,
2057 Interrupter* interrupter = nullptr)
2058 : mLocalDataTable(&dataTable)
2059 , mPrim(prim)
2060 , mSubdivisionCount(subdivisionCount)
2061 , mPolygonCount(polygonCount)
2062 , mInterrupter(interrupter)
2063 {
2064 }
2065
2066 void operator()() const
2067 {
2068 if (mSubdivisionCount <= 0 || mPolygonCount >= POLYGON_LIMIT) {
2069
2070 typename VoxelizationDataType::Ptr& dataPtr = mLocalDataTable->local();
2071 if (!dataPtr) dataPtr.reset(new VoxelizationDataType());
2072
2073 voxelizeTriangle(mPrim, *dataPtr, mInterrupter);
2074
2075 } else if (!(mInterrupter && mInterrupter->wasInterrupted())) {
2076 spawnTasks(mPrim, *mLocalDataTable, mSubdivisionCount, mPolygonCount, mInterrupter);
2077 }
2078 }
2079
2080 DataTable * const mLocalDataTable;
2081 Triangle const mPrim;
2082 int const mSubdivisionCount;
2083 size_t const mPolygonCount;
2084 Interrupter * const mInterrupter;
2085 }; // struct SubTask
2086
2087 inline static int evalSubdivisionCount(const Triangle& prim)
2088 {
2089 const double ax = prim.a[0], bx = prim.b[0], cx = prim.c[0];
2090 const double dx = std::max(ax, std::max(bx, cx)) - std::min(ax, std::min(bx, cx));
2091
2092 const double ay = prim.a[1], by = prim.b[1], cy = prim.c[1];
2093 const double dy = std::max(ay, std::max(by, cy)) - std::min(ay, std::min(by, cy));
2094
2095 const double az = prim.a[2], bz = prim.b[2], cz = prim.c[2];
2096 const double dz = std::max(az, std::max(bz, cz)) - std::min(az, std::min(bz, cz));
2097
2098 return int(std::max(dx, std::max(dy, dz)) / double(TreeType::LeafNodeType::DIM * 2));
2099 }
2100
2101 void evalTriangle(const Triangle& prim, VoxelizationDataType& data) const
2102 {
2103 const size_t polygonCount = mMesh->polygonCount();
2104 const int subdivisionCount =
2105 polygonCount < SubTask::POLYGON_LIMIT ? evalSubdivisionCount(prim) : 0;
2106
2107 if (subdivisionCount <= 0) {
2108 voxelizeTriangle(prim, data, mInterrupter);
2109 } else {
2110 spawnTasks(prim, *mDataTable, subdivisionCount, polygonCount, mInterrupter);
2111 }
2112 }
2113
2114 static void spawnTasks(
2115 const Triangle& mainPrim,
2116 DataTable& dataTable,
2117 int subdivisionCount,
2118 size_t polygonCount,
2119 Interrupter* const interrupter)
2120 {
2121 subdivisionCount -= 1;
2122 polygonCount *= 4;
2123
2124 tbb::task_group tasks;
2125
2126 const Vec3d ac = (mainPrim.a + mainPrim.c) * 0.5;
2127 const Vec3d bc = (mainPrim.b + mainPrim.c) * 0.5;
2128 const Vec3d ab = (mainPrim.a + mainPrim.b) * 0.5;
2129
2130 Triangle prim;
2131 prim.index = mainPrim.index;
2132
2133 prim.a = mainPrim.a;
2134 prim.b = ab;
2135 prim.c = ac;
2136 tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount, interrupter));
2137
2138 prim.a = ab;
2139 prim.b = bc;
2140 prim.c = ac;
2141 tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount, interrupter));
2142
2143 prim.a = ab;
2144 prim.b = mainPrim.b;
2145 prim.c = bc;
2146 tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount, interrupter));
2147
2148 prim.a = ac;
2149 prim.b = bc;
2150 prim.c = mainPrim.c;
2151 tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount, interrupter));
2152
2153 tasks.wait();
2154 }
2155
2156 static void voxelizeTriangle(const Triangle& prim, VoxelizationDataType& data, Interrupter* const interrupter)
2157 {
2158 std::deque<Coord> coordList;
2159 Coord ijk, nijk;
2160
2161 ijk = Coord::floor(prim.a);
2162 coordList.push_back(ijk);
2163
2164 // The first point may not be quite in bounds, and rely
2165 // on one of the neighbours to have the first valid seed,
2166 // so we cannot early-exit here.
2167 updateDistance(ijk, prim, data);
2168
2169 unsigned char primId = data.getNewPrimId();
2170 data.primIdAcc.setValueOnly(ijk, primId);
2171
2172 // iteration number to check for an interrupt
2173 constexpr Int32 freq = 2<<12;
2174
2175 while (!coordList.empty()) {
2176 if (interrupter && interrupter->wasInterrupted()) {
2177 thread::cancelGroupExecution();
2178 break;
2179 }
2180 for (Int32 pass = 0; pass < freq && !coordList.empty(); ++pass) {
2181 ijk = coordList.back();
2182 coordList.pop_back();
2183
2184 for (Int32 i = 0; i < 26; ++i) {
2185 nijk = ijk + util::COORD_OFFSETS[i];
2186 if (primId != data.primIdAcc.getValue(nijk)) {
2187 data.primIdAcc.setValueOnly(nijk, primId);
2188 if (updateDistance(nijk, prim, data)) coordList.push_back(nijk);
2189 }
2190 }
2191 }
2192 }
2193 }
2194
2195 static bool updateDistance(const Coord& ijk, const Triangle& prim, VoxelizationDataType& data)
2196 {
2197 Vec3d uvw, voxelCenter(ijk[0], ijk[1], ijk[2]);
2198
2199 using ValueType = typename TreeType::ValueType;
2200
2201 const ValueType dist = ValueType((voxelCenter -
2202 closestPointOnTriangleToPoint(prim.a, prim.c, prim.b, voxelCenter, uvw)).lengthSqr());
2203
2204 // Either the points may be NAN, or they could be far enough from
2205 // the origin that computing distance fails.
2206 if (std::isnan(dist))
2207 return false;
2208
2209 const ValueType oldDist = data.distAcc.getValue(ijk);
2210
2211 if (dist < oldDist) {
2212 data.distAcc.setValue(ijk, dist);
2213 data.indexAcc.setValue(ijk, prim.index);
2214 } else if (math::isExactlyEqual(dist, oldDist)) {
2215 // makes reduction deterministic when different polygons
2216 // produce the same distance value.
2217 data.indexAcc.setValueOnly(ijk, std::min(prim.index, data.indexAcc.getValue(ijk)));
2218 }
2219
2220 return !(dist > 0.75); // true if the primitive intersects the voxel.
2221 }
2222
2223 DataTable * const mDataTable;
2224 MeshDataAdapter const * const mMesh;
2225 Interrupter * const mInterrupter;
2226}; // VoxelizePolygons
2227
2228
2229////////////////////////////////////////
2230
2231
2232template<typename TreeType>
2233struct DiffLeafNodeMask
2234{
2235 using AccessorType = typename tree::ValueAccessor<TreeType>;
2236 using LeafNodeType = typename TreeType::LeafNodeType;
2237
2238 using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2239 using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2240
2241 DiffLeafNodeMask(const TreeType& rhsTree,
2242 std::vector<BoolLeafNodeType*>& lhsNodes)
2243 : mRhsTree(&rhsTree), mLhsNodes(lhsNodes.empty() ? nullptr : &lhsNodes[0])
2244 {
2245 }
2246
2247 void operator()(const tbb::blocked_range<size_t>& range) const {
2248
2249 tree::ValueAccessor<const TreeType> acc(*mRhsTree);
2250
2251 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2252
2253 BoolLeafNodeType* lhsNode = mLhsNodes[n];
2254 const LeafNodeType* rhsNode = acc.probeConstLeaf(lhsNode->origin());
2255
2256 if (rhsNode) lhsNode->topologyDifference(*rhsNode, false);
2257 }
2258 }
2259
2260private:
2261 TreeType const * const mRhsTree;
2262 BoolLeafNodeType ** const mLhsNodes;
2263};
2264
2265
2266template<typename LeafNodeTypeA, typename LeafNodeTypeB>
2267struct UnionValueMasks
2268{
2269 UnionValueMasks(std::vector<LeafNodeTypeA*>& nodesA, std::vector<LeafNodeTypeB*>& nodesB)
2270 : mNodesA(nodesA.empty() ? nullptr : &nodesA[0])
2271 , mNodesB(nodesB.empty() ? nullptr : &nodesB[0])
2272 {
2273 }
2274
2275 void operator()(const tbb::blocked_range<size_t>& range) const {
2276 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2277 mNodesA[n]->topologyUnion(*mNodesB[n]);
2278 }
2279 }
2280
2281private:
2282 LeafNodeTypeA ** const mNodesA;
2283 LeafNodeTypeB ** const mNodesB;
2284};
2285
2286
2287template<typename TreeType>
2288struct ConstructVoxelMask
2289{
2290 using LeafNodeType = typename TreeType::LeafNodeType;
2291
2292 using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2293 using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2294
2295 ConstructVoxelMask(BoolTreeType& maskTree, const TreeType& tree,
2296 std::vector<LeafNodeType*>& nodes)
2297 : mTree(&tree)
2298 , mNodes(nodes.empty() ? nullptr : &nodes[0])
2299 , mLocalMaskTree(false)
2300 , mMaskTree(&maskTree)
2301 {
2302 }
2303
2304 ConstructVoxelMask(ConstructVoxelMask& rhs, tbb::split)
2305 : mTree(rhs.mTree)
2306 , mNodes(rhs.mNodes)
2307 , mLocalMaskTree(false)
2308 , mMaskTree(&mLocalMaskTree)
2309 {
2310 }
2311
2312 void operator()(const tbb::blocked_range<size_t>& range)
2313 {
2314 using Iterator = typename LeafNodeType::ValueOnCIter;
2315
2316 tree::ValueAccessor<const TreeType> acc(*mTree);
2317 tree::ValueAccessor<BoolTreeType> maskAcc(*mMaskTree);
2318
2319 Coord ijk, nijk, localCorod;
2320 Index pos, npos;
2321
2322 for (size_t n = range.begin(); n != range.end(); ++n) {
2323
2324 LeafNodeType& node = *mNodes[n];
2325
2326 CoordBBox bbox = node.getNodeBoundingBox();
2327 bbox.expand(-1);
2328
2329 BoolLeafNodeType& maskNode = *maskAcc.touchLeaf(node.origin());
2330
2331 for (Iterator it = node.cbeginValueOn(); it; ++it) {
2332 ijk = it.getCoord();
2333 pos = it.pos();
2334
2335 localCorod = LeafNodeType::offsetToLocalCoord(pos);
2336
2337 if (localCorod[2] < int(LeafNodeType::DIM - 1)) {
2338 npos = pos + 1;
2339 if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2340 } else {
2341 nijk = ijk.offsetBy(0, 0, 1);
2342 if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2343 }
2344
2345 if (localCorod[2] > 0) {
2346 npos = pos - 1;
2347 if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2348 } else {
2349 nijk = ijk.offsetBy(0, 0, -1);
2350 if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2351 }
2352
2353 if (localCorod[1] < int(LeafNodeType::DIM - 1)) {
2354 npos = pos + LeafNodeType::DIM;
2355 if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2356 } else {
2357 nijk = ijk.offsetBy(0, 1, 0);
2358 if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2359 }
2360
2361 if (localCorod[1] > 0) {
2362 npos = pos - LeafNodeType::DIM;
2363 if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2364 } else {
2365 nijk = ijk.offsetBy(0, -1, 0);
2366 if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2367 }
2368
2369 if (localCorod[0] < int(LeafNodeType::DIM - 1)) {
2370 npos = pos + LeafNodeType::DIM * LeafNodeType::DIM;
2371 if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2372 } else {
2373 nijk = ijk.offsetBy(1, 0, 0);
2374 if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2375 }
2376
2377 if (localCorod[0] > 0) {
2378 npos = pos - LeafNodeType::DIM * LeafNodeType::DIM;
2379 if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2380 } else {
2381 nijk = ijk.offsetBy(-1, 0, 0);
2382 if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2383 }
2384 }
2385 }
2386 }
2387
2388 void join(ConstructVoxelMask& rhs) { mMaskTree->merge(*rhs.mMaskTree); }
2389
2390private:
2391 TreeType const * const mTree;
2392 LeafNodeType ** const mNodes;
2393
2394 BoolTreeType mLocalMaskTree;
2395 BoolTreeType * const mMaskTree;
2396};
2397
2398
2399/// @note The interior and exterior widths should be in world space units and squared.
2400template<typename TreeType, typename MeshDataAdapter>
2401struct ExpandNarrowband
2402{
2403 using ValueType = typename TreeType::ValueType;
2404 using LeafNodeType = typename TreeType::LeafNodeType;
2405 using NodeMaskType = typename LeafNodeType::NodeMaskType;
2406 using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
2407 using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
2408 using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2409 using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2410
2411 struct Fragment
2412 {
2413 Int32 idx, x, y, z;
2414 ValueType dist;
2415
2416 Fragment() : idx(0), x(0), y(0), z(0), dist(0.0) {}
2417
2418 Fragment(Int32 idx_, Int32 x_, Int32 y_, Int32 z_, ValueType dist_)
2419 : idx(idx_), x(x_), y(y_), z(z_), dist(dist_)
2420 {
2421 }
2422
2423 bool operator<(const Fragment& rhs) const { return idx < rhs.idx; }
2424 }; // struct Fragment
2425
2426 ////////////////////
2427
2428 ExpandNarrowband(
2429 std::vector<BoolLeafNodeType*>& maskNodes,
2430 BoolTreeType& maskTree,
2431 TreeType& distTree,
2432 Int32TreeType& indexTree,
2433 const MeshDataAdapter& mesh,
2434 ValueType exteriorBandWidth,
2435 ValueType interiorBandWidth,
2436 ValueType voxelSize)
2437 : mMaskNodes(maskNodes.empty() ? nullptr : &maskNodes[0])
2438 , mMaskTree(&maskTree)
2439 , mDistTree(&distTree)
2440 , mIndexTree(&indexTree)
2441 , mMesh(&mesh)
2442 , mNewMaskTree(false)
2443 , mDistNodes()
2444 , mUpdatedDistNodes()
2445 , mIndexNodes()
2446 , mUpdatedIndexNodes()
2447 , mExteriorBandWidth(exteriorBandWidth)
2448 , mInteriorBandWidth(interiorBandWidth)
2449 , mVoxelSize(voxelSize)
2450 {
2451 }
2452
2453 ExpandNarrowband(const ExpandNarrowband& rhs, tbb::split)
2454 : mMaskNodes(rhs.mMaskNodes)
2455 , mMaskTree(rhs.mMaskTree)
2456 , mDistTree(rhs.mDistTree)
2457 , mIndexTree(rhs.mIndexTree)
2458 , mMesh(rhs.mMesh)
2459 , mNewMaskTree(false)
2460 , mDistNodes()
2461 , mUpdatedDistNodes()
2462 , mIndexNodes()
2463 , mUpdatedIndexNodes()
2464 , mExteriorBandWidth(rhs.mExteriorBandWidth)
2465 , mInteriorBandWidth(rhs.mInteriorBandWidth)
2466 , mVoxelSize(rhs.mVoxelSize)
2467 {
2468 }
2469
2470 void join(ExpandNarrowband& rhs)
2471 {
2472 mDistNodes.insert(mDistNodes.end(), rhs.mDistNodes.begin(), rhs.mDistNodes.end());
2473 mIndexNodes.insert(mIndexNodes.end(), rhs.mIndexNodes.begin(), rhs.mIndexNodes.end());
2474
2475 mUpdatedDistNodes.insert(mUpdatedDistNodes.end(),
2476 rhs.mUpdatedDistNodes.begin(), rhs.mUpdatedDistNodes.end());
2477
2478 mUpdatedIndexNodes.insert(mUpdatedIndexNodes.end(),
2479 rhs.mUpdatedIndexNodes.begin(), rhs.mUpdatedIndexNodes.end());
2480
2481 mNewMaskTree.merge(rhs.mNewMaskTree);
2482 }
2483
2484 void operator()(const tbb::blocked_range<size_t>& range)
2485 {
2486 tree::ValueAccessor<BoolTreeType> newMaskAcc(mNewMaskTree);
2487 tree::ValueAccessor<TreeType> distAcc(*mDistTree);
2488 tree::ValueAccessor<Int32TreeType> indexAcc(*mIndexTree);
2489
2490 std::vector<Fragment> fragments;
2491 fragments.reserve(256);
2492
2493 std::unique_ptr<LeafNodeType> newDistNodePt;
2494 std::unique_ptr<Int32LeafNodeType> newIndexNodePt;
2495
2496 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2497
2498 BoolLeafNodeType& maskNode = *mMaskNodes[n];
2499 if (maskNode.isEmpty()) continue;
2500
2501 // Setup local caches
2502
2503 const Coord& origin = maskNode.origin();
2504
2505 LeafNodeType * distNodePt = distAcc.probeLeaf(origin);
2506 Int32LeafNodeType * indexNodePt = indexAcc.probeLeaf(origin);
2507
2508 OPENVDB_ASSERT(!distNodePt == !indexNodePt);
2509
2510 bool usingNewNodes = false;
2511
2512 if (!distNodePt && !indexNodePt) {
2513
2514 const ValueType backgroundDist = distAcc.getValue(origin);
2515
2516 if (!newDistNodePt.get() && !newIndexNodePt.get()) {
2517 newDistNodePt.reset(new LeafNodeType(origin, backgroundDist));
2518 newIndexNodePt.reset(new Int32LeafNodeType(origin, indexAcc.getValue(origin)));
2519 } else {
2520
2521 if ((backgroundDist < ValueType(0.0)) !=
2522 (newDistNodePt->getValue(0) < ValueType(0.0))) {
2523 newDistNodePt->buffer().fill(backgroundDist);
2524 }
2525
2526 newDistNodePt->setOrigin(origin);
2527 newIndexNodePt->setOrigin(origin);
2528 }
2529
2530 distNodePt = newDistNodePt.get();
2531 indexNodePt = newIndexNodePt.get();
2532
2533 usingNewNodes = true;
2534 }
2535
2536
2537 // Gather neighbour information
2538
2539 CoordBBox bbox(Coord::max(), Coord::min());
2540 for (typename BoolLeafNodeType::ValueOnIter it = maskNode.beginValueOn(); it; ++it) {
2541 bbox.expand(it.getCoord());
2542 }
2543
2544 bbox.expand(1);
2545
2546 gatherFragments(fragments, bbox, distAcc, indexAcc);
2547
2548
2549 // Compute first voxel layer
2550
2551 bbox = maskNode.getNodeBoundingBox();
2552 NodeMaskType mask;
2553 bool updatedLeafNodes = false;
2554
2555 for (typename BoolLeafNodeType::ValueOnIter it = maskNode.beginValueOn(); it; ++it) {
2556
2557 const Coord ijk = it.getCoord();
2558
2559 if (updateVoxel(ijk, 5, fragments, *distNodePt, *indexNodePt, &updatedLeafNodes)) {
2560
2561 for (Int32 i = 0; i < 6; ++i) {
2562 const Coord nijk = ijk + util::COORD_OFFSETS[i];
2563 if (bbox.isInside(nijk)) {
2564 mask.setOn(BoolLeafNodeType::coordToOffset(nijk));
2565 } else {
2566 newMaskAcc.setValueOn(nijk);
2567 }
2568 }
2569
2570 for (Int32 i = 6; i < 26; ++i) {
2571 const Coord nijk = ijk + util::COORD_OFFSETS[i];
2572 if (bbox.isInside(nijk)) {
2573 mask.setOn(BoolLeafNodeType::coordToOffset(nijk));
2574 }
2575 }
2576 }
2577 }
2578
2579 if (updatedLeafNodes) {
2580
2581 // Compute second voxel layer
2582 mask -= indexNodePt->getValueMask();
2583
2584 for (typename NodeMaskType::OnIterator it = mask.beginOn(); it; ++it) {
2585
2586 const Index pos = it.pos();
2587 const Coord ijk = maskNode.origin() + LeafNodeType::offsetToLocalCoord(pos);
2588
2589 if (updateVoxel(ijk, 6, fragments, *distNodePt, *indexNodePt)) {
2590 for (Int32 i = 0; i < 6; ++i) {
2591 newMaskAcc.setValueOn(ijk + util::COORD_OFFSETS[i]);
2592 }
2593 }
2594 }
2595
2596 // Export new distance values
2597 if (usingNewNodes) {
2598 newDistNodePt->topologyUnion(*newIndexNodePt);
2599 mDistNodes.push_back(newDistNodePt.release());
2600 mIndexNodes.push_back(newIndexNodePt.release());
2601 } else {
2602 mUpdatedDistNodes.push_back(distNodePt);
2603 mUpdatedIndexNodes.push_back(indexNodePt);
2604 }
2605 }
2606 } // end leafnode loop
2607 }
2608
2609 //////////
2610
2611 BoolTreeType& newMaskTree() { return mNewMaskTree; }
2612
2613 std::vector<LeafNodeType*>& newDistNodes() { return mDistNodes; }
2614 std::vector<LeafNodeType*>& updatedDistNodes() { return mUpdatedDistNodes; }
2615
2616 std::vector<Int32LeafNodeType*>& newIndexNodes() { return mIndexNodes; }
2617 std::vector<Int32LeafNodeType*>& updatedIndexNodes() { return mUpdatedIndexNodes; }
2618
2619private:
2620
2621 /// @note The output fragment list is ordered by the primitive index
2622 void
2623 gatherFragments(std::vector<Fragment>& fragments, const CoordBBox& bbox,
2624 tree::ValueAccessor<TreeType>& distAcc, tree::ValueAccessor<Int32TreeType>& indexAcc)
2625 {
2626 fragments.clear();
2627 const Coord nodeMin = bbox.min() & ~(LeafNodeType::DIM - 1);
2628 const Coord nodeMax = bbox.max() & ~(LeafNodeType::DIM - 1);
2629
2630 CoordBBox region;
2631 Coord ijk;
2632
2633 for (ijk[0] = nodeMin[0]; ijk[0] <= nodeMax[0]; ijk[0] += LeafNodeType::DIM) {
2634 for (ijk[1] = nodeMin[1]; ijk[1] <= nodeMax[1]; ijk[1] += LeafNodeType::DIM) {
2635 for (ijk[2] = nodeMin[2]; ijk[2] <= nodeMax[2]; ijk[2] += LeafNodeType::DIM) {
2636 if (LeafNodeType* distleaf = distAcc.probeLeaf(ijk)) {
2637 region.min() = Coord::maxComponent(bbox.min(), ijk);
2638 region.max() = Coord::minComponent(bbox.max(),
2639 ijk.offsetBy(LeafNodeType::DIM - 1));
2640 gatherFragments(fragments, region, *distleaf, *indexAcc.probeLeaf(ijk));
2641 }
2642 }
2643 }
2644 }
2645
2646 std::sort(fragments.begin(), fragments.end());
2647 }
2648
2649 void
2650 gatherFragments(std::vector<Fragment>& fragments, const CoordBBox& bbox,
2651 const LeafNodeType& distLeaf, const Int32LeafNodeType& idxLeaf) const
2652 {
2653 const typename LeafNodeType::NodeMaskType& mask = distLeaf.getValueMask();
2654 const ValueType* distData = distLeaf.buffer().data();
2655 const Int32* idxData = idxLeaf.buffer().data();
2656
2657 for (int x = bbox.min()[0]; x <= bbox.max()[0]; ++x) {
2658 const Index xPos = (x & (LeafNodeType::DIM - 1u)) << (2 * LeafNodeType::LOG2DIM);
2659 for (int y = bbox.min()[1]; y <= bbox.max()[1]; ++y) {
2660 const Index yPos = xPos + ((y & (LeafNodeType::DIM - 1u)) << LeafNodeType::LOG2DIM);
2661 for (int z = bbox.min()[2]; z <= bbox.max()[2]; ++z) {
2662 const Index pos = yPos + (z & (LeafNodeType::DIM - 1u));
2663 if (mask.isOn(pos)) {
2664 fragments.push_back(Fragment(idxData[pos],x,y,z, std::abs(distData[pos])));
2665 }
2666 }
2667 }
2668 }
2669 }
2670
2671 /// @note This method expects the fragment list to be ordered by the primitive index
2672 /// to avoid redundant distance computations.
2673 ValueType
2674 computeDistance(const Coord& ijk, const Int32 manhattanLimit,
2675 const std::vector<Fragment>& fragments, Int32& closestPrimIdx) const
2676 {
2677 Vec3d a, b, c, uvw, voxelCenter(ijk[0], ijk[1], ijk[2]);
2678 double primDist, tmpDist, dist = std::numeric_limits<double>::max();
2679 Int32 lastIdx = Int32(util::INVALID_IDX);
2680
2681 for (size_t n = 0, N = fragments.size(); n < N; ++n) {
2682
2683 const Fragment& fragment = fragments[n];
2684 if (lastIdx == fragment.idx) continue;
2685
2686 const Int32 dx = std::abs(fragment.x - ijk[0]);
2687 const Int32 dy = std::abs(fragment.y - ijk[1]);
2688 const Int32 dz = std::abs(fragment.z - ijk[2]);
2689
2690 const Int32 manhattan = dx + dy + dz;
2691 if (manhattan > manhattanLimit) continue;
2692
2693 lastIdx = fragment.idx;
2694
2695 const size_t polygon = size_t(lastIdx);
2696
2697 mMesh->getIndexSpacePoint(polygon, 0, a);
2698 mMesh->getIndexSpacePoint(polygon, 1, b);
2699 mMesh->getIndexSpacePoint(polygon, 2, c);
2700
2701 primDist = (voxelCenter -
2702 closestPointOnTriangleToPoint(a, c, b, voxelCenter, uvw)).lengthSqr();
2703
2704 // Split quad into a second triangle
2705 if (4 == mMesh->vertexCount(polygon)) {
2706
2707 mMesh->getIndexSpacePoint(polygon, 3, b);
2708
2709 tmpDist = (voxelCenter - closestPointOnTriangleToPoint(
2710 a, b, c, voxelCenter, uvw)).lengthSqr();
2711
2712 if (tmpDist < primDist) primDist = tmpDist;
2713 }
2714
2715 if (primDist < dist) {
2716 dist = primDist;
2717 closestPrimIdx = lastIdx;
2718 }
2719 }
2720
2721 return ValueType(std::sqrt(dist)) * mVoxelSize;
2722 }
2723
2724 /// @note Returns true if the current voxel was updated and neighboring
2725 /// voxels need to be evaluated.
2726 bool
2727 updateVoxel(const Coord& ijk, const Int32 manhattanLimit,
2728 const std::vector<Fragment>& fragments,
2729 LeafNodeType& distLeaf, Int32LeafNodeType& idxLeaf, bool* updatedLeafNodes = nullptr)
2730 {
2731 Int32 closestPrimIdx = 0;
2732 const ValueType distance = computeDistance(ijk, manhattanLimit, fragments, closestPrimIdx);
2733
2734 const Index pos = LeafNodeType::coordToOffset(ijk);
2735 const bool inside = distLeaf.getValue(pos) < ValueType(0.0);
2736
2737 bool activateNeighbourVoxels = false;
2738
2739 if (!inside && distance < mExteriorBandWidth) {
2740 if (updatedLeafNodes) *updatedLeafNodes = true;
2741 activateNeighbourVoxels = (distance + mVoxelSize) < mExteriorBandWidth;
2742 distLeaf.setValueOnly(pos, distance);
2743 idxLeaf.setValueOn(pos, closestPrimIdx);
2744 } else if (inside && distance < mInteriorBandWidth) {
2745 if (updatedLeafNodes) *updatedLeafNodes = true;
2746 activateNeighbourVoxels = (distance + mVoxelSize) < mInteriorBandWidth;
2747 distLeaf.setValueOnly(pos, -distance);
2748 idxLeaf.setValueOn(pos, closestPrimIdx);
2749 }
2750
2751 return activateNeighbourVoxels;
2752 }
2753
2754 //////////
2755
2756 BoolLeafNodeType ** const mMaskNodes;
2757 BoolTreeType * const mMaskTree;
2758 TreeType * const mDistTree;
2759 Int32TreeType * const mIndexTree;
2760
2761 MeshDataAdapter const * const mMesh;
2762
2763 BoolTreeType mNewMaskTree;
2764
2765 std::vector<LeafNodeType*> mDistNodes, mUpdatedDistNodes;
2766 std::vector<Int32LeafNodeType*> mIndexNodes, mUpdatedIndexNodes;
2767
2768 const ValueType mExteriorBandWidth, mInteriorBandWidth, mVoxelSize;
2769}; // struct ExpandNarrowband
2770
2771
2772template<typename TreeType>
2773struct AddNodes {
2774 using LeafNodeType = typename TreeType::LeafNodeType;
2775
2776 AddNodes(TreeType& tree, std::vector<LeafNodeType*>& nodes)
2777 : mTree(&tree) , mNodes(&nodes)
2778 {
2779 }
2780
2781 void operator()() const {
2782 tree::ValueAccessor<TreeType> acc(*mTree);
2783 std::vector<LeafNodeType*>& nodes = *mNodes;
2784 for (size_t n = 0, N = nodes.size(); n < N; ++n) {
2785 acc.addLeaf(nodes[n]);
2786 }
2787 }
2788
2789 TreeType * const mTree;
2790 std::vector<LeafNodeType*> * const mNodes;
2791}; // AddNodes
2792
2793
2794template<typename TreeType, typename Int32TreeType, typename BoolTreeType, typename MeshDataAdapter>
2795inline void
2796expandNarrowband(
2797 TreeType& distTree,
2798 Int32TreeType& indexTree,
2799 BoolTreeType& maskTree,
2800 std::vector<typename BoolTreeType::LeafNodeType*>& maskNodes,
2801 const MeshDataAdapter& mesh,
2802 typename TreeType::ValueType exteriorBandWidth,
2803 typename TreeType::ValueType interiorBandWidth,
2804 typename TreeType::ValueType voxelSize)
2805{
2806 ExpandNarrowband<TreeType, MeshDataAdapter> expandOp(maskNodes, maskTree,
2807 distTree, indexTree, mesh, exteriorBandWidth, interiorBandWidth, voxelSize);
2808
2809 tbb::parallel_reduce(tbb::blocked_range<size_t>(0, maskNodes.size()), expandOp);
2810
2811 tbb::parallel_for(tbb::blocked_range<size_t>(0, expandOp.updatedIndexNodes().size()),
2812 UnionValueMasks<typename TreeType::LeafNodeType, typename Int32TreeType::LeafNodeType>(
2813 expandOp.updatedDistNodes(), expandOp.updatedIndexNodes()));
2814
2815 tbb::task_group tasks;
2816 tasks.run(AddNodes<TreeType>(distTree, expandOp.newDistNodes()));
2817 tasks.run(AddNodes<Int32TreeType>(indexTree, expandOp.newIndexNodes()));
2818 tasks.wait();
2819
2820 maskTree.clear();
2821 maskTree.merge(expandOp.newMaskTree());
2822}
2823
2824
2825////////////////////////////////////////
2826
2827
2828// Transform values (sqrt, world space scaling and sign flip if sdf)
2829template<typename TreeType>
2830struct TransformValues
2831{
2832 using LeafNodeType = typename TreeType::LeafNodeType;
2833 using ValueType = typename TreeType::ValueType;
2834
2835 TransformValues(std::vector<LeafNodeType*>& nodes,
2836 ValueType voxelSize, bool unsignedDist)
2837 : mNodes(&nodes[0])
2838 , mVoxelSize(voxelSize)
2839 , mUnsigned(unsignedDist)
2840 {
2841 }
2842
2843 void operator()(const tbb::blocked_range<size_t>& range) const {
2844
2845 typename LeafNodeType::ValueOnIter iter;
2846
2847 const bool udf = mUnsigned;
2848 const ValueType w[2] = { -mVoxelSize, mVoxelSize };
2849
2850 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2851
2852 for (iter = mNodes[n]->beginValueOn(); iter; ++iter) {
2853 ValueType& val = const_cast<ValueType&>(iter.getValue());
2854 val = w[udf || (val < ValueType(0.0))] * std::sqrt(std::abs(val));
2855 }
2856 }
2857 }
2858
2859private:
2860 LeafNodeType * * const mNodes;
2861 const ValueType mVoxelSize;
2862 const bool mUnsigned;
2863};
2864
2865
2866// Inactivate values outside the (exBandWidth, inBandWidth) range.
2867template<typename TreeType>
2868struct InactivateValues
2869{
2870 using LeafNodeType = typename TreeType::LeafNodeType;
2871 using ValueType = typename TreeType::ValueType;
2872
2873 InactivateValues(std::vector<LeafNodeType*>& nodes,
2874 ValueType exBandWidth, ValueType inBandWidth)
2875 : mNodes(nodes.empty() ? nullptr : &nodes[0])
2876 , mExBandWidth(exBandWidth)
2877 , mInBandWidth(inBandWidth)
2878 {
2879 }
2880
2881 void operator()(const tbb::blocked_range<size_t>& range) const {
2882
2883 typename LeafNodeType::ValueOnIter iter;
2884 const ValueType exVal = mExBandWidth;
2885 const ValueType inVal = -mInBandWidth;
2886
2887 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2888
2889 for (iter = mNodes[n]->beginValueOn(); iter; ++iter) {
2890
2891 ValueType& val = const_cast<ValueType&>(iter.getValue());
2892
2893 const bool inside = val < ValueType(0.0);
2894
2895 if (inside && !(val > inVal)) {
2896 val = inVal;
2897 iter.setValueOff();
2898 } else if (!inside && !(val < exVal)) {
2899 val = exVal;
2900 iter.setValueOff();
2901 }
2902 }
2903 }
2904 }
2905
2906private:
2907 LeafNodeType * * const mNodes;
2908 const ValueType mExBandWidth, mInBandWidth;
2909};
2910
2911
2912template<typename TreeType>
2913struct OffsetValues
2914{
2915 using LeafNodeType = typename TreeType::LeafNodeType;
2916 using ValueType = typename TreeType::ValueType;
2917
2918 OffsetValues(std::vector<LeafNodeType*>& nodes, ValueType offset)
2919 : mNodes(nodes.empty() ? nullptr : &nodes[0]), mOffset(offset)
2920 {
2921 }
2922
2923 void operator()(const tbb::blocked_range<size_t>& range) const {
2924
2925 const ValueType offset = mOffset;
2926
2927 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2928
2929 typename LeafNodeType::ValueOnIter iter = mNodes[n]->beginValueOn();
2930
2931 for (; iter; ++iter) {
2932 ValueType& val = const_cast<ValueType&>(iter.getValue());
2933 val += offset;
2934 }
2935 }
2936 }
2937
2938private:
2939 LeafNodeType * * const mNodes;
2940 const ValueType mOffset;
2941};
2942
2943
2944template<typename TreeType>
2945struct Renormalize
2946{
2947 using LeafNodeType = typename TreeType::LeafNodeType;
2948 using ValueType = typename TreeType::ValueType;
2949
2950 Renormalize(const TreeType& tree, const std::vector<LeafNodeType*>& nodes,
2951 ValueType* buffer, ValueType voxelSize)
2952 : mTree(&tree)
2953 , mNodes(nodes.empty() ? nullptr : &nodes[0])
2954 , mBuffer(buffer)
2955 , mVoxelSize(voxelSize)
2956 {
2957 }
2958
2959 void operator()(const tbb::blocked_range<size_t>& range) const
2960 {
2961 using Vec3Type = math::Vec3<ValueType>;
2962
2963 tree::ValueAccessor<const TreeType> acc(*mTree);
2964
2965 Coord ijk;
2966 Vec3Type up, down;
2967
2968 const ValueType dx = mVoxelSize, invDx = ValueType(1.0) / mVoxelSize;
2969
2970 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2971
2972 ValueType* bufferData = &mBuffer[n * LeafNodeType::SIZE];
2973
2974 typename LeafNodeType::ValueOnCIter iter = mNodes[n]->cbeginValueOn();
2975 for (; iter; ++iter) {
2976
2977 const ValueType phi0 = *iter;
2978
2979 ijk = iter.getCoord();
2980
2981 up[0] = acc.getValue(ijk.offsetBy(1, 0, 0)) - phi0;
2982 up[1] = acc.getValue(ijk.offsetBy(0, 1, 0)) - phi0;
2983 up[2] = acc.getValue(ijk.offsetBy(0, 0, 1)) - phi0;
2984
2985 down[0] = phi0 - acc.getValue(ijk.offsetBy(-1, 0, 0));
2986 down[1] = phi0 - acc.getValue(ijk.offsetBy(0, -1, 0));
2987 down[2] = phi0 - acc.getValue(ijk.offsetBy(0, 0, -1));
2988
2989 const ValueType normSqGradPhi = math::GodunovsNormSqrd(phi0 > 0.0, down, up);
2990
2991 const ValueType diff = math::Sqrt(normSqGradPhi) * invDx - ValueType(1.0);
2992 const ValueType S = phi0 / (math::Sqrt(math::Pow2(phi0) + normSqGradPhi));
2993
2994 bufferData[iter.pos()] = phi0 - dx * S * diff;
2995 }
2996 }
2997 }
2998
2999private:
3000 TreeType const * const mTree;
3001 LeafNodeType const * const * const mNodes;
3002 ValueType * const mBuffer;
3003
3004 const ValueType mVoxelSize;
3005};
3006
3007
3008template<typename TreeType>
3009struct MinCombine
3010{
3011 using LeafNodeType = typename TreeType::LeafNodeType;
3012 using ValueType = typename TreeType::ValueType;
3013
3014 MinCombine(std::vector<LeafNodeType*>& nodes, const ValueType* buffer)
3015 : mNodes(nodes.empty() ? nullptr : &nodes[0]), mBuffer(buffer)
3016 {
3017 }
3018
3019 void operator()(const tbb::blocked_range<size_t>& range) const {
3020
3021 for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
3022
3023 const ValueType* bufferData = &mBuffer[n * LeafNodeType::SIZE];
3024
3025 typename LeafNodeType::ValueOnIter iter = mNodes[n]->beginValueOn();
3026
3027 for (; iter; ++iter) {
3028 ValueType& val = const_cast<ValueType&>(iter.getValue());
3029 val = std::min(val, bufferData[iter.pos()]);
3030 }
3031 }
3032 }
3033
3034private:
3035 LeafNodeType * * const mNodes;
3036 ValueType const * const mBuffer;
3037};
3038
3039
3040} // mesh_to_volume_internal namespace
3041
3042/// @endcond
3043
3044
3045////////////////////////////////////////
3046
3047// Utility method implementation
3048
3049
3050template <typename FloatTreeT>
3051void
3053{
3054 using ConnectivityTable = mesh_to_volume_internal::LeafNodeConnectivityTable<FloatTreeT>;
3055
3056 // Build a node connectivity table where each leaf node has an offset into a
3057 // linearized list of nodes, and each leaf stores its six axis aligned neighbor
3058 // offsets
3059 ConnectivityTable nodeConnectivity(tree);
3060
3061 std::vector<size_t> zStartNodes, yStartNodes, xStartNodes;
3062
3063 // Store all nodes which do not have negative neighbors i.e. the nodes furthest
3064 // in -X, -Y, -Z. We sweep from lowest coordinate positions +axis and then
3065 // from the furthest positive coordinate positions -axis
3066 for (size_t n = 0; n < nodeConnectivity.size(); ++n) {
3067 if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevX()[n]) {
3068 xStartNodes.push_back(n);
3069 }
3070
3071 if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevY()[n]) {
3072 yStartNodes.push_back(n);
3073 }
3074
3075 if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevZ()[n]) {
3076 zStartNodes.push_back(n);
3077 }
3078 }
3079
3080 using SweepingOp = mesh_to_volume_internal::SweepExteriorSign<FloatTreeT>;
3081
3082 // Sweep the exterior value signs (make them negative) up until the voxel intersection
3083 // with the isosurface. Do this in both lowest -> + and largest -> - directions
3084
3085 tbb::parallel_for(tbb::blocked_range<size_t>(0, zStartNodes.size()),
3086 SweepingOp(SweepingOp::Z_AXIS, zStartNodes, nodeConnectivity));
3087
3088 tbb::parallel_for(tbb::blocked_range<size_t>(0, yStartNodes.size()),
3089 SweepingOp(SweepingOp::Y_AXIS, yStartNodes, nodeConnectivity));
3090
3091 tbb::parallel_for(tbb::blocked_range<size_t>(0, xStartNodes.size()),
3092 SweepingOp(SweepingOp::X_AXIS, xStartNodes, nodeConnectivity));
3093
3094 const size_t numLeafNodes = nodeConnectivity.size();
3095 const size_t numVoxels = numLeafNodes * FloatTreeT::LeafNodeType::SIZE;
3096
3097 std::unique_ptr<bool[]> changedNodeMaskA{new bool[numLeafNodes]};
3098 std::unique_ptr<bool[]> changedNodeMaskB{new bool[numLeafNodes]};
3099 std::unique_ptr<bool[]> changedVoxelMask{new bool[numVoxels]};
3100
3101 mesh_to_volume_internal::fillArray(changedNodeMaskA.get(), true, numLeafNodes);
3102 mesh_to_volume_internal::fillArray(changedNodeMaskB.get(), false, numLeafNodes);
3103 mesh_to_volume_internal::fillArray(changedVoxelMask.get(), false, numVoxels);
3104
3105 const tbb::blocked_range<size_t> nodeRange(0, numLeafNodes);
3106
3107 bool nodesUpdated = false;
3108 do {
3109 // Perform per leaf node localized propagation of signs by looping over
3110 // all voxels and checking to see if any of their neighbors (within the
3111 // same leaf) are negative
3112 tbb::parallel_for(nodeRange, mesh_to_volume_internal::SeedFillExteriorSign<FloatTreeT>(
3113 nodeConnectivity.nodes(), changedNodeMaskA.get()));
3114
3115 // For each leaf, check its axis aligned neighbors and propagate any changes
3116 // which occurred previously (in SeedFillExteriorSign OR in SyncVoxelMask) to
3117 // the leaf faces. Note that this operation stores the propagated face results
3118 // in a separate buffer (changedVoxelMask) to avoid writing to nodes being read
3119 // from other threads. Additionally mark any leaf nodes which will absorb any
3120 // changes from its neighbors in changedNodeMaskB
3121 tbb::parallel_for(nodeRange, mesh_to_volume_internal::SeedPoints<FloatTreeT>(
3122 nodeConnectivity, changedNodeMaskA.get(), changedNodeMaskB.get(),
3123 changedVoxelMask.get()));
3124
3125 // Only nodes where a value was influenced by an adjacent node need to be
3126 // processed on the next pass.
3127 changedNodeMaskA.swap(changedNodeMaskB);
3128
3129 nodesUpdated = false;
3130 for (size_t n = 0; n < numLeafNodes; ++n) {
3131 nodesUpdated |= changedNodeMaskA[n];
3132 if (nodesUpdated) break;
3133 }
3134
3135 // Use the voxel mask updates in ::SeedPoints to actually assign the new values
3136 // across leaf node faces
3137 if (nodesUpdated) {
3138 tbb::parallel_for(nodeRange, mesh_to_volume_internal::SyncVoxelMask<FloatTreeT>(
3139 nodeConnectivity.nodes(), changedNodeMaskA.get(), changedVoxelMask.get()));
3140 }
3141 } while (nodesUpdated);
3142
3143} // void traceExteriorBoundaries()
3144
3145
3146////////////////////////////////////////
3147
3148template <typename T, Index Log2Dim, typename InteriorTest>
3149void
3150floodFillLeafNode(tree::LeafNode<T,Log2Dim>& leafNode, const InteriorTest& interiorTest) {
3151
3152 // Floods fills a single leaf node.
3153 // Starts with all voxels in NOT_VISITED.
3154 // Final result is voxels in either POSITIVE, NEGATIVE, or NOT_ASSIGNED.
3155 // Voxels that were categorized as NEGATIVE are negated.
3156 // The NOT_ASSIGNED is all voxels within 0.75 of the zero-crossing.
3157 //
3158 // NOT_VISITED voxels, if outside the 0.75 band, will query the oracle
3159 // to get a POSITIVE Or NEGATIVE sign (with interior being POSITIVE!)
3160 //
3161 // After setting a NOT_VISITED to either POSITIVE or NEGATIVE, an 8-way
3162 // depth-first floodfill is done, stopping at either the 0.75 boundary
3163 // or visited voxels.
3164 enum VoxelState {
3165 NOT_VISITED = 0,
3166 POSITIVE = 1,
3167 NEGATIVE = 2,
3168 NOT_ASSIGNED = 3
3169 };
3170
3171 const auto DIM = leafNode.DIM;
3172 const auto SIZE = leafNode.SIZE;
3173
3174 std::vector<VoxelState> voxelState(SIZE, NOT_VISITED);
3175
3176 std::vector<std::pair<Index, VoxelState>> offsetStack;
3177 offsetStack.reserve(SIZE);
3178
3179 for (Index offset=0; offset<SIZE; offset++) {
3180 const auto value = leafNode.getValue(offset);
3181
3182 // We do not assign anything for voxel close to the mesh
3183 // This condition is aligned with the condition in traceVoxelLine
3184 if (std::abs(value) <= 0.75) {
3185 voxelState[offset] = NOT_ASSIGNED;
3186 } else if (voxelState[offset] == NOT_VISITED) {
3187
3188 auto coord = leafNode.offsetToGlobalCoord(offset);
3189
3190 if (interiorTest(coord)){
3191 // Yes we assigne positive values to interior points
3192 // this is aligned with how meshToVolume works internally
3193 offsetStack.push_back({offset, POSITIVE});
3194 voxelState[offset] = POSITIVE;
3195 } else {
3196 offsetStack.push_back({offset, NEGATIVE});
3197 voxelState[offset] = NEGATIVE;
3198 }
3199
3200 while(!offsetStack.empty()){
3201
3202 auto [off, state] = offsetStack[offsetStack.size()-1];
3203 offsetStack.pop_back();
3204
3205 if (state == NEGATIVE) {
3206 leafNode.setValueOnly(off, -leafNode.getValue(off));
3207 }
3208
3209 // iterate over all neighbours and assign identical state
3210 // if they have not been visited and if they are far away
3211 // from the mesh (the condition is same as in traceVoxelLine)
3212 for (int dim=2; dim>=0; dim--){
3213 for (int i = -1; i <=1; ++(++i)){
3214 int dimIdx = (off >> dim * Log2Dim) % DIM;
3215 auto neighOff = off + (1 << dim * Log2Dim) * i;
3216 if ((0 < dimIdx) &&
3217 (dimIdx < (int)DIM - 1) &&
3218 (voxelState[neighOff] == NOT_VISITED)) {
3219
3220 if (std::abs(leafNode.getValue(neighOff)) <= 0.75) {
3221 voxelState[neighOff] = NOT_ASSIGNED;
3222 } else {
3223 offsetStack.push_back({neighOff, state});
3224 voxelState[neighOff] = state;
3225 }
3226 }
3227 }
3228 }
3229 }
3230 }
3231 }
3232}
3233
3234////////////////////////////////////////
3235
3236/// @brief Sets the sign of voxel values of `tree` based on the `interiorTest`
3237///
3238/// Inside is set to positive and outside to negative. This is in reverse to the usual
3239/// level set convention, but `meshToVolume` uses the opposite convention at certain point.
3240///
3241/// InteriorTest has to be a function `Coord -> bool` which evaluates true
3242/// inside of the mesh and false outside.
3243///
3244/// Furthermore, InteriorTest does not have to be thread-safe, but it has to be
3245/// copy constructible and evaluating different coppy has to be thread-safe.
3246///
3247/// Example of a interior test
3248///
3249/// auto acc = tree->getAccessor();
3250///
3251/// auto test = [acc = grid.getConstAccessor()](const Cood& coord) -> bool {
3252/// return acc->get(coord) <= 0 ? true : false;
3253/// }
3254template <typename FloatTreeT, typename InteriorTest>
3255void
3256evaluateInteriorTest(FloatTreeT& tree, InteriorTest interiorTest, InteriorTestStrategy interiorTestStrategy)
3257{
3258 static_assert(std::is_invocable_r<bool, InteriorTest, Coord>::value,
3259 "InteriorTest has to be a function `Coord -> bool`!");
3260 static_assert(std::is_copy_constructible_v<InteriorTest>,
3261 "InteriorTest has to be copyable!");
3262
3263 using LeafT = typename FloatTreeT::LeafNodeType;
3264
3265 if (interiorTestStrategy == EVAL_EVERY_VOXEL) {
3266
3267 auto op = [interiorTest](auto& node) {
3268 using Node = std::decay_t<decltype(node)>;
3269
3270 if constexpr (std::is_same_v<Node, LeafT>) {
3271
3272 for (auto iter = node.beginValueAll(); iter; ++iter) {
3273 if (!interiorTest(iter.getCoord())) {
3274 iter.setValue(-*iter);
3275 }
3276 }
3277
3278 } else {
3279 for (auto iter = node.beginChildOff(); iter; ++iter) {
3280 if (!interiorTest(iter.getCoord())) {
3281 iter.setValue(-*iter);
3282 }
3283 }
3284 }
3285 };
3286
3287 openvdb::tree::NodeManager nodes(tree);
3288 nodes.foreachBottomUp(op);
3289 }
3290
3291 if (interiorTestStrategy == EVAL_EVERY_TILE) {
3292
3293 auto op = [interiorTest](auto& node) {
3294 using Node = std::decay_t<decltype(node)>;
3295
3296 if constexpr (std::is_same_v<Node, LeafT>) {
3297 // // leaf node
3298 LeafT& leaf = static_cast<LeafT&>(node);
3299
3300 floodFillLeafNode(leaf, interiorTest);
3301
3302 } else {
3303 for (auto iter = node.beginChildOff(); iter; ++iter) {
3304 if (!interiorTest(iter.getCoord())) {
3305 iter.setValue(-*iter);
3306 }
3307 }
3308 }
3309 };
3310
3311 openvdb::tree::NodeManager nodes(tree);
3312 nodes.foreachBottomUp(op);
3313 }
3314} // void evaluateInteriorTest()
3315
3316////////////////////////////////////////
3317
3318
3319template <typename GridType, typename MeshDataAdapter, typename Interrupter, typename InteriorTest>
3320typename GridType::Ptr
3322 Interrupter& interrupter,
3323 const MeshDataAdapter& mesh,
3324 const math::Transform& transform,
3325 float exteriorBandWidth,
3326 float interiorBandWidth,
3327 int flags,
3328 typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid,
3329 InteriorTest interiorTest,
3330 InteriorTestStrategy interiorTestStrat)
3331{
3332 using GridTypePtr = typename GridType::Ptr;
3333 using TreeType = typename GridType::TreeType;
3334 using LeafNodeType = typename TreeType::LeafNodeType;
3335 using ValueType = typename GridType::ValueType;
3336
3337 using Int32GridType = typename GridType::template ValueConverter<Int32>::Type;
3338 using Int32TreeType = typename Int32GridType::TreeType;
3339
3340 using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
3341
3342 //////////
3343
3344 // Setup
3345
3346 GridTypePtr distGrid(new GridType(std::numeric_limits<ValueType>::max()));
3347 distGrid->setTransform(transform.copy());
3348
3349 ValueType exteriorWidth = ValueType(exteriorBandWidth);
3350 ValueType interiorWidth = ValueType(interiorBandWidth);
3351
3352 // Note: inf interior width is all right, this value makes the converter fill
3353 // interior regions with distance values.
3354 if (!std::isfinite(exteriorWidth) || std::isnan(interiorWidth)) {
3355 std::stringstream msg;
3356 msg << "Illegal narrow band width: exterior = " << exteriorWidth
3357 << ", interior = " << interiorWidth;
3358 OPENVDB_LOG_DEBUG(msg.str());
3359 return distGrid;
3360 }
3361
3362 const ValueType voxelSize = ValueType(transform.voxelSize()[0]);
3363
3364 if (!std::isfinite(voxelSize) || math::isZero(voxelSize)) {
3365 std::stringstream msg;
3366 msg << "Illegal transform, voxel size = " << voxelSize;
3367 OPENVDB_LOG_DEBUG(msg.str());
3368 return distGrid;
3369 }
3370
3371 // Convert narrow band width from voxel units to world space units.
3372 exteriorWidth *= voxelSize;
3373 // Avoid the unit conversion if the interior band width is set to
3374 // inf or std::numeric_limits<float>::max().
3375 if (interiorWidth < std::numeric_limits<ValueType>::max()) {
3376 interiorWidth *= voxelSize;
3377 }
3378
3379 const bool computeSignedDistanceField = (flags & UNSIGNED_DISTANCE_FIELD) == 0;
3380 const bool removeIntersectingVoxels = (flags & DISABLE_INTERSECTING_VOXEL_REMOVAL) == 0;
3381 const bool renormalizeValues = (flags & DISABLE_RENORMALIZATION) == 0;
3382 const bool trimNarrowBand = (flags & DISABLE_NARROW_BAND_TRIMMING) == 0;
3383
3384 Int32GridType* indexGrid = nullptr;
3385
3386 typename Int32GridType::Ptr temporaryIndexGrid;
3387
3388 if (polygonIndexGrid) {
3389 indexGrid = polygonIndexGrid;
3390 } else {
3391 temporaryIndexGrid.reset(new Int32GridType(Int32(util::INVALID_IDX)));
3392 indexGrid = temporaryIndexGrid.get();
3393 }
3394
3395 indexGrid->newTree();
3396 indexGrid->setTransform(transform.copy());
3397
3398 if (computeSignedDistanceField) {
3399 distGrid->setGridClass(GRID_LEVEL_SET);
3400 } else {
3401 distGrid->setGridClass(GRID_UNKNOWN);
3402 interiorWidth = ValueType(0.0);
3403 }
3404
3405 TreeType& distTree = distGrid->tree();
3406 Int32TreeType& indexTree = indexGrid->tree();
3407
3408
3409 //////////
3410
3411 // Voxelize mesh
3412
3413 {
3414 using VoxelizationDataType = mesh_to_volume_internal::VoxelizationData<TreeType>;
3415 using DataTable = tbb::enumerable_thread_specific<typename VoxelizationDataType::Ptr>;
3416
3417 DataTable data;
3418 using Voxelizer =
3419 mesh_to_volume_internal::VoxelizePolygons<TreeType, MeshDataAdapter, Interrupter>;
3420
3421 const tbb::blocked_range<size_t> polygonRange(0, mesh.polygonCount());
3422
3423 tbb::parallel_for(polygonRange, Voxelizer(data, mesh, &interrupter));
3424
3425 for (typename DataTable::iterator i = data.begin(); i != data.end(); ++i) {
3426 VoxelizationDataType& dataItem = **i;
3427 mesh_to_volume_internal::combineData(
3428 distTree, indexTree, dataItem.distTree, dataItem.indexTree);
3429 }
3430 }
3431
3432 // The progress estimates are based on the observed average time for a few different
3433 // test cases and is only intended to provide some rough progression feedback to the user.
3434 if (interrupter.wasInterrupted(30)) return distGrid;
3435
3436
3437 //////////
3438
3439 // Classify interior and exterior regions
3440
3441 if (computeSignedDistanceField) {
3442
3443 /// If interior test is not provided
3444 if constexpr (std::is_same_v<InteriorTest, std::nullptr_t>) {
3445 // Determines the inside/outside state for the narrow band of voxels.
3446 (void) interiorTest; // Trigger usage.
3447 traceExteriorBoundaries(distTree);
3448 } else {
3449 evaluateInteriorTest(distTree, interiorTest, interiorTestStrat);
3450 }
3451
3452 /// Do not fix intersecting voxels if we have evaluated interior test for every voxel.
3453 bool signInitializedForEveryVoxel =
3454 /// interior test was provided i.e. not null
3455 !std::is_same_v<InteriorTest, std::nullptr_t> &&
3456 /// interior test was evaluated for every voxel
3457 interiorTestStrat == EVAL_EVERY_VOXEL;
3458
3459 if (!signInitializedForEveryVoxel) {
3460
3461 std::vector<LeafNodeType*> nodes;
3462 nodes.reserve(distTree.leafCount());
3463 distTree.getNodes(nodes);
3464
3465 const tbb::blocked_range<size_t> nodeRange(0, nodes.size());
3466
3467 using SignOp =
3468 mesh_to_volume_internal::ComputeIntersectingVoxelSign<TreeType, MeshDataAdapter>;
3469
3470 tbb::parallel_for(nodeRange, SignOp(nodes, distTree, indexTree, mesh));
3471
3472 if (interrupter.wasInterrupted(45)) return distGrid;
3473
3474 // Remove voxels created by self intersecting portions of the mesh.
3475 if (removeIntersectingVoxels) {
3476
3477 tbb::parallel_for(nodeRange,
3478 mesh_to_volume_internal::ValidateIntersectingVoxels<TreeType>(distTree, nodes));
3479
3480 tbb::parallel_for(nodeRange,
3481 mesh_to_volume_internal::RemoveSelfIntersectingSurface<TreeType>(
3482 nodes, distTree, indexTree));
3483
3484 tools::pruneInactive(distTree, /*threading=*/true);
3485 tools::pruneInactive(indexTree, /*threading=*/true);
3486 }
3487 }
3488 }
3489
3490 if (interrupter.wasInterrupted(50)) return distGrid;
3491
3492 if (distTree.activeVoxelCount() == 0) {
3493 distTree.clear();
3494 distTree.root().setBackground(exteriorWidth, /*updateChildNodes=*/false);
3495 return distGrid;
3496 }
3497
3498 // Transform values (world space scaling etc.).
3499 {
3500 std::vector<LeafNodeType*> nodes;
3501 nodes.reserve(distTree.leafCount());
3502 distTree.getNodes(nodes);
3503
3504 tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3505 mesh_to_volume_internal::TransformValues<TreeType>(
3506 nodes, voxelSize, !computeSignedDistanceField));
3507 }
3508
3509 // Propagate sign information into tile regions.
3510 if (computeSignedDistanceField) {
3511 distTree.root().setBackground(exteriorWidth, /*updateChildNodes=*/false);
3512 tools::signedFloodFillWithValues(distTree, exteriorWidth, -interiorWidth);
3513 } else {
3514 tools::changeBackground(distTree, exteriorWidth);
3515 }
3516
3517 if (interrupter.wasInterrupted(54)) return distGrid;
3518
3519
3520 //////////
3521
3522 // Expand the narrow band region
3523
3524 const ValueType minBandWidth = voxelSize * ValueType(2.0);
3525
3526 if (interiorWidth > minBandWidth || exteriorWidth > minBandWidth) {
3527
3528 // Create the initial voxel mask.
3529 BoolTreeType maskTree(false);
3530
3531 {
3532 std::vector<LeafNodeType*> nodes;
3533 nodes.reserve(distTree.leafCount());
3534 distTree.getNodes(nodes);
3535
3536 mesh_to_volume_internal::ConstructVoxelMask<TreeType> op(maskTree, distTree, nodes);
3537 tbb::parallel_reduce(tbb::blocked_range<size_t>(0, nodes.size()), op);
3538 }
3539
3540 // Progress estimation
3541 unsigned maxIterations = std::numeric_limits<unsigned>::max();
3542
3543 float progress = 54.0f, step = 0.0f;
3544 double estimated =
3545 2.0 * std::ceil((std::max(interiorWidth, exteriorWidth) - minBandWidth) / voxelSize);
3546
3547 if (estimated < double(maxIterations)) {
3548 maxIterations = unsigned(estimated);
3549 step = 40.0f / float(maxIterations);
3550 }
3551
3552 std::vector<typename BoolTreeType::LeafNodeType*> maskNodes;
3553
3554 unsigned count = 0;
3555 while (true) {
3556
3557 if (interrupter.wasInterrupted(int(progress))) return distGrid;
3558
3559 const size_t maskNodeCount = maskTree.leafCount();
3560 if (maskNodeCount == 0) break;
3561
3562 maskNodes.clear();
3563 maskNodes.reserve(maskNodeCount);
3564 maskTree.getNodes(maskNodes);
3565
3566 const tbb::blocked_range<size_t> range(0, maskNodes.size());
3567
3568 tbb::parallel_for(range,
3569 mesh_to_volume_internal::DiffLeafNodeMask<TreeType>(distTree, maskNodes));
3570
3571 mesh_to_volume_internal::expandNarrowband(distTree, indexTree, maskTree, maskNodes,
3572 mesh, exteriorWidth, interiorWidth, voxelSize);
3573
3574 if ((++count) >= maxIterations) break;
3575 progress += step;
3576 }
3577 }
3578
3579 if (interrupter.wasInterrupted(94)) return distGrid;
3580
3581 if (!polygonIndexGrid) indexGrid->clear();
3582
3583
3584 /////////
3585
3586 // Renormalize distances to smooth out bumps caused by self intersecting
3587 // and overlapping portions of the mesh and renormalize the level set.
3588
3589 if (computeSignedDistanceField && renormalizeValues) {
3590
3591 std::vector<LeafNodeType*> nodes;
3592 nodes.reserve(distTree.leafCount());
3593 distTree.getNodes(nodes);
3594
3595 std::unique_ptr<ValueType[]> buffer{new ValueType[LeafNodeType::SIZE * nodes.size()]};
3596
3597 const ValueType offset = ValueType(0.8 * voxelSize);
3598
3599 tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3600 mesh_to_volume_internal::OffsetValues<TreeType>(nodes, -offset));
3601
3602 tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3603 mesh_to_volume_internal::Renormalize<TreeType>(
3604 distTree, nodes, buffer.get(), voxelSize));
3605
3606 tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3607 mesh_to_volume_internal::MinCombine<TreeType>(nodes, buffer.get()));
3608
3609 tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3610 mesh_to_volume_internal::OffsetValues<TreeType>(
3611 nodes, offset - mesh_to_volume_internal::Tolerance<ValueType>::epsilon()));
3612 }
3613
3614 if (interrupter.wasInterrupted(99)) return distGrid;
3615
3616
3617 /////////
3618
3619 // Remove active voxels that exceed the narrow band limits
3620
3621 if (trimNarrowBand && std::min(interiorWidth, exteriorWidth) < voxelSize * ValueType(4.0)) {
3622
3623 std::vector<LeafNodeType*> nodes;
3624 nodes.reserve(distTree.leafCount());
3625 distTree.getNodes(nodes);
3626
3627 tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3628 mesh_to_volume_internal::InactivateValues<TreeType>(
3629 nodes, exteriorWidth, computeSignedDistanceField ? interiorWidth : exteriorWidth));
3630
3632 distTree, exteriorWidth, computeSignedDistanceField ? -interiorWidth : -exteriorWidth);
3633 }
3634
3635 return distGrid;
3636}
3637
3638
3639template <typename GridType, typename MeshDataAdapter, typename InteriorTest>
3640typename GridType::Ptr
3642 const MeshDataAdapter& mesh,
3643 const math::Transform& transform,
3644 float exteriorBandWidth,
3645 float interiorBandWidth,
3646 int flags,
3647 typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid,
3648 InteriorTest /*interiorTest*/,
3649 InteriorTestStrategy /*interiorTestStrat*/)
3650{
3651 util::NullInterrupter nullInterrupter;
3652 return meshToVolume<GridType>(nullInterrupter, mesh, transform,
3653 exteriorBandWidth, interiorBandWidth, flags, polygonIndexGrid);
3654}
3655
3656
3657////////////////////////////////////////
3658
3659
3660//{
3661/// @cond OPENVDB_DOCS_INTERNAL
3662
3663/// @internal This overload is enabled only for grids with a scalar, floating-point ValueType.
3664template<typename GridType, typename Interrupter>
3665inline typename std::enable_if<std::is_floating_point<typename GridType::ValueType>::value,
3666 typename GridType::Ptr>::type
3667doMeshConversion(
3668 Interrupter& interrupter,
3669 const openvdb::math::Transform& xform,
3670 const std::vector<Vec3s>& points,
3671 const std::vector<Vec3I>& triangles,
3672 const std::vector<Vec4I>& quads,
3673 float exBandWidth,
3674 float inBandWidth,
3675 bool unsignedDistanceField = false)
3676{
3677 if (points.empty()) {
3678 return typename GridType::Ptr(new GridType(typename GridType::ValueType(exBandWidth)));
3679 }
3680
3681 const size_t numPoints = points.size();
3682 std::unique_ptr<Vec3s[]> indexSpacePoints{new Vec3s[numPoints]};
3683
3684 // transform points to local grid index space
3685 tbb::parallel_for(tbb::blocked_range<size_t>(0, numPoints),
3686 mesh_to_volume_internal::TransformPoints<Vec3s>(
3687 &points[0], indexSpacePoints.get(), xform));
3688
3689 const int conversionFlags = unsignedDistanceField ? UNSIGNED_DISTANCE_FIELD : 0;
3690
3691 if (quads.empty()) {
3692
3693 QuadAndTriangleDataAdapter<Vec3s, Vec3I>
3694 mesh(indexSpacePoints.get(), numPoints, &triangles[0], triangles.size());
3695
3696 return meshToVolume<GridType>(
3697 interrupter, mesh, xform, exBandWidth, inBandWidth, conversionFlags);
3698
3699 } else if (triangles.empty()) {
3700
3701 QuadAndTriangleDataAdapter<Vec3s, Vec4I>
3702 mesh(indexSpacePoints.get(), numPoints, &quads[0], quads.size());
3703
3704 return meshToVolume<GridType>(
3705 interrupter, mesh, xform, exBandWidth, inBandWidth, conversionFlags);
3706 }
3707
3708 // pack primitives
3709
3710 const size_t numPrimitives = triangles.size() + quads.size();
3711 std::unique_ptr<Vec4I[]> prims{new Vec4I[numPrimitives]};
3712
3713 for (size_t n = 0, N = triangles.size(); n < N; ++n) {
3714 const Vec3I& triangle = triangles[n];
3715 Vec4I& prim = prims[n];
3716 prim[0] = triangle[0];
3717 prim[1] = triangle[1];
3718 prim[2] = triangle[2];
3719 prim[3] = util::INVALID_IDX;
3720 }
3721
3722 const size_t offset = triangles.size();
3723 for (size_t n = 0, N = quads.size(); n < N; ++n) {
3724 prims[offset + n] = quads[n];
3725 }
3726
3727 QuadAndTriangleDataAdapter<Vec3s, Vec4I>
3728 mesh(indexSpacePoints.get(), numPoints, prims.get(), numPrimitives);
3729
3730 return meshToVolume<GridType>(interrupter, mesh, xform,
3731 exBandWidth, inBandWidth, conversionFlags);
3732}
3733
3734
3735/// @internal This overload is enabled only for grids that do not have a scalar,
3736/// floating-point ValueType.
3737template<typename GridType, typename Interrupter>
3738inline typename std::enable_if<!std::is_floating_point<typename GridType::ValueType>::value,
3739 typename GridType::Ptr>::type
3740doMeshConversion(
3741 Interrupter&,
3742 const math::Transform& /*xform*/,
3743 const std::vector<Vec3s>& /*points*/,
3744 const std::vector<Vec3I>& /*triangles*/,
3745 const std::vector<Vec4I>& /*quads*/,
3746 float /*exBandWidth*/,
3747 float /*inBandWidth*/,
3748 bool /*unsignedDistanceField*/ = false)
3749{
3750 OPENVDB_THROW(TypeError,
3751 "mesh to volume conversion is supported only for scalar floating-point grids");
3752}
3753
3754/// @endcond
3755//}
3756
3757
3758////////////////////////////////////////
3759
3760
3761template<typename GridType>
3762typename GridType::Ptr
3764 const openvdb::math::Transform& xform,
3765 const std::vector<Vec3s>& points,
3766 const std::vector<Vec3I>& triangles,
3767 float halfWidth)
3768{
3769 util::NullInterrupter nullInterrupter;
3770 return meshToLevelSet<GridType>(nullInterrupter, xform, points, triangles, halfWidth);
3771}
3772
3773
3774template<typename GridType, typename Interrupter>
3775typename GridType::Ptr
3777 Interrupter& interrupter,
3778 const openvdb::math::Transform& xform,
3779 const std::vector<Vec3s>& points,
3780 const std::vector<Vec3I>& triangles,
3781 float halfWidth)
3782{
3783 std::vector<Vec4I> quads(0);
3784 return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3785 halfWidth, halfWidth);
3786}
3787
3788
3789template<typename GridType>
3790typename GridType::Ptr
3792 const openvdb::math::Transform& xform,
3793 const std::vector<Vec3s>& points,
3794 const std::vector<Vec4I>& quads,
3795 float halfWidth)
3796{
3797 util::NullInterrupter nullInterrupter;
3798 return meshToLevelSet<GridType>(nullInterrupter, xform, points, quads, halfWidth);
3799}
3800
3801
3802template<typename GridType, typename Interrupter>
3803typename GridType::Ptr
3805 Interrupter& interrupter,
3806 const openvdb::math::Transform& xform,
3807 const std::vector<Vec3s>& points,
3808 const std::vector<Vec4I>& quads,
3809 float halfWidth)
3810{
3811 std::vector<Vec3I> triangles(0);
3812 return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3813 halfWidth, halfWidth);
3814}
3815
3816
3817template<typename GridType>
3818typename GridType::Ptr
3820 const openvdb::math::Transform& xform,
3821 const std::vector<Vec3s>& points,
3822 const std::vector<Vec3I>& triangles,
3823 const std::vector<Vec4I>& quads,
3824 float halfWidth)
3825{
3826 util::NullInterrupter nullInterrupter;
3828 nullInterrupter, xform, points, triangles, quads, halfWidth);
3829}
3830
3831
3832template<typename GridType, typename Interrupter>
3833typename GridType::Ptr
3835 Interrupter& interrupter,
3836 const openvdb::math::Transform& xform,
3837 const std::vector<Vec3s>& points,
3838 const std::vector<Vec3I>& triangles,
3839 const std::vector<Vec4I>& quads,
3840 float halfWidth)
3841{
3842 return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3843 halfWidth, halfWidth);
3844}
3845
3846
3847template<typename GridType>
3848typename GridType::Ptr
3850 const openvdb::math::Transform& xform,
3851 const std::vector<Vec3s>& points,
3852 const std::vector<Vec3I>& triangles,
3853 const std::vector<Vec4I>& quads,
3854 float exBandWidth,
3855 float inBandWidth)
3856{
3857 util::NullInterrupter nullInterrupter;
3859 nullInterrupter, xform, points, triangles, quads, exBandWidth, inBandWidth);
3860}
3861
3862
3863template<typename GridType, typename Interrupter>
3864typename GridType::Ptr
3866 Interrupter& interrupter,
3867 const openvdb::math::Transform& xform,
3868 const std::vector<Vec3s>& points,
3869 const std::vector<Vec3I>& triangles,
3870 const std::vector<Vec4I>& quads,
3871 float exBandWidth,
3872 float inBandWidth)
3873{
3874 return doMeshConversion<GridType>(interrupter, xform, points, triangles,
3875 quads, exBandWidth, inBandWidth);
3876}
3877
3878
3879template<typename GridType>
3880typename GridType::Ptr
3882 const openvdb::math::Transform& xform,
3883 const std::vector<Vec3s>& points,
3884 const std::vector<Vec3I>& triangles,
3885 const std::vector<Vec4I>& quads,
3886 float bandWidth)
3887{
3888 util::NullInterrupter nullInterrupter;
3890 nullInterrupter, xform, points, triangles, quads, bandWidth);
3891}
3892
3893
3894template<typename GridType, typename Interrupter>
3895typename GridType::Ptr
3897 Interrupter& interrupter,
3898 const openvdb::math::Transform& xform,
3899 const std::vector<Vec3s>& points,
3900 const std::vector<Vec3I>& triangles,
3901 const std::vector<Vec4I>& quads,
3902 float bandWidth)
3903{
3904 return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3905 bandWidth, bandWidth, true);
3906}
3907
3908
3909////////////////////////////////////////////////////////////////////////////////
3910
3911
3912// Required by several of the tree nodes
3913inline std::ostream&
3914operator<<(std::ostream& ostr, const MeshToVoxelEdgeData::EdgeData& rhs)
3915{
3916 ostr << "{[ " << rhs.mXPrim << ", " << rhs.mXDist << "]";
3917 ostr << " [ " << rhs.mYPrim << ", " << rhs.mYDist << "]";
3918 ostr << " [ " << rhs.mZPrim << ", " << rhs.mZDist << "]}";
3919 return ostr;
3920}
3921
3922// Required by math::Abs
3923inline MeshToVoxelEdgeData::EdgeData
3925{
3926 return x;
3927}
3928
3929
3930////////////////////////////////////////
3931
3932
3934{
3935public:
3936
3938 const std::vector<Vec3s>& pointList,
3939 const std::vector<Vec4I>& polygonList);
3940
3941 void run(bool threaded = true);
3942
3943 GenEdgeData(GenEdgeData& rhs, tbb::split);
3944 inline void operator() (const tbb::blocked_range<size_t> &range);
3945 inline void join(GenEdgeData& rhs);
3946
3947 inline TreeType& tree() { return mTree; }
3948
3949private:
3950 void operator=(const GenEdgeData&) {}
3951
3952 struct Primitive { Vec3d a, b, c, d; Int32 index; };
3953
3954 template<bool IsQuad>
3955 inline void voxelize(const Primitive&);
3956
3957 template<bool IsQuad>
3958 inline bool evalPrimitive(const Coord&, const Primitive&);
3959
3960 inline bool rayTriangleIntersection( const Vec3d& origin, const Vec3d& dir,
3961 const Vec3d& a, const Vec3d& b, const Vec3d& c, double& t);
3962
3963
3964 TreeType mTree;
3965 Accessor mAccessor;
3966
3967 const std::vector<Vec3s>& mPointList;
3968 const std::vector<Vec4I>& mPolygonList;
3969
3970 // Used internally for acceleration
3971 using IntTreeT = TreeType::ValueConverter<Int32>::Type;
3972 IntTreeT mLastPrimTree;
3973 tree::ValueAccessor<IntTreeT> mLastPrimAccessor;
3974}; // class MeshToVoxelEdgeData::GenEdgeData
3975
3976
3977inline
3979 const std::vector<Vec3s>& pointList,
3980 const std::vector<Vec4I>& polygonList)
3981 : mTree(EdgeData())
3982 , mAccessor(mTree)
3983 , mPointList(pointList)
3984 , mPolygonList(polygonList)
3985 , mLastPrimTree(Int32(util::INVALID_IDX))
3986 , mLastPrimAccessor(mLastPrimTree)
3987{
3988}
3989
3990
3991inline
3993 : mTree(EdgeData())
3994 , mAccessor(mTree)
3995 , mPointList(rhs.mPointList)
3996 , mPolygonList(rhs.mPolygonList)
3997 , mLastPrimTree(Int32(util::INVALID_IDX))
3998 , mLastPrimAccessor(mLastPrimTree)
3999{
4000}
4001
4002
4003inline void
4005{
4006 if (threaded) {
4007 tbb::parallel_reduce(tbb::blocked_range<size_t>(0, mPolygonList.size()), *this);
4008 } else {
4009 (*this)(tbb::blocked_range<size_t>(0, mPolygonList.size()));
4010 }
4011}
4012
4013
4014inline void
4016{
4017 using RootNodeType = TreeType::RootNodeType;
4018 using NodeChainType = RootNodeType::NodeChainType;
4019 static_assert(NodeChainType::Size > 1, "expected tree height > 1");
4020 using InternalNodeType = typename NodeChainType::template Get<1>;
4021
4022 Coord ijk;
4023 Index offset;
4024
4025 rhs.mTree.clearAllAccessors();
4026
4027 TreeType::LeafIter leafIt = rhs.mTree.beginLeaf();
4028 for ( ; leafIt; ++leafIt) {
4029 ijk = leafIt->origin();
4030
4031 TreeType::LeafNodeType* lhsLeafPt = mTree.probeLeaf(ijk);
4032
4033 if (!lhsLeafPt) {
4034
4035 mAccessor.addLeaf(rhs.mAccessor.probeLeaf(ijk));
4036 InternalNodeType* node = rhs.mAccessor.getNode<InternalNodeType>();
4037 node->stealNode<TreeType::LeafNodeType>(ijk, EdgeData(), false);
4038 rhs.mAccessor.clear();
4039
4040 } else {
4041
4042 TreeType::LeafNodeType::ValueOnCIter it = leafIt->cbeginValueOn();
4043 for ( ; it; ++it) {
4044
4045 offset = it.pos();
4046 const EdgeData& rhsValue = it.getValue();
4047
4048 if (!lhsLeafPt->isValueOn(offset)) {
4049 lhsLeafPt->setValueOn(offset, rhsValue);
4050 } else {
4051
4052 EdgeData& lhsValue = const_cast<EdgeData&>(lhsLeafPt->getValue(offset));
4053
4054 if (rhsValue.mXDist < lhsValue.mXDist) {
4055 lhsValue.mXDist = rhsValue.mXDist;
4056 lhsValue.mXPrim = rhsValue.mXPrim;
4057 }
4058
4059 if (rhsValue.mYDist < lhsValue.mYDist) {
4060 lhsValue.mYDist = rhsValue.mYDist;
4061 lhsValue.mYPrim = rhsValue.mYPrim;
4062 }
4063
4064 if (rhsValue.mZDist < lhsValue.mZDist) {
4065 lhsValue.mZDist = rhsValue.mZDist;
4066 lhsValue.mZPrim = rhsValue.mZPrim;
4067 }
4068
4069 }
4070 } // end value iteration
4071 }
4072 } // end leaf iteration
4073}
4074
4075
4076inline void
4077MeshToVoxelEdgeData::GenEdgeData::operator()(const tbb::blocked_range<size_t> &range)
4078{
4079 Primitive prim;
4080
4081 for (size_t n = range.begin(); n < range.end(); ++n) {
4082
4083 const Vec4I& verts = mPolygonList[n];
4084
4085 prim.index = Int32(n);
4086 prim.a = Vec3d(mPointList[verts[0]]);
4087 prim.b = Vec3d(mPointList[verts[1]]);
4088 prim.c = Vec3d(mPointList[verts[2]]);
4089
4090 if (util::INVALID_IDX != verts[3]) {
4091 prim.d = Vec3d(mPointList[verts[3]]);
4092 voxelize<true>(prim);
4093 } else {
4094 voxelize<false>(prim);
4095 }
4096 }
4097}
4098
4099
4100template<bool IsQuad>
4101inline void
4102MeshToVoxelEdgeData::GenEdgeData::voxelize(const Primitive& prim)
4103{
4104 std::deque<Coord> coordList;
4105 Coord ijk, nijk;
4106
4107 ijk = Coord::floor(prim.a);
4108 coordList.push_back(ijk);
4109
4110 evalPrimitive<IsQuad>(ijk, prim);
4111
4112 while (!coordList.empty()) {
4113
4114 ijk = coordList.back();
4115 coordList.pop_back();
4116
4117 for (Int32 i = 0; i < 26; ++i) {
4118 nijk = ijk + util::COORD_OFFSETS[i];
4119
4120 if (prim.index != mLastPrimAccessor.getValue(nijk)) {
4121 mLastPrimAccessor.setValue(nijk, prim.index);
4122 if(evalPrimitive<IsQuad>(nijk, prim)) coordList.push_back(nijk);
4123 }
4124 }
4125 }
4126}
4127
4128
4129template<bool IsQuad>
4130inline bool
4131MeshToVoxelEdgeData::GenEdgeData::evalPrimitive(const Coord& ijk, const Primitive& prim)
4132{
4133 Vec3d uvw, org(ijk[0], ijk[1], ijk[2]);
4134 bool intersecting = false;
4135 double t;
4136
4137 EdgeData edgeData;
4138 mAccessor.probeValue(ijk, edgeData);
4139
4140 // Evaluate first triangle
4141 double dist = (org -
4142 closestPointOnTriangleToPoint(prim.a, prim.c, prim.b, org, uvw)).lengthSqr();
4143
4144 if (rayTriangleIntersection(org, Vec3d(1.0, 0.0, 0.0), prim.a, prim.c, prim.b, t)) {
4145 if (t < edgeData.mXDist) {
4146 edgeData.mXDist = float(t);
4147 edgeData.mXPrim = prim.index;
4148 intersecting = true;
4149 }
4150 }
4151
4152 if (rayTriangleIntersection(org, Vec3d(0.0, 1.0, 0.0), prim.a, prim.c, prim.b, t)) {
4153 if (t < edgeData.mYDist) {
4154 edgeData.mYDist = float(t);
4155 edgeData.mYPrim = prim.index;
4156 intersecting = true;
4157 }
4158 }
4159
4160 if (rayTriangleIntersection(org, Vec3d(0.0, 0.0, 1.0), prim.a, prim.c, prim.b, t)) {
4161 if (t < edgeData.mZDist) {
4162 edgeData.mZDist = float(t);
4163 edgeData.mZPrim = prim.index;
4164 intersecting = true;
4165 }
4166 }
4167
4168 if (IsQuad) {
4169 // Split quad into a second triangle and calculate distance.
4170 double secondDist = (org -
4171 closestPointOnTriangleToPoint(prim.a, prim.d, prim.c, org, uvw)).lengthSqr();
4172
4173 if (secondDist < dist) dist = secondDist;
4174
4175 if (rayTriangleIntersection(org, Vec3d(1.0, 0.0, 0.0), prim.a, prim.d, prim.c, t)) {
4176 if (t < edgeData.mXDist) {
4177 edgeData.mXDist = float(t);
4178 edgeData.mXPrim = prim.index;
4179 intersecting = true;
4180 }
4181 }
4182
4183 if (rayTriangleIntersection(org, Vec3d(0.0, 1.0, 0.0), prim.a, prim.d, prim.c, t)) {
4184 if (t < edgeData.mYDist) {
4185 edgeData.mYDist = float(t);
4186 edgeData.mYPrim = prim.index;
4187 intersecting = true;
4188 }
4189 }
4190
4191 if (rayTriangleIntersection(org, Vec3d(0.0, 0.0, 1.0), prim.a, prim.d, prim.c, t)) {
4192 if (t < edgeData.mZDist) {
4193 edgeData.mZDist = float(t);
4194 edgeData.mZPrim = prim.index;
4195 intersecting = true;
4196 }
4197 }
4198 }
4199
4200 if (intersecting) mAccessor.setValue(ijk, edgeData);
4201
4202 return (dist < 0.86602540378443861);
4203}
4204
4205
4206inline bool
4207MeshToVoxelEdgeData::GenEdgeData::rayTriangleIntersection(
4208 const Vec3d& origin, const Vec3d& dir,
4209 const Vec3d& a, const Vec3d& b, const Vec3d& c,
4210 double& t)
4211{
4212 // Check if ray is parallel with triangle
4213
4214 Vec3d e1 = b - a;
4215 Vec3d e2 = c - a;
4216 Vec3d s1 = dir.cross(e2);
4217
4218 double divisor = s1.dot(e1);
4219 if (!(std::abs(divisor) > 0.0)) return false;
4220
4221 // Compute barycentric coordinates
4222
4223 double inv_divisor = 1.0 / divisor;
4224 Vec3d d = origin - a;
4225 double b1 = d.dot(s1) * inv_divisor;
4226
4227 if (b1 < 0.0 || b1 > 1.0) return false;
4228
4229 Vec3d s2 = d.cross(e1);
4230 double b2 = dir.dot(s2) * inv_divisor;
4231
4232 if (b2 < 0.0 || (b1 + b2) > 1.0) return false;
4233
4234 // Compute distance to intersection point
4235
4236 t = e2.dot(s2) * inv_divisor;
4237 return (t < 0.0) ? false : true;
4238}
4239
4240
4241////////////////////////////////////////
4242
4243
4244inline
4249
4250
4251inline void
4253 const std::vector<Vec3s>& pointList,
4254 const std::vector<Vec4I>& polygonList)
4255{
4256 GenEdgeData converter(pointList, polygonList);
4257 converter.run();
4258
4259 mTree.clear();
4260 mTree.merge(converter.tree());
4261}
4262
4263
4264inline void
4266 Accessor& acc,
4267 const Coord& ijk,
4268 std::vector<Vec3d>& points,
4269 std::vector<Index32>& primitives)
4270{
4271 EdgeData data;
4272 Vec3d point;
4273
4274 Coord coord = ijk;
4275
4276 if (acc.probeValue(coord, data)) {
4277
4278 if (data.mXPrim != util::INVALID_IDX) {
4279 point[0] = double(coord[0]) + data.mXDist;
4280 point[1] = double(coord[1]);
4281 point[2] = double(coord[2]);
4282
4283 points.push_back(point);
4284 primitives.push_back(data.mXPrim);
4285 }
4286
4287 if (data.mYPrim != util::INVALID_IDX) {
4288 point[0] = double(coord[0]);
4289 point[1] = double(coord[1]) + data.mYDist;
4290 point[2] = double(coord[2]);
4291
4292 points.push_back(point);
4293 primitives.push_back(data.mYPrim);
4294 }
4295
4296 if (data.mZPrim != util::INVALID_IDX) {
4297 point[0] = double(coord[0]);
4298 point[1] = double(coord[1]);
4299 point[2] = double(coord[2]) + data.mZDist;
4300
4301 points.push_back(point);
4302 primitives.push_back(data.mZPrim);
4303 }
4304
4305 }
4306
4307 coord[0] += 1;
4308
4309 if (acc.probeValue(coord, data)) {
4310
4311 if (data.mYPrim != util::INVALID_IDX) {
4312 point[0] = double(coord[0]);
4313 point[1] = double(coord[1]) + data.mYDist;
4314 point[2] = double(coord[2]);
4315
4316 points.push_back(point);
4317 primitives.push_back(data.mYPrim);
4318 }
4319
4320 if (data.mZPrim != util::INVALID_IDX) {
4321 point[0] = double(coord[0]);
4322 point[1] = double(coord[1]);
4323 point[2] = double(coord[2]) + data.mZDist;
4324
4325 points.push_back(point);
4326 primitives.push_back(data.mZPrim);
4327 }
4328 }
4329
4330 coord[2] += 1;
4331
4332 if (acc.probeValue(coord, data)) {
4333 if (data.mYPrim != util::INVALID_IDX) {
4334 point[0] = double(coord[0]);
4335 point[1] = double(coord[1]) + data.mYDist;
4336 point[2] = double(coord[2]);
4337
4338 points.push_back(point);
4339 primitives.push_back(data.mYPrim);
4340 }
4341 }
4342
4343 coord[0] -= 1;
4344
4345 if (acc.probeValue(coord, data)) {
4346
4347 if (data.mXPrim != util::INVALID_IDX) {
4348 point[0] = double(coord[0]) + data.mXDist;
4349 point[1] = double(coord[1]);
4350 point[2] = double(coord[2]);
4351
4352 points.push_back(point);
4353 primitives.push_back(data.mXPrim);
4354 }
4355
4356 if (data.mYPrim != util::INVALID_IDX) {
4357 point[0] = double(coord[0]);
4358 point[1] = double(coord[1]) + data.mYDist;
4359 point[2] = double(coord[2]);
4360
4361 points.push_back(point);
4362 primitives.push_back(data.mYPrim);
4363 }
4364 }
4365
4366
4367 coord[1] += 1;
4368
4369 if (acc.probeValue(coord, data)) {
4370
4371 if (data.mXPrim != util::INVALID_IDX) {
4372 point[0] = double(coord[0]) + data.mXDist;
4373 point[1] = double(coord[1]);
4374 point[2] = double(coord[2]);
4375
4376 points.push_back(point);
4377 primitives.push_back(data.mXPrim);
4378 }
4379 }
4380
4381 coord[2] -= 1;
4382
4383 if (acc.probeValue(coord, data)) {
4384
4385 if (data.mXPrim != util::INVALID_IDX) {
4386 point[0] = double(coord[0]) + data.mXDist;
4387 point[1] = double(coord[1]);
4388 point[2] = double(coord[2]);
4389
4390 points.push_back(point);
4391 primitives.push_back(data.mXPrim);
4392 }
4393
4394 if (data.mZPrim != util::INVALID_IDX) {
4395 point[0] = double(coord[0]);
4396 point[1] = double(coord[1]);
4397 point[2] = double(coord[2]) + data.mZDist;
4398
4399 points.push_back(point);
4400 primitives.push_back(data.mZPrim);
4401 }
4402 }
4403
4404 coord[0] += 1;
4405
4406 if (acc.probeValue(coord, data)) {
4407
4408 if (data.mZPrim != util::INVALID_IDX) {
4409 point[0] = double(coord[0]);
4410 point[1] = double(coord[1]);
4411 point[2] = double(coord[2]) + data.mZDist;
4412
4413 points.push_back(point);
4414 primitives.push_back(data.mZPrim);
4415 }
4416 }
4417}
4418
4419
4420template<typename GridType, typename VecType>
4421typename GridType::Ptr
4423 const openvdb::math::Transform& xform,
4424 typename VecType::ValueType halfWidth)
4425{
4426 const Vec3s pmin = Vec3s(xform.worldToIndex(bbox.min()));
4427 const Vec3s pmax = Vec3s(xform.worldToIndex(bbox.max()));
4428
4429 Vec3s points[8];
4430 points[0] = Vec3s(pmin[0], pmin[1], pmin[2]);
4431 points[1] = Vec3s(pmin[0], pmin[1], pmax[2]);
4432 points[2] = Vec3s(pmax[0], pmin[1], pmax[2]);
4433 points[3] = Vec3s(pmax[0], pmin[1], pmin[2]);
4434 points[4] = Vec3s(pmin[0], pmax[1], pmin[2]);
4435 points[5] = Vec3s(pmin[0], pmax[1], pmax[2]);
4436 points[6] = Vec3s(pmax[0], pmax[1], pmax[2]);
4437 points[7] = Vec3s(pmax[0], pmax[1], pmin[2]);
4438
4439 Vec4I faces[6];
4440 faces[0] = Vec4I(0, 1, 2, 3); // bottom
4441 faces[1] = Vec4I(7, 6, 5, 4); // top
4442 faces[2] = Vec4I(4, 5, 1, 0); // front
4443 faces[3] = Vec4I(6, 7, 3, 2); // back
4444 faces[4] = Vec4I(0, 3, 7, 4); // left
4445 faces[5] = Vec4I(1, 5, 6, 2); // right
4446
4448
4449 return meshToVolume<GridType>(mesh, xform, static_cast<float>(halfWidth), static_cast<float>(halfWidth));
4450}
4451
4452
4453////////////////////////////////////////
4454
4455
4456// Explicit Template Instantiation
4457
4458#ifdef OPENVDB_USE_EXPLICIT_INSTANTIATION
4459
4460#ifdef OPENVDB_INSTANTIATE_MESHTOVOLUME
4462#endif
4463
4464#define _FUNCTION(TreeT) \
4465 Grid<TreeT>::Ptr meshToVolume<Grid<TreeT>>(util::NullInterrupter&, \
4466 const QuadAndTriangleDataAdapter<Vec3s, Vec3I>&, const openvdb::math::Transform&, \
4467 float, float, int, Grid<TreeT>::ValueConverter<Int32>::Type*, std::nullptr_t, InteriorTestStrategy)
4469#undef _FUNCTION
4470
4471#define _FUNCTION(TreeT) \
4472 Grid<TreeT>::Ptr meshToVolume<Grid<TreeT>>(util::NullInterrupter&, \
4473 const QuadAndTriangleDataAdapter<Vec3s, Vec4I>&, const openvdb::math::Transform&, \
4474 float, float, int, Grid<TreeT>::ValueConverter<Int32>::Type*, std::nullptr_t, InteriorTestStrategy)
4476#undef _FUNCTION
4477
4478#define _FUNCTION(TreeT) \
4479 Grid<TreeT>::Ptr meshToLevelSet<Grid<TreeT>>(util::NullInterrupter&, \
4480 const openvdb::math::Transform&, const std::vector<Vec3s>&, const std::vector<Vec3I>&, \
4481 float)
4483#undef _FUNCTION
4484
4485#define _FUNCTION(TreeT) \
4486 Grid<TreeT>::Ptr meshToLevelSet<Grid<TreeT>>(util::NullInterrupter&, \
4487 const openvdb::math::Transform&, const std::vector<Vec3s>&, const std::vector<Vec4I>&, \
4488 float)
4490#undef _FUNCTION
4491
4492#define _FUNCTION(TreeT) \
4493 Grid<TreeT>::Ptr meshToLevelSet<Grid<TreeT>>(util::NullInterrupter&, \
4494 const openvdb::math::Transform&, const std::vector<Vec3s>&, \
4495 const std::vector<Vec3I>&, const std::vector<Vec4I>&, float)
4497#undef _FUNCTION
4498
4499#define _FUNCTION(TreeT) \
4500 Grid<TreeT>::Ptr meshToSignedDistanceField<Grid<TreeT>>(util::NullInterrupter&, \
4501 const openvdb::math::Transform&, const std::vector<Vec3s>&, \
4502 const std::vector<Vec3I>&, const std::vector<Vec4I>&, float, float)
4504#undef _FUNCTION
4505
4506#define _FUNCTION(TreeT) \
4507 Grid<TreeT>::Ptr meshToUnsignedDistanceField<Grid<TreeT>>(util::NullInterrupter&, \
4508 const openvdb::math::Transform&, const std::vector<Vec3s>&, \
4509 const std::vector<Vec3I>&, const std::vector<Vec4I>&, float)
4511#undef _FUNCTION
4512
4513#define _FUNCTION(TreeT) \
4514 Grid<TreeT>::Ptr createLevelSetBox<Grid<TreeT>>(const math::BBox<Vec3s>&, \
4515 const openvdb::math::Transform&, float)
4517#undef _FUNCTION
4518
4519#define _FUNCTION(TreeT) \
4520 Grid<TreeT>::Ptr createLevelSetBox<Grid<TreeT>>(const math::BBox<Vec3d>&, \
4521 const openvdb::math::Transform&, double)
4523#undef _FUNCTION
4524
4525#define _FUNCTION(TreeT) \
4526 void traceExteriorBoundaries(TreeT&)
4528#undef _FUNCTION
4529
4530#endif // OPENVDB_USE_EXPLICIT_INSTANTIATION
4531
4532
4533} // namespace tools
4534} // namespace OPENVDB_VERSION_NAME
4535} // namespace openvdb
4536
4537#endif // OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
#define OPENVDB_ASSERT(X)
Definition Assert.h:41
Efficient multi-threaded replacement of the background values in tree.
Defined various multi-threaded utility functions for trees.
Propagate the signs of distance values from the active voxels in the narrow band to the inactive valu...
static Coord floor(const Vec3< T > &xyz)
Return the largest integer coordinates that are not greater than xyz (node centered conversion).
Definition Coord.h:57
Axis-aligned bounding box.
Definition BBox.h:24
const Vec3T & max() const
Return a const reference to the maximum point of this bounding box.
Definition BBox.h:64
const Vec3T & min() const
Return a const reference to the minimum point of this bounding box.
Definition BBox.h:62
Signed (x, y, z) 32-bit integer coordinates.
Definition Coord.h:26
Definition Transform.h:40
Vec3d voxelSize() const
Return the size of a voxel using the linear component of the map.
Definition Transform.h:93
Ptr copy() const
Definition Transform.h:50
T dot(const Vec3< T > &v) const
Dot product.
Definition Vec3.h:192
Vec3< T > cross(const Vec3< T > &v) const
Return the cross product of "this" vector and v;.
Definition Vec3.h:221
TreeType & tree()
Definition MeshToVolume.h:3947
void operator()(const tbb::blocked_range< size_t > &range)
Definition MeshToVolume.h:4077
void run(bool threaded=true)
Definition MeshToVolume.h:4004
void join(GenEdgeData &rhs)
Definition MeshToVolume.h:4015
GenEdgeData(const std::vector< Vec3s > &pointList, const std::vector< Vec4I > &polygonList)
Definition MeshToVolume.h:3978
Extracts and stores voxel edge intersection data from a mesh.
Definition MeshToVolume.h:457
tree::Tree4< EdgeData, 5, 4, 3 >::Type TreeType
Definition MeshToVolume.h:491
tree::ValueAccessor< TreeType > Accessor
Definition MeshToVolume.h:492
void convert(const std::vector< Vec3s > &pointList, const std::vector< Vec4I > &polygonList)
Threaded method to extract voxel edge data, the closest intersection point and corresponding primitiv...
Definition MeshToVolume.h:4252
MeshToVoxelEdgeData()
Definition MeshToVolume.h:4245
Accessor getAccessor()
Definition MeshToVolume.h:518
void getEdgeData(Accessor &acc, const Coord &ijk, std::vector< Vec3d > &points, std::vector< Index32 > &primitives)
Returns intersection points with corresponding primitive indices for the given ijk voxel.
Definition MeshToVolume.h:4265
Templated block class to hold specific data types and a fixed number of values determined by Log2Dim....
Definition LeafNode.h:39
const ValueType & getValue(const Coord &xyz) const
Return the value of the voxel at the given coordinates.
Definition LeafNode.h:1104
void setValueOnly(const Coord &xyz, const ValueType &val)
Set the value of the voxel at the given coordinates but don't change its active state.
Definition LeafNode.h:1162
static const Index DIM
Definition LeafNode.h:51
Coord offsetToGlobalCoord(Index n) const
Return the global coordinates for a linear table offset.
Definition LeafNode.h:1093
static const Index SIZE
Definition LeafNode.h:54
const ValueT & getValue() const
Return the tile or voxel value to which this iterator is currently pointing.
Definition TreeIterator.h:693
void clearAllAccessors()
Clear all registered accessors.
Definition Tree.h:1457
_RootNodeType RootNodeType
Definition Tree.h:200
TreeValueIteratorBase< const Tree, typename RootNodeType::ValueOnCIter > ValueOnCIter
Definition Tree.h:1049
LeafIteratorBase< Tree, typename RootNodeType::ChildOnIter > LeafIter
Iterator over all leaf nodes in this tree.
Definition Tree.h:1028
typename RootNodeType::LeafNodeType LeafNodeType
Definition Tree.h:203
LeafIter beginLeaf()
Return an iterator over all leaf nodes in this tree.
Definition Tree.h:1041
void clear() override final
Remove all the cached nodes and invalidate the corresponding hash-keys.
Definition ValueAccessor.h:880
LeafNodeT * probeLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains the voxel coordinate xyz. If no LeafNode exists,...
Definition ValueAccessor.h:836
bool probeValue(const Coord &xyz, ValueType &value) const
Return the active state of the value at a given coordinate as well as its value.
Definition ValueAccessor.h:492
NodeT * getNode()
Return the node of type NodeT that has been cached on this accessor. If this accessor does not cache ...
Definition ValueAccessor.h:848
Convert polygonal meshes that consist of quads and/or triangles into signed or unsigned distance fiel...
#define OPENVDB_LOG_DEBUG(message)
In debug builds only, log a debugging message of the form 'someVar << "text" << .....
Definition logging.h:266
bool empty(const char *str)
tests if a c-string str is empty, that is its first value is '\0'
Definition Util.h:156
PointType
Definition NanoVDB.h:395
Vec3d closestPointOnTriangleToPoint(const Vec3d &a, const Vec3d &b, const Vec3d &c, const Vec3d &p, Vec3d &uvw)
Closest Point on Triangle to Point. Given a triangle abc and a point p, return the point on abc close...
Vec3< double > Vec3d
Definition Vec3.h:708
bool operator<(const Vec2< T1 > &a, const Vec2< T2 > &b)=delete
bool isZero(const Type &x)
Return true if x is exactly equal to zero.
Definition Math.h:350
Axis
Definition Math.h:969
@ Z_AXIS
Definition Math.h:972
@ X_AXIS
Definition Math.h:970
@ Y_AXIS
Definition Math.h:971
Vec3< float > Vec3s
Definition Vec3.h:707
Definition AttributeArray.h:42
const std::enable_if<!VecTraits< T >::IsVec, T >::type & max(const T &a, const T &b)
Definition Composite.h:110
void signedFloodFillWithValues(TreeOrLeafManagerT &tree, const typename TreeOrLeafManagerT::ValueType &outsideWidth, const typename TreeOrLeafManagerT::ValueType &insideWidth, bool threaded=true, size_t grainSize=1, Index minLevel=0)
Set the values of all inactive voxels and tiles of a narrow-band level set from the signs of the acti...
Definition SignedFloodFill.h:253
MeshToVolumeFlags
Mesh to volume conversion flags.
Definition MeshToVolume.h:60
@ DISABLE_INTERSECTING_VOXEL_REMOVAL
Definition MeshToVolume.h:70
@ DISABLE_RENORMALIZATION
Definition MeshToVolume.h:74
@ DISABLE_NARROW_BAND_TRIMMING
Definition MeshToVolume.h:78
@ UNSIGNED_DISTANCE_FIELD
Definition MeshToVolume.h:66
void floodFillLeafNode(tree::LeafNode< T, Log2Dim > &leafNode, const InteriorTest &interiorTest)
Definition MeshToVolume.h:3150
MeshToVoxelEdgeData::EdgeData Abs(const MeshToVoxelEdgeData::EdgeData &x)
Definition MeshToVolume.h:3924
void pruneLevelSet(TreeT &tree, bool threaded=true, size_t grainSize=1)
Reduce the memory footprint of a tree by replacing nodes whose values are all inactive with inactive ...
Definition Prune.h:392
GridType::Ptr meshToLevelSet(const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, float halfWidth=float(LEVEL_SET_HALF_WIDTH))
Convert a triangle mesh to a level set volume.
Definition MeshToVolume.h:3763
void traceExteriorBoundaries(FloatTreeT &tree)
Traces the exterior voxel boundary of closed objects in the input volume tree. Exterior voxels are ma...
Definition MeshToVolume.h:3052
GridType::Ptr meshToUnsignedDistanceField(const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, const std::vector< Vec4I > &quads, float bandWidth)
Convert a triangle and quad mesh to an unsigned distance field.
Definition MeshToVolume.h:3881
std::ostream & operator<<(std::ostream &ostr, const MeshToVoxelEdgeData::EdgeData &rhs)
Definition MeshToVolume.h:3914
GridType::Ptr meshToVolume(const MeshDataAdapter &mesh, const math::Transform &transform, float exteriorBandWidth=3.0f, float interiorBandWidth=3.0f, int flags=0, typename GridType::template ValueConverter< Int32 >::Type *polygonIndexGrid=nullptr, InteriorTest interiorTest=nullptr, InteriorTestStrategy interiorTestStrat=EVAL_EVERY_VOXEL)
Definition MeshToVolume.h:3641
GridType::Ptr createLevelSetBox(const math::BBox< VecType > &bbox, const openvdb::math::Transform &xform, typename VecType::ValueType halfWidth=LEVEL_SET_HALF_WIDTH)
Return a grid of type GridType containing a narrow-band level set representation of a box.
Definition MeshToVolume.h:4422
GridType::Ptr meshToSignedDistanceField(const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, const std::vector< Vec4I > &quads, float exBandWidth, float inBandWidth)
Convert a triangle and quad mesh to a signed distance field with an asymmetrical narrow band.
Definition MeshToVolume.h:3849
void changeBackground(TreeOrLeafManagerT &tree, const typename TreeOrLeafManagerT::ValueType &background, bool threaded=true, size_t grainSize=32)
Replace the background value in all the nodes of a tree.
Definition ChangeBackground.h:204
void pruneInactive(TreeT &tree, bool threaded=true, size_t grainSize=1)
Reduce the memory footprint of a tree by replacing with background tiles any nodes whose values are a...
Definition Prune.h:357
void evaluateInteriorTest(FloatTreeT &tree, InteriorTest interiorTest, InteriorTestStrategy interiorTestStrategy)
Sets the sign of voxel values of tree based on the interiorTest
Definition MeshToVolume.h:3256
InteriorTestStrategy
Different staregies how to determine sign of an SDF when using interior test.
Definition MeshToVolume.h:84
@ EVAL_EVERY_VOXEL
Definition MeshToVolume.h:88
@ EVAL_EVERY_TILE
Evaluates interior test at least once per tile and flood fills within the tile.
Definition MeshToVolume.h:91
Definition PointDataGrid.h:170
ValueAccessorImpl< TreeType, IsSafe, MutexType, openvdb::make_index_sequence< CacheLevels > > ValueAccessor
Default alias for a ValueAccessor. This is simply a helper alias for the generic definition but takes...
Definition ValueAccessor.h:86
Definition CpuTimer.h:18
constexpr Index32 INVALID_IDX
Definition Util.h:19
constexpr Coord COORD_OFFSETS[26]
coordinate offset table for neighboring voxels
Definition Util.h:22
bool wasInterrupted(T *i, int percent=-1)
Definition NullInterrupter.h:49
static const Real LEVEL_SET_HALF_WIDTH
Definition Types.h:532
Index32 Index
Definition Types.h:34
math::Vec4< Index32 > Vec4I
Definition Types.h:69
@ GRID_LEVEL_SET
Definition Types.h:526
@ GRID_UNKNOWN
Definition Types.h:525
uint32_t Index32
Definition Types.h:32
math::Vec3< Index32 > Vec3I
Definition Types.h:54
int32_t Int32
Definition Types.h:36
Definition Exceptions.h:13
#define OPENVDB_THROW(exception, message)
Definition Exceptions.h:74
Internal edge data type.
Definition MeshToVolume.h:463
EdgeData(float dist=1.0)
Definition MeshToVolume.h:464
bool operator==(const EdgeData &rhs) const
Definition MeshToVolume.h:482
Index32 mXPrim
Definition MeshToVolume.h:488
float mZDist
Definition MeshToVolume.h:487
EdgeData operator+(const T &) const
Definition MeshToVolume.h:477
float mYDist
Definition MeshToVolume.h:487
float mXDist
Definition MeshToVolume.h:487
Index32 mZPrim
Definition MeshToVolume.h:488
EdgeData operator-(const T &) const
Definition MeshToVolume.h:478
Index32 mYPrim
Definition MeshToVolume.h:488
EdgeData operator-() const
Definition MeshToVolume.h:479
Contiguous quad and triangle data adapter class.
Definition MeshToVolume.h:187
size_t polygonCount() const
Definition MeshToVolume.h:207
void getIndexSpacePoint(size_t n, size_t v, Vec3d &pos) const
Returns position pos in local grid index space for polygon n and vertex v.
Definition MeshToVolume.h:217
QuadAndTriangleDataAdapter(const std::vector< PointType > &points, const std::vector< PolygonType > &polygons)
Definition MeshToVolume.h:189
size_t pointCount() const
Definition MeshToVolume.h:208
QuadAndTriangleDataAdapter(const PointType *pointArray, size_t pointArraySize, const PolygonType *polygonArray, size_t polygonArraySize)
Definition MeshToVolume.h:198
size_t vertexCount(size_t n) const
Vertex count for polygon n.
Definition MeshToVolume.h:211
Tree< RootNode< InternalNode< InternalNode< LeafNode< T, N3 >, N2 >, N1 > > > Type
Definition Tree.h:1126
Base class for interrupters.
Definition NullInterrupter.h:26
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition version.h.in:121
#define OPENVDB_USE_VERSION_NAMESPACE
Definition version.h.in:284
#define OPENVDB_REAL_TREE_INSTANTIATE(Function)
Definition version.h.in:228