OpenVDB  3.0.0
Morphology.h
Go to the documentation of this file.
1 //
3 // Copyright (c) 2012-2014 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 //
45 
46 #ifndef OPENVDB_TOOLS_MORPHOLOGY_HAS_BEEN_INCLUDED
47 #define OPENVDB_TOOLS_MORPHOLOGY_HAS_BEEN_INCLUDED
48 
49 #include <openvdb/Types.h>
50 #include <openvdb/Grid.h>
51 #include <openvdb/math/Math.h> // for isApproxEqual()
52 #include <openvdb/tree/TreeIterator.h>
53 #include <openvdb/tree/ValueAccessor.h>
54 #include <openvdb/tree/LeafManager.h>
55 #include <boost/scoped_array.hpp>
56 #include <boost/bind.hpp>
57 #include "Prune.h"// for pruneLevelSet
58 #include "ValueTransformer.h" // for foreach()
59 
60 namespace openvdb {
62 namespace OPENVDB_VERSION_NAME {
63 namespace tools {
64 
82 
83 
96 template<typename TreeType> OPENVDB_STATIC_SPECIALIZATION
97 inline void dilateVoxels(TreeType& tree,
98  int iterations = 1,
100 
113 template<typename TreeType> OPENVDB_STATIC_SPECIALIZATION
114 inline void dilateVoxels(tree::LeafManager<TreeType>& manager,
115  int iterations = 1,
117 
118 
120 template<typename TreeType> OPENVDB_STATIC_SPECIALIZATION
126 inline void erodeVoxels(TreeType& tree,
127  int iterations=1,
129 
130 template<typename TreeType> OPENVDB_STATIC_SPECIALIZATION
131 inline void erodeVoxels(tree::LeafManager<TreeType>& manager,
132  int iterations = 1,
135 
136 
139 template<typename GridOrTree>
140 inline void activate(
141  GridOrTree&,
142  const typename GridOrTree::ValueType& value,
143  const typename GridOrTree::ValueType& tolerance = zeroVal<typename GridOrTree::ValueType>()
144 );
145 
146 
149 template<typename GridOrTree>
150 inline void deactivate(
151  GridOrTree&,
152  const typename GridOrTree::ValueType& value,
153  const typename GridOrTree::ValueType& tolerance = zeroVal<typename GridOrTree::ValueType>()
154 );
155 
156 
158 
159 
161 template<Index Log2Dim> struct DimToWord {};
162 template<> struct DimToWord<3> { typedef uint8_t Type; };
163 template<> struct DimToWord<4> { typedef uint16_t Type; };
164 template<> struct DimToWord<5> { typedef uint32_t Type; };
165 template<> struct DimToWord<6> { typedef uint64_t Type; };
166 
167 
169 
170 
171 template<typename TreeType>
173 {
174 public:
176 
177  Morphology(TreeType& tree):
178  mOwnsManager(true), mManager(new ManagerType(tree)), mAcc(tree), mSteps(1) {}
179  Morphology(ManagerType* mgr):
180  mOwnsManager(false), mManager(mgr), mAcc(mgr->tree()), mSteps(1) {}
181  virtual ~Morphology() { if (mOwnsManager) delete mManager; }
182 
184  void dilateVoxels6();
186  void dilateVoxels18();
188  void dilateVoxels26();
189  void dilateVoxels(int iterations = 1, NearestNeighbors nn = NN_FACE);
190 
192  void erodeVoxels6() { mSteps = 1; this->doErosion(NN_FACE); }
194  void erodeVoxels18() { mSteps = 1; this->doErosion(NN_FACE_EDGE); }
196  void erodeVoxels26() { mSteps = 1; this->doErosion(NN_FACE_EDGE_VERTEX); }
197  void erodeVoxels(int iterations = 1, NearestNeighbors nn = NN_FACE)
198  {
199  mSteps = iterations;
200  this->doErosion(nn);
201  }
202 
203 protected:
204 
205  void doErosion(NearestNeighbors nn);
206 
207  typedef typename TreeType::LeafNodeType LeafType;
208  typedef typename LeafType::NodeMaskType MaskType;
210 
211  const bool mOwnsManager;
212  ManagerType* mManager;
213  AccessorType mAcc;
214  int mSteps;
215 
216  static const int LEAF_DIM = LeafType::DIM;
217  static const int LEAF_LOG2DIM = LeafType::LOG2DIM;
219 
220  struct Neighbor {
221  LeafType* leaf;//null if a tile
222  bool init;//true if initialization is required
223  bool isOn;//true if an active tile
224  Neighbor() : leaf(NULL), init(true) {}
225  inline void clear() { leaf = NULL; init = true; }
226  template<int DX, int DY, int DZ>
227  void scatter(AccessorType& acc, const Coord &xyz, int indx, Word mask)
228  {
229  if (init) {
230  init = false;
231  Coord orig = xyz.offsetBy(DX*LEAF_DIM, DY*LEAF_DIM, DZ*LEAF_DIM);
232  leaf = acc.probeLeaf(orig);
233  if (leaf==NULL && !acc.isValueOn(orig)) leaf = acc.touchLeaf(orig);
234  }
235 #ifndef _MSC_VER // Visual C++ doesn't guarantee thread-safe initialization of local statics
236  static
237 #endif
238  const int N = (LEAF_DIM - 1)*(DY + DX*LEAF_DIM);
239  if (leaf) leaf->getValueMask().template getWord<Word>(indx-N) |= mask;
240  }
241 
242  template<int DX, int DY, int DZ>
243  Word gather(AccessorType& acc, const Coord &xyz, int indx)
244  {
245  if (init) {
246  init = false;
247  Coord orig = xyz.offsetBy(DX*LEAF_DIM, DY*LEAF_DIM, DZ*LEAF_DIM);
248  leaf = acc.probeLeaf(orig);
249  isOn = leaf ? false : acc.isValueOn(orig);
250  }
251 #ifndef _MSC_VER // Visual C++ doesn't guarantee thread-safe initialization of local statics
252  static
253 #endif
254  const int N = (LEAF_DIM -1 )*(DY + DX*LEAF_DIM);
255  return leaf ? leaf->getValueMask().template getWord<Word>(indx-N)
256  : isOn ? ~Word(0) : Word(0);
257  }
258  };// Neighbor
259 
260  struct LeafCache
261  {
262  LeafCache(size_t n, TreeType& tree) : size(n), leafs(new LeafType*[n]), acc(tree)
263  {
264  onTile.setValuesOn();
265  this->clear();
266  }
267  ~LeafCache() { delete [] leafs; }
268  LeafType*& operator[](int offset) { return leafs[offset]; }
269  inline void clear() { for (size_t i=0; i<size; ++i) leafs[i]=NULL; }
270  inline void setOrigin(const Coord& xyz) { origin = &xyz; }
271  inline void scatter(int n, int indx)
272  {
273  assert(leafs[n]);
274  leafs[n]->getValueMask().template getWord<Word>(indx) |= mask;
275  }
276  template<int DX, int DY, int DZ>
277  inline void scatter(int n, int indx)
278  {
279  if (!leafs[n]) {
280  const Coord xyz = origin->offsetBy(DX*LEAF_DIM, DY*LEAF_DIM, DZ*LEAF_DIM);
281  leafs[n] = acc.probeLeaf(xyz);
282  if (!leafs[n]) leafs[n] = acc.isValueOn(xyz) ? &onTile : acc.touchLeaf(xyz);
283  }
284  this->scatter(n, indx - (LEAF_DIM - 1)*(DY + DX*LEAF_DIM));
285  }
286  inline Word gather(int n, int indx)
287  {
288  assert(leafs[n]);
289  return leafs[n]->getValueMask().template getWord<Word>(indx);
290  }
291  template<int DX, int DY, int DZ>
292  inline Word gather(int n, int indx)
293  {
294  if (!leafs[n]) {
295  const Coord xyz = origin->offsetBy(DX*LEAF_DIM, DY*LEAF_DIM, DZ*LEAF_DIM);
296  leafs[n] = acc.probeLeaf(xyz);
297  if (!leafs[n]) leafs[n] = acc.isValueOn(xyz) ? &onTile : &offTile;
298  }
299  return this->gather(n, indx - (LEAF_DIM -1 )*(DY + DX*LEAF_DIM));
300  }
301  // Scatters in the xy face-directions relative to leaf i1
302  void scatterFacesXY(int x, int y, int i1, int n, int i2);
303 
304  // Scatters in the xy edge-directions relative to leaf i1
305  void scatterEdgesXY(int x, int y, int i1, int n, int i2);
306 
307  Word gatherFacesXY(int x, int y, int i1, int n, int i2);
308 
309  Word gatherEdgesXY(int x, int y, int i1, int n, int i2);
310 
311  const Coord* origin;
312  size_t size;
313  LeafType** leafs;
314  LeafType onTile, offTile;
315  AccessorType acc;
316  Word mask;
317  };// LeafCache
318 
319  struct ErodeVoxelsOp {
320  typedef tbb::blocked_range<size_t> RangeT;
321  ErodeVoxelsOp(std::vector<MaskType>& masks, ManagerType& manager)
322  : mTask(0), mSavedMasks(masks) , mManager(manager) {}
323  void runParallel(NearestNeighbors nn);
324  void operator()(const RangeT& r) const {mTask(const_cast<ErodeVoxelsOp*>(this), r);}
325  void erode6( const RangeT&) const;
326  void erode18(const RangeT&) const;
327  void erode26(const RangeT&) const;
328  private:
329  typedef typename boost::function<void (ErodeVoxelsOp*, const RangeT&)> FuncT;
330  FuncT mTask;
331  std::vector<MaskType>& mSavedMasks;
332  ManagerType& mManager;
333  };// ErodeVoxelsOp
334 
335  struct MaskManager {
336  MaskManager(std::vector<MaskType>& masks, ManagerType& manager)
337  : mMasks(masks) , mManager(manager), mSaveMasks(true) {}
338 
339  void save() { mSaveMasks = true; tbb::parallel_for(mManager.getRange(), *this); }
340  void update() { mSaveMasks = false; tbb::parallel_for(mManager.getRange(), *this); }
341  void operator()(const tbb::blocked_range<size_t>& range) const
342  {
343  if (mSaveMasks) {
344  for (size_t i = range.begin(); i < range.end(); ++i) {
345  mMasks[i] = mManager.leaf(i).getValueMask();
346  }
347  } else {
348  for (size_t i = range.begin(); i < range.end(); ++i) {
349  mManager.leaf(i).setValueMask(mMasks[i]);
350  }
351  }
352  }
353  private:
354  std::vector<MaskType>& mMasks;
355  ManagerType& mManager;
356  bool mSaveMasks;
357  };// MaskManager
358 
359  struct UpdateMasks {
360  UpdateMasks(const std::vector<MaskType>& masks, ManagerType& manager)
361  : mMasks(masks), mManager(manager) {}
362  void update() { tbb::parallel_for(mManager.getRange(), *this); }
363  void operator()(const tbb::blocked_range<size_t>& r) const {
364  for (size_t i=r.begin(); i<r.end(); ++i) mManager.leaf(i).setValueMask(mMasks[i]);
365  }
366  const std::vector<MaskType>& mMasks;
367  ManagerType& mManager;
368  };
369  struct CopyMasks {
370  CopyMasks(std::vector<MaskType>& masks, const ManagerType& manager)
371  : mMasks(masks), mManager(manager) {}
372  void copy() { tbb::parallel_for(mManager.getRange(), *this); }
373  void operator()(const tbb::blocked_range<size_t>& r) const {
374  for (size_t i=r.begin(); i<r.end(); ++i) mMasks[i]=mManager.leaf(i).getValueMask();
375  }
376  std::vector<MaskType>& mMasks;
377  const ManagerType& mManager;
378  };
379  void copyMasks(std::vector<MaskType>& a, const ManagerType& b) {CopyMasks c(a, b); c.copy();}
380 };// Morphology
381 
382 template<typename TreeType>
383 void
385 {
386  for (int i=0; i<iterations; ++i) {
387  switch (nn) {
388  case NN_FACE_EDGE: this->dilateVoxels18(); break;
389  case NN_FACE_EDGE_VERTEX: this->dilateVoxels26(); break;
390  default: this->dilateVoxels6();
391  }
392  }
393 }
394 
395 template<typename TreeType>
396 void
398 {
400  const int leafCount = static_cast<int>(mManager->leafCount());
401 
402  // Save the value masks of all leaf nodes.
403  std::vector<MaskType> savedMasks(leafCount);
404  this->copyMasks(savedMasks, *mManager);
405  LeafCache cache(7, mManager->tree());
406  for (int leafIdx = 0; leafIdx < leafCount; ++leafIdx) {
407  const MaskType& oldMask = savedMasks[leafIdx];//original bit-mask of current leaf node
408  cache[0] = &mManager->leaf(leafIdx);
409  cache.setOrigin(cache[0]->origin());
410  for (int x = 0; x < LEAF_DIM; ++x ) {
411  for (int y = 0, n = (x << LEAF_LOG2DIM); y < LEAF_DIM; ++y, ++n) {
412  // Extract the portion of the original mask that corresponds to a row in z.
413  if (const Word w = oldMask.template getWord<Word>(n)) {
414 
415  // Dilate the current leaf in the +z and -z direction
416  cache.mask = Word(w | (w>>1) | (w<<1)); cache.scatter(0, n);
417 
418  // Dilate into neighbor leaf in the -z direction
419  if ( (cache.mask = Word(w<<(LEAF_DIM-1))) ) {
420  cache.template scatter< 0, 0,-1>(1, n);
421  }
422  // Dilate into neighbor leaf in the +z direction
423  if ( (cache.mask = Word(w>>(LEAF_DIM-1))) ) {
424  cache.template scatter< 0, 0, 1>(2, n);
425  }
426  // Dilate in the xy-face directions relative to the center leaf
427  cache.mask = w; cache.scatterFacesXY(x, y, 0, n, 3);
428  }
429  }// loop over y
430  }//loop over x
431  cache.clear();
432  }//loop over leafs
433 
434  mManager->rebuildLeafArray();
435 }//dilateVoxels6
436 
437 template<typename TreeType>
438 void
440 {
442  const int leafCount = static_cast<int>(mManager->leafCount());
443 
444  // Save the value masks of all leaf nodes.
445  std::vector<MaskType> savedMasks(leafCount);
446  this->copyMasks(savedMasks, *mManager);
447  LeafCache cache(19, mManager->tree());
448  Coord orig_mz, orig_pz;//origins of neighbor leaf nodes in the -z and +z directions
449  for (int leafIdx = 0; leafIdx < leafCount; ++leafIdx) {
450  const MaskType& oldMask = savedMasks[leafIdx];//original bit-mask of current leaf node
451  cache[0] = &mManager->leaf(leafIdx);
452  orig_mz = cache[0]->origin().offsetBy(0, 0, -LEAF_DIM);
453  orig_pz = cache[0]->origin().offsetBy(0, 0, LEAF_DIM);
454  for (int x = 0; x < LEAF_DIM; ++x ) {
455  for (int y = 0, n = (x << LEAF_LOG2DIM); y < LEAF_DIM; ++y, ++n) {
456  if (const Word w = oldMask.template getWord<Word>(n)) {
457  {
458  cache.mask = Word(w | (w>>1) | (w<<1));
459  cache.setOrigin(cache[0]->origin());
460  cache.scatter(0, n);
461  cache.scatterFacesXY(x, y, 0, n, 3);
462  cache.mask = w;
463  cache.scatterEdgesXY(x, y, 0, n, 3);
464  }
465  if ( (cache.mask = Word(w<<(LEAF_DIM-1))) ) {
466  cache.setOrigin(cache[0]->origin());
467  cache.template scatter< 0, 0,-1>(1, n);
468  cache.setOrigin(orig_mz);
469  cache.scatterFacesXY(x, y, 1, n, 11);
470  }
471  if ( (cache.mask = Word(w>>(LEAF_DIM-1))) ) {
472  cache.setOrigin(cache[0]->origin());
473  cache.template scatter< 0, 0, 1>(2, n);
474  cache.setOrigin(orig_pz);
475  cache.scatterFacesXY(x, y, 2, n, 15);
476  }
477  }
478  }// loop over y
479  }//loop over x
480  cache.clear();
481  }//loop over leafs
482 
483  mManager->rebuildLeafArray();
484 }// dilateVoxels18
485 
486 template<typename TreeType>
487 void
489 {
491  const int leafCount = static_cast<int>(mManager->leafCount());
492 
493  // Save the value masks of all leaf nodes.
494  std::vector<MaskType> savedMasks(leafCount);
495  this->copyMasks(savedMasks, *mManager);
496  LeafCache cache(27, mManager->tree());
497  Coord orig_mz, orig_pz;//origins of neighbor leaf nodes in the -z and +z directions
498  for (int leafIdx = 0; leafIdx < leafCount; ++leafIdx) {
499  const MaskType& oldMask = savedMasks[leafIdx];//original bit-mask of current leaf node
500  cache[0] = &mManager->leaf(leafIdx);
501  orig_mz = cache[0]->origin().offsetBy(0, 0, -LEAF_DIM);
502  orig_pz = cache[0]->origin().offsetBy(0, 0, LEAF_DIM);
503  for (int x = 0; x < LEAF_DIM; ++x ) {
504  for (int y = 0, n = (x << LEAF_LOG2DIM); y < LEAF_DIM; ++y, ++n) {
505  if (const Word w = oldMask.template getWord<Word>(n)) {
506  {
507  cache.mask = Word(w | (w>>1) | (w<<1));
508  cache.setOrigin(cache[0]->origin());
509  cache.scatter(0, n);
510  cache.scatterFacesXY(x, y, 0, n, 3);
511  cache.scatterEdgesXY(x, y, 0, n, 3);
512  }
513  if ( (cache.mask = Word(w<<(LEAF_DIM-1))) ) {
514  cache.setOrigin(cache[0]->origin());
515  cache.template scatter< 0, 0,-1>(1, n);
516  cache.setOrigin(orig_mz);
517  cache.scatterFacesXY(x, y, 1, n, 11);
518  cache.scatterEdgesXY(x, y, 1, n, 11);
519  }
520  if ( (cache.mask = Word(w>>(LEAF_DIM-1))) ) {
521  cache.setOrigin(cache[0]->origin());
522  cache.template scatter< 0, 0, 1>(2, n);
523  cache.setOrigin(orig_pz);
524  cache.scatterFacesXY(x, y, 2, n, 19);
525  cache.scatterEdgesXY(x, y, 2, n, 19);
526  }
527  }
528  }// loop over y
529  }//loop over x
530  cache.clear();
531  }//loop over leafs
532 
533  mManager->rebuildLeafArray();
534 }// dilateVoxels26
535 
536 template<typename TreeType>
538 scatterFacesXY(int x, int y, int i1, int n, int i2)
539 {
540  // dilate current leaf or neighbor in the -x direction
541  if (x > 0) {
542  this->scatter(i1, n-LEAF_DIM);
543  } else {
544  this->template scatter<-1, 0, 0>(i2, n);
545  }
546  // dilate current leaf or neighbor in the +x direction
547  if (x < LEAF_DIM-1) {
548  this->scatter(i1, n+LEAF_DIM);
549  } else {
550  this->template scatter< 1, 0, 0>(i2+1, n);
551  }
552  // dilate current leaf or neighbor in the -y direction
553  if (y > 0) {
554  this->scatter(i1, n-1);
555  } else {
556  this->template scatter< 0,-1, 0>(i2+2, n);
557  }
558  // dilate current leaf or neighbor in the +y direction
559  if (y < LEAF_DIM-1) {
560  this->scatter(i1, n+1);
561  } else {
562  this->template scatter< 0, 1, 0>(i2+3, n);
563  }
564 }
565 
566 template<typename TreeType>
567 void
569 scatterEdgesXY(int x, int y, int i1, int n, int i2)
570 {
571  if (x > 0) {
572  if (y > 0) {
573  this->scatter(i1, n-LEAF_DIM-1);
574  } else {
575  this->template scatter< 0,-1, 0>(i2+2, n-LEAF_DIM);
576  }
577  if (y < LEAF_DIM-1) {
578  this->scatter(i1, n-LEAF_DIM+1);
579  } else {
580  this->template scatter< 0, 1, 0>(i2+3, n-LEAF_DIM);
581  }
582  } else {
583  if (y < LEAF_DIM-1) {
584  this->template scatter<-1, 0, 0>(i2 , n+1);
585  } else {
586  this->template scatter<-1, 1, 0>(i2+7, n );
587  }
588  if (y > 0) {
589  this->template scatter<-1, 0, 0>(i2 , n-1);
590  } else {
591  this->template scatter<-1,-1, 0>(i2+4, n );
592  }
593  }
594  if (x < LEAF_DIM-1) {
595  if (y > 0) {
596  this->scatter(i1, n+LEAF_DIM-1);
597  } else {
598  this->template scatter< 0,-1, 0>(i2+2, n+LEAF_DIM);
599  }
600  if (y < LEAF_DIM-1) {
601  this->scatter(i1, n+LEAF_DIM+1);
602  } else {
603  this->template scatter< 0, 1, 0>(i2+3, n+LEAF_DIM);
604  }
605  } else {
606  if (y > 0) {
607  this->template scatter< 1, 0, 0>(i2+1, n-1);
608  } else {
609  this->template scatter< 1,-1, 0>(i2+6, n );
610  }
611  if (y < LEAF_DIM-1) {
612  this->template scatter< 1, 0, 0>(i2+1, n+1);
613  } else {
614  this->template scatter< 1, 1, 0>(i2+5, n );
615  }
616  }
617 }
618 
619 template<typename TreeType>
620 inline void
623 {
624  switch (nn) {
625  case NN_FACE_EDGE:
626  mTask = boost::bind(&ErodeVoxelsOp::erode18, _1, _2);
627  break;
628  case NN_FACE_EDGE_VERTEX:
629  mTask = boost::bind(&ErodeVoxelsOp::erode26, _1, _2);
630  break;
631  default:
632  mTask = boost::bind(&ErodeVoxelsOp::erode6, _1, _2);
633  }
634  tbb::parallel_for(mManager.getRange(), *this);
635 }
636 
637 template<typename TreeType>
638 inline typename Morphology<TreeType>::Word
640 gatherFacesXY(int x, int y, int i1, int n, int i2)
641 {
642  // erode current leaf or neighbor in negative x-direction
643  Word w = x>0 ? this->gather(i1,n-LEAF_DIM) : this->template gather<-1,0,0>(i2, n);
644 
645  // erode current leaf or neighbor in positive x-direction
646  w = Word(w & (x<LEAF_DIM-1?this->gather(i1,n+LEAF_DIM):this->template gather<1,0,0>(i2+1,n)));
647 
648  // erode current leaf or neighbor in negative y-direction
649  w = Word(w & (y>0 ? this->gather(i1, n-1) : this->template gather<0,-1,0>(i2+2, n)));
650 
651  // erode current leaf or neighbor in positive y-direction
652  w = Word(w & (y<LEAF_DIM-1 ? this->gather(i1, n+1) : this->template gather<0,1,0>(i2+3, n)));
653 
654  return w;
655 }
656 
657 template<typename TreeType>
658 inline
661 gatherEdgesXY(int x, int y, int i1, int n, int i2)
662 {
663  Word w = ~Word(0);
664 
665  if (x > 0) {
666  w &= y > 0 ? this->gather(i1, n-LEAF_DIM-1) :
667  this->template gather< 0,-1, 0>(i2+2, n-LEAF_DIM);
668  w &= y < LEAF_DIM-1 ? this->gather(i1, n-LEAF_DIM+1) :
669  this->template gather< 0, 1, 0>(i2+3, n-LEAF_DIM);
670  } else {
671  w &= y < LEAF_DIM-1 ? this->template gather<-1, 0, 0>(i2 , n+1):
672  this->template gather<-1, 1, 0>(i2+7, n );
673  w &= y > 0 ? this->template gather<-1, 0, 0>(i2 , n-1):
674  this->template gather<-1,-1, 0>(i2+4, n );
675  }
676  if (x < LEAF_DIM-1) {
677  w &= y > 0 ? this->gather(i1, n+LEAF_DIM-1) :
678  this->template gather< 0,-1, 0>(i2+2, n+LEAF_DIM);
679  w &= y < LEAF_DIM-1 ? this->gather(i1, n+LEAF_DIM+1) :
680  this->template gather< 0, 1, 0>(i2+3, n+LEAF_DIM);
681  } else {
682  w &= y > 0 ? this->template gather< 1, 0, 0>(i2+1, n-1):
683  this->template gather< 1,-1, 0>(i2+6, n );
684  w &= y < LEAF_DIM-1 ? this->template gather< 1, 0, 0>(i2+1, n+1):
685  this->template gather< 1, 1, 0>(i2+5, n );
686  }
687 
688  return w;
689 }
690 
691 template <typename TreeType>
692 void
694 erode6(const RangeT& range) const
695 {
696  LeafCache cache(7, mManager.tree());
697  for (size_t leafIdx = range.begin(); leafIdx < range.end(); ++leafIdx) {
698  cache[0] = &mManager.leaf(leafIdx);
699  if (cache[0]->isEmpty()) continue;
700  cache.setOrigin(cache[0]->origin());
701  MaskType& newMask = mSavedMasks[leafIdx];//original bit-mask of current leaf node
702  for (int x = 0; x < LEAF_DIM; ++x ) {
703  for (int y = 0, n = (x << LEAF_LOG2DIM); y < LEAF_DIM; ++y, ++n) {
704  // Extract the portion of the original mask that corresponds to a row in z.
705  if (Word& w = newMask.template getWord<Word>(n)) {
706 
707  // erode in two z directions (this is first since it uses the original w)
708  w = Word(w &
709  (Word(w<<1 | (cache.template gather<0,0,-1>(1, n)>>(LEAF_DIM-1))) &
710  Word(w>>1 | (cache.template gather<0,0, 1>(2, n)<<(LEAF_DIM-1)))));
711 
712  w = Word(w & cache.gatherFacesXY(x, y, 0, n, 3));
713  }
714  }// loop over y
715  }//loop over x
716  cache.clear();
717  }//loop over leafs
718 }
719 
720 template <typename TreeType>
721 void
723 erode18(const RangeT&) const
724 {
725  OPENVDB_THROW(RuntimeError, "tools::erode18 is not implemented yet!");
726 }
727 
728 template <typename TreeType>
729 void
731 erode26(const RangeT&) const
732 {
733  OPENVDB_THROW(RuntimeError, "tools::erode26 is not implemented yet!");
734 }
735 
736 
737 template<typename TreeType>
738 void
740 {
742  const size_t leafCount = mManager->leafCount();
743 
744  // Save the value masks of all leaf nodes.
745  std::vector<MaskType> savedMasks(leafCount);
746  this->copyMasks(savedMasks, *mManager);
747  UpdateMasks a(savedMasks, *mManager);
748  ErodeVoxelsOp erode(savedMasks, *mManager);
749 
750  for (int i = 0; i < mSteps; ++i) {
751  erode.runParallel(nn);
752  a.update();
753  }
754 
755  tools::pruneLevelSet(mManager->tree());
756 }
757 
758 
760 
761 
762 template<typename TreeType>
765 {
766  if (iterations > 0 ) {
767  Morphology<TreeType> m(&manager);
768  m.dilateVoxels(iterations, nn);
769  }
770 }
771 
772 template<typename TreeType>
774 dilateVoxels(TreeType& tree, int iterations, NearestNeighbors nn)
775 {
776  if (iterations > 0 ) {
777  Morphology<TreeType> m(tree);
778  m.dilateVoxels(iterations, nn);
779  }
780 }
781 
782 template<typename TreeType>
785 {
786  if (iterations > 0 ) {
787  Morphology<TreeType> m(&manager);
788  m.erodeVoxels(iterations, nn);
789  }
790 }
791 
792 template<typename TreeType>
794 erodeVoxels(TreeType& tree, int iterations, NearestNeighbors nn)
795 {
796  if (iterations > 0 ) {
797  Morphology<TreeType> m(tree);
798  m.erodeVoxels(iterations, nn);
799  }
800 }
801 
802 
804 
805 
806 namespace activation {
807 
808 template<typename TreeType>
810 {
811 public:
812  typedef typename TreeType::ValueType ValueT;
813 
814  ActivationOp(bool state, const ValueT& val, const ValueT& tol)
815  : mActivate(state)
816  , mValue(val)
817  , mTolerance(tol)
818  {}
819 
820  void operator()(const typename TreeType::ValueOnIter& it) const
821  {
822  if (math::isApproxEqual(*it, mValue, mTolerance)) {
823  it.setValueOff();
824  }
825  }
826 
827  void operator()(const typename TreeType::ValueOffIter& it) const
828  {
829  if (math::isApproxEqual(*it, mValue, mTolerance)) {
830  it.setActiveState(/*on=*/true);
831  }
832  }
833 
834  void operator()(const typename TreeType::LeafIter& lit) const
835  {
836  typedef typename TreeType::LeafNodeType LeafT;
837  LeafT& leaf = *lit;
838  if (mActivate) {
839  for (typename LeafT::ValueOffIter it = leaf.beginValueOff(); it; ++it) {
840  if (math::isApproxEqual(*it, mValue, mTolerance)) {
841  leaf.setValueOn(it.pos());
842  }
843  }
844  } else {
845  for (typename LeafT::ValueOnIter it = leaf.beginValueOn(); it; ++it) {
846  if (math::isApproxEqual(*it, mValue, mTolerance)) {
847  leaf.setValueOff(it.pos());
848  }
849  }
850  }
851  }
852 
853 private:
854  bool mActivate;
855  const ValueT mValue, mTolerance;
856 }; // class ActivationOp
857 
858 } // namespace activation
859 
860 
861 template<typename GridOrTree>
862 inline void
863 activate(GridOrTree& gridOrTree, const typename GridOrTree::ValueType& value,
864  const typename GridOrTree::ValueType& tolerance)
865 {
866  typedef TreeAdapter<GridOrTree> Adapter;
867  typedef typename Adapter::TreeType TreeType;
868 
869  TreeType& tree = Adapter::tree(gridOrTree);
870 
871  activation::ActivationOp<TreeType> op(/*activate=*/true, value, tolerance);
872 
873  // Process all leaf nodes in parallel.
874  foreach(tree.beginLeaf(), op);
875 
876  // Process all other inactive values serially (because changing active states
877  // is not thread-safe unless no two threads modify the same node).
878  typename TreeType::ValueOffIter it = tree.beginValueOff();
879  it.setMaxDepth(tree.treeDepth() - 2);
880  foreach(it, op, /*threaded=*/false);
881 }
882 
883 
884 template<typename GridOrTree>
885 inline void
886 deactivate(GridOrTree& gridOrTree, const typename GridOrTree::ValueType& value,
887  const typename GridOrTree::ValueType& tolerance)
888 {
889  typedef TreeAdapter<GridOrTree> Adapter;
890  typedef typename Adapter::TreeType TreeType;
891 
892  TreeType& tree = Adapter::tree(gridOrTree);
893 
894  activation::ActivationOp<TreeType> op(/*activate=*/false, value, tolerance);
895 
896  // Process all leaf nodes in parallel.
897  foreach(tree.beginLeaf(), op);
898 
899  // Process all other active values serially (because changing active states
900  // is not thread-safe unless no two threads modify the same node).
901  typename TreeType::ValueOnIter it = tree.beginValueOn();
902  it.setMaxDepth(tree.treeDepth() - 2);
903  foreach(it, op, /*threaded=*/false);
904 }
905 
906 } // namespace tools
907 } // namespace OPENVDB_VERSION_NAME
908 } // namespace openvdb
909 
910 #endif // OPENVDB_TOOLS_MORPHOLOGY_HAS_BEEN_INCLUDED
911 
912 // Copyright (c) 2012-2014 DreamWorks Animation LLC
913 // All rights reserved. This software is distributed under the
914 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
void operator()(const typename TreeType::LeafIter &lit) const
Definition: Morphology.h:834
LeafNodeT * probeLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z), or NULL if no such node exists...
Definition: ValueAccessor.h:378
void scatter(int n, int indx)
Definition: Morphology.h:271
~LeafCache()
Definition: Morphology.h:267
Morphology(TreeType &tree)
Definition: Morphology.h:177
void operator()(const typename TreeType::ValueOffIter &it) const
Definition: Morphology.h:827
Word gather(int n, int indx)
Definition: Morphology.h:286
int mSteps
Definition: Morphology.h:214
const ManagerType & mManager
Definition: Morphology.h:377
void operator()(const typename TreeType::ValueOnIter &it) const
Definition: Morphology.h:820
LeafType onTile
Definition: Morphology.h:314
uint8_t Type
Definition: Morphology.h:162
bool isOn
Definition: Morphology.h:223
CopyMasks(std::vector< MaskType > &masks, const ManagerType &manager)
Definition: Morphology.h:370
virtual ~Morphology()
Definition: Morphology.h:181
Definition: Morphology.h:172
void copyMasks(std::vector< MaskType > &a, const ManagerType &b)
Definition: Morphology.h:379
DimToWord< LEAF_LOG2DIM >::Type Word
Definition: Morphology.h:218
void erodeVoxels(int iterations=1, NearestNeighbors nn=NN_FACE)
Definition: Morphology.h:197
uint32_t Type
Definition: Morphology.h:164
#define OPENVDB_THROW(exception, message)
Definition: Exceptions.h:97
void clear()
Definition: Morphology.h:225
void operator()(const tbb::blocked_range< size_t > &r) const
Definition: Morphology.h:363
tree::ValueAccessor< TreeType > AccessorType
Definition: Morphology.h:209
This class manages a linear array of pointers to a given tree's leaf nodes, as well as optional auxil...
Definition: LeafManager.h:109
tree::LeafManager< TreeType > ManagerType
Definition: Morphology.h:175
size_t size
Definition: Morphology.h:312
LeafCache(size_t n, TreeType &tree)
Definition: Morphology.h:262
RangeType getRange(size_t grainsize=1) const
Return a tbb::blocked_range of leaf array indices.
Definition: LeafManager.h:342
LeafType ** leafs
Definition: Morphology.h:313
void update()
Definition: Morphology.h:340
void runParallel(NearestNeighbors nn)
Definition: Morphology.h:622
NearestNeighbors
Voxel topology of nearest neighbors.
Definition: Morphology.h:81
Definition: Morphology.h:81
void save()
Definition: Morphology.h:339
LeafType * leaf
Definition: Morphology.h:221
Defined various multi-threaded utility functions for trees.
AccessorType acc
Definition: Morphology.h:315
Word gather(AccessorType &acc, const Coord &xyz, int indx)
Definition: Morphology.h:243
Morphology(ManagerType *mgr)
Definition: Morphology.h:179
ErodeVoxelsOp(std::vector< MaskType > &masks, ManagerType &manager)
Definition: Morphology.h:321
OPENVDB_STATIC_SPECIALIZATION void dilateVoxels(tree::LeafManager< TreeType > &manager, int iterations=1, NearestNeighbors nn=NN_FACE)
Topologically dilate all leaf-level active voxels in a tree using one of three nearest neighbor conne...
Definition: Morphology.h:764
const std::vector< MaskType > & mMasks
Definition: Morphology.h:366
UpdateMasks(const std::vector< MaskType > &masks, ManagerType &manager)
Definition: Morphology.h:360
Definition: Exceptions.h:86
ManagerType * mManager
Definition: Morphology.h:212
bool init
Definition: Morphology.h:222
#define OPENVDB_VERSION_NAME
Definition: version.h:43
AccessorType mAcc
Definition: Morphology.h:213
bool isValueOn(const Coord &xyz) const
Return the active state of the voxel at the given coordinates.
Definition: ValueAccessor.h:217
void erodeVoxels18()
Face- and edge-adjacent erosion pattern.
Definition: Morphology.h:194
ManagerType & mManager
Definition: Morphology.h:367
LeafType *& operator[](int offset)
Definition: Morphology.h:268
void scatter(AccessorType &acc, const Coord &xyz, int indx, Word mask)
Definition: Morphology.h:227
TreeType::LeafNodeType LeafType
Definition: Morphology.h:207
void setOrigin(const Coord &xyz)
Definition: Morphology.h:270
LeafType::NodeMaskType MaskType
Definition: Morphology.h:208
void scatter(int n, int indx)
Definition: Morphology.h:277
Definition: Exceptions.h:39
OPENVDB_STATIC_SPECIALIZATION void erodeVoxels(tree::LeafManager< TreeType > &manager, int iterations=1, NearestNeighbors nn=NN_FACE)
Topologically erode all leaf-level active voxels in the given tree.
Definition: Morphology.h:784
bool isApproxEqual(const Hermite &lhs, const Hermite &rhs)
Definition: Hermite.h:470
Word mask
Definition: Morphology.h:316
LeafNodeT * touchLeaf(const Coord &xyz)
Return a pointer to the leaf node that contains voxel (x, y, z). If no such node exists, create one, but preserve the values and active states of all voxels.
Definition: ValueAccessor.h:347
void deactivate(GridOrTree &, const typename GridOrTree::ValueType &value, const typename GridOrTree::ValueType &tolerance=zeroVal< typename GridOrTree::ValueType >())
Mark as inactive any active tiles or voxels in the given grid or tree whose values are equal to value...
Definition: Morphology.h:886
ActivationOp(bool state, const ValueT &val, const ValueT &tol)
Definition: Morphology.h:814
MaskManager(std::vector< MaskType > &masks, ManagerType &manager)
Definition: Morphology.h:336
void dilateVoxels(int iterations=1, NearestNeighbors nn=NN_FACE)
Definition: Morphology.h:384
const Coord * origin
Definition: Morphology.h:311
uint16_t Type
Definition: Morphology.h:163
void update()
Definition: Morphology.h:362
Mapping from a Log2Dim to a data type of size 2^Log2Dim bits.
Definition: Morphology.h:161
void operator()(const RangeT &r) const
Definition: Morphology.h:324
#define OPENVDB_STATIC_SPECIALIZATION
Macro for determining if there are sufficient C++0x/C++11 features.
Definition: Platform.h:89
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:369
tbb::blocked_range< size_t > RangeT
Definition: Morphology.h:320
void operator()(const tbb::blocked_range< size_t > &r) const
Definition: Morphology.h:373
void operator()(const tbb::blocked_range< size_t > &range) const
Definition: Morphology.h:341
void activate(GridOrTree &, const typename GridOrTree::ValueType &value, const typename GridOrTree::ValueType &tolerance=zeroVal< typename GridOrTree::ValueType >())
Mark as active any inactive tiles or voxels in the given grid or tree whose values are equal to value...
Definition: Morphology.h:863
This adapter allows code that is templated on a Tree type to accept either a Tree type or a Grid type...
Definition: Grid.h:858
Definition: Morphology.h:81
const bool mOwnsManager
Definition: Morphology.h:211
Word gather(int n, int indx)
Definition: Morphology.h:292
uint64_t Type
Definition: Morphology.h:165
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:71
std::vector< MaskType > & mMasks
Definition: Morphology.h:376
void erodeVoxels26()
Face-, edge- and vertex-adjacent erosion pattern.
Definition: Morphology.h:196
void copy()
Definition: Morphology.h:372
LeafType & leaf(size_t leafIdx) const
Return a pointer to the leaf node at index leafIdx in the array.
Definition: LeafManager.h:318
void erodeVoxels6()
Face-adjacent erosion pattern.
Definition: Morphology.h:192
TreeType::ValueType ValueT
Definition: Morphology.h:812
Neighbor()
Definition: Morphology.h:224
void clear()
Definition: Morphology.h:269