OpenVDB  6.0.0
MeshToVolume.h
Go to the documentation of this file.
1 //
3 // Copyright (c) 2012-2018 DreamWorks Animation LLC
4 //
5 // All rights reserved. This software is distributed under the
6 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
7 //
8 // Redistributions of source code must retain the above copyright
9 // and license notice and the following restrictions and disclaimer.
10 //
11 // * Neither the name of DreamWorks Animation nor the names of
12 // its contributors may be used to endorse or promote products derived
13 // from this software without specific prior written permission.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
20 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 // IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
27 // LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
28 //
30 
42 
43 #ifndef OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
44 #define OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
45 
46 #include <openvdb/Platform.h> // for OPENVDB_HAS_CXX11
47 #include <openvdb/Types.h>
48 #include <openvdb/math/FiniteDifference.h> // for GodunovsNormSqrd
49 #include <openvdb/math/Proximity.h> // for closestPointOnTriangleToPoint
51 #include <openvdb/util/Util.h>
52 
53 #include "ChangeBackground.h"
54 #include "Prune.h" // for pruneInactive and pruneLevelSet
55 #include "SignedFloodFill.h" // for signedFloodFillWithValues
56 
57 #include <tbb/blocked_range.h>
58 #include <tbb/enumerable_thread_specific.h>
59 #include <tbb/parallel_for.h>
60 #include <tbb/parallel_reduce.h>
61 #include <tbb/partitioner.h>
62 #include <tbb/task_group.h>
63 #include <tbb/task_scheduler_init.h>
64 
65 #include <boost/mpl/at.hpp>
66 #include <boost/mpl/int.hpp>
67 #include <boost/mpl/size.hpp>
68 
69 #include <algorithm> // for std::sort()
70 #include <cmath> // for std::isfinite(), std::isnan()
71 #include <deque>
72 #include <limits>
73 #include <memory>
74 #include <sstream>
75 #include <type_traits>
76 #include <vector>
77 
78 namespace openvdb {
80 namespace OPENVDB_VERSION_NAME {
81 namespace tools {
82 
83 
85 
86 
89 
95 
99 
103 
107 };
108 
109 
140 template <typename GridType, typename MeshDataAdapter>
141 inline typename GridType::Ptr
143  const MeshDataAdapter& mesh,
144  const math::Transform& transform,
145  float exteriorBandWidth = 3.0f,
146  float interiorBandWidth = 3.0f,
147  int flags = 0,
148  typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid = nullptr);
149 
150 
166 template <typename GridType, typename MeshDataAdapter, typename Interrupter>
167 inline typename GridType::Ptr
169  Interrupter& interrupter,
170  const MeshDataAdapter& mesh,
171  const math::Transform& transform,
172  float exteriorBandWidth = 3.0f,
173  float interiorBandWidth = 3.0f,
174  int flags = 0,
175  typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid = nullptr);
176 
177 
179 
180 
191 template<typename PointType, typename PolygonType>
193 
194  QuadAndTriangleDataAdapter(const std::vector<PointType>& points,
195  const std::vector<PolygonType>& polygons)
196  : mPointArray(points.empty() ? nullptr : &points[0])
197  , mPointArraySize(points.size())
198  , mPolygonArray(polygons.empty() ? nullptr : &polygons[0])
199  , mPolygonArraySize(polygons.size())
200  {
201  }
202 
203  QuadAndTriangleDataAdapter(const PointType * pointArray, size_t pointArraySize,
204  const PolygonType* polygonArray, size_t polygonArraySize)
205  : mPointArray(pointArray)
206  , mPointArraySize(pointArraySize)
207  , mPolygonArray(polygonArray)
208  , mPolygonArraySize(polygonArraySize)
209  {
210  }
211 
212  size_t polygonCount() const { return mPolygonArraySize; }
213  size_t pointCount() const { return mPointArraySize; }
214 
216  size_t vertexCount(size_t n) const {
217  return (PolygonType::size == 3 || mPolygonArray[n][3] == util::INVALID_IDX) ? 3 : 4;
218  }
219 
222  void getIndexSpacePoint(size_t n, size_t v, Vec3d& pos) const {
223  const PointType& p = mPointArray[mPolygonArray[n][int(v)]];
224  pos[0] = double(p[0]);
225  pos[1] = double(p[1]);
226  pos[2] = double(p[2]);
227  }
228 
229 private:
230  PointType const * const mPointArray;
231  size_t const mPointArraySize;
232  PolygonType const * const mPolygonArray;
233  size_t const mPolygonArraySize;
234 }; // struct QuadAndTriangleDataAdapter
235 
236 
238 
239 
240 // Convenience functions for the mesh to volume converter that wrap stl containers.
241 //
242 // Note the meshToVolume() method declared above is more flexible and better suited
243 // for arbitrary data structures.
244 
245 
261 template<typename GridType>
262 inline typename GridType::Ptr
264  const openvdb::math::Transform& xform,
265  const std::vector<Vec3s>& points,
266  const std::vector<Vec3I>& triangles,
267  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
268 
270 template<typename GridType, typename Interrupter>
271 inline typename GridType::Ptr
273  Interrupter& interrupter,
274  const openvdb::math::Transform& xform,
275  const std::vector<Vec3s>& points,
276  const std::vector<Vec3I>& triangles,
277  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
278 
279 
295 template<typename GridType>
296 inline typename GridType::Ptr
298  const openvdb::math::Transform& xform,
299  const std::vector<Vec3s>& points,
300  const std::vector<Vec4I>& quads,
301  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
302 
304 template<typename GridType, typename Interrupter>
305 inline typename GridType::Ptr
307  Interrupter& interrupter,
308  const openvdb::math::Transform& xform,
309  const std::vector<Vec3s>& points,
310  const std::vector<Vec4I>& quads,
311  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
312 
313 
330 template<typename GridType>
331 inline typename GridType::Ptr
333  const openvdb::math::Transform& xform,
334  const std::vector<Vec3s>& points,
335  const std::vector<Vec3I>& triangles,
336  const std::vector<Vec4I>& quads,
337  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
338 
340 template<typename GridType, typename Interrupter>
341 inline typename GridType::Ptr
343  Interrupter& interrupter,
344  const openvdb::math::Transform& xform,
345  const std::vector<Vec3s>& points,
346  const std::vector<Vec3I>& triangles,
347  const std::vector<Vec4I>& quads,
348  float halfWidth = float(LEVEL_SET_HALF_WIDTH));
349 
350 
369 template<typename GridType>
370 inline typename GridType::Ptr
372  const openvdb::math::Transform& xform,
373  const std::vector<Vec3s>& points,
374  const std::vector<Vec3I>& triangles,
375  const std::vector<Vec4I>& quads,
376  float exBandWidth,
377  float inBandWidth);
378 
380 template<typename GridType, typename Interrupter>
381 inline typename GridType::Ptr
383  Interrupter& interrupter,
384  const openvdb::math::Transform& xform,
385  const std::vector<Vec3s>& points,
386  const std::vector<Vec3I>& triangles,
387  const std::vector<Vec4I>& quads,
388  float exBandWidth,
389  float inBandWidth);
390 
391 
406 template<typename GridType>
407 inline typename GridType::Ptr
409  const openvdb::math::Transform& xform,
410  const std::vector<Vec3s>& points,
411  const std::vector<Vec3I>& triangles,
412  const std::vector<Vec4I>& quads,
413  float bandWidth);
414 
416 template<typename GridType, typename Interrupter>
417 inline typename GridType::Ptr
419  Interrupter& interrupter,
420  const openvdb::math::Transform& xform,
421  const std::vector<Vec3s>& points,
422  const std::vector<Vec3I>& triangles,
423  const std::vector<Vec4I>& quads,
424  float bandWidth);
425 
426 
428 
429 
436 template<typename GridType, typename VecType>
437 inline typename GridType::Ptr
439  const openvdb::math::Transform& xform,
440  typename VecType::ValueType halfWidth = LEVEL_SET_HALF_WIDTH);
441 
442 
444 
445 
452 template <typename FloatTreeT>
453 inline void
454 traceExteriorBoundaries(FloatTreeT& tree);
455 
456 
458 
459 
462 {
463 public:
464 
466 
468  struct EdgeData {
469  EdgeData(float dist = 1.0)
470  : mXDist(dist), mYDist(dist), mZDist(dist)
471  , mXPrim(util::INVALID_IDX)
472  , mYPrim(util::INVALID_IDX)
473  , mZPrim(util::INVALID_IDX)
474  {
475  }
476 
478  bool operator< (const EdgeData&) const { return false; }
481  bool operator> (const EdgeData&) const { return false; }
482  template<class T> EdgeData operator+(const T&) const { return *this; }
483  template<class T> EdgeData operator-(const T&) const { return *this; }
484  EdgeData operator-() const { return *this; }
486 
487  bool operator==(const EdgeData& rhs) const
488  {
489  return mXPrim == rhs.mXPrim && mYPrim == rhs.mYPrim && mZPrim == rhs.mZPrim;
490  }
491 
492  float mXDist, mYDist, mZDist;
493  Index32 mXPrim, mYPrim, mZPrim;
494  };
495 
498 
499 
501 
502 
504 
505 
513  void convert(const std::vector<Vec3s>& pointList, const std::vector<Vec4I>& polygonList);
514 
515 
518  void getEdgeData(Accessor& acc, const Coord& ijk,
519  std::vector<Vec3d>& points, std::vector<Index32>& primitives);
520 
523  Accessor getAccessor() { return Accessor(mTree); }
524 
525 private:
526  void operator=(const MeshToVoxelEdgeData&) {}
527  TreeType mTree;
528  class GenEdgeData;
529 };
530 
531 
534 
535 
536 // Internal utility objects and implementation details
537 
538 namespace mesh_to_volume_internal {
539 
540 template<typename PointType>
542 
543  TransformPoints(const PointType* pointsIn, PointType* pointsOut,
544  const math::Transform& xform)
545  : mPointsIn(pointsIn), mPointsOut(pointsOut), mXform(&xform)
546  {
547  }
548 
549  void operator()(const tbb::blocked_range<size_t>& range) const {
550 
551  Vec3d pos;
552 
553  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
554 
555  const PointType& wsP = mPointsIn[n];
556  pos[0] = double(wsP[0]);
557  pos[1] = double(wsP[1]);
558  pos[2] = double(wsP[2]);
559 
560  pos = mXform->worldToIndex(pos);
561 
562  PointType& isP = mPointsOut[n];
563  isP[0] = typename PointType::value_type(pos[0]);
564  isP[1] = typename PointType::value_type(pos[1]);
565  isP[2] = typename PointType::value_type(pos[2]);
566  }
567  }
568 
569  PointType const * const mPointsIn;
570  PointType * const mPointsOut;
571  math::Transform const * const mXform;
572 }; // TransformPoints
573 
574 
575 template<typename ValueType>
576 struct Tolerance
577 {
578  static ValueType epsilon() { return ValueType(1e-7); }
579  static ValueType minNarrowBandWidth() { return ValueType(1.0 + 1e-6); }
580 };
581 
582 
584 
585 
586 template<typename TreeType>
588 {
589 public:
590 
591  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
592 
593  using LeafNodeType = typename TreeType::LeafNodeType;
594  using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
595 
596  CombineLeafNodes(TreeType& lhsDistTree, Int32TreeType& lhsIdxTree,
597  LeafNodeType ** rhsDistNodes, Int32LeafNodeType ** rhsIdxNodes)
598  : mDistTree(&lhsDistTree)
599  , mIdxTree(&lhsIdxTree)
600  , mRhsDistNodes(rhsDistNodes)
601  , mRhsIdxNodes(rhsIdxNodes)
602  {
603  }
604 
605  void operator()(const tbb::blocked_range<size_t>& range) const {
606 
607  tree::ValueAccessor<TreeType> distAcc(*mDistTree);
608  tree::ValueAccessor<Int32TreeType> idxAcc(*mIdxTree);
609 
610  using DistValueType = typename LeafNodeType::ValueType;
611  using IndexValueType = typename Int32LeafNodeType::ValueType;
612 
613  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
614 
615  const Coord& origin = mRhsDistNodes[n]->origin();
616 
617  LeafNodeType* lhsDistNode = distAcc.probeLeaf(origin);
618  Int32LeafNodeType* lhsIdxNode = idxAcc.probeLeaf(origin);
619 
620  DistValueType* lhsDistData = lhsDistNode->buffer().data();
621  IndexValueType* lhsIdxData = lhsIdxNode->buffer().data();
622 
623  const DistValueType* rhsDistData = mRhsDistNodes[n]->buffer().data();
624  const IndexValueType* rhsIdxData = mRhsIdxNodes[n]->buffer().data();
625 
626 
627  for (Index32 offset = 0; offset < LeafNodeType::SIZE; ++offset) {
628 
629  if (rhsIdxData[offset] != Int32(util::INVALID_IDX)) {
630 
631  const DistValueType& lhsValue = lhsDistData[offset];
632  const DistValueType& rhsValue = rhsDistData[offset];
633 
634  if (rhsValue < lhsValue) {
635  lhsDistNode->setValueOn(offset, rhsValue);
636  lhsIdxNode->setValueOn(offset, rhsIdxData[offset]);
637  } else if (math::isExactlyEqual(rhsValue, lhsValue)) {
638  lhsIdxNode->setValueOn(offset,
639  std::min(lhsIdxData[offset], rhsIdxData[offset]));
640  }
641  }
642  }
643 
644  delete mRhsDistNodes[n];
645  delete mRhsIdxNodes[n];
646  }
647  }
648 
649 private:
650 
651  TreeType * const mDistTree;
652  Int32TreeType * const mIdxTree;
653 
654  LeafNodeType ** const mRhsDistNodes;
655  Int32LeafNodeType ** const mRhsIdxNodes;
656 }; // class CombineLeafNodes
657 
658 
660 
661 
662 template<typename TreeType>
664 {
665  using LeafNodeType = typename TreeType::LeafNodeType;
666 
667  StashOriginAndStoreOffset(std::vector<LeafNodeType*>& nodes, Coord* coordinates)
668  : mNodes(nodes.empty() ? nullptr : &nodes[0]), mCoordinates(coordinates)
669  {
670  }
671 
672  void operator()(const tbb::blocked_range<size_t>& range) const {
673  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
674  Coord& origin = const_cast<Coord&>(mNodes[n]->origin());
675  mCoordinates[n] = origin;
676  origin[0] = static_cast<int>(n);
677  }
678  }
679 
682 };
683 
684 
685 template<typename TreeType>
687 {
688  using LeafNodeType = typename TreeType::LeafNodeType;
689 
690  RestoreOrigin(std::vector<LeafNodeType*>& nodes, const Coord* coordinates)
691  : mNodes(nodes.empty() ? nullptr : &nodes[0]), mCoordinates(coordinates)
692  {
693  }
694 
695  void operator()(const tbb::blocked_range<size_t>& range) const {
696  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
697  Coord& origin = const_cast<Coord&>(mNodes[n]->origin());
698  origin[0] = mCoordinates[n][0];
699  }
700  }
701 
703  Coord const * const mCoordinates;
704 };
705 
706 
707 template<typename TreeType>
709 {
710 public:
711  using LeafNodeType = typename TreeType::LeafNodeType;
712 
713  ComputeNodeConnectivity(const TreeType& tree, const Coord* coordinates,
714  size_t* offsets, size_t numNodes, const CoordBBox& bbox)
715  : mTree(&tree)
716  , mCoordinates(coordinates)
717  , mOffsets(offsets)
718  , mNumNodes(numNodes)
719  , mBBox(bbox)
720  {
721  }
722 
724 
725  // Disallow assignment
726  ComputeNodeConnectivity& operator=(const ComputeNodeConnectivity&) = delete;
727 
728  void operator()(const tbb::blocked_range<size_t>& range) const {
729 
730  size_t* offsetsNextX = mOffsets;
731  size_t* offsetsPrevX = mOffsets + mNumNodes;
732  size_t* offsetsNextY = mOffsets + mNumNodes * 2;
733  size_t* offsetsPrevY = mOffsets + mNumNodes * 3;
734  size_t* offsetsNextZ = mOffsets + mNumNodes * 4;
735  size_t* offsetsPrevZ = mOffsets + mNumNodes * 5;
736 
738  Coord ijk;
739 
740  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
741  const Coord& origin = mCoordinates[n];
742  offsetsNextX[n] = findNeighbourNode(acc, origin, Coord(LeafNodeType::DIM, 0, 0));
743  offsetsPrevX[n] = findNeighbourNode(acc, origin, Coord(-LeafNodeType::DIM, 0, 0));
744  offsetsNextY[n] = findNeighbourNode(acc, origin, Coord(0, LeafNodeType::DIM, 0));
745  offsetsPrevY[n] = findNeighbourNode(acc, origin, Coord(0, -LeafNodeType::DIM, 0));
746  offsetsNextZ[n] = findNeighbourNode(acc, origin, Coord(0, 0, LeafNodeType::DIM));
747  offsetsPrevZ[n] = findNeighbourNode(acc, origin, Coord(0, 0, -LeafNodeType::DIM));
748  }
749  }
750 
752  const Coord& start, const Coord& step) const
753  {
754  Coord ijk = start + step;
755  CoordBBox bbox(mBBox);
756 
757  while (bbox.isInside(ijk)) {
758  const LeafNodeType* node = acc.probeConstLeaf(ijk);
759  if (node) return static_cast<size_t>(node->origin()[0]);
760  ijk += step;
761  }
762 
764  }
765 
766 
767 private:
768  TreeType const * const mTree;
769  Coord const * const mCoordinates;
770  size_t * const mOffsets;
771 
772  const size_t mNumNodes;
773  const CoordBBox mBBox;
774 }; // class ComputeNodeConnectivity
775 
776 
777 template<typename TreeType>
779 {
780  enum { INVALID_OFFSET = std::numeric_limits<size_t>::max() };
781 
782  using LeafNodeType = typename TreeType::LeafNodeType;
783 
785  {
786  mLeafNodes.reserve(tree.leafCount());
787  tree.getNodes(mLeafNodes);
788 
789  if (mLeafNodes.empty()) return;
790 
791  CoordBBox bbox;
792  tree.evalLeafBoundingBox(bbox);
793 
794  const tbb::blocked_range<size_t> range(0, mLeafNodes.size());
795 
796  // stash the leafnode origin coordinate and temporarily store the
797  // linear offset in the origin.x variable.
798  std::unique_ptr<Coord[]> coordinates{new Coord[mLeafNodes.size()]};
799  tbb::parallel_for(range,
800  StashOriginAndStoreOffset<TreeType>(mLeafNodes, coordinates.get()));
801 
802  // build the leafnode offset table
803  mOffsets.reset(new size_t[mLeafNodes.size() * 6]);
804 
805 
806  tbb::parallel_for(range, ComputeNodeConnectivity<TreeType>(
807  tree, coordinates.get(), mOffsets.get(), mLeafNodes.size(), bbox));
808 
809  // restore the leafnode origin coordinate
810  tbb::parallel_for(range, RestoreOrigin<TreeType>(mLeafNodes, coordinates.get()));
811  }
812 
813  size_t size() const { return mLeafNodes.size(); }
814 
815  std::vector<LeafNodeType*>& nodes() { return mLeafNodes; }
816  const std::vector<LeafNodeType*>& nodes() const { return mLeafNodes; }
817 
818 
819  const size_t* offsetsNextX() const { return mOffsets.get(); }
820  const size_t* offsetsPrevX() const { return mOffsets.get() + mLeafNodes.size(); }
821 
822  const size_t* offsetsNextY() const { return mOffsets.get() + mLeafNodes.size() * 2; }
823  const size_t* offsetsPrevY() const { return mOffsets.get() + mLeafNodes.size() * 3; }
824 
825  const size_t* offsetsNextZ() const { return mOffsets.get() + mLeafNodes.size() * 4; }
826  const size_t* offsetsPrevZ() const { return mOffsets.get() + mLeafNodes.size() * 5; }
827 
828 private:
829  std::vector<LeafNodeType*> mLeafNodes;
830  std::unique_ptr<size_t[]> mOffsets;
831 }; // struct LeafNodeConnectivityTable
832 
833 
834 template<typename TreeType>
836 {
837 public:
838 
839  enum Axis { X_AXIS = 0, Y_AXIS = 1, Z_AXIS = 2 };
840 
841  using ValueType = typename TreeType::ValueType;
842  using LeafNodeType = typename TreeType::LeafNodeType;
844 
845  SweepExteriorSign(Axis axis, const std::vector<size_t>& startNodeIndices,
846  ConnectivityTable& connectivity)
847  : mStartNodeIndices(startNodeIndices.empty() ? nullptr : &startNodeIndices[0])
848  , mConnectivity(&connectivity)
849  , mAxis(axis)
850  {
851  }
852 
853  void operator()(const tbb::blocked_range<size_t>& range) const {
854 
855  std::vector<LeafNodeType*>& nodes = mConnectivity->nodes();
856 
857  // Z Axis
858  size_t idxA = 0, idxB = 1;
859  Index 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 = LeafNodeType::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 = LeafNodeType::DIM * LeafNodeType::DIM;
878 
879  nextOffsets = mConnectivity->offsetsNextX();
880  prevOffsets = mConnectivity->offsetsPrevX();
881  }
882 
883  Coord ijk(0, 0, 0);
884 
885  int& a = ijk[idxA];
886  int& 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  Index pos(0);
894 
895  for (a = 0; a < int(LeafNodeType::DIM); ++a) {
896  for (b = 0; b < int(LeafNodeType::DIM); ++b) {
897 
898  pos = 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 * (LeafNodeType::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, Index pos, Index 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  ValueType& dist = data[pos];
938 
939  if (dist < ValueType(0.0)) {
940  isOutside = true;
941  } else {
942  // Boundary voxel check. (Voxel that intersects the surface)
943  if (!(dist > ValueType(0.75))) isOutside = false;
944 
945  if (isOutside) dist = ValueType(-dist);
946  }
947 
948  pos += step;
949  }
950 
951  return isOutside;
952  }
953 
954 
955 private:
956  size_t const * const mStartNodeIndices;
957  ConnectivityTable * const mConnectivity;
958 
959  const Axis mAxis;
960 }; // class SweepExteriorSign
961 
962 
963 template<typename LeafNodeType>
964 inline void
965 seedFill(LeafNodeType& node)
966 {
967  using ValueType = typename LeafNodeType::ValueType;
968  using Queue = std::deque<Index>;
969 
970 
971  ValueType* data = node.buffer().data();
972 
973  // find seed points
974  Queue seedPoints;
975  for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
976  if (data[pos] < 0.0) seedPoints.push_back(pos);
977  }
978 
979  if (seedPoints.empty()) return;
980 
981  // clear sign information
982  for (Queue::iterator it = seedPoints.begin(); it != seedPoints.end(); ++it) {
983  ValueType& dist = data[*it];
984  dist = -dist;
985  }
986 
987  // flood fill
988 
989  Coord ijk(0, 0, 0);
990  Index pos(0), nextPos(0);
991 
992  while (!seedPoints.empty()) {
993 
994  pos = seedPoints.back();
995  seedPoints.pop_back();
996 
997  ValueType& dist = data[pos];
998 
999  if (!(dist < ValueType(0.0))) {
1000 
1001  dist = -dist; // flip sign
1002 
1003  ijk = LeafNodeType::offsetToLocalCoord(pos);
1004 
1005  if (ijk[0] != 0) { // i - 1, j, k
1006  nextPos = pos - LeafNodeType::DIM * LeafNodeType::DIM;
1007  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1008  }
1009 
1010  if (ijk[0] != (LeafNodeType::DIM - 1)) { // i + 1, j, k
1011  nextPos = pos + LeafNodeType::DIM * LeafNodeType::DIM;
1012  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1013  }
1014 
1015  if (ijk[1] != 0) { // i, j - 1, k
1016  nextPos = pos - LeafNodeType::DIM;
1017  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1018  }
1019 
1020  if (ijk[1] != (LeafNodeType::DIM - 1)) { // i, j + 1, k
1021  nextPos = pos + LeafNodeType::DIM;
1022  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1023  }
1024 
1025  if (ijk[2] != 0) { // i, j, k - 1
1026  nextPos = pos - 1;
1027  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1028  }
1029 
1030  if (ijk[2] != (LeafNodeType::DIM - 1)) { // i, j, k + 1
1031  nextPos = pos + 1;
1032  if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
1033  }
1034  }
1035  }
1036 } // seedFill()
1037 
1038 
1039 template<typename LeafNodeType>
1040 inline bool
1041 scanFill(LeafNodeType& node)
1042 {
1043  bool updatedNode = false;
1044 
1045  using ValueType = typename LeafNodeType::ValueType;
1046  ValueType* data = node.buffer().data();
1047 
1048  Coord ijk(0, 0, 0);
1049 
1050  bool updatedSign = true;
1051  while (updatedSign) {
1052 
1053  updatedSign = false;
1054 
1055  for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
1056 
1057  ValueType& dist = data[pos];
1058 
1059  if (!(dist < ValueType(0.0)) && dist > ValueType(0.75)) {
1060 
1061  ijk = LeafNodeType::offsetToLocalCoord(pos);
1062 
1063  // i, j, k - 1
1064  if (ijk[2] != 0 && data[pos - 1] < ValueType(0.0)) {
1065  updatedSign = true;
1066  dist = ValueType(-dist);
1067 
1068  // i, j, k + 1
1069  } else if (ijk[2] != (LeafNodeType::DIM - 1) && data[pos + 1] < ValueType(0.0)) {
1070  updatedSign = true;
1071  dist = ValueType(-dist);
1072 
1073  // i, j - 1, k
1074  } else if (ijk[1] != 0 && data[pos - LeafNodeType::DIM] < ValueType(0.0)) {
1075  updatedSign = true;
1076  dist = ValueType(-dist);
1077 
1078  // i, j + 1, k
1079  } else if (ijk[1] != (LeafNodeType::DIM - 1)
1080  && data[pos + LeafNodeType::DIM] < ValueType(0.0))
1081  {
1082  updatedSign = true;
1083  dist = ValueType(-dist);
1084 
1085  // i - 1, j, k
1086  } else if (ijk[0] != 0
1087  && data[pos - LeafNodeType::DIM * LeafNodeType::DIM] < ValueType(0.0))
1088  {
1089  updatedSign = true;
1090  dist = ValueType(-dist);
1091 
1092  // i + 1, j, k
1093  } else if (ijk[0] != (LeafNodeType::DIM - 1)
1094  && data[pos + LeafNodeType::DIM * LeafNodeType::DIM] < ValueType(0.0))
1095  {
1096  updatedSign = true;
1097  dist = ValueType(-dist);
1098  }
1099  }
1100  } // end value loop
1101 
1102  updatedNode |= updatedSign;
1103  } // end update loop
1104 
1105  return updatedNode;
1106 } // scanFill()
1107 
1108 
1109 template<typename TreeType>
1111 {
1112 public:
1113  using ValueType = typename TreeType::ValueType;
1114  using LeafNodeType = typename TreeType::LeafNodeType;
1115 
1116  SeedFillExteriorSign(std::vector<LeafNodeType*>& nodes, bool* changedNodeMask)
1117  : mNodes(nodes.empty() ? nullptr : &nodes[0])
1118  , mChangedNodeMask(changedNodeMask)
1119  {
1120  }
1121 
1122  void operator()(const tbb::blocked_range<size_t>& range) const {
1123  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1124  if (mChangedNodeMask[n]) {
1125  //seedFill(*mNodes[n]);
1126  mChangedNodeMask[n] = scanFill(*mNodes[n]);
1127  }
1128  }
1129  }
1130 
1132  bool * const mChangedNodeMask;
1133 };
1134 
1135 
1136 template<typename ValueType>
1138 {
1139  FillArray(ValueType* array, const ValueType v) : mArray(array), mValue(v) { }
1140 
1141  void operator()(const tbb::blocked_range<size_t>& range) const {
1142  const ValueType v = mValue;
1143  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1144  mArray[n] = v;
1145  }
1146  }
1147 
1148  ValueType * const mArray;
1149  const ValueType mValue;
1150 };
1151 
1152 
1153 template<typename ValueType>
1154 inline void
1155 fillArray(ValueType* array, const ValueType val, const size_t length)
1156 {
1157  const auto grainSize = std::max<size_t>(
1158  length / tbb::task_scheduler_init::default_num_threads(), 1024);
1159  const tbb::blocked_range<size_t> range(0, length, grainSize);
1160  tbb::parallel_for(range, FillArray<ValueType>(array, val), tbb::simple_partitioner());
1161 }
1162 
1163 
1164 template<typename TreeType>
1166 {
1167 public:
1168  using ValueType = typename TreeType::ValueType;
1169  using LeafNodeType = typename TreeType::LeafNodeType;
1170 
1171  SyncVoxelMask(std::vector<LeafNodeType*>& nodes,
1172  const bool* changedNodeMask, bool* changedVoxelMask)
1173  : mNodes(nodes.empty() ? nullptr : &nodes[0])
1174  , mChangedNodeMask(changedNodeMask)
1175  , mChangedVoxelMask(changedVoxelMask)
1176  {
1177  }
1178 
1179  void operator()(const tbb::blocked_range<size_t>& range) const {
1180  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1181 
1182  if (mChangedNodeMask[n]) {
1183  bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
1184 
1185  ValueType* data = mNodes[n]->buffer().data();
1186 
1187  for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
1188  if (mask[pos]) {
1189  data[pos] = ValueType(-data[pos]);
1190  mask[pos] = false;
1191  }
1192  }
1193  }
1194  }
1195  }
1196 
1198  bool const * const mChangedNodeMask;
1199  bool * const mChangedVoxelMask;
1200 };
1201 
1202 
1203 template<typename TreeType>
1205 {
1206 public:
1207  using ValueType = typename TreeType::ValueType;
1208  using LeafNodeType = typename TreeType::LeafNodeType;
1210 
1212  bool* changedNodeMask, bool* nodeMask, bool* changedVoxelMask)
1213  : mConnectivity(&connectivity)
1214  , mChangedNodeMask(changedNodeMask)
1215  , mNodeMask(nodeMask)
1216  , mChangedVoxelMask(changedVoxelMask)
1217  {
1218  }
1219 
1220  void operator()(const tbb::blocked_range<size_t>& range) const {
1221 
1222  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1223 
1224  if (!mChangedNodeMask[n]) {
1225 
1226  bool changedValue = false;
1227 
1228  changedValue |= processZ(n, /*firstFace=*/true);
1229  changedValue |= processZ(n, /*firstFace=*/false);
1230 
1231  changedValue |= processY(n, /*firstFace=*/true);
1232  changedValue |= processY(n, /*firstFace=*/false);
1233 
1234  changedValue |= processX(n, /*firstFace=*/true);
1235  changedValue |= processX(n, /*firstFace=*/false);
1236 
1237  mNodeMask[n] = changedValue;
1238  }
1239  }
1240  }
1241 
1242 
1243  bool processZ(const size_t n, bool firstFace) const
1244  {
1245  const size_t offset =
1246  firstFace ? mConnectivity->offsetsPrevZ()[n] : mConnectivity->offsetsNextZ()[n];
1247  if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1248 
1249  bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
1250 
1251  const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1252  const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1253 
1254  const Index lastOffset = LeafNodeType::DIM - 1;
1255  const Index lhsOffset =
1256  firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1257 
1258  Index tmpPos(0), pos(0);
1259  bool changedValue = false;
1260 
1261  for (Index x = 0; x < LeafNodeType::DIM; ++x) {
1262  tmpPos = x << (2 * LeafNodeType::LOG2DIM);
1263  for (Index y = 0; y < LeafNodeType::DIM; ++y) {
1264  pos = tmpPos + (y << LeafNodeType::LOG2DIM);
1265 
1266  if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1267  if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1268  changedValue = true;
1269  mask[pos + lhsOffset] = true;
1270  }
1271  }
1272  }
1273  }
1274 
1275  return changedValue;
1276  }
1277 
1278  return false;
1279  }
1280 
1281  bool processY(const size_t n, bool firstFace) const
1282  {
1283  const size_t offset =
1284  firstFace ? mConnectivity->offsetsPrevY()[n] : mConnectivity->offsetsNextY()[n];
1285  if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1286 
1287  bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
1288 
1289  const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1290  const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1291 
1292  const Index lastOffset = LeafNodeType::DIM * (LeafNodeType::DIM - 1);
1293  const Index lhsOffset =
1294  firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1295 
1296  Index tmpPos(0), pos(0);
1297  bool changedValue = false;
1298 
1299  for (Index x = 0; x < LeafNodeType::DIM; ++x) {
1300  tmpPos = x << (2 * LeafNodeType::LOG2DIM);
1301  for (Index z = 0; z < LeafNodeType::DIM; ++z) {
1302  pos = tmpPos + z;
1303 
1304  if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1305  if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1306  changedValue = true;
1307  mask[pos + lhsOffset] = true;
1308  }
1309  }
1310  }
1311  }
1312 
1313  return changedValue;
1314  }
1315 
1316  return false;
1317  }
1318 
1319  bool processX(const size_t n, bool firstFace) const
1320  {
1321  const size_t offset =
1322  firstFace ? mConnectivity->offsetsPrevX()[n] : mConnectivity->offsetsNextX()[n];
1323  if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
1324 
1325  bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
1326 
1327  const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
1328  const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
1329 
1330  const Index lastOffset = LeafNodeType::DIM * LeafNodeType::DIM * (LeafNodeType::DIM-1);
1331  const Index lhsOffset =
1332  firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
1333 
1334  Index tmpPos(0), pos(0);
1335  bool changedValue = false;
1336 
1337  for (Index y = 0; y < LeafNodeType::DIM; ++y) {
1338  tmpPos = y << LeafNodeType::LOG2DIM;
1339  for (Index z = 0; z < LeafNodeType::DIM; ++z) {
1340  pos = tmpPos + z;
1341 
1342  if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
1343  if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
1344  changedValue = true;
1345  mask[pos + lhsOffset] = true;
1346  }
1347  }
1348  }
1349  }
1350 
1351  return changedValue;
1352  }
1353 
1354  return false;
1355  }
1356 
1358  bool * const mChangedNodeMask;
1359  bool * const mNodeMask;
1360  bool * const mChangedVoxelMask;
1361 };
1362 
1363 
1365 
1366 template<typename TreeType, typename MeshDataAdapter>
1368 {
1369  using ValueType = typename TreeType::ValueType;
1370  using LeafNodeType = typename TreeType::LeafNodeType;
1371  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1372  using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
1373 
1374  using PointArray = std::unique_ptr<Vec3d[]>;
1375  using MaskArray = std::unique_ptr<bool[]>;
1376  using LocalData = std::pair<PointArray, MaskArray>;
1377  using LocalDataTable = tbb::enumerable_thread_specific<LocalData>;
1378 
1380  std::vector<LeafNodeType*>& distNodes,
1381  const TreeType& distTree,
1382  const Int32TreeType& indexTree,
1383  const MeshDataAdapter& mesh)
1384  : mDistNodes(distNodes.empty() ? nullptr : &distNodes[0])
1385  , mDistTree(&distTree)
1386  , mIndexTree(&indexTree)
1387  , mMesh(&mesh)
1388  , mLocalDataTable(new LocalDataTable())
1389  {
1390  }
1391 
1392 
1393  void operator()(const tbb::blocked_range<size_t>& range) const {
1394 
1395  tree::ValueAccessor<const TreeType> distAcc(*mDistTree);
1396  tree::ValueAccessor<const Int32TreeType> idxAcc(*mIndexTree);
1397 
1398  ValueType nval;
1399  CoordBBox bbox;
1400  Index xPos(0), yPos(0);
1401  Coord ijk, nijk, nodeMin, nodeMax;
1402  Vec3d cp, xyz, nxyz, dir1, dir2;
1403 
1404  LocalData& localData = mLocalDataTable->local();
1405 
1406  PointArray& points = localData.first;
1407  if (!points) points.reset(new Vec3d[LeafNodeType::SIZE * 2]);
1408 
1409  MaskArray& mask = localData.second;
1410  if (!mask) mask.reset(new bool[LeafNodeType::SIZE]);
1411 
1412 
1413  typename LeafNodeType::ValueOnCIter it;
1414 
1415  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1416 
1417  LeafNodeType& node = *mDistNodes[n];
1418  ValueType* data = node.buffer().data();
1419 
1420  const Int32LeafNodeType* idxNode = idxAcc.probeConstLeaf(node.origin());
1421  const Int32* idxData = idxNode->buffer().data();
1422 
1423  nodeMin = node.origin();
1424  nodeMax = nodeMin.offsetBy(LeafNodeType::DIM - 1);
1425 
1426  // reset computed voxel mask.
1427  memset(mask.get(), 0, sizeof(bool) * LeafNodeType::SIZE);
1428 
1429  for (it = node.cbeginValueOn(); it; ++it) {
1430  Index pos = it.pos();
1431 
1432  ValueType& dist = data[pos];
1433  if (dist < 0.0 || dist > 0.75) continue;
1434 
1435  ijk = node.offsetToGlobalCoord(pos);
1436 
1437  xyz[0] = double(ijk[0]);
1438  xyz[1] = double(ijk[1]);
1439  xyz[2] = double(ijk[2]);
1440 
1441 
1442  bbox.min() = Coord::maxComponent(ijk.offsetBy(-1), nodeMin);
1443  bbox.max() = Coord::minComponent(ijk.offsetBy(1), nodeMax);
1444 
1445  bool flipSign = false;
1446 
1447  for (nijk[0] = bbox.min()[0]; nijk[0] <= bbox.max()[0] && !flipSign; ++nijk[0]) {
1448  xPos = (nijk[0] & (LeafNodeType::DIM - 1u)) << (2 * LeafNodeType::LOG2DIM);
1449  for (nijk[1]=bbox.min()[1]; nijk[1] <= bbox.max()[1] && !flipSign; ++nijk[1]) {
1450  yPos = xPos + ((nijk[1] & (LeafNodeType::DIM-1u)) << LeafNodeType::LOG2DIM);
1451  for (nijk[2] = bbox.min()[2]; nijk[2] <= bbox.max()[2]; ++nijk[2]) {
1452  pos = yPos + (nijk[2] & (LeafNodeType::DIM - 1u));
1453 
1454  const Int32& polyIdx = idxData[pos];
1455 
1456  if (polyIdx == Int32(util::INVALID_IDX) || !(data[pos] < -0.75))
1457  continue;
1458 
1459  const Index pointIndex = pos * 2;
1460 
1461  if (!mask[pos]) {
1462 
1463  mask[pos] = true;
1464 
1465  nxyz[0] = double(nijk[0]);
1466  nxyz[1] = double(nijk[1]);
1467  nxyz[2] = double(nijk[2]);
1468 
1469  Vec3d& point = points[pointIndex];
1470 
1471  point = closestPoint(nxyz, polyIdx);
1472 
1473  Vec3d& direction = points[pointIndex + 1];
1474  direction = nxyz - point;
1475  direction.normalize();
1476  }
1477 
1478  dir1 = xyz - points[pointIndex];
1479  dir1.normalize();
1480 
1481  if (points[pointIndex + 1].dot(dir1) > 0.0) {
1482  flipSign = true;
1483  break;
1484  }
1485  }
1486  }
1487  }
1488 
1489  if (flipSign) {
1490  dist = -dist;
1491  } else {
1492  for (Int32 m = 0; m < 26; ++m) {
1493  nijk = ijk + util::COORD_OFFSETS[m];
1494 
1495  if (!bbox.isInside(nijk) && distAcc.probeValue(nijk, nval) && nval<-0.75) {
1496  nxyz[0] = double(nijk[0]);
1497  nxyz[1] = double(nijk[1]);
1498  nxyz[2] = double(nijk[2]);
1499 
1500  cp = closestPoint(nxyz, idxAcc.getValue(nijk));
1501 
1502  dir1 = xyz - cp;
1503  dir1.normalize();
1504 
1505  dir2 = nxyz - cp;
1506  dir2.normalize();
1507 
1508  if (dir2.dot(dir1) > 0.0) {
1509  dist = -dist;
1510  break;
1511  }
1512  }
1513  }
1514  }
1515 
1516  } // active voxel loop
1517  } // leaf node loop
1518  }
1519 
1520 private:
1521 
1522  Vec3d closestPoint(const Vec3d& center, Int32 polyIdx) const
1523  {
1524  Vec3d a, b, c, cp, uvw;
1525 
1526  const size_t polygon = size_t(polyIdx);
1527  mMesh->getIndexSpacePoint(polygon, 0, a);
1528  mMesh->getIndexSpacePoint(polygon, 1, b);
1529  mMesh->getIndexSpacePoint(polygon, 2, c);
1530 
1531  cp = closestPointOnTriangleToPoint(a, c, b, center, uvw);
1532 
1533  if (4 == mMesh->vertexCount(polygon)) {
1534 
1535  mMesh->getIndexSpacePoint(polygon, 3, b);
1536 
1537  c = closestPointOnTriangleToPoint(a, b, c, center, uvw);
1538 
1539  if ((center - c).lengthSqr() < (center - cp).lengthSqr()) {
1540  cp = c;
1541  }
1542  }
1543 
1544  return cp;
1545  }
1546 
1547 
1548  LeafNodeType ** const mDistNodes;
1549  TreeType const * const mDistTree;
1550  Int32TreeType const * const mIndexTree;
1551  MeshDataAdapter const * const mMesh;
1552 
1553  SharedPtr<LocalDataTable> mLocalDataTable;
1554 }; // ComputeIntersectingVoxelSign
1555 
1556 
1558 
1559 
1560 template<typename LeafNodeType>
1561 inline void
1562 maskNodeInternalNeighbours(const Index pos, bool (&mask)[26])
1563 {
1564  using NodeT = LeafNodeType;
1565 
1566  const Coord ijk = NodeT::offsetToLocalCoord(pos);
1567 
1568  // Face adjacent neighbours
1569  // i+1, j, k
1570  mask[0] = ijk[0] != (NodeT::DIM - 1);
1571  // i-1, j, k
1572  mask[1] = ijk[0] != 0;
1573  // i, j+1, k
1574  mask[2] = ijk[1] != (NodeT::DIM - 1);
1575  // i, j-1, k
1576  mask[3] = ijk[1] != 0;
1577  // i, j, k+1
1578  mask[4] = ijk[2] != (NodeT::DIM - 1);
1579  // i, j, k-1
1580  mask[5] = ijk[2] != 0;
1581 
1582  // Edge adjacent neighbour
1583  // i+1, j, k-1
1584  mask[6] = mask[0] && mask[5];
1585  // i-1, j, k-1
1586  mask[7] = mask[1] && mask[5];
1587  // i+1, j, k+1
1588  mask[8] = mask[0] && mask[4];
1589  // i-1, j, k+1
1590  mask[9] = mask[1] && mask[4];
1591  // i+1, j+1, k
1592  mask[10] = mask[0] && mask[2];
1593  // i-1, j+1, k
1594  mask[11] = mask[1] && mask[2];
1595  // i+1, j-1, k
1596  mask[12] = mask[0] && mask[3];
1597  // i-1, j-1, k
1598  mask[13] = mask[1] && mask[3];
1599  // i, j-1, k+1
1600  mask[14] = mask[3] && mask[4];
1601  // i, j-1, k-1
1602  mask[15] = mask[3] && mask[5];
1603  // i, j+1, k+1
1604  mask[16] = mask[2] && mask[4];
1605  // i, j+1, k-1
1606  mask[17] = mask[2] && mask[5];
1607 
1608  // Corner adjacent neighbours
1609  // i-1, j-1, k-1
1610  mask[18] = mask[1] && mask[3] && mask[5];
1611  // i-1, j-1, k+1
1612  mask[19] = mask[1] && mask[3] && mask[4];
1613  // i+1, j-1, k+1
1614  mask[20] = mask[0] && mask[3] && mask[4];
1615  // i+1, j-1, k-1
1616  mask[21] = mask[0] && mask[3] && mask[5];
1617  // i-1, j+1, k-1
1618  mask[22] = mask[1] && mask[2] && mask[5];
1619  // i-1, j+1, k+1
1620  mask[23] = mask[1] && mask[2] && mask[4];
1621  // i+1, j+1, k+1
1622  mask[24] = mask[0] && mask[2] && mask[4];
1623  // i+1, j+1, k-1
1624  mask[25] = mask[0] && mask[2] && mask[5];
1625 }
1626 
1627 
1628 template<typename Compare, typename LeafNodeType>
1629 inline bool
1630 checkNeighbours(const Index pos, const typename LeafNodeType::ValueType * data, bool (&mask)[26])
1631 {
1632  using NodeT = LeafNodeType;
1633 
1634  // i, j, k - 1
1635  if (mask[5] && Compare::check(data[pos - 1])) return true;
1636  // i, j, k + 1
1637  if (mask[4] && Compare::check(data[pos + 1])) return true;
1638  // i, j - 1, k
1639  if (mask[3] && Compare::check(data[pos - NodeT::DIM])) return true;
1640  // i, j + 1, k
1641  if (mask[2] && Compare::check(data[pos + NodeT::DIM])) return true;
1642  // i - 1, j, k
1643  if (mask[1] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM])) return true;
1644  // i + 1, j, k
1645  if (mask[0] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM])) return true;
1646  // i+1, j, k-1
1647  if (mask[6] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM])) return true;
1648  // i-1, j, k-1
1649  if (mask[7] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - 1])) return true;
1650  // i+1, j, k+1
1651  if (mask[8] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + 1])) return true;
1652  // i-1, j, k+1
1653  if (mask[9] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + 1])) return true;
1654  // i+1, j+1, k
1655  if (mask[10] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM])) return true;
1656  // i-1, j+1, k
1657  if (mask[11] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM])) return true;
1658  // i+1, j-1, k
1659  if (mask[12] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM])) return true;
1660  // i-1, j-1, k
1661  if (mask[13] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM])) return true;
1662  // i, j-1, k+1
1663  if (mask[14] && Compare::check(data[pos - NodeT::DIM + 1])) return true;
1664  // i, j-1, k-1
1665  if (mask[15] && Compare::check(data[pos - NodeT::DIM - 1])) return true;
1666  // i, j+1, k+1
1667  if (mask[16] && Compare::check(data[pos + NodeT::DIM + 1])) return true;
1668  // i, j+1, k-1
1669  if (mask[17] && Compare::check(data[pos + NodeT::DIM - 1])) return true;
1670  // i-1, j-1, k-1
1671  if (mask[18] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM - 1])) return true;
1672  // i-1, j-1, k+1
1673  if (mask[19] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM + 1])) return true;
1674  // i+1, j-1, k+1
1675  if (mask[20] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM + 1])) return true;
1676  // i+1, j-1, k-1
1677  if (mask[21] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM - 1])) return true;
1678  // i-1, j+1, k-1
1679  if (mask[22] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM - 1])) return true;
1680  // i-1, j+1, k+1
1681  if (mask[23] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM + 1])) return true;
1682  // i+1, j+1, k+1
1683  if (mask[24] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM + 1])) return true;
1684  // i+1, j+1, k-1
1685  if (mask[25] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM - 1])) return true;
1686 
1687  return false;
1688 }
1689 
1690 
1691 template<typename Compare, typename AccessorType>
1692 inline bool
1693 checkNeighbours(const Coord& ijk, AccessorType& acc, bool (&mask)[26])
1694 {
1695  for (Int32 m = 0; m < 26; ++m) {
1696  if (!mask[m] && Compare::check(acc.getValue(ijk + util::COORD_OFFSETS[m]))) {
1697  return true;
1698  }
1699  }
1700 
1701  return false;
1702 }
1703 
1704 
1705 template<typename TreeType>
1707 {
1708  using ValueType = typename TreeType::ValueType;
1709  using LeafNodeType = typename TreeType::LeafNodeType;
1710 
1711  struct IsNegative { static bool check(const ValueType v) { return v < ValueType(0.0); } };
1712 
1713  ValidateIntersectingVoxels(TreeType& tree, std::vector<LeafNodeType*>& nodes)
1714  : mTree(&tree)
1715  , mNodes(nodes.empty() ? nullptr : &nodes[0])
1716  {
1717  }
1718 
1719  void operator()(const tbb::blocked_range<size_t>& range) const
1720  {
1722  bool neighbourMask[26];
1723 
1724  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1725 
1726  LeafNodeType& node = *mNodes[n];
1727  ValueType* data = node.buffer().data();
1728 
1729  typename LeafNodeType::ValueOnCIter it;
1730  for (it = node.cbeginValueOn(); it; ++it) {
1731 
1732  const Index pos = it.pos();
1733 
1734  ValueType& dist = data[pos];
1735  if (dist < 0.0 || dist > 0.75) continue;
1736 
1737  // Mask node internal neighbours
1738  maskNodeInternalNeighbours<LeafNodeType>(pos, neighbourMask);
1739 
1740  const bool hasNegativeNeighbour =
1741  checkNeighbours<IsNegative, LeafNodeType>(pos, data, neighbourMask) ||
1742  checkNeighbours<IsNegative>(node.offsetToGlobalCoord(pos), acc, neighbourMask);
1743 
1744  if (!hasNegativeNeighbour) {
1745  // push over boundary voxel distance
1746  dist = ValueType(0.75) + Tolerance<ValueType>::epsilon();
1747  }
1748  }
1749  }
1750  }
1751 
1752  TreeType * const mTree;
1754 }; // ValidateIntersectingVoxels
1755 
1756 
1757 template<typename TreeType>
1759 {
1760  using ValueType = typename TreeType::ValueType;
1761  using LeafNodeType = typename TreeType::LeafNodeType;
1762  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1763 
1764  struct Comp { static bool check(const ValueType v) { return !(v > ValueType(0.75)); } };
1765 
1766  RemoveSelfIntersectingSurface(std::vector<LeafNodeType*>& nodes,
1767  TreeType& distTree, Int32TreeType& indexTree)
1768  : mNodes(nodes.empty() ? nullptr : &nodes[0])
1769  , mDistTree(&distTree)
1770  , mIndexTree(&indexTree)
1771  {
1772  }
1773 
1774  void operator()(const tbb::blocked_range<size_t>& range) const
1775  {
1776  tree::ValueAccessor<const TreeType> distAcc(*mDistTree);
1777  tree::ValueAccessor<Int32TreeType> idxAcc(*mIndexTree);
1778  bool neighbourMask[26];
1779 
1780  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1781 
1782  LeafNodeType& distNode = *mNodes[n];
1783  ValueType* data = distNode.buffer().data();
1784 
1785  typename Int32TreeType::LeafNodeType* idxNode =
1786  idxAcc.probeLeaf(distNode.origin());
1787 
1788  typename LeafNodeType::ValueOnCIter it;
1789  for (it = distNode.cbeginValueOn(); it; ++it) {
1790 
1791  const Index pos = it.pos();
1792 
1793  if (!(data[pos] > 0.75)) continue;
1794 
1795  // Mask node internal neighbours
1796  maskNodeInternalNeighbours<LeafNodeType>(pos, neighbourMask);
1797 
1798  const bool hasBoundaryNeighbour =
1799  checkNeighbours<Comp, LeafNodeType>(pos, data, neighbourMask) ||
1800  checkNeighbours<Comp>(distNode.offsetToGlobalCoord(pos),distAcc,neighbourMask);
1801 
1802  if (!hasBoundaryNeighbour) {
1803  distNode.setValueOff(pos);
1804  idxNode->setValueOff(pos);
1805  }
1806  }
1807  }
1808  }
1809 
1811  TreeType * const mDistTree;
1813 }; // RemoveSelfIntersectingSurface
1814 
1815 
1817 
1818 
1819 template<typename NodeType>
1821 {
1822  ReleaseChildNodes(NodeType ** nodes) : mNodes(nodes) {}
1823 
1824  void operator()(const tbb::blocked_range<size_t>& range) const {
1825 
1826  using NodeMaskType = typename NodeType::NodeMaskType;
1827 
1828  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
1829  const_cast<NodeMaskType&>(mNodes[n]->getChildMask()).setOff();
1830  }
1831  }
1832 
1833  NodeType ** const mNodes;
1834 };
1835 
1836 
1837 template<typename TreeType>
1838 inline void
1839 releaseLeafNodes(TreeType& tree)
1840 {
1841  using RootNodeType = typename TreeType::RootNodeType;
1842  using NodeChainType = typename RootNodeType::NodeChainType;
1843  using InternalNodeType = typename boost::mpl::at<NodeChainType, boost::mpl::int_<1> >::type;
1844 
1845  std::vector<InternalNodeType*> nodes;
1846  tree.getNodes(nodes);
1847 
1848  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
1849  ReleaseChildNodes<InternalNodeType>(nodes.empty() ? nullptr : &nodes[0]));
1850 }
1851 
1852 
1853 template<typename TreeType>
1855 {
1856  using LeafNodeType = typename TreeType::LeafNodeType;
1857 
1858  StealUniqueLeafNodes(TreeType& lhsTree, TreeType& rhsTree,
1859  std::vector<LeafNodeType*>& overlappingNodes)
1860  : mLhsTree(&lhsTree)
1861  , mRhsTree(&rhsTree)
1862  , mNodes(&overlappingNodes)
1863  {
1864  }
1865 
1866  void operator()() const {
1867 
1868  std::vector<LeafNodeType*> rhsLeafNodes;
1869 
1870  rhsLeafNodes.reserve(mRhsTree->leafCount());
1871  //mRhsTree->getNodes(rhsLeafNodes);
1872  //releaseLeafNodes(*mRhsTree);
1873  mRhsTree->stealNodes(rhsLeafNodes);
1874 
1875  tree::ValueAccessor<TreeType> acc(*mLhsTree);
1876 
1877  for (size_t n = 0, N = rhsLeafNodes.size(); n < N; ++n) {
1878  if (!acc.probeLeaf(rhsLeafNodes[n]->origin())) {
1879  acc.addLeaf(rhsLeafNodes[n]);
1880  } else {
1881  mNodes->push_back(rhsLeafNodes[n]);
1882  }
1883  }
1884  }
1885 
1886 private:
1887  TreeType * const mLhsTree;
1888  TreeType * const mRhsTree;
1889  std::vector<LeafNodeType*> * const mNodes;
1890 };
1891 
1892 
1893 template<typename DistTreeType, typename IndexTreeType>
1894 inline void
1895 combineData(DistTreeType& lhsDist, IndexTreeType& lhsIdx,
1896  DistTreeType& rhsDist, IndexTreeType& rhsIdx)
1897 {
1898  using DistLeafNodeType = typename DistTreeType::LeafNodeType;
1899  using IndexLeafNodeType = typename IndexTreeType::LeafNodeType;
1900 
1901  std::vector<DistLeafNodeType*> overlappingDistNodes;
1902  std::vector<IndexLeafNodeType*> overlappingIdxNodes;
1903 
1904  // Steal unique leafnodes
1905  tbb::task_group tasks;
1906  tasks.run(StealUniqueLeafNodes<DistTreeType>(lhsDist, rhsDist, overlappingDistNodes));
1907  tasks.run(StealUniqueLeafNodes<IndexTreeType>(lhsIdx, rhsIdx, overlappingIdxNodes));
1908  tasks.wait();
1909 
1910  // Combine overlapping leaf nodes
1911  if (!overlappingDistNodes.empty() && !overlappingIdxNodes.empty()) {
1912  tbb::parallel_for(tbb::blocked_range<size_t>(0, overlappingDistNodes.size()),
1913  CombineLeafNodes<DistTreeType>(lhsDist, lhsIdx,
1914  &overlappingDistNodes[0], &overlappingIdxNodes[0]));
1915  }
1916 }
1917 
1924 template<typename TreeType>
1926 
1927  using Ptr = std::unique_ptr<VoxelizationData>;
1928  using ValueType = typename TreeType::ValueType;
1929 
1930  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
1931  using UCharTreeType = typename TreeType::template ValueConverter<unsigned char>::Type;
1932 
1936 
1937 
1939  : distTree(std::numeric_limits<ValueType>::max())
1940  , distAcc(distTree)
1941  , indexTree(Int32(util::INVALID_IDX))
1942  , indexAcc(indexTree)
1943  , primIdTree(MaxPrimId)
1944  , primIdAcc(primIdTree)
1945  , mPrimCount(0)
1946  {
1947  }
1948 
1949  TreeType distTree;
1951 
1954 
1957 
1958  unsigned char getNewPrimId() {
1959 
1960  if (mPrimCount == MaxPrimId || primIdTree.leafCount() > 1000) {
1961  mPrimCount = 0;
1962  primIdTree.clear();
1963  }
1964 
1965  return mPrimCount++;
1966  }
1967 
1968 private:
1969 
1970  enum { MaxPrimId = 100 };
1971 
1972  unsigned char mPrimCount;
1973 };
1974 
1975 
1976 template<typename TreeType, typename MeshDataAdapter, typename Interrupter = util::NullInterrupter>
1978 {
1979 public:
1980 
1982  using DataTable = tbb::enumerable_thread_specific<typename VoxelizationDataType::Ptr>;
1983 
1985  const MeshDataAdapter& mesh,
1986  Interrupter* interrupter = nullptr)
1987  : mDataTable(&dataTable)
1988  , mMesh(&mesh)
1989  , mInterrupter(interrupter)
1990  {
1991  }
1992 
1993  void operator()(const tbb::blocked_range<size_t>& range) const {
1994 
1995  typename VoxelizationDataType::Ptr& dataPtr = mDataTable->local();
1996  if (!dataPtr) dataPtr.reset(new VoxelizationDataType());
1997 
1998  Triangle prim;
1999 
2000  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2001 
2002  if (this->wasInterrupted()) {
2003  tbb::task::self().cancel_group_execution();
2004  break;
2005  }
2006 
2007  const size_t numVerts = mMesh->vertexCount(n);
2008 
2009  // rasterize triangles and quads.
2010  if (numVerts == 3 || numVerts == 4) {
2011 
2012  prim.index = Int32(n);
2013 
2014  mMesh->getIndexSpacePoint(n, 0, prim.a);
2015  mMesh->getIndexSpacePoint(n, 1, prim.b);
2016  mMesh->getIndexSpacePoint(n, 2, prim.c);
2017 
2018  evalTriangle(prim, *dataPtr);
2019 
2020  if (numVerts == 4) {
2021  mMesh->getIndexSpacePoint(n, 3, prim.b);
2022  evalTriangle(prim, *dataPtr);
2023  }
2024  }
2025  }
2026  }
2027 
2028 private:
2029 
2030  bool wasInterrupted() const { return mInterrupter && mInterrupter->wasInterrupted(); }
2031 
2032  struct Triangle { Vec3d a, b, c; Int32 index; };
2033 
2034  struct SubTask
2035  {
2036  enum { POLYGON_LIMIT = 1000 };
2037 
2038  SubTask(const Triangle& prim, DataTable& dataTable,
2039  int subdivisionCount, size_t polygonCount,
2040  Interrupter* interrupter = nullptr)
2041  : mLocalDataTable(&dataTable)
2042  , mPrim(prim)
2043  , mSubdivisionCount(subdivisionCount)
2044  , mPolygonCount(polygonCount)
2045  , mInterrupter(interrupter)
2046  {
2047  }
2048 
2049  void operator()() const
2050  {
2051  if (mSubdivisionCount <= 0 || mPolygonCount >= POLYGON_LIMIT) {
2052 
2053  typename VoxelizationDataType::Ptr& dataPtr = mLocalDataTable->local();
2054  if (!dataPtr) dataPtr.reset(new VoxelizationDataType());
2055 
2056  voxelizeTriangle(mPrim, *dataPtr);
2057 
2058  } else if (!(mInterrupter && mInterrupter->wasInterrupted())) {
2059  spawnTasks(mPrim, *mLocalDataTable, mSubdivisionCount, mPolygonCount, mInterrupter);
2060  }
2061  }
2062 
2063  DataTable * const mLocalDataTable;
2064  Triangle const mPrim;
2065  int const mSubdivisionCount;
2066  size_t const mPolygonCount;
2067  Interrupter * const mInterrupter;
2068  }; // struct SubTask
2069 
2070  inline static int evalSubdivisionCount(const Triangle& prim)
2071  {
2072  const double ax = prim.a[0], bx = prim.b[0], cx = prim.c[0];
2073  const double dx = std::max(ax, std::max(bx, cx)) - std::min(ax, std::min(bx, cx));
2074 
2075  const double ay = prim.a[1], by = prim.b[1], cy = prim.c[1];
2076  const double dy = std::max(ay, std::max(by, cy)) - std::min(ay, std::min(by, cy));
2077 
2078  const double az = prim.a[2], bz = prim.b[2], cz = prim.c[2];
2079  const double dz = std::max(az, std::max(bz, cz)) - std::min(az, std::min(bz, cz));
2080 
2081  return int(std::max(dx, std::max(dy, dz)) / double(TreeType::LeafNodeType::DIM * 2));
2082  }
2083 
2084  void evalTriangle(const Triangle& prim, VoxelizationDataType& data) const
2085  {
2086  const size_t polygonCount = mMesh->polygonCount();
2087  const int subdivisionCount =
2088  polygonCount < SubTask::POLYGON_LIMIT ? evalSubdivisionCount(prim) : 0;
2089 
2090  if (subdivisionCount <= 0) {
2091  voxelizeTriangle(prim, data);
2092  } else {
2093  spawnTasks(prim, *mDataTable, subdivisionCount, polygonCount, mInterrupter);
2094  }
2095  }
2096 
2097  static void spawnTasks(
2098  const Triangle& mainPrim,
2099  DataTable& dataTable,
2100  int subdivisionCount,
2101  size_t polygonCount,
2102  Interrupter* const interrupter)
2103  {
2104  subdivisionCount -= 1;
2105  polygonCount *= 4;
2106 
2107  tbb::task_group tasks;
2108 
2109  const Vec3d ac = (mainPrim.a + mainPrim.c) * 0.5;
2110  const Vec3d bc = (mainPrim.b + mainPrim.c) * 0.5;
2111  const Vec3d ab = (mainPrim.a + mainPrim.b) * 0.5;
2112 
2113  Triangle prim;
2114  prim.index = mainPrim.index;
2115 
2116  prim.a = mainPrim.a;
2117  prim.b = ab;
2118  prim.c = ac;
2119  tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount, interrupter));
2120 
2121  prim.a = ab;
2122  prim.b = bc;
2123  prim.c = ac;
2124  tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount, interrupter));
2125 
2126  prim.a = ab;
2127  prim.b = mainPrim.b;
2128  prim.c = bc;
2129  tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount, interrupter));
2130 
2131  prim.a = ac;
2132  prim.b = bc;
2133  prim.c = mainPrim.c;
2134  tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount, interrupter));
2135 
2136  tasks.wait();
2137  }
2138 
2139  static void voxelizeTriangle(const Triangle& prim, VoxelizationDataType& data)
2140  {
2141  std::deque<Coord> coordList;
2142  Coord ijk, nijk;
2143 
2144  ijk = Coord::floor(prim.a);
2145  coordList.push_back(ijk);
2146 
2147  computeDistance(ijk, prim, data);
2148 
2149  unsigned char primId = data.getNewPrimId();
2150  data.primIdAcc.setValueOnly(ijk, primId);
2151 
2152  while (!coordList.empty()) {
2153  ijk = coordList.back();
2154  coordList.pop_back();
2155 
2156  for (Int32 i = 0; i < 26; ++i) {
2157  nijk = ijk + util::COORD_OFFSETS[i];
2158  if (primId != data.primIdAcc.getValue(nijk)) {
2159  data.primIdAcc.setValueOnly(nijk, primId);
2160  if(computeDistance(nijk, prim, data)) coordList.push_back(nijk);
2161  }
2162  }
2163  }
2164  }
2165 
2166  static bool computeDistance(const Coord& ijk, const Triangle& prim, VoxelizationDataType& data)
2167  {
2168  Vec3d uvw, voxelCenter(ijk[0], ijk[1], ijk[2]);
2169 
2170  using ValueType = typename TreeType::ValueType;
2171 
2172  const ValueType dist = ValueType((voxelCenter -
2173  closestPointOnTriangleToPoint(prim.a, prim.c, prim.b, voxelCenter, uvw)).lengthSqr());
2174 
2175  const ValueType oldDist = data.distAcc.getValue(ijk);
2176 
2177  if (dist < oldDist) {
2178  data.distAcc.setValue(ijk, dist);
2179  data.indexAcc.setValue(ijk, prim.index);
2180  } else if (math::isExactlyEqual(dist, oldDist)) {
2181  // makes reduction deterministic when different polygons
2182  // produce the same distance value.
2183  data.indexAcc.setValueOnly(ijk, std::min(prim.index, data.indexAcc.getValue(ijk)));
2184  }
2185 
2186  return !(dist > 0.75); // true if the primitive intersects the voxel.
2187  }
2188 
2189  DataTable * const mDataTable;
2190  MeshDataAdapter const * const mMesh;
2191  Interrupter * const mInterrupter;
2192 }; // VoxelizePolygons
2193 
2194 
2196 
2197 
2198 template<typename TreeType>
2200 {
2202  using LeafNodeType = typename TreeType::LeafNodeType;
2203 
2204  using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2205  using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2206 
2207  DiffLeafNodeMask(const TreeType& rhsTree,
2208  std::vector<BoolLeafNodeType*>& lhsNodes)
2209  : mRhsTree(&rhsTree), mLhsNodes(lhsNodes.empty() ? nullptr : &lhsNodes[0])
2210  {
2211  }
2212 
2213  void operator()(const tbb::blocked_range<size_t>& range) const {
2214 
2215  tree::ValueAccessor<const TreeType> acc(*mRhsTree);
2216 
2217  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2218 
2219  BoolLeafNodeType* lhsNode = mLhsNodes[n];
2220  const LeafNodeType* rhsNode = acc.probeConstLeaf(lhsNode->origin());
2221 
2222  if (rhsNode) lhsNode->topologyDifference(*rhsNode, false);
2223  }
2224  }
2225 
2226 private:
2227  TreeType const * const mRhsTree;
2228  BoolLeafNodeType ** const mLhsNodes;
2229 };
2230 
2231 
2232 template<typename LeafNodeTypeA, typename LeafNodeTypeB>
2234 {
2235  UnionValueMasks(std::vector<LeafNodeTypeA*>& nodesA, std::vector<LeafNodeTypeB*>& nodesB)
2236  : mNodesA(nodesA.empty() ? nullptr : &nodesA[0])
2237  , mNodesB(nodesB.empty() ? nullptr : &nodesB[0])
2238  {
2239  }
2240 
2241  void operator()(const tbb::blocked_range<size_t>& range) const {
2242  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2243  mNodesA[n]->topologyUnion(*mNodesB[n]);
2244  }
2245  }
2246 
2247 private:
2248  LeafNodeTypeA ** const mNodesA;
2249  LeafNodeTypeB ** const mNodesB;
2250 };
2251 
2252 
2253 template<typename TreeType>
2255 {
2256  using LeafNodeType = typename TreeType::LeafNodeType;
2257 
2258  using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2259  using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2260 
2261  ConstructVoxelMask(BoolTreeType& maskTree, const TreeType& tree,
2262  std::vector<LeafNodeType*>& nodes)
2263  : mTree(&tree)
2264  , mNodes(nodes.empty() ? nullptr : &nodes[0])
2265  , mLocalMaskTree(false)
2266  , mMaskTree(&maskTree)
2267  {
2268  }
2269 
2271  : mTree(rhs.mTree)
2272  , mNodes(rhs.mNodes)
2273  , mLocalMaskTree(false)
2274  , mMaskTree(&mLocalMaskTree)
2275  {
2276  }
2277 
2278  void operator()(const tbb::blocked_range<size_t>& range)
2279  {
2280  using Iterator = typename LeafNodeType::ValueOnCIter;
2281 
2283  tree::ValueAccessor<BoolTreeType> maskAcc(*mMaskTree);
2284 
2285  Coord ijk, nijk, localCorod;
2286  Index pos, npos;
2287 
2288  for (size_t n = range.begin(); n != range.end(); ++n) {
2289 
2290  LeafNodeType& node = *mNodes[n];
2291 
2292  CoordBBox bbox = node.getNodeBoundingBox();
2293  bbox.expand(-1);
2294 
2295  BoolLeafNodeType& maskNode = *maskAcc.touchLeaf(node.origin());
2296 
2297  for (Iterator it = node.cbeginValueOn(); it; ++it) {
2298  ijk = it.getCoord();
2299  pos = it.pos();
2300 
2301  localCorod = LeafNodeType::offsetToLocalCoord(pos);
2302 
2303  if (localCorod[2] < int(LeafNodeType::DIM - 1)) {
2304  npos = pos + 1;
2305  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2306  } else {
2307  nijk = ijk.offsetBy(0, 0, 1);
2308  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2309  }
2310 
2311  if (localCorod[2] > 0) {
2312  npos = pos - 1;
2313  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2314  } else {
2315  nijk = ijk.offsetBy(0, 0, -1);
2316  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2317  }
2318 
2319  if (localCorod[1] < int(LeafNodeType::DIM - 1)) {
2320  npos = pos + LeafNodeType::DIM;
2321  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2322  } else {
2323  nijk = ijk.offsetBy(0, 1, 0);
2324  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2325  }
2326 
2327  if (localCorod[1] > 0) {
2328  npos = pos - LeafNodeType::DIM;
2329  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2330  } else {
2331  nijk = ijk.offsetBy(0, -1, 0);
2332  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2333  }
2334 
2335  if (localCorod[0] < int(LeafNodeType::DIM - 1)) {
2336  npos = pos + LeafNodeType::DIM * LeafNodeType::DIM;
2337  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2338  } else {
2339  nijk = ijk.offsetBy(1, 0, 0);
2340  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2341  }
2342 
2343  if (localCorod[0] > 0) {
2344  npos = pos - LeafNodeType::DIM * LeafNodeType::DIM;
2345  if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
2346  } else {
2347  nijk = ijk.offsetBy(-1, 0, 0);
2348  if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
2349  }
2350  }
2351  }
2352  }
2353 
2354  void join(ConstructVoxelMask& rhs) { mMaskTree->merge(*rhs.mMaskTree); }
2355 
2356 private:
2357  TreeType const * const mTree;
2358  LeafNodeType ** const mNodes;
2359 
2360  BoolTreeType mLocalMaskTree;
2361  BoolTreeType * const mMaskTree;
2362 };
2363 
2364 
2366 template<typename TreeType, typename MeshDataAdapter>
2368 {
2369  using ValueType = typename TreeType::ValueType;
2370  using LeafNodeType = typename TreeType::LeafNodeType;
2371  using NodeMaskType = typename LeafNodeType::NodeMaskType;
2372  using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
2373  using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
2374  using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
2375  using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
2376 
2377  struct Fragment
2378  {
2379  Int32 idx, x, y, z;
2381 
2382  Fragment() : idx(0), x(0), y(0), z(0), dist(0.0) {}
2383 
2384  Fragment(Int32 idx_, Int32 x_, Int32 y_, Int32 z_, ValueType dist_)
2385  : idx(idx_), x(x_), y(y_), z(z_), dist(dist_)
2386  {
2387  }
2388 
2389  bool operator<(const Fragment& rhs) const { return idx < rhs.idx; }
2390  }; // struct Fragment
2391 
2393 
2395  std::vector<BoolLeafNodeType*>& maskNodes,
2396  BoolTreeType& maskTree,
2397  TreeType& distTree,
2398  Int32TreeType& indexTree,
2399  const MeshDataAdapter& mesh,
2400  ValueType exteriorBandWidth,
2401  ValueType interiorBandWidth,
2402  ValueType voxelSize)
2403  : mMaskNodes(maskNodes.empty() ? nullptr : &maskNodes[0])
2404  , mMaskTree(&maskTree)
2405  , mDistTree(&distTree)
2406  , mIndexTree(&indexTree)
2407  , mMesh(&mesh)
2408  , mNewMaskTree(false)
2409  , mDistNodes()
2410  , mUpdatedDistNodes()
2411  , mIndexNodes()
2412  , mUpdatedIndexNodes()
2413  , mExteriorBandWidth(exteriorBandWidth)
2414  , mInteriorBandWidth(interiorBandWidth)
2415  , mVoxelSize(voxelSize)
2416  {
2417  }
2418 
2419  ExpandNarrowband(const ExpandNarrowband& rhs, tbb::split)
2420  : mMaskNodes(rhs.mMaskNodes)
2421  , mMaskTree(rhs.mMaskTree)
2422  , mDistTree(rhs.mDistTree)
2423  , mIndexTree(rhs.mIndexTree)
2424  , mMesh(rhs.mMesh)
2425  , mNewMaskTree(false)
2426  , mDistNodes()
2427  , mUpdatedDistNodes()
2428  , mIndexNodes()
2429  , mUpdatedIndexNodes()
2430  , mExteriorBandWidth(rhs.mExteriorBandWidth)
2431  , mInteriorBandWidth(rhs.mInteriorBandWidth)
2432  , mVoxelSize(rhs.mVoxelSize)
2433  {
2434  }
2435 
2437  {
2438  mDistNodes.insert(mDistNodes.end(), rhs.mDistNodes.begin(), rhs.mDistNodes.end());
2439  mIndexNodes.insert(mIndexNodes.end(), rhs.mIndexNodes.begin(), rhs.mIndexNodes.end());
2440 
2441  mUpdatedDistNodes.insert(mUpdatedDistNodes.end(),
2442  rhs.mUpdatedDistNodes.begin(), rhs.mUpdatedDistNodes.end());
2443 
2444  mUpdatedIndexNodes.insert(mUpdatedIndexNodes.end(),
2445  rhs.mUpdatedIndexNodes.begin(), rhs.mUpdatedIndexNodes.end());
2446 
2447  mNewMaskTree.merge(rhs.mNewMaskTree);
2448  }
2449 
2450  void operator()(const tbb::blocked_range<size_t>& range)
2451  {
2452  tree::ValueAccessor<BoolTreeType> newMaskAcc(mNewMaskTree);
2453  tree::ValueAccessor<TreeType> distAcc(*mDistTree);
2454  tree::ValueAccessor<Int32TreeType> indexAcc(*mIndexTree);
2455 
2456  std::vector<Fragment> fragments;
2457  fragments.reserve(256);
2458 
2459  std::unique_ptr<LeafNodeType> newDistNodePt;
2460  std::unique_ptr<Int32LeafNodeType> newIndexNodePt;
2461 
2462  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2463 
2464  BoolLeafNodeType& maskNode = *mMaskNodes[n];
2465  if (maskNode.isEmpty()) continue;
2466 
2467  // Setup local caches
2468 
2469  const Coord& origin = maskNode.origin();
2470 
2471  LeafNodeType * distNodePt = distAcc.probeLeaf(origin);
2472  Int32LeafNodeType * indexNodePt = indexAcc.probeLeaf(origin);
2473 
2474  assert(!distNodePt == !indexNodePt);
2475 
2476  bool usingNewNodes = false;
2477 
2478  if (!distNodePt && !indexNodePt) {
2479 
2480  const ValueType backgroundDist = distAcc.getValue(origin);
2481 
2482  if (!newDistNodePt.get() && !newIndexNodePt.get()) {
2483  newDistNodePt.reset(new LeafNodeType(origin, backgroundDist));
2484  newIndexNodePt.reset(new Int32LeafNodeType(origin, indexAcc.getValue(origin)));
2485  } else {
2486 
2487  if ((backgroundDist < ValueType(0.0)) !=
2488  (newDistNodePt->getValue(0) < ValueType(0.0))) {
2489  newDistNodePt->buffer().fill(backgroundDist);
2490  }
2491 
2492  newDistNodePt->setOrigin(origin);
2493  newIndexNodePt->setOrigin(origin);
2494  }
2495 
2496  distNodePt = newDistNodePt.get();
2497  indexNodePt = newIndexNodePt.get();
2498 
2499  usingNewNodes = true;
2500  }
2501 
2502 
2503  // Gather neighbour information
2504 
2505  CoordBBox bbox(Coord::max(), Coord::min());
2506  for (typename BoolLeafNodeType::ValueOnIter it = maskNode.beginValueOn(); it; ++it) {
2507  bbox.expand(it.getCoord());
2508  }
2509 
2510  bbox.expand(1);
2511 
2512  gatherFragments(fragments, bbox, distAcc, indexAcc);
2513 
2514 
2515  // Compute first voxel layer
2516 
2517  bbox = maskNode.getNodeBoundingBox();
2518  NodeMaskType mask;
2519  bool updatedLeafNodes = false;
2520 
2521  for (typename BoolLeafNodeType::ValueOnIter it = maskNode.beginValueOn(); it; ++it) {
2522 
2523  const Coord ijk = it.getCoord();
2524 
2525  if (updateVoxel(ijk, 5, fragments, *distNodePt, *indexNodePt, &updatedLeafNodes)) {
2526 
2527  for (Int32 i = 0; i < 6; ++i) {
2528  const Coord nijk = ijk + util::COORD_OFFSETS[i];
2529  if (bbox.isInside(nijk)) {
2530  mask.setOn(BoolLeafNodeType::coordToOffset(nijk));
2531  } else {
2532  newMaskAcc.setValueOn(nijk);
2533  }
2534  }
2535 
2536  for (Int32 i = 6; i < 26; ++i) {
2537  const Coord nijk = ijk + util::COORD_OFFSETS[i];
2538  if (bbox.isInside(nijk)) {
2539  mask.setOn(BoolLeafNodeType::coordToOffset(nijk));
2540  }
2541  }
2542  }
2543  }
2544 
2545  if (updatedLeafNodes) {
2546 
2547  // Compute second voxel layer
2548  mask -= indexNodePt->getValueMask();
2549 
2550  for (typename NodeMaskType::OnIterator it = mask.beginOn(); it; ++it) {
2551 
2552  const Index pos = it.pos();
2553  const Coord ijk = maskNode.origin() + LeafNodeType::offsetToLocalCoord(pos);
2554 
2555  if (updateVoxel(ijk, 6, fragments, *distNodePt, *indexNodePt)) {
2556  for (Int32 i = 0; i < 6; ++i) {
2557  newMaskAcc.setValueOn(ijk + util::COORD_OFFSETS[i]);
2558  }
2559  }
2560  }
2561 
2562  // Export new distance values
2563  if (usingNewNodes) {
2564  newDistNodePt->topologyUnion(*newIndexNodePt);
2565  mDistNodes.push_back(newDistNodePt.release());
2566  mIndexNodes.push_back(newIndexNodePt.release());
2567  } else {
2568  mUpdatedDistNodes.push_back(distNodePt);
2569  mUpdatedIndexNodes.push_back(indexNodePt);
2570  }
2571  }
2572  } // end leafnode loop
2573  }
2574 
2576 
2577  BoolTreeType& newMaskTree() { return mNewMaskTree; }
2578 
2579  std::vector<LeafNodeType*>& newDistNodes() { return mDistNodes; }
2580  std::vector<LeafNodeType*>& updatedDistNodes() { return mUpdatedDistNodes; }
2581 
2582  std::vector<Int32LeafNodeType*>& newIndexNodes() { return mIndexNodes; }
2583  std::vector<Int32LeafNodeType*>& updatedIndexNodes() { return mUpdatedIndexNodes; }
2584 
2585 private:
2586 
2588  void
2589  gatherFragments(std::vector<Fragment>& fragments, const CoordBBox& bbox,
2591  {
2592  fragments.clear();
2593  const Coord nodeMin = bbox.min() & ~(LeafNodeType::DIM - 1);
2594  const Coord nodeMax = bbox.max() & ~(LeafNodeType::DIM - 1);
2595 
2596  CoordBBox region;
2597  Coord ijk;
2598 
2599  for (ijk[0] = nodeMin[0]; ijk[0] <= nodeMax[0]; ijk[0] += LeafNodeType::DIM) {
2600  for (ijk[1] = nodeMin[1]; ijk[1] <= nodeMax[1]; ijk[1] += LeafNodeType::DIM) {
2601  for (ijk[2] = nodeMin[2]; ijk[2] <= nodeMax[2]; ijk[2] += LeafNodeType::DIM) {
2602  if (LeafNodeType* distleaf = distAcc.probeLeaf(ijk)) {
2603  region.min() = Coord::maxComponent(bbox.min(), ijk);
2604  region.max() = Coord::minComponent(bbox.max(),
2605  ijk.offsetBy(LeafNodeType::DIM - 1));
2606  gatherFragments(fragments, region, *distleaf, *indexAcc.probeLeaf(ijk));
2607  }
2608  }
2609  }
2610  }
2611 
2612  std::sort(fragments.begin(), fragments.end());
2613  }
2614 
2615  void
2616  gatherFragments(std::vector<Fragment>& fragments, const CoordBBox& bbox,
2617  const LeafNodeType& distLeaf, const Int32LeafNodeType& idxLeaf) const
2618  {
2619  const typename LeafNodeType::NodeMaskType& mask = distLeaf.getValueMask();
2620  const ValueType* distData = distLeaf.buffer().data();
2621  const Int32* idxData = idxLeaf.buffer().data();
2622 
2623  for (int x = bbox.min()[0]; x <= bbox.max()[0]; ++x) {
2624  const Index xPos = (x & (LeafNodeType::DIM - 1u)) << (2 * LeafNodeType::LOG2DIM);
2625  for (int y = bbox.min()[1]; y <= bbox.max()[1]; ++y) {
2626  const Index yPos = xPos + ((y & (LeafNodeType::DIM - 1u)) << LeafNodeType::LOG2DIM);
2627  for (int z = bbox.min()[2]; z <= bbox.max()[2]; ++z) {
2628  const Index pos = yPos + (z & (LeafNodeType::DIM - 1u));
2629  if (mask.isOn(pos)) {
2630  fragments.push_back(Fragment(idxData[pos],x,y,z, std::abs(distData[pos])));
2631  }
2632  }
2633  }
2634  }
2635  }
2636 
2639  ValueType
2640  computeDistance(const Coord& ijk, const Int32 manhattanLimit,
2641  const std::vector<Fragment>& fragments, Int32& closestPrimIdx) const
2642  {
2643  Vec3d a, b, c, uvw, voxelCenter(ijk[0], ijk[1], ijk[2]);
2644  double primDist, tmpDist, dist = std::numeric_limits<double>::max();
2645  Int32 lastIdx = Int32(util::INVALID_IDX);
2646 
2647  for (size_t n = 0, N = fragments.size(); n < N; ++n) {
2648 
2649  const Fragment& fragment = fragments[n];
2650  if (lastIdx == fragment.idx) continue;
2651 
2652  const Int32 dx = std::abs(fragment.x - ijk[0]);
2653  const Int32 dy = std::abs(fragment.y - ijk[1]);
2654  const Int32 dz = std::abs(fragment.z - ijk[2]);
2655 
2656  const Int32 manhattan = dx + dy + dz;
2657  if (manhattan > manhattanLimit) continue;
2658 
2659  lastIdx = fragment.idx;
2660 
2661  const size_t polygon = size_t(lastIdx);
2662 
2663  mMesh->getIndexSpacePoint(polygon, 0, a);
2664  mMesh->getIndexSpacePoint(polygon, 1, b);
2665  mMesh->getIndexSpacePoint(polygon, 2, c);
2666 
2667  primDist = (voxelCenter -
2668  closestPointOnTriangleToPoint(a, c, b, voxelCenter, uvw)).lengthSqr();
2669 
2670  // Split quad into a second triangle
2671  if (4 == mMesh->vertexCount(polygon)) {
2672 
2673  mMesh->getIndexSpacePoint(polygon, 3, b);
2674 
2675  tmpDist = (voxelCenter - closestPointOnTriangleToPoint(
2676  a, b, c, voxelCenter, uvw)).lengthSqr();
2677 
2678  if (tmpDist < primDist) primDist = tmpDist;
2679  }
2680 
2681  if (primDist < dist) {
2682  dist = primDist;
2683  closestPrimIdx = lastIdx;
2684  }
2685  }
2686 
2687  return ValueType(std::sqrt(dist)) * mVoxelSize;
2688  }
2689 
2692  bool
2693  updateVoxel(const Coord& ijk, const Int32 manhattanLimit,
2694  const std::vector<Fragment>& fragments,
2695  LeafNodeType& distLeaf, Int32LeafNodeType& idxLeaf, bool* updatedLeafNodes = nullptr)
2696  {
2697  Int32 closestPrimIdx = 0;
2698  const ValueType distance = computeDistance(ijk, manhattanLimit, fragments, closestPrimIdx);
2699 
2700  const Index pos = LeafNodeType::coordToOffset(ijk);
2701  const bool inside = distLeaf.getValue(pos) < ValueType(0.0);
2702 
2703  bool activateNeighbourVoxels = false;
2704 
2705  if (!inside && distance < mExteriorBandWidth) {
2706  if (updatedLeafNodes) *updatedLeafNodes = true;
2707  activateNeighbourVoxels = (distance + mVoxelSize) < mExteriorBandWidth;
2708  distLeaf.setValueOnly(pos, distance);
2709  idxLeaf.setValueOn(pos, closestPrimIdx);
2710  } else if (inside && distance < mInteriorBandWidth) {
2711  if (updatedLeafNodes) *updatedLeafNodes = true;
2712  activateNeighbourVoxels = (distance + mVoxelSize) < mInteriorBandWidth;
2713  distLeaf.setValueOnly(pos, -distance);
2714  idxLeaf.setValueOn(pos, closestPrimIdx);
2715  }
2716 
2717  return activateNeighbourVoxels;
2718  }
2719 
2721 
2722  BoolLeafNodeType ** const mMaskNodes;
2723  BoolTreeType * const mMaskTree;
2724  TreeType * const mDistTree;
2725  Int32TreeType * const mIndexTree;
2726 
2727  MeshDataAdapter const * const mMesh;
2728 
2729  BoolTreeType mNewMaskTree;
2730 
2731  std::vector<LeafNodeType*> mDistNodes, mUpdatedDistNodes;
2732  std::vector<Int32LeafNodeType*> mIndexNodes, mUpdatedIndexNodes;
2733 
2734  const ValueType mExteriorBandWidth, mInteriorBandWidth, mVoxelSize;
2735 }; // struct ExpandNarrowband
2736 
2737 
2738 template<typename TreeType>
2739 struct AddNodes {
2740  using LeafNodeType = typename TreeType::LeafNodeType;
2741 
2742  AddNodes(TreeType& tree, std::vector<LeafNodeType*>& nodes)
2743  : mTree(&tree) , mNodes(&nodes)
2744  {
2745  }
2746 
2747  void operator()() const {
2748  tree::ValueAccessor<TreeType> acc(*mTree);
2749  std::vector<LeafNodeType*>& nodes = *mNodes;
2750  for (size_t n = 0, N = nodes.size(); n < N; ++n) {
2751  acc.addLeaf(nodes[n]);
2752  }
2753  }
2754 
2755  TreeType * const mTree;
2756  std::vector<LeafNodeType*> * const mNodes;
2757 }; // AddNodes
2758 
2759 
2760 template<typename TreeType, typename Int32TreeType, typename BoolTreeType, typename MeshDataAdapter>
2761 inline void
2763  TreeType& distTree,
2764  Int32TreeType& indexTree,
2765  BoolTreeType& maskTree,
2766  std::vector<typename BoolTreeType::LeafNodeType*>& maskNodes,
2767  const MeshDataAdapter& mesh,
2768  typename TreeType::ValueType exteriorBandWidth,
2769  typename TreeType::ValueType interiorBandWidth,
2770  typename TreeType::ValueType voxelSize)
2771 {
2772  ExpandNarrowband<TreeType, MeshDataAdapter> expandOp(maskNodes, maskTree,
2773  distTree, indexTree, mesh, exteriorBandWidth, interiorBandWidth, voxelSize);
2774 
2775  tbb::parallel_reduce(tbb::blocked_range<size_t>(0, maskNodes.size()), expandOp);
2776 
2777  tbb::parallel_for(tbb::blocked_range<size_t>(0, expandOp.updatedIndexNodes().size()),
2779  expandOp.updatedDistNodes(), expandOp.updatedIndexNodes()));
2780 
2781  tbb::task_group tasks;
2782  tasks.run(AddNodes<TreeType>(distTree, expandOp.newDistNodes()));
2783  tasks.run(AddNodes<Int32TreeType>(indexTree, expandOp.newIndexNodes()));
2784  tasks.wait();
2785 
2786  maskTree.clear();
2787  maskTree.merge(expandOp.newMaskTree());
2788 }
2789 
2790 
2792 
2793 
2794 // Transform values (sqrt, world space scaling and sign flip if sdf)
2795 template<typename TreeType>
2797 {
2798  using LeafNodeType = typename TreeType::LeafNodeType;
2799  using ValueType = typename TreeType::ValueType;
2800 
2801  TransformValues(std::vector<LeafNodeType*>& nodes,
2802  ValueType voxelSize, bool unsignedDist)
2803  : mNodes(&nodes[0])
2804  , mVoxelSize(voxelSize)
2805  , mUnsigned(unsignedDist)
2806  {
2807  }
2808 
2809  void operator()(const tbb::blocked_range<size_t>& range) const {
2810 
2811  typename LeafNodeType::ValueOnIter iter;
2812 
2813  const bool udf = mUnsigned;
2814  const ValueType w[2] = { -mVoxelSize, mVoxelSize };
2815 
2816  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2817 
2818  for (iter = mNodes[n]->beginValueOn(); iter; ++iter) {
2819  ValueType& val = const_cast<ValueType&>(iter.getValue());
2820  val = w[udf || (val < ValueType(0.0))] * std::sqrt(std::abs(val));
2821  }
2822  }
2823  }
2824 
2825 private:
2826  LeafNodeType * * const mNodes;
2827  const ValueType mVoxelSize;
2828  const bool mUnsigned;
2829 };
2830 
2831 
2832 // Inactivate values outside the (exBandWidth, inBandWidth) range.
2833 template<typename TreeType>
2835 {
2836  using LeafNodeType = typename TreeType::LeafNodeType;
2837  using ValueType = typename TreeType::ValueType;
2838 
2839  InactivateValues(std::vector<LeafNodeType*>& nodes,
2840  ValueType exBandWidth, ValueType inBandWidth)
2841  : mNodes(nodes.empty() ? nullptr : &nodes[0])
2842  , mExBandWidth(exBandWidth)
2843  , mInBandWidth(inBandWidth)
2844  {
2845  }
2846 
2847  void operator()(const tbb::blocked_range<size_t>& range) const {
2848 
2849  typename LeafNodeType::ValueOnIter iter;
2850  const ValueType exVal = mExBandWidth;
2851  const ValueType inVal = -mInBandWidth;
2852 
2853  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2854 
2855  for (iter = mNodes[n]->beginValueOn(); iter; ++iter) {
2856 
2857  ValueType& val = const_cast<ValueType&>(iter.getValue());
2858 
2859  const bool inside = val < ValueType(0.0);
2860 
2861  if (inside && !(val > inVal)) {
2862  val = inVal;
2863  iter.setValueOff();
2864  } else if (!inside && !(val < exVal)) {
2865  val = exVal;
2866  iter.setValueOff();
2867  }
2868  }
2869  }
2870  }
2871 
2872 private:
2873  LeafNodeType * * const mNodes;
2874  const ValueType mExBandWidth, mInBandWidth;
2875 };
2876 
2877 
2878 template<typename TreeType>
2880 {
2881  using LeafNodeType = typename TreeType::LeafNodeType;
2882  using ValueType = typename TreeType::ValueType;
2883 
2884  OffsetValues(std::vector<LeafNodeType*>& nodes, ValueType offset)
2885  : mNodes(nodes.empty() ? nullptr : &nodes[0]), mOffset(offset)
2886  {
2887  }
2888 
2889  void operator()(const tbb::blocked_range<size_t>& range) const {
2890 
2891  const ValueType offset = mOffset;
2892 
2893  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2894 
2895  typename LeafNodeType::ValueOnIter iter = mNodes[n]->beginValueOn();
2896 
2897  for (; iter; ++iter) {
2898  ValueType& val = const_cast<ValueType&>(iter.getValue());
2899  val += offset;
2900  }
2901  }
2902  }
2903 
2904 private:
2905  LeafNodeType * * const mNodes;
2906  const ValueType mOffset;
2907 };
2908 
2909 
2910 template<typename TreeType>
2912 {
2913  using LeafNodeType = typename TreeType::LeafNodeType;
2914  using ValueType = typename TreeType::ValueType;
2915 
2916  Renormalize(const TreeType& tree, const std::vector<LeafNodeType*>& nodes,
2917  ValueType* buffer, ValueType voxelSize)
2918  : mTree(&tree)
2919  , mNodes(nodes.empty() ? nullptr : &nodes[0])
2920  , mBuffer(buffer)
2921  , mVoxelSize(voxelSize)
2922  {
2923  }
2924 
2925  void operator()(const tbb::blocked_range<size_t>& range) const
2926  {
2927  using Vec3Type = math::Vec3<ValueType>;
2928 
2930 
2931  Coord ijk;
2932  Vec3Type up, down;
2933 
2934  const ValueType dx = mVoxelSize, invDx = ValueType(1.0) / mVoxelSize;
2935 
2936  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2937 
2938  ValueType* bufferData = &mBuffer[n * LeafNodeType::SIZE];
2939 
2940  typename LeafNodeType::ValueOnCIter iter = mNodes[n]->cbeginValueOn();
2941  for (; iter; ++iter) {
2942 
2943  const ValueType phi0 = *iter;
2944 
2945  ijk = iter.getCoord();
2946 
2947  up[0] = acc.getValue(ijk.offsetBy(1, 0, 0)) - phi0;
2948  up[1] = acc.getValue(ijk.offsetBy(0, 1, 0)) - phi0;
2949  up[2] = acc.getValue(ijk.offsetBy(0, 0, 1)) - phi0;
2950 
2951  down[0] = phi0 - acc.getValue(ijk.offsetBy(-1, 0, 0));
2952  down[1] = phi0 - acc.getValue(ijk.offsetBy(0, -1, 0));
2953  down[2] = phi0 - acc.getValue(ijk.offsetBy(0, 0, -1));
2954 
2955  const ValueType normSqGradPhi = math::GodunovsNormSqrd(phi0 > 0.0, down, up);
2956 
2957  const ValueType diff = math::Sqrt(normSqGradPhi) * invDx - ValueType(1.0);
2958  const ValueType S = phi0 / (math::Sqrt(math::Pow2(phi0) + normSqGradPhi));
2959 
2960  bufferData[iter.pos()] = phi0 - dx * S * diff;
2961  }
2962  }
2963  }
2964 
2965 private:
2966  TreeType const * const mTree;
2967  LeafNodeType const * const * const mNodes;
2968  ValueType * const mBuffer;
2969 
2970  const ValueType mVoxelSize;
2971 };
2972 
2973 
2974 template<typename TreeType>
2976 {
2977  using LeafNodeType = typename TreeType::LeafNodeType;
2978  using ValueType = typename TreeType::ValueType;
2979 
2980  MinCombine(std::vector<LeafNodeType*>& nodes, const ValueType* buffer)
2981  : mNodes(nodes.empty() ? nullptr : &nodes[0]), mBuffer(buffer)
2982  {
2983  }
2984 
2985  void operator()(const tbb::blocked_range<size_t>& range) const {
2986 
2987  for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
2988 
2989  const ValueType* bufferData = &mBuffer[n * LeafNodeType::SIZE];
2990 
2991  typename LeafNodeType::ValueOnIter iter = mNodes[n]->beginValueOn();
2992 
2993  for (; iter; ++iter) {
2994  ValueType& val = const_cast<ValueType&>(iter.getValue());
2995  val = std::min(val, bufferData[iter.pos()]);
2996  }
2997  }
2998  }
2999 
3000 private:
3001  LeafNodeType * * const mNodes;
3002  ValueType const * const mBuffer;
3003 };
3004 
3005 
3006 } // mesh_to_volume_internal namespace
3007 
3008 
3010 
3011 // Utility method implementation
3012 
3013 
3014 template <typename FloatTreeT>
3015 inline void
3016 traceExteriorBoundaries(FloatTreeT& tree)
3017 {
3019 
3020  ConnectivityTable nodeConnectivity(tree);
3021 
3022  std::vector<size_t> zStartNodes, yStartNodes, xStartNodes;
3023 
3024  for (size_t n = 0; n < nodeConnectivity.size(); ++n) {
3025  if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevX()[n]) {
3026  xStartNodes.push_back(n);
3027  }
3028 
3029  if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevY()[n]) {
3030  yStartNodes.push_back(n);
3031  }
3032 
3033  if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevZ()[n]) {
3034  zStartNodes.push_back(n);
3035  }
3036  }
3037 
3039 
3040  tbb::parallel_for(tbb::blocked_range<size_t>(0, zStartNodes.size()),
3041  SweepingOp(SweepingOp::Z_AXIS, zStartNodes, nodeConnectivity));
3042 
3043  tbb::parallel_for(tbb::blocked_range<size_t>(0, yStartNodes.size()),
3044  SweepingOp(SweepingOp::Y_AXIS, yStartNodes, nodeConnectivity));
3045 
3046  tbb::parallel_for(tbb::blocked_range<size_t>(0, xStartNodes.size()),
3047  SweepingOp(SweepingOp::X_AXIS, xStartNodes, nodeConnectivity));
3048 
3049  const size_t numLeafNodes = nodeConnectivity.size();
3050  const size_t numVoxels = numLeafNodes * FloatTreeT::LeafNodeType::SIZE;
3051 
3052  std::unique_ptr<bool[]> changedNodeMaskA{new bool[numLeafNodes]};
3053  std::unique_ptr<bool[]> changedNodeMaskB{new bool[numLeafNodes]};
3054  std::unique_ptr<bool[]> changedVoxelMask{new bool[numVoxels]};
3055 
3056  mesh_to_volume_internal::fillArray(changedNodeMaskA.get(), true, numLeafNodes);
3057  mesh_to_volume_internal::fillArray(changedNodeMaskB.get(), false, numLeafNodes);
3058  mesh_to_volume_internal::fillArray(changedVoxelMask.get(), false, numVoxels);
3059 
3060  const tbb::blocked_range<size_t> nodeRange(0, numLeafNodes);
3061 
3062  bool nodesUpdated = false;
3063  do {
3064  tbb::parallel_for(nodeRange, mesh_to_volume_internal::SeedFillExteriorSign<FloatTreeT>(
3065  nodeConnectivity.nodes(), changedNodeMaskA.get()));
3066 
3067  tbb::parallel_for(nodeRange, mesh_to_volume_internal::SeedPoints<FloatTreeT>(
3068  nodeConnectivity, changedNodeMaskA.get(), changedNodeMaskB.get(),
3069  changedVoxelMask.get()));
3070 
3071  changedNodeMaskA.swap(changedNodeMaskB);
3072 
3073  nodesUpdated = false;
3074  for (size_t n = 0; n < numLeafNodes; ++n) {
3075  nodesUpdated |= changedNodeMaskA[n];
3076  if (nodesUpdated) break;
3077  }
3078 
3079  if (nodesUpdated) {
3080  tbb::parallel_for(nodeRange, mesh_to_volume_internal::SyncVoxelMask<FloatTreeT>(
3081  nodeConnectivity.nodes(), changedNodeMaskA.get(), changedVoxelMask.get()));
3082  }
3083  } while (nodesUpdated);
3084 
3085 } // void traceExteriorBoundaries()
3086 
3087 
3089 
3090 
3091 template <typename GridType, typename MeshDataAdapter, typename Interrupter>
3092 inline typename GridType::Ptr
3094  Interrupter& interrupter,
3095  const MeshDataAdapter& mesh,
3096  const math::Transform& transform,
3097  float exteriorBandWidth,
3098  float interiorBandWidth,
3099  int flags,
3100  typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid)
3101 {
3102  using GridTypePtr = typename GridType::Ptr;
3103  using TreeType = typename GridType::TreeType;
3104  using LeafNodeType = typename TreeType::LeafNodeType;
3105  using ValueType = typename GridType::ValueType;
3106 
3107  using Int32GridType = typename GridType::template ValueConverter<Int32>::Type;
3108  using Int32TreeType = typename Int32GridType::TreeType;
3109 
3110  using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
3111 
3113 
3114  // Setup
3115 
3116  GridTypePtr distGrid(new GridType(std::numeric_limits<ValueType>::max()));
3117  distGrid->setTransform(transform.copy());
3118 
3119  ValueType exteriorWidth = ValueType(exteriorBandWidth);
3120  ValueType interiorWidth = ValueType(interiorBandWidth);
3121 
3122  // Note: inf interior width is all right, this value makes the converter fill
3123  // interior regions with distance values.
3124  if (!std::isfinite(exteriorWidth) || std::isnan(interiorWidth)) {
3125  std::stringstream msg;
3126  msg << "Illegal narrow band width: exterior = " << exteriorWidth
3127  << ", interior = " << interiorWidth;
3128  OPENVDB_LOG_DEBUG(msg.str());
3129  return distGrid;
3130  }
3131 
3132  const ValueType voxelSize = ValueType(transform.voxelSize()[0]);
3133 
3134  if (!std::isfinite(voxelSize) || math::isZero(voxelSize)) {
3135  std::stringstream msg;
3136  msg << "Illegal transform, voxel size = " << voxelSize;
3137  OPENVDB_LOG_DEBUG(msg.str());
3138  return distGrid;
3139  }
3140 
3141  // Convert narrow band width from voxel units to world space units.
3142  exteriorWidth *= voxelSize;
3143  // Avoid the unit conversion if the interior band width is set to
3144  // inf or std::numeric_limits<float>::max().
3145  if (interiorWidth < std::numeric_limits<ValueType>::max()) {
3146  interiorWidth *= voxelSize;
3147  }
3148 
3149  const bool computeSignedDistanceField = (flags & UNSIGNED_DISTANCE_FIELD) == 0;
3150  const bool removeIntersectingVoxels = (flags & DISABLE_INTERSECTING_VOXEL_REMOVAL) == 0;
3151  const bool renormalizeValues = (flags & DISABLE_RENORMALIZATION) == 0;
3152  const bool trimNarrowBand = (flags & DISABLE_NARROW_BAND_TRIMMING) == 0;
3153 
3154  Int32GridType* indexGrid = nullptr;
3155 
3156  typename Int32GridType::Ptr temporaryIndexGrid;
3157 
3158  if (polygonIndexGrid) {
3159  indexGrid = polygonIndexGrid;
3160  } else {
3161  temporaryIndexGrid.reset(new Int32GridType(Int32(util::INVALID_IDX)));
3162  indexGrid = temporaryIndexGrid.get();
3163  }
3164 
3165  indexGrid->newTree();
3166  indexGrid->setTransform(transform.copy());
3167 
3168  if (computeSignedDistanceField) {
3169  distGrid->setGridClass(GRID_LEVEL_SET);
3170  } else {
3171  distGrid->setGridClass(GRID_UNKNOWN);
3172  interiorWidth = ValueType(0.0);
3173  }
3174 
3175  TreeType& distTree = distGrid->tree();
3176  Int32TreeType& indexTree = indexGrid->tree();
3177 
3178 
3180 
3181  // Voxelize mesh
3182 
3183  {
3184  using VoxelizationDataType = mesh_to_volume_internal::VoxelizationData<TreeType>;
3185  using DataTable = tbb::enumerable_thread_specific<typename VoxelizationDataType::Ptr>;
3186 
3187  DataTable data;
3188  using Voxelizer =
3190 
3191  const tbb::blocked_range<size_t> polygonRange(0, mesh.polygonCount());
3192 
3193  tbb::parallel_for(polygonRange, Voxelizer(data, mesh, &interrupter));
3194 
3195  for (typename DataTable::iterator i = data.begin(); i != data.end(); ++i) {
3196  VoxelizationDataType& dataItem = **i;
3198  distTree, indexTree, dataItem.distTree, dataItem.indexTree);
3199  }
3200  }
3201 
3202  // The progress estimates are based on the observed average time for a few different
3203  // test cases and is only intended to provide some rough progression feedback to the user.
3204  if (interrupter.wasInterrupted(30)) return distGrid;
3205 
3206 
3208 
3209  // Classify interior and exterior regions
3210 
3211  if (computeSignedDistanceField) {
3212 
3213  // Determines the inside/outside state for the narrow band of voxels.
3214  traceExteriorBoundaries(distTree);
3215 
3216  std::vector<LeafNodeType*> nodes;
3217  nodes.reserve(distTree.leafCount());
3218  distTree.getNodes(nodes);
3219 
3220  const tbb::blocked_range<size_t> nodeRange(0, nodes.size());
3221 
3222  using SignOp =
3224 
3225  tbb::parallel_for(nodeRange, SignOp(nodes, distTree, indexTree, mesh));
3226 
3227  if (interrupter.wasInterrupted(45)) return distGrid;
3228 
3229  // Remove voxels created by self intersecting portions of the mesh.
3230  if (removeIntersectingVoxels) {
3231 
3232  tbb::parallel_for(nodeRange,
3234 
3235  tbb::parallel_for(nodeRange,
3237  nodes, distTree, indexTree));
3238 
3239  tools::pruneInactive(distTree, /*threading=*/true);
3240  tools::pruneInactive(indexTree, /*threading=*/true);
3241  }
3242  }
3243 
3244  if (interrupter.wasInterrupted(50)) return distGrid;
3245 
3246  if (distTree.activeVoxelCount() == 0) {
3247  distTree.clear();
3248  distTree.root().setBackground(exteriorWidth, /*updateChildNodes=*/false);
3249  return distGrid;
3250  }
3251 
3252  // Transform values (world space scaling etc.).
3253  {
3254  std::vector<LeafNodeType*> nodes;
3255  nodes.reserve(distTree.leafCount());
3256  distTree.getNodes(nodes);
3257 
3258  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3260  nodes, voxelSize, !computeSignedDistanceField));
3261  }
3262 
3263  // Propagate sign information into tile regions.
3264  if (computeSignedDistanceField) {
3265  distTree.root().setBackground(exteriorWidth, /*updateChildNodes=*/false);
3266  tools::signedFloodFillWithValues(distTree, exteriorWidth, -interiorWidth);
3267  } else {
3268  tools::changeBackground(distTree, exteriorWidth);
3269  }
3270 
3271  if (interrupter.wasInterrupted(54)) return distGrid;
3272 
3273 
3275 
3276  // Expand the narrow band region
3277 
3278  const ValueType minBandWidth = voxelSize * ValueType(2.0);
3279 
3280  if (interiorWidth > minBandWidth || exteriorWidth > minBandWidth) {
3281 
3282  // Create the initial voxel mask.
3283  BoolTreeType maskTree(false);
3284 
3285  {
3286  std::vector<LeafNodeType*> nodes;
3287  nodes.reserve(distTree.leafCount());
3288  distTree.getNodes(nodes);
3289 
3290  mesh_to_volume_internal::ConstructVoxelMask<TreeType> op(maskTree, distTree, nodes);
3291  tbb::parallel_reduce(tbb::blocked_range<size_t>(0, nodes.size()), op);
3292  }
3293 
3294  // Progress estimation
3295  unsigned maxIterations = std::numeric_limits<unsigned>::max();
3296 
3297  float progress = 54.0f, step = 0.0f;
3298  double estimated =
3299  2.0 * std::ceil((std::max(interiorWidth, exteriorWidth) - minBandWidth) / voxelSize);
3300 
3301  if (estimated < double(maxIterations)) {
3302  maxIterations = unsigned(estimated);
3303  step = 40.0f / float(maxIterations);
3304  }
3305 
3306  std::vector<typename BoolTreeType::LeafNodeType*> maskNodes;
3307 
3308  unsigned count = 0;
3309  while (true) {
3310 
3311  if (interrupter.wasInterrupted(int(progress))) return distGrid;
3312 
3313  const size_t maskNodeCount = maskTree.leafCount();
3314  if (maskNodeCount == 0) break;
3315 
3316  maskNodes.clear();
3317  maskNodes.reserve(maskNodeCount);
3318  maskTree.getNodes(maskNodes);
3319 
3320  const tbb::blocked_range<size_t> range(0, maskNodes.size());
3321 
3322  tbb::parallel_for(range,
3324 
3325  mesh_to_volume_internal::expandNarrowband(distTree, indexTree, maskTree, maskNodes,
3326  mesh, exteriorWidth, interiorWidth, voxelSize);
3327 
3328  if ((++count) >= maxIterations) break;
3329  progress += step;
3330  }
3331  }
3332 
3333  if (interrupter.wasInterrupted(94)) return distGrid;
3334 
3335  if (!polygonIndexGrid) indexGrid->clear();
3336 
3337 
3339 
3340  // Renormalize distances to smooth out bumps caused by self intersecting
3341  // and overlapping portions of the mesh and renormalize the level set.
3342 
3343  if (computeSignedDistanceField && renormalizeValues) {
3344 
3345  std::vector<LeafNodeType*> nodes;
3346  nodes.reserve(distTree.leafCount());
3347  distTree.getNodes(nodes);
3348 
3349  std::unique_ptr<ValueType[]> buffer{new ValueType[LeafNodeType::SIZE * nodes.size()]};
3350 
3351  const ValueType offset = ValueType(0.8 * voxelSize);
3352 
3353  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3355 
3356  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3358  distTree, nodes, buffer.get(), voxelSize));
3359 
3360  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3361  mesh_to_volume_internal::MinCombine<TreeType>(nodes, buffer.get()));
3362 
3363  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3366  }
3367 
3368  if (interrupter.wasInterrupted(99)) return distGrid;
3369 
3370 
3372 
3373  // Remove active voxels that exceed the narrow band limits
3374 
3375  if (trimNarrowBand && std::min(interiorWidth, exteriorWidth) < voxelSize * ValueType(4.0)) {
3376 
3377  std::vector<LeafNodeType*> nodes;
3378  nodes.reserve(distTree.leafCount());
3379  distTree.getNodes(nodes);
3380 
3381  tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
3383  nodes, exteriorWidth, computeSignedDistanceField ? interiorWidth : exteriorWidth));
3384 
3386  distTree, exteriorWidth, computeSignedDistanceField ? -interiorWidth : -exteriorWidth);
3387  }
3388 
3389  return distGrid;
3390 }
3391 
3392 
3393 template <typename GridType, typename MeshDataAdapter>
3394 inline typename GridType::Ptr
3396  const MeshDataAdapter& mesh,
3397  const math::Transform& transform,
3398  float exteriorBandWidth,
3399  float interiorBandWidth,
3400  int flags,
3401  typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid)
3402 {
3403  util::NullInterrupter nullInterrupter;
3404  return meshToVolume<GridType>(nullInterrupter, mesh, transform,
3405  exteriorBandWidth, interiorBandWidth, flags, polygonIndexGrid);
3406 }
3407 
3408 
3410 
3411 
3412 //{
3414 
3416 template<typename GridType, typename Interrupter>
3417 inline typename std::enable_if<std::is_floating_point<typename GridType::ValueType>::value,
3418  typename GridType::Ptr>::type
3419 doMeshConversion(
3420  Interrupter& interrupter,
3421  const openvdb::math::Transform& xform,
3422  const std::vector<Vec3s>& points,
3423  const std::vector<Vec3I>& triangles,
3424  const std::vector<Vec4I>& quads,
3425  float exBandWidth,
3426  float inBandWidth,
3427  bool unsignedDistanceField = false)
3428 {
3429  if (points.empty()) {
3430  return typename GridType::Ptr(new GridType(typename GridType::ValueType(exBandWidth)));
3431  }
3432 
3433  const size_t numPoints = points.size();
3434  std::unique_ptr<Vec3s[]> indexSpacePoints{new Vec3s[numPoints]};
3435 
3436  // transform points to local grid index space
3437  tbb::parallel_for(tbb::blocked_range<size_t>(0, numPoints),
3438  mesh_to_volume_internal::TransformPoints<Vec3s>(
3439  &points[0], indexSpacePoints.get(), xform));
3440 
3441  const int conversionFlags = unsignedDistanceField ? UNSIGNED_DISTANCE_FIELD : 0;
3442 
3443  if (quads.empty()) {
3444 
3445  QuadAndTriangleDataAdapter<Vec3s, Vec3I>
3446  mesh(indexSpacePoints.get(), numPoints, &triangles[0], triangles.size());
3447 
3448  return meshToVolume<GridType>(
3449  interrupter, mesh, xform, exBandWidth, inBandWidth, conversionFlags);
3450 
3451  } else if (triangles.empty()) {
3452 
3453  QuadAndTriangleDataAdapter<Vec3s, Vec4I>
3454  mesh(indexSpacePoints.get(), numPoints, &quads[0], quads.size());
3455 
3456  return meshToVolume<GridType>(
3457  interrupter, mesh, xform, exBandWidth, inBandWidth, conversionFlags);
3458  }
3459 
3460  // pack primitives
3461 
3462  const size_t numPrimitives = triangles.size() + quads.size();
3463  std::unique_ptr<Vec4I[]> prims{new Vec4I[numPrimitives]};
3464 
3465  for (size_t n = 0, N = triangles.size(); n < N; ++n) {
3466  const Vec3I& triangle = triangles[n];
3467  Vec4I& prim = prims[n];
3468  prim[0] = triangle[0];
3469  prim[1] = triangle[1];
3470  prim[2] = triangle[2];
3471  prim[3] = util::INVALID_IDX;
3472  }
3473 
3474  const size_t offset = triangles.size();
3475  for (size_t n = 0, N = quads.size(); n < N; ++n) {
3476  prims[offset + n] = quads[n];
3477  }
3478 
3479  QuadAndTriangleDataAdapter<Vec3s, Vec4I>
3480  mesh(indexSpacePoints.get(), numPoints, prims.get(), numPrimitives);
3481 
3482  return meshToVolume<GridType>(interrupter, mesh, xform,
3483  exBandWidth, inBandWidth, conversionFlags);
3484 }
3485 
3486 
3489 template<typename GridType, typename Interrupter>
3490 inline typename std::enable_if<!std::is_floating_point<typename GridType::ValueType>::value,
3491  typename GridType::Ptr>::type
3492 doMeshConversion(
3493  Interrupter&,
3494  const math::Transform& /*xform*/,
3495  const std::vector<Vec3s>& /*points*/,
3496  const std::vector<Vec3I>& /*triangles*/,
3497  const std::vector<Vec4I>& /*quads*/,
3498  float /*exBandWidth*/,
3499  float /*inBandWidth*/,
3500  bool /*unsignedDistanceField*/ = false)
3501 {
3502  OPENVDB_THROW(TypeError,
3503  "mesh to volume conversion is supported only for scalar floating-point grids");
3504 }
3505 
3507 //}
3508 
3509 
3511 
3512 
3513 template<typename GridType>
3514 inline typename GridType::Ptr
3516  const openvdb::math::Transform& xform,
3517  const std::vector<Vec3s>& points,
3518  const std::vector<Vec3I>& triangles,
3519  float halfWidth)
3520 {
3521  util::NullInterrupter nullInterrupter;
3522  std::vector<Vec4I> quads(0);
3523  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
3524  halfWidth, halfWidth);
3525 }
3526 
3527 
3528 template<typename GridType, typename Interrupter>
3529 inline typename GridType::Ptr
3531  Interrupter& interrupter,
3532  const openvdb::math::Transform& xform,
3533  const std::vector<Vec3s>& points,
3534  const std::vector<Vec3I>& triangles,
3535  float halfWidth)
3536 {
3537  std::vector<Vec4I> quads(0);
3538  return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3539  halfWidth, halfWidth);
3540 }
3541 
3542 
3543 template<typename GridType>
3544 inline typename GridType::Ptr
3546  const openvdb::math::Transform& xform,
3547  const std::vector<Vec3s>& points,
3548  const std::vector<Vec4I>& quads,
3549  float halfWidth)
3550 {
3551  util::NullInterrupter nullInterrupter;
3552  std::vector<Vec3I> triangles(0);
3553  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
3554  halfWidth, halfWidth);
3555 }
3556 
3557 
3558 template<typename GridType, typename Interrupter>
3559 inline typename GridType::Ptr
3561  Interrupter& interrupter,
3562  const openvdb::math::Transform& xform,
3563  const std::vector<Vec3s>& points,
3564  const std::vector<Vec4I>& quads,
3565  float halfWidth)
3566 {
3567  std::vector<Vec3I> triangles(0);
3568  return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3569  halfWidth, halfWidth);
3570 }
3571 
3572 
3573 template<typename GridType>
3574 inline typename GridType::Ptr
3576  const openvdb::math::Transform& xform,
3577  const std::vector<Vec3s>& points,
3578  const std::vector<Vec3I>& triangles,
3579  const std::vector<Vec4I>& quads,
3580  float halfWidth)
3581 {
3582  util::NullInterrupter nullInterrupter;
3583  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
3584  halfWidth, halfWidth);
3585 }
3586 
3587 
3588 template<typename GridType, typename Interrupter>
3589 inline typename GridType::Ptr
3591  Interrupter& interrupter,
3592  const openvdb::math::Transform& xform,
3593  const std::vector<Vec3s>& points,
3594  const std::vector<Vec3I>& triangles,
3595  const std::vector<Vec4I>& quads,
3596  float halfWidth)
3597 {
3598  return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3599  halfWidth, halfWidth);
3600 }
3601 
3602 
3603 template<typename GridType>
3604 inline typename GridType::Ptr
3606  const openvdb::math::Transform& xform,
3607  const std::vector<Vec3s>& points,
3608  const std::vector<Vec3I>& triangles,
3609  const std::vector<Vec4I>& quads,
3610  float exBandWidth,
3611  float inBandWidth)
3612 {
3613  util::NullInterrupter nullInterrupter;
3614  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles,
3615  quads, exBandWidth, inBandWidth);
3616 }
3617 
3618 
3619 template<typename GridType, typename Interrupter>
3620 inline typename GridType::Ptr
3622  Interrupter& interrupter,
3623  const openvdb::math::Transform& xform,
3624  const std::vector<Vec3s>& points,
3625  const std::vector<Vec3I>& triangles,
3626  const std::vector<Vec4I>& quads,
3627  float exBandWidth,
3628  float inBandWidth)
3629 {
3630  return doMeshConversion<GridType>(interrupter, xform, points, triangles,
3631  quads, exBandWidth, inBandWidth);
3632 }
3633 
3634 
3635 template<typename GridType>
3636 inline typename GridType::Ptr
3638  const openvdb::math::Transform& xform,
3639  const std::vector<Vec3s>& points,
3640  const std::vector<Vec3I>& triangles,
3641  const std::vector<Vec4I>& quads,
3642  float bandWidth)
3643 {
3644  util::NullInterrupter nullInterrupter;
3645  return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
3646  bandWidth, bandWidth, true);
3647 }
3648 
3649 
3650 template<typename GridType, typename Interrupter>
3651 inline typename GridType::Ptr
3653  Interrupter& interrupter,
3654  const openvdb::math::Transform& xform,
3655  const std::vector<Vec3s>& points,
3656  const std::vector<Vec3I>& triangles,
3657  const std::vector<Vec4I>& quads,
3658  float bandWidth)
3659 {
3660  return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
3661  bandWidth, bandWidth, true);
3662 }
3663 
3664 
3666 
3667 
3668 // Required by several of the tree nodes
3669 inline std::ostream&
3670 operator<<(std::ostream& ostr, const MeshToVoxelEdgeData::EdgeData& rhs)
3671 {
3672  ostr << "{[ " << rhs.mXPrim << ", " << rhs.mXDist << "]";
3673  ostr << " [ " << rhs.mYPrim << ", " << rhs.mYDist << "]";
3674  ostr << " [ " << rhs.mZPrim << ", " << rhs.mZDist << "]}";
3675  return ostr;
3676 }
3677 
3678 // Required by math::Abs
3679 inline MeshToVoxelEdgeData::EdgeData
3681 {
3682  return x;
3683 }
3684 
3685 
3687 
3688 
3690 {
3691 public:
3692 
3693  GenEdgeData(
3694  const std::vector<Vec3s>& pointList,
3695  const std::vector<Vec4I>& polygonList);
3696 
3697  void run(bool threaded = true);
3698 
3699  GenEdgeData(GenEdgeData& rhs, tbb::split);
3700  inline void operator() (const tbb::blocked_range<size_t> &range);
3701  inline void join(GenEdgeData& rhs);
3702 
3703  inline TreeType& tree() { return mTree; }
3704 
3705 private:
3706  void operator=(const GenEdgeData&) {}
3707 
3708  struct Primitive { Vec3d a, b, c, d; Int32 index; };
3709 
3710  template<bool IsQuad>
3711  inline void voxelize(const Primitive&);
3712 
3713  template<bool IsQuad>
3714  inline bool evalPrimitive(const Coord&, const Primitive&);
3715 
3716  inline bool rayTriangleIntersection( const Vec3d& origin, const Vec3d& dir,
3717  const Vec3d& a, const Vec3d& b, const Vec3d& c, double& t);
3718 
3719 
3720  TreeType mTree;
3721  Accessor mAccessor;
3722 
3723  const std::vector<Vec3s>& mPointList;
3724  const std::vector<Vec4I>& mPolygonList;
3725 
3726  // Used internally for acceleration
3727  using IntTreeT = TreeType::ValueConverter<Int32>::Type;
3728  IntTreeT mLastPrimTree;
3729  tree::ValueAccessor<IntTreeT> mLastPrimAccessor;
3730 }; // class MeshToVoxelEdgeData::GenEdgeData
3731 
3732 
3733 inline
3734 MeshToVoxelEdgeData::GenEdgeData::GenEdgeData(
3735  const std::vector<Vec3s>& pointList,
3736  const std::vector<Vec4I>& polygonList)
3737  : mTree(EdgeData())
3738  , mAccessor(mTree)
3739  , mPointList(pointList)
3740  , mPolygonList(polygonList)
3741  , mLastPrimTree(Int32(util::INVALID_IDX))
3742  , mLastPrimAccessor(mLastPrimTree)
3743 {
3744 }
3745 
3746 
3747 inline
3749  : mTree(EdgeData())
3750  , mAccessor(mTree)
3751  , mPointList(rhs.mPointList)
3752  , mPolygonList(rhs.mPolygonList)
3753  , mLastPrimTree(Int32(util::INVALID_IDX))
3754  , mLastPrimAccessor(mLastPrimTree)
3755 {
3756 }
3757 
3758 
3759 inline void
3761 {
3762  if (threaded) {
3763  tbb::parallel_reduce(tbb::blocked_range<size_t>(0, mPolygonList.size()), *this);
3764  } else {
3765  (*this)(tbb::blocked_range<size_t>(0, mPolygonList.size()));
3766  }
3767 }
3768 
3769 
3770 inline void
3772 {
3773  using RootNodeType = TreeType::RootNodeType;
3774  using NodeChainType = RootNodeType::NodeChainType;
3775  static_assert(boost::mpl::size<NodeChainType>::value > 1, "expected tree height > 1");
3776  using InternalNodeType = boost::mpl::at<NodeChainType, boost::mpl::int_<1> >::type;
3777 
3778  Coord ijk;
3779  Index offset;
3780 
3781  rhs.mTree.clearAllAccessors();
3782 
3783  TreeType::LeafIter leafIt = rhs.mTree.beginLeaf();
3784  for ( ; leafIt; ++leafIt) {
3785  ijk = leafIt->origin();
3786 
3787  TreeType::LeafNodeType* lhsLeafPt = mTree.probeLeaf(ijk);
3788 
3789  if (!lhsLeafPt) {
3790 
3791  mAccessor.addLeaf(rhs.mAccessor.probeLeaf(ijk));
3792  InternalNodeType* node = rhs.mAccessor.getNode<InternalNodeType>();
3793  node->stealNode<TreeType::LeafNodeType>(ijk, EdgeData(), false);
3794  rhs.mAccessor.clear();
3795 
3796  } else {
3797 
3798  TreeType::LeafNodeType::ValueOnCIter it = leafIt->cbeginValueOn();
3799  for ( ; it; ++it) {
3800 
3801  offset = it.pos();
3802  const EdgeData& rhsValue = it.getValue();
3803 
3804  if (!lhsLeafPt->isValueOn(offset)) {
3805  lhsLeafPt->setValueOn(offset, rhsValue);
3806  } else {
3807 
3808  EdgeData& lhsValue = const_cast<EdgeData&>(lhsLeafPt->getValue(offset));
3809 
3810  if (rhsValue.mXDist < lhsValue.mXDist) {
3811  lhsValue.mXDist = rhsValue.mXDist;
3812  lhsValue.mXPrim = rhsValue.mXPrim;
3813  }
3814 
3815  if (rhsValue.mYDist < lhsValue.mYDist) {
3816  lhsValue.mYDist = rhsValue.mYDist;
3817  lhsValue.mYPrim = rhsValue.mYPrim;
3818  }
3819 
3820  if (rhsValue.mZDist < lhsValue.mZDist) {
3821  lhsValue.mZDist = rhsValue.mZDist;
3822  lhsValue.mZPrim = rhsValue.mZPrim;
3823  }
3824 
3825  }
3826  } // end value iteration
3827  }
3828  } // end leaf iteration
3829 }
3830 
3831 
3832 inline void
3833 MeshToVoxelEdgeData::GenEdgeData::operator()(const tbb::blocked_range<size_t> &range)
3834 {
3835  Primitive prim;
3836 
3837  for (size_t n = range.begin(); n < range.end(); ++n) {
3838 
3839  const Vec4I& verts = mPolygonList[n];
3840 
3841  prim.index = Int32(n);
3842  prim.a = Vec3d(mPointList[verts[0]]);
3843  prim.b = Vec3d(mPointList[verts[1]]);
3844  prim.c = Vec3d(mPointList[verts[2]]);
3845 
3846  if (util::INVALID_IDX != verts[3]) {
3847  prim.d = Vec3d(mPointList[verts[3]]);
3848  voxelize<true>(prim);
3849  } else {
3850  voxelize<false>(prim);
3851  }
3852  }
3853 }
3854 
3855 
3856 template<bool IsQuad>
3857 inline void
3858 MeshToVoxelEdgeData::GenEdgeData::voxelize(const Primitive& prim)
3859 {
3860  std::deque<Coord> coordList;
3861  Coord ijk, nijk;
3862 
3863  ijk = Coord::floor(prim.a);
3864  coordList.push_back(ijk);
3865 
3866  evalPrimitive<IsQuad>(ijk, prim);
3867 
3868  while (!coordList.empty()) {
3869 
3870  ijk = coordList.back();
3871  coordList.pop_back();
3872 
3873  for (Int32 i = 0; i < 26; ++i) {
3874  nijk = ijk + util::COORD_OFFSETS[i];
3875 
3876  if (prim.index != mLastPrimAccessor.getValue(nijk)) {
3877  mLastPrimAccessor.setValue(nijk, prim.index);
3878  if(evalPrimitive<IsQuad>(nijk, prim)) coordList.push_back(nijk);
3879  }
3880  }
3881  }
3882 }
3883 
3884 
3885 template<bool IsQuad>
3886 inline bool
3887 MeshToVoxelEdgeData::GenEdgeData::evalPrimitive(const Coord& ijk, const Primitive& prim)
3888 {
3889  Vec3d uvw, org(ijk[0], ijk[1], ijk[2]);
3890  bool intersecting = false;
3891  double t;
3892 
3893  EdgeData edgeData;
3894  mAccessor.probeValue(ijk, edgeData);
3895 
3896  // Evaluate first triangle
3897  double dist = (org -
3898  closestPointOnTriangleToPoint(prim.a, prim.c, prim.b, org, uvw)).lengthSqr();
3899 
3900  if (rayTriangleIntersection(org, Vec3d(1.0, 0.0, 0.0), prim.a, prim.c, prim.b, t)) {
3901  if (t < edgeData.mXDist) {
3902  edgeData.mXDist = float(t);
3903  edgeData.mXPrim = prim.index;
3904  intersecting = true;
3905  }
3906  }
3907 
3908  if (rayTriangleIntersection(org, Vec3d(0.0, 1.0, 0.0), prim.a, prim.c, prim.b, t)) {
3909  if (t < edgeData.mYDist) {
3910  edgeData.mYDist = float(t);
3911  edgeData.mYPrim = prim.index;
3912  intersecting = true;
3913  }
3914  }
3915 
3916  if (rayTriangleIntersection(org, Vec3d(0.0, 0.0, 1.0), prim.a, prim.c, prim.b, t)) {
3917  if (t < edgeData.mZDist) {
3918  edgeData.mZDist = float(t);
3919  edgeData.mZPrim = prim.index;
3920  intersecting = true;
3921  }
3922  }
3923 
3924  if (IsQuad) {
3925  // Split quad into a second triangle and calculate distance.
3926  double secondDist = (org -
3927  closestPointOnTriangleToPoint(prim.a, prim.d, prim.c, org, uvw)).lengthSqr();
3928 
3929  if (secondDist < dist) dist = secondDist;
3930 
3931  if (rayTriangleIntersection(org, Vec3d(1.0, 0.0, 0.0), prim.a, prim.d, prim.c, t)) {
3932  if (t < edgeData.mXDist) {
3933  edgeData.mXDist = float(t);
3934  edgeData.mXPrim = prim.index;
3935  intersecting = true;
3936  }
3937  }
3938 
3939  if (rayTriangleIntersection(org, Vec3d(0.0, 1.0, 0.0), prim.a, prim.d, prim.c, t)) {
3940  if (t < edgeData.mYDist) {
3941  edgeData.mYDist = float(t);
3942  edgeData.mYPrim = prim.index;
3943  intersecting = true;
3944  }
3945  }
3946 
3947  if (rayTriangleIntersection(org, Vec3d(0.0, 0.0, 1.0), prim.a, prim.d, prim.c, t)) {
3948  if (t < edgeData.mZDist) {
3949  edgeData.mZDist = float(t);
3950  edgeData.mZPrim = prim.index;
3951  intersecting = true;
3952  }
3953  }
3954  }
3955 
3956  if (intersecting) mAccessor.setValue(ijk, edgeData);
3957 
3958  return (dist < 0.86602540378443861);
3959 }
3960 
3961 
3962 inline bool
3963 MeshToVoxelEdgeData::GenEdgeData::rayTriangleIntersection(
3964  const Vec3d& origin, const Vec3d& dir,
3965  const Vec3d& a, const Vec3d& b, const Vec3d& c,
3966  double& t)
3967 {
3968  // Check if ray is parallel with triangle
3969 
3970  Vec3d e1 = b - a;
3971  Vec3d e2 = c - a;
3972  Vec3d s1 = dir.cross(e2);
3973 
3974  double divisor = s1.dot(e1);
3975  if (!(std::abs(divisor) > 0.0)) return false;
3976 
3977  // Compute barycentric coordinates
3978 
3979  double inv_divisor = 1.0 / divisor;
3980  Vec3d d = origin - a;
3981  double b1 = d.dot(s1) * inv_divisor;
3982 
3983  if (b1 < 0.0 || b1 > 1.0) return false;
3984 
3985  Vec3d s2 = d.cross(e1);
3986  double b2 = dir.dot(s2) * inv_divisor;
3987 
3988  if (b2 < 0.0 || (b1 + b2) > 1.0) return false;
3989 
3990  // Compute distance to intersection point
3991 
3992  t = e2.dot(s2) * inv_divisor;
3993  return (t < 0.0) ? false : true;
3994 }
3995 
3996 
3998 
3999 
4000 inline
4002  : mTree(EdgeData())
4003 {
4004 }
4005 
4006 
4007 inline void
4009  const std::vector<Vec3s>& pointList,
4010  const std::vector<Vec4I>& polygonList)
4011 {
4012  GenEdgeData converter(pointList, polygonList);
4013  converter.run();
4014 
4015  mTree.clear();
4016  mTree.merge(converter.tree());
4017 }
4018 
4019 
4020 inline void
4022  Accessor& acc,
4023  const Coord& ijk,
4024  std::vector<Vec3d>& points,
4025  std::vector<Index32>& primitives)
4026 {
4027  EdgeData data;
4028  Vec3d point;
4029 
4030  Coord coord = ijk;
4031 
4032  if (acc.probeValue(coord, data)) {
4033 
4034  if (data.mXPrim != util::INVALID_IDX) {
4035  point[0] = double(coord[0]) + data.mXDist;
4036  point[1] = double(coord[1]);
4037  point[2] = double(coord[2]);
4038 
4039  points.push_back(point);
4040  primitives.push_back(data.mXPrim);
4041  }
4042 
4043  if (data.mYPrim != util::INVALID_IDX) {
4044  point[0] = double(coord[0]);
4045  point[1] = double(coord[1]) + data.mYDist;
4046  point[2] = double(coord[2]);
4047 
4048  points.push_back(point);
4049  primitives.push_back(data.mYPrim);
4050  }
4051 
4052  if (data.mZPrim != util::INVALID_IDX) {
4053  point[0] = double(coord[0]);
4054  point[1] = double(coord[1]);
4055  point[2] = double(coord[2]) + data.mZDist;
4056 
4057  points.push_back(point);
4058  primitives.push_back(data.mZPrim);
4059  }
4060 
4061  }
4062 
4063  coord[0] += 1;
4064 
4065  if (acc.probeValue(coord, data)) {
4066 
4067  if (data.mYPrim != util::INVALID_IDX) {
4068  point[0] = double(coord[0]);
4069  point[1] = double(coord[1]) + data.mYDist;
4070  point[2] = double(coord[2]);
4071 
4072  points.push_back(point);
4073  primitives.push_back(data.mYPrim);
4074  }
4075 
4076  if (data.mZPrim != util::INVALID_IDX) {
4077  point[0] = double(coord[0]);
4078  point[1] = double(coord[1]);
4079  point[2] = double(coord[2]) + data.mZDist;
4080 
4081  points.push_back(point);
4082  primitives.push_back(data.mZPrim);
4083  }
4084  }
4085 
4086  coord[2] += 1;
4087 
4088  if (acc.probeValue(coord, data)) {
4089  if (data.mYPrim != util::INVALID_IDX) {
4090  point[0] = double(coord[0]);
4091  point[1] = double(coord[1]) + data.mYDist;
4092  point[2] = double(coord[2]);
4093 
4094  points.push_back(point);
4095  primitives.push_back(data.mYPrim);
4096  }
4097  }
4098 
4099  coord[0] -= 1;
4100 
4101  if (acc.probeValue(coord, data)) {
4102 
4103  if (data.mXPrim != util::INVALID_IDX) {
4104  point[0] = double(coord[0]) + data.mXDist;
4105  point[1] = double(coord[1]);
4106  point[2] = double(coord[2]);
4107 
4108  points.push_back(point);
4109  primitives.push_back(data.mXPrim);
4110  }
4111 
4112  if (data.mYPrim != util::INVALID_IDX) {
4113  point[0] = double(coord[0]);
4114  point[1] = double(coord[1]) + data.mYDist;
4115  point[2] = double(coord[2]);
4116 
4117  points.push_back(point);
4118  primitives.push_back(data.mYPrim);
4119  }
4120  }
4121 
4122 
4123  coord[1] += 1;
4124 
4125  if (acc.probeValue(coord, data)) {
4126 
4127  if (data.mXPrim != util::INVALID_IDX) {
4128  point[0] = double(coord[0]) + data.mXDist;
4129  point[1] = double(coord[1]);
4130  point[2] = double(coord[2]);
4131 
4132  points.push_back(point);
4133  primitives.push_back(data.mXPrim);
4134  }
4135  }
4136 
4137  coord[2] -= 1;
4138 
4139  if (acc.probeValue(coord, data)) {
4140 
4141  if (data.mXPrim != util::INVALID_IDX) {
4142  point[0] = double(coord[0]) + data.mXDist;
4143  point[1] = double(coord[1]);
4144  point[2] = double(coord[2]);
4145 
4146  points.push_back(point);
4147  primitives.push_back(data.mXPrim);
4148  }
4149 
4150  if (data.mZPrim != util::INVALID_IDX) {
4151  point[0] = double(coord[0]);
4152  point[1] = double(coord[1]);
4153  point[2] = double(coord[2]) + data.mZDist;
4154 
4155  points.push_back(point);
4156  primitives.push_back(data.mZPrim);
4157  }
4158  }
4159 
4160  coord[0] += 1;
4161 
4162  if (acc.probeValue(coord, data)) {
4163 
4164  if (data.mZPrim != util::INVALID_IDX) {
4165  point[0] = double(coord[0]);
4166  point[1] = double(coord[1]);
4167  point[2] = double(coord[2]) + data.mZDist;
4168 
4169  points.push_back(point);
4170  primitives.push_back(data.mZPrim);
4171  }
4172  }
4173 }
4174 
4175 
4176 template<typename GridType, typename VecType>
4177 inline typename GridType::Ptr
4179  const openvdb::math::Transform& xform,
4180  typename VecType::ValueType halfWidth)
4181 {
4182  const Vec3s pmin = Vec3s(xform.worldToIndex(bbox.min()));
4183  const Vec3s pmax = Vec3s(xform.worldToIndex(bbox.max()));
4184 
4185  Vec3s points[8];
4186  points[0] = Vec3s(pmin[0], pmin[1], pmin[2]);
4187  points[1] = Vec3s(pmin[0], pmin[1], pmax[2]);
4188  points[2] = Vec3s(pmax[0], pmin[1], pmax[2]);
4189  points[3] = Vec3s(pmax[0], pmin[1], pmin[2]);
4190  points[4] = Vec3s(pmin[0], pmax[1], pmin[2]);
4191  points[5] = Vec3s(pmin[0], pmax[1], pmax[2]);
4192  points[6] = Vec3s(pmax[0], pmax[1], pmax[2]);
4193  points[7] = Vec3s(pmax[0], pmax[1], pmin[2]);
4194 
4195  Vec4I faces[6];
4196  faces[0] = Vec4I(0, 1, 2, 3); // bottom
4197  faces[1] = Vec4I(7, 6, 5, 4); // top
4198  faces[2] = Vec4I(4, 5, 1, 0); // front
4199  faces[3] = Vec4I(6, 7, 3, 2); // back
4200  faces[4] = Vec4I(0, 3, 7, 4); // left
4201  faces[5] = Vec4I(1, 5, 6, 2); // right
4202 
4203  QuadAndTriangleDataAdapter<Vec3s, Vec4I> mesh(points, 8, faces, 6);
4204 
4205  return meshToVolume<GridType>(mesh, xform, halfWidth, halfWidth);
4206 }
4207 
4208 
4209 } // namespace tools
4210 } // namespace OPENVDB_VERSION_NAME
4211 } // namespace openvdb
4212 
4213 #endif // OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
4214 
4215 // Copyright (c) 2012-2018 DreamWorks Animation LLC
4216 // All rights reserved. This software is distributed under the
4217 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
LeafNodeT * probeLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z), or nullptr if no such node exists.
Definition: ValueAccessor.h:417
typename TreeType::template ValueConverter< Int32 >::Type Int32TreeType
Definition: MeshToVolume.h:1371
T dot(const Vec3< T > &v) const
Dot product.
Definition: Vec3.h:216
Index32 mYPrim
Definition: MeshToVolume.h:493
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:381
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:2241
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:2978
void join(ExpandNarrowband &rhs)
Definition: MeshToVolume.h:2436
typename TreeType::template ValueConverter< bool >::Type BoolTreeType
Definition: MeshToVolume.h:2258
const size_t * offsetsPrevX() const
Definition: MeshToVolume.h:820
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:416
Definition: Math.h:857
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1179
ValueType *const mArray
Definition: MeshToVolume.h:1148
std::ostream & operator<<(std::ostream &ostr, const MeshToVoxelEdgeData::EdgeData &rhs)
Definition: MeshToVolume.h:3670
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2836
QuadAndTriangleDataAdapter(const PointType *pointArray, size_t pointArraySize, const PolygonType *polygonArray, size_t polygonArraySize)
Definition: MeshToVolume.h:203
bool operator==(const EdgeData &rhs) const
Definition: MeshToVolume.h:487
TransformValues(std::vector< LeafNodeType * > &nodes, ValueType voxelSize, bool unsignedDist)
Definition: MeshToVolume.h:2801
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:1760
void operator()(const tbb::blocked_range< size_t > &range)
Definition: MeshToVolume.h:2450
Index32 Index
Definition: Types.h:61
tbb::enumerable_thread_specific< LocalData > LocalDataTable
Definition: MeshToVolume.h:1377
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:2369
PointType *const mPointsOut
Definition: MeshToVolume.h:570
void fillArray(ValueType *array, const ValueType val, const size_t length)
Definition: MeshToVolume.h:1155
InactivateValues(std::vector< LeafNodeType * > &nodes, ValueType exBandWidth, ValueType inBandWidth)
Definition: MeshToVolume.h:2839
typename TreeType::template ValueConverter< Int32 >::Type Int32TreeType
Definition: MeshToVolume.h:2372
Fragment(Int32 idx_, Int32 x_, Int32 y_, Int32 z_, ValueType dist_)
Definition: MeshToVolume.h:2384
void operator()(const tbb::blocked_range< size_t > &range)
Definition: MeshToVolume.h:3833
LeafNodeType * probeLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z). If no such node exists,...
Definition: Tree.h:1734
Vec3d voxelSize() const
Return the size of a voxel using the linear component of the map.
Definition: Transform.h:120
LeafNodeType **const mNodes
Definition: MeshToVolume.h:1131
const size_t * offsetsNextZ() const
Definition: MeshToVolume.h:825
Base class for tree-traversal iterators over all leaf nodes (but not leaf voxels)
Definition: TreeIterator.h:1235
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:1928
SyncVoxelMask(std::vector< LeafNodeType * > &nodes, const bool *changedNodeMask, bool *changedVoxelMask)
Definition: MeshToVolume.h:1171
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2798
#define OPENVDB_LOG_DEBUG(message)
In debug builds only, log a debugging message of the form 'someVar << "text" << .....
Definition: logging.h:290
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1220
void setValueOn(const Coord &xyz, const ValueType &value)
Set the value of the voxel at the given coordinates and mark the voxel as active.
Definition: ValueAccessor.h:293
static Coord floor(const Vec3< T > &xyz)
Return the largest integer coordinates that are not greater than xyz (node centered conversion).
Definition: Coord.h:83
float Sqrt(float x)
Return the square root of a floating-point value.
Definition: Math.h:715
const size_t * offsetsPrevZ() const
Definition: MeshToVolume.h:826
OPENVDB_API 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...
Base class for tree-traversal iterators over tile and voxel values.
Definition: TreeIterator.h:665
Convert polygonal meshes that consist of quads and/or triangles into signed or unsigned distance fiel...
Real GodunovsNormSqrd(bool isOutside, Real dP_xm, Real dP_xp, Real dP_ym, Real dP_yp, Real dP_zm, Real dP_zp)
Definition: FiniteDifference.h:353
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:2809
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:4008
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:665
typename Int32TreeType::LeafNodeType Int32LeafNodeType
Definition: MeshToVolume.h:2373
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:1370
bool isValueOn(const Coord &xyz) const
Return the active state of the voxel at the given coordinates.
Definition: ValueAccessor.h:264
static bool check(const ValueType v)
Definition: MeshToVolume.h:1764
SweepExteriorSign(Axis axis, const std::vector< size_t > &startNodeIndices, ConnectivityTable &connectivity)
Definition: MeshToVolume.h:845
#define OPENVDB_THROW(exception, message)
Definition: Exceptions.h:109
bool probeValue(const Coord &xyz, ValueType &value) const
Return the active state of the voxel as well as its value.
Definition: ValueAccessor.h:267
const Vec3T & max() const
Return a const reference to the maximum point of this bounding box.
Definition: BBox.h:91
EdgeData operator+(const T &) const
Definition: MeshToVolume.h:482
bool isExactlyEqual(const T0 &a, const T1 &b)
Return true if a is exactly equal to b.
Definition: Math.h:395
const size_t * offsetsNextY() const
Definition: MeshToVolume.h:822
void releaseLeafNodes(TreeType &tree)
Definition: MeshToVolume.h:1839
Ptr copy() const
Definition: Transform.h:77
math::Vec4< Index32 > Vec4I
Definition: Types.h:95
Vec3< double > Vec3d
Definition: Vec3.h:679
Efficient multi-threaded replacement of the background values in tree.
void maskNodeInternalNeighbours(const Index pos, bool(&mask)[26])
Definition: MeshToVolume.h:1562
const ValueType mValue
Definition: MeshToVolume.h:1149
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:2985
Definition: Mat.h:197
const Coord & max() const
Definition: Coord.h:338
DiffLeafNodeMask(const TreeType &rhsTree, std::vector< BoolLeafNodeType * > &lhsNodes)
Definition: MeshToVolume.h:2207
std::vector< Int32LeafNodeType * > & newIndexNodes()
Definition: MeshToVolume.h:2582
bool wasInterrupted(T *i, int percent=-1)
Definition: NullInterrupter.h:76
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1141
static bool check(const ValueType v)
Definition: MeshToVolume.h:1711
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:2914
LeafNodeConnectivityTable(TreeType &tree)
Definition: MeshToVolume.h:784
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:1369
typename TreeType::template ValueConverter< Int32 >::Type Int32TreeType
Definition: MeshToVolume.h:1930
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:1169
ConstructVoxelMask(BoolTreeType &maskTree, const TreeType &tree, std::vector< LeafNodeType * > &nodes)
Definition: MeshToVolume.h:2261
Vec3< T > cross(const Vec3< T > &v) const
Return the cross product of "this" vector and v;.
Definition: Vec3.h:245
const ValueT & getValue() const
Return the tile or voxel value to which this iterator is currently pointing.
Definition: TreeIterator.h:741
TBB body object to voxelize a mesh of triangles and/or quads into a collection of VDB grids,...
Definition: MeshToVolume.h:1925
bool const *const mChangedNodeMask
Definition: MeshToVolume.h:1198
Int32TreeType *const mIndexTree
Definition: MeshToVolume.h:1812
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1993
tbb::enumerable_thread_specific< typename VoxelizationDataType::Ptr > DataTable
Definition: MeshToVolume.h:1982
Signed (x, y, z) 32-bit integer coordinates.
Definition: Coord.h:51
GridType::Ptr meshToVolume(Interrupter &interrupter, 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)
Convert polygonal meshes that consist of quads and/or triangles into signed or unsigned distance fiel...
Definition: MeshToVolume.h:3093
MeshToVolumeFlags
Mesh to volume conversion flags.
Definition: MeshToVolume.h:88
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:853
SeedFillExteriorSign(std::vector< LeafNodeType * > &nodes, bool *changedNodeMask)
Definition: MeshToVolume.h:1116
int32_t Int32
Definition: Types.h:63
LeafNodeType **const mNodes
Definition: MeshToVolume.h:680
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:1856
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:222
Definition: Math.h:858
LeafNodeType **const mNodes
Definition: MeshToVolume.h:1753
TreeType *const mTree
Definition: MeshToVolume.h:2755
Extracts and stores voxel edge intersection data from a mesh.
Definition: MeshToVolume.h:461
void join(ConstructVoxelMask &rhs)
Definition: MeshToVolume.h:2354
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:695
bool operator<(const Tuple< SIZE, T0 > &t0, const Tuple< SIZE, T1 > &t1)
Definition: Tuple.h:207
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:1709
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1719
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:728
const size_t * offsetsPrevY() const
Definition: MeshToVolume.h:823
std::vector< LeafNodeType * > & updatedDistNodes()
Definition: MeshToVolume.h:2580
Defined various multi-threaded utility functions for trees.
ConnectivityTable *const mConnectivity
Definition: MeshToVolume.h:1357
Definition: Tree.h:203
Definition: Types.h:277
bool isInside(const Coord &xyz) const
Return true if point (x, y, z) is inside this bounding box.
Definition: Coord.h:404
LeafNodeType **const mNodes
Definition: MeshToVolume.h:702
Tree< typename RootNodeType::template ValueConverter< Int32 >::Type > Type
Definition: Tree.h:224
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:782
Renormalize(const TreeType &tree, const std::vector< LeafNodeType * > &nodes, ValueType *buffer, ValueType voxelSize)
Definition: MeshToVolume.h:2916
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:672
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2202
std::unique_ptr< bool[]> MaskArray
Definition: MeshToVolume.h:1375
bool operator<(const Fragment &rhs) const
Definition: MeshToVolume.h:2389
Int32TreeType indexTree
Definition: MeshToVolume.h:1952
uint32_t Index32
Definition: Types.h:59
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:688
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2913
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:1114
typename TreeType::template ValueConverter< Int32 >::Type Int32TreeType
Definition: MeshToVolume.h:1762
static const Real LEVEL_SET_HALF_WIDTH
Definition: Types.h:283
bool *const mChangedNodeMask
Definition: MeshToVolume.h:1358
Definition: Types.h:276
GridType::Ptr meshToLevelSet(Interrupter &interrupter, const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, const std::vector< Vec4I > &quads, float halfWidth=float(LEVEL_SET_HALF_WIDTH))
Adds support for a interrupter callback used to cancel the conversion.
Definition: MeshToVolume.h:3590
void run(bool threaded=true)
Definition: MeshToVolume.h:3760
Definition: MeshToVolume.h:102
math::Transform const *const mXform
Definition: MeshToVolume.h:571
const std::vector< LeafNodeType * > & nodes() const
Definition: MeshToVolume.h:816
void clear() override
Remove all nodes from this cache, then reinsert the root node.
Definition: ValueAccessor.h:431
bool traceVoxelLine(LeafNodeType &node, Index pos, Index step) const
Definition: MeshToVolume.h:929
std::pair< PointArray, MaskArray > LocalData
Definition: MeshToVolume.h:1376
std::vector< Int32LeafNodeType * > & updatedIndexNodes()
Definition: MeshToVolume.h:2583
LeafNodeType **const mNodes
Definition: MeshToVolume.h:1810
Axis
Definition: Math.h:856
QuadAndTriangleDataAdapter(const std::vector< PointType > &points, const std::vector< PolygonType > &polygons)
Definition: MeshToVolume.h:194
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition: version.h:136
OPENVDB_API const Coord COORD_OFFSETS[26]
coordinate offset table for neighboring voxels
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:841
bool isZero(const Type &x)
Return true if x is exactly equal to zero.
Definition: Math.h:308
ExpandNarrowband(std::vector< BoolLeafNodeType * > &maskNodes, BoolTreeType &maskTree, TreeType &distTree, Int32TreeType &indexTree, const MeshDataAdapter &mesh, ValueType exteriorBandWidth, ValueType interiorBandWidth, ValueType voxelSize)
Definition: MeshToVolume.h:2394
RestoreOrigin(std::vector< LeafNodeType * > &nodes, const Coord *coordinates)
Definition: MeshToVolume.h:690
bool *const mNodeMask
Definition: MeshToVolume.h:1359
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:605
float mYDist
Definition: MeshToVolume.h:492
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:2213
size_t pointCount() const
Definition: MeshToVolume.h:213
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:2889
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:2837
bool *const mChangedVoxelMask
Definition: MeshToVolume.h:1199
bool processY(const size_t n, bool firstFace) const
Definition: MeshToVolume.h:1281
Propagate the signs of distance values from the active voxels in the narrow band to the inactive valu...
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:4021
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:1208
bool processX(const size_t n, bool firstFace) const
Definition: MeshToVolume.h:1319
std::vector< LeafNodeType * > *const mNodes
Definition: MeshToVolume.h:2756
float mXDist
Definition: MeshToVolume.h:492
EdgeData operator-(const T &) const
Definition: MeshToVolume.h:483
const Coord & min() const
Definition: Coord.h:337
bool *const mChangedNodeMask
Definition: MeshToVolume.h:1132
Internal edge data type.
Definition: MeshToVolume.h:468
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:711
const ValueType & getValue(const Coord &xyz) const
Return the value of the voxel at the given coordinates.
Definition: ValueAccessor.h:257
bool scanFill(LeafNodeType &node)
Definition: MeshToVolume.h:1041
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:842
RemoveSelfIntersectingSurface(std::vector< LeafNodeType * > &nodes, TreeType &distTree, Int32TreeType &indexTree)
Definition: MeshToVolume.h:1766
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:1761
Definition: Exceptions.h:40
Axis-aligned bounding box of signed integer coordinates.
Definition: Coord.h:264
MinCombine(std::vector< LeafNodeType * > &nodes, const ValueType *buffer)
Definition: MeshToVolume.h:2980
Accessor getAccessor()
Definition: MeshToVolume.h:523
bool processZ(const size_t n, bool firstFace) const
Definition: MeshToVolume.h:1243
ComputeIntersectingVoxelSign(std::vector< LeafNodeType * > &distNodes, const TreeType &distTree, const Int32TreeType &indexTree, const MeshDataAdapter &mesh)
Definition: MeshToVolume.h:1379
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1824
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:593
ExpandNarrowband(const ExpandNarrowband &rhs, tbb::split)
Definition: MeshToVolume.h:2419
typename TreeType::template ValueConverter< Int32 >::Type Int32TreeType
Definition: MeshToVolume.h:591
std::unique_ptr< VoxelizationData > Ptr
Definition: MeshToVolume.h:1927
size_t vertexCount(size_t n) const
Vertex count for polygon n.
Definition: MeshToVolume.h:216
Index32 mZPrim
Definition: MeshToVolume.h:493
typename Int32TreeType::LeafNodeType Int32LeafNodeType
Definition: MeshToVolume.h:1372
static ValueType epsilon()
Definition: MeshToVolume.h:578
UnionValueMasks(std::vector< LeafNodeTypeA * > &nodesA, std::vector< LeafNodeTypeB * > &nodesB)
Definition: MeshToVolume.h:2235
ReleaseChildNodes(NodeType **nodes)
Definition: MeshToVolume.h:1822
void maxComponent(const Coord &other)
Perform a component-wise maximum with the other Coord.
Definition: Coord.h:210
typename TreeType::template ValueConverter< unsigned char >::Type UCharTreeType
Definition: MeshToVolume.h:1931
Definition: Transform.h:66
std::vector< LeafNodeType * > & newDistNodes()
Definition: MeshToVolume.h:2579
void expand(ValueType padding)
Pad this bounding box with the specified padding.
Definition: Coord.h:422
CombineLeafNodes(TreeType &lhsDistTree, Int32TreeType &lhsIdxTree, LeafNodeType **rhsDistNodes, Int32LeafNodeType **rhsIdxNodes)
Definition: MeshToVolume.h:596
const std::enable_if<!VecTraits< T >::IsVec, T >::type & min(const T &a, const T &b)
Definition: Composite.h:129
EdgeData operator-() const
Definition: MeshToVolume.h:484
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:549
TreeType & tree()
Definition: MeshToVolume.h:3703
VoxelizePolygons(DataTable &dataTable, const MeshDataAdapter &mesh, Interrupter *interrupter=nullptr)
Definition: MeshToVolume.h:1984
MeshToVoxelEdgeData()
Definition: MeshToVolume.h:4001
FillArray(ValueType *array, const ValueType v)
Definition: MeshToVolume.h:1139
BoolTreeType & newMaskTree()
Definition: MeshToVolume.h:2577
void clearAllAccessors()
Clear all registered accessors.
Definition: Tree.h:1547
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2370
Dummy NOOP interrupter class defining interface.
Definition: NullInterrupter.h:52
LeafIter beginLeaf()
Return an iterator over all leaf nodes in this tree.
Definition: Tree.h:1179
void operator()() const
Definition: MeshToVolume.h:1866
FloatTreeAcc distAcc
Definition: MeshToVolume.h:1950
void operator()() const
Definition: MeshToVolume.h:2747
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1393
Axis-aligned bounding box.
Definition: BBox.h:50
typename TreeType::template ValueConverter< bool >::Type BoolTreeType
Definition: MeshToVolume.h:2374
void combineData(DistTreeType &lhsDist, IndexTreeType &lhsIdx, DistTreeType &rhsDist, IndexTreeType &rhsIdx)
Definition: MeshToVolume.h:1895
typename LeafNodeType::NodeMaskType NodeMaskType
Definition: MeshToVolume.h:2371
ValidateIntersectingVoxels(TreeType &tree, std::vector< LeafNodeType * > &nodes)
Definition: MeshToVolume.h:1713
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2256
static Coord min()
Return the smallest possible coordinate.
Definition: Coord.h:70
const Vec3T & min() const
Return a const reference to the minimum point of this bounding box.
Definition: BBox.h:89
const std::enable_if<!VecTraits< T >::IsVec, T >::type & max(const T &a, const T &b)
Definition: Composite.h:133
LeafNodeT * touchLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z). If no such node exists,...
Definition: ValueAccessor.h:386
typename BoolTreeType::LeafNodeType BoolLeafNodeType
Definition: MeshToVolume.h:2375
std::shared_ptr< T > SharedPtr
Definition: Types.h:139
typename BoolTreeType::LeafNodeType BoolLeafNodeType
Definition: MeshToVolume.h:2205
UCharTreeType primIdTree
Definition: MeshToVolume.h:1955
GridType::Ptr meshToUnsignedDistanceField(Interrupter &interrupter, const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, const std::vector< Vec4I > &quads, float bandWidth)
Adds support for a interrupter callback used to cancel the conversion.
Definition: MeshToVolume.h:3652
MeshToVoxelEdgeData::EdgeData Abs(const MeshToVoxelEdgeData::EdgeData &x)
Definition: MeshToVolume.h:3680
typename RootNodeType::LeafNodeType LeafNodeType
Definition: Tree.h:212
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2881
size_t findNeighbourNode(tree::ValueAccessor< const TreeType > &acc, const Coord &start, const Coord &step) const
Definition: MeshToVolume.h:751
math::Vec3< Index32 > Vec3I
Definition: Types.h:80
const size_t * offsetsNextX() const
Definition: MeshToVolume.h:819
static Coord max()
Return the largest possible coordinate.
Definition: Coord.h:73
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:230
StashOriginAndStoreOffset(std::vector< LeafNodeType * > &nodes, Coord *coordinates)
Definition: MeshToVolume.h:667
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2740
void join(GenEdgeData &rhs)
Definition: MeshToVolume.h:3771
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:280
GridType::Ptr meshToSignedDistanceField(Interrupter &interrupter, const openvdb::math::Transform &xform, const std::vector< Vec3s > &points, const std::vector< Vec3I > &triangles, const std::vector< Vec4I > &quads, float exBandWidth, float inBandWidth)
Adds support for a interrupter callback used to cancel the conversion.
Definition: MeshToVolume.h:3621
typename tree::ValueAccessor< TreeType > AccessorType
Definition: MeshToVolume.h:2201
const LeafNodeT * probeConstLeaf(const Coord &xyz) const
Return a pointer to the leaf node that contains voxel (x, y, z), or nullptr if no such node exists.
Definition: ValueAccessor.h:422
void operator()(const tbb::blocked_range< size_t > &range)
Definition: MeshToVolume.h:2278
void traceExteriorBoundaries(FloatTreeT &tree)
Traces the exterior voxel boundary of closed objects in the input volume tree. Exterior voxels are ma...
Definition: MeshToVolume.h:3016
bool operator>(const Tuple< SIZE, T0 > &t0, const Tuple< SIZE, T1 > &t1)
Definition: Tuple.h:219
SeedPoints(ConnectivityTable &connectivity, bool *changedNodeMask, bool *nodeMask, bool *changedVoxelMask)
Definition: MeshToVolume.h:1211
TransformPoints(const PointType *pointsIn, PointType *pointsOut, const math::Transform &xform)
Definition: MeshToVolume.h:543
Coord const *const mCoordinates
Definition: MeshToVolume.h:703
typename Int32TreeType::LeafNodeType Int32LeafNodeType
Definition: MeshToVolume.h:594
Definition: Math.h:859
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1774
GenEdgeData(const std::vector< Vec3s > &pointList, const std::vector< Vec4I > &polygonList)
Definition: MeshToVolume.h:3734
void addLeaf(LeafNodeT *leaf)
Add the specified leaf to this tree, possibly creating a child branch in the process....
Definition: ValueAccessor.h:367
EdgeData(float dist=1.0)
Definition: MeshToVolume.h:469
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:1708
ConstructVoxelMask(ConstructVoxelMask &rhs, tbb::split)
Definition: MeshToVolume.h:2270
void expandNarrowband(TreeType &distTree, Int32TreeType &indexTree, BoolTreeType &maskTree, std::vector< typename BoolTreeType::LeafNodeType * > &maskNodes, const MeshDataAdapter &mesh, typename TreeType::ValueType exteriorBandWidth, typename TreeType::ValueType interiorBandWidth, typename TreeType::ValueType voxelSize)
Definition: MeshToVolume.h:2762
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:188
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:1113
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:2925
void minComponent(const Coord &other)
Perform a component-wise minimum with the other Coord.
Definition: Coord.h:202
typename BoolTreeType::LeafNodeType BoolLeafNodeType
Definition: MeshToVolume.h:2259
Vec3< float > Vec3s
Definition: Vec3.h:678
OffsetValues(std::vector< LeafNodeType * > &nodes, ValueType offset)
Definition: MeshToVolume.h:2884
size_t polygonCount() const
Definition: MeshToVolume.h:212
UCharTreeAcc primIdAcc
Definition: MeshToVolume.h:1956
float mZDist
Definition: MeshToVolume.h:492
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:1168
_RootNodeType RootNodeType
Definition: Tree.h:209
AddNodes(TreeType &tree, std::vector< LeafNodeType * > &nodes)
Definition: MeshToVolume.h:2742
NodeType **const mNodes
Definition: MeshToVolume.h:1833
unsigned char getNewPrimId()
Definition: MeshToVolume.h:1958
typename TreeType::LeafNodeType LeafNodeType
Definition: MeshToVolume.h:2977
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:1122
ComputeNodeConnectivity(const TreeType &tree, const Coord *coordinates, size_t *offsets, size_t numNodes, const CoordBBox &bbox)
Definition: MeshToVolume.h:713
Contiguous quad and triangle data adapter class.
Definition: MeshToVolume.h:192
Int32TreeAcc indexAcc
Definition: MeshToVolume.h:1953
PointType const *const mPointsIn
Definition: MeshToVolume.h:569
std::vector< LeafNodeType * > & nodes()
Definition: MeshToVolume.h:815
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:2799
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:1207
StealUniqueLeafNodes(TreeType &lhsTree, TreeType &rhsTree, std::vector< LeafNodeType * > &overlappingNodes)
Definition: MeshToVolume.h:1858
bool checkNeighbours(const Coord &ijk, AccessorType &acc, bool(&mask)[26])
Definition: MeshToVolume.h:1693
bool *const mChangedVoxelMask
Definition: MeshToVolume.h:1360
OPENVDB_API const Index32 INVALID_IDX
void merge(Tree &other, MergePolicy=MERGE_ACTIVE_STATES)
Efficiently merge another tree into this tree using one of several schemes.
Definition: Tree.h:1864
Index32 mXPrim
Definition: MeshToVolume.h:493
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:4178
NodeType * getNode()
Return the cached node of type NodeType. [Mainly for internal use].
Definition: ValueAccessor.h:342
void clear()
Remove all tiles from this tree and all nodes other than the root node.
Definition: Tree.h:1488
Partitions points into BucketLog2Dim aligned buckets using a parallel radix-based sorting algorithm.
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: MeshToVolume.h:2847
Type Pow2(Type x)
Return x2.
Definition: Math.h:502
Coord offsetBy(Int32 dx, Int32 dy, Int32 dz) const
Definition: Coord.h:118
LeafNodeType **const mNodes
Definition: MeshToVolume.h:1197
typename TreeType::ValueType ValueType
Definition: MeshToVolume.h:2882
static ValueType minNarrowBandWidth()
Definition: MeshToVolume.h:579
typename TreeType::template ValueConverter< bool >::Type BoolTreeType
Definition: MeshToVolume.h:2204
Definition: Mat4.h:51
void seedFill(LeafNodeType &node)
Definition: MeshToVolume.h:965