HDK
PoissonSolver.h
Go to the documentation of this file.
1 // Copyright Contributors to the OpenVDB Project
3 //
4 /// @file PoissonSolver.h
5 ///
6 /// @authors D.J. Hill, Peter Cucka
7 ///
8 /// @brief Solve Poisson's equation &nabla;<sup><small>2</small></sup><i>x</i> = <i>b</i>
9 /// for <i>x</i>, where @e b is a vector comprising the values of all of the active voxels
10 /// in a grid.
11 ///
12 /// @par Example:
13 /// Solve for the pressure in a cubic tank of liquid, assuming uniform boundary conditions:
14 /// @code
15 /// FloatTree source(/*background=*/0.0f);
16 /// // Activate voxels to indicate that they contain liquid.
17 /// source.fill(CoordBBox(Coord(0, -10, 0), Coord(10, 0, 10)), /*value=*/0.0f);
18 ///
19 /// math::pcg::State state = math::pcg::terminationDefaults<float>();
20 /// FloatTree::Ptr solution = tools::poisson::solve(source, state);
21 /// @endcode
22 ///
23 /// @par Example:
24 /// Solve for the pressure, <i>P</i>, in a cubic tank of liquid that is open at the top.
25 /// Boundary conditions are <i>P</i>&nbsp;=&nbsp;0 at the top,
26 /// &part;<i>P</i>/&part;<i>y</i>&nbsp;=&nbsp;&minus;1 at the bottom
27 /// and &part;<i>P</i>/&part;<i>x</i>&nbsp;=&nbsp;0 at the sides:
28 /// <pre>
29 /// P = 0
30 /// +--------+ (N,0,N)
31 /// /| /|
32 /// (0,0,0) +--------+ |
33 /// | | | | dP/dx = 0
34 /// dP/dx = 0 | +------|-+
35 /// |/ |/
36 /// (0,-N,0) +--------+ (N,-N,0)
37 /// dP/dy = -1
38 /// </pre>
39 /// @code
40 /// const int N = 10;
41 /// DoubleTree source(/*background=*/0.0);
42 /// // Activate voxels to indicate that they contain liquid.
43 /// source.fill(CoordBBox(Coord(0, -N, 0), Coord(N, 0, N)), /*value=*/0.0);
44 ///
45 /// auto boundary = [](const openvdb::Coord& ijk, const openvdb::Coord& neighbor,
46 /// double& source, double& diagonal)
47 /// {
48 /// if (neighbor.x() == ijk.x() && neighbor.z() == ijk.z()) {
49 /// if (neighbor.y() < ijk.y()) source -= 1.0;
50 /// else diagonal -= 1.0;
51 /// }
52 /// };
53 ///
54 /// math::pcg::State state = math::pcg::terminationDefaults<double>();
55 /// util::NullInterrupter interrupter;
56 ///
57 /// DoubleTree::Ptr solution = tools::poisson::solveWithBoundaryConditions(
58 /// source, boundary, state, interrupter);
59 /// @endcode
60
61 #ifndef OPENVDB_TOOLS_POISSONSOLVER_HAS_BEEN_INCLUDED
62 #define OPENVDB_TOOLS_POISSONSOLVER_HAS_BEEN_INCLUDED
63
64 #include <openvdb/Types.h>
67 #include <openvdb/tree/Tree.h>
69 #include "Morphology.h" // for erodeVoxels
70
71
72 namespace openvdb {
74 namespace OPENVDB_VERSION_NAME {
75 namespace tools {
76 namespace poisson {
77
78 // This type should be at least as wide as math::pcg::SizeType.
79 using VIndex = Int32;
80
81 /// The type of a matrix used to represent a three-dimensional %Laplacian operator
83
84
85 //@{
86 /// @brief Solve &nabla;<sup><small>2</small></sup><i>x</i> = <i>b</i> for <i>x</i>,
87 /// where @e b is a vector comprising the values of all of the active voxels
88 /// in the input tree.
89 /// @return a new tree, with the same active voxel topology as the input tree,
90 /// whose voxel values are the elements of the solution vector <i>x</i>.
91 /// @details On input, the State object should specify convergence criteria
92 /// (minimum error and maximum number of iterations); on output, it gives
93 /// the actual termination conditions.
94 /// @details The solution is computed using the conjugate gradient method
95 /// with (where possible) incomplete Cholesky preconditioning, falling back
96 /// to Jacobi preconditioning.
97 /// @sa solveWithBoundaryConditions
98 template<typename TreeType>
99 inline typename TreeType::Ptr
100 solve(const TreeType&, math::pcg::State&, bool staggered = false);
101
102 template<typename TreeType, typename Interrupter>
103 inline typename TreeType::Ptr
104 solve(const TreeType&, math::pcg::State&, Interrupter&, bool staggered = false);
105 //@}
106
107
108 //@{
109 /// @brief Solve &nabla;<sup><small>2</small></sup><i>x</i> = <i>b</i> for <i>x</i>
110 /// with user-specified boundary conditions, where @e b is a vector comprising
111 /// the values of all of the active voxels in the input tree or domain mask if provided
112 /// @return a new tree, with the same active voxel topology as the input tree,
113 /// whose voxel values are the elements of the solution vector <i>x</i>.
114 /// @details On input, the State object should specify convergence criteria
115 /// (minimum error and maximum number of iterations); on output, it gives
116 /// the actual termination conditions.
117 /// @details The solution is computed using the conjugate gradient method with
118 /// the specified type of preconditioner (default: incomplete Cholesky),
119 /// falling back to Jacobi preconditioning if necessary.
120 /// @details Each thread gets its own copy of the BoundaryOp, which should be
121 /// a functor of the form
122 /// @code
123 /// struct BoundaryOp {
124 /// using ValueType = LaplacianMatrix::ValueType;
125 /// void operator()(
126 /// const Coord& ijk, // coordinates of a boundary voxel
127 /// const Coord& ijkNeighbor, // coordinates of an exterior neighbor of ijk
128 /// ValueType& source, // element of b corresponding to ijk
129 /// ValueType& diagonal // element of Laplacian matrix corresponding to ijk
130 /// ) const;
131 /// };
132 /// @endcode
133 /// The functor is called for each of the exterior neighbors of each boundary voxel @ijk,
134 /// and it must specify a boundary condition for @ijk by modifying one or both of two
135 /// provided values: the entry in the source vector @e b corresponding to @ijk and
136 /// the weighting coefficient for @ijk in the Laplacian operator matrix.
137 ///
138 /// @sa solve
139 template<typename TreeType, typename BoundaryOp, typename Interrupter>
140 inline typename TreeType::Ptr
142  const TreeType&,
143  const BoundaryOp&,
145  Interrupter&,
146  bool staggered = false);
147
148 template<
149  typename PreconditionerType,
150  typename TreeType,
151  typename BoundaryOp,
152  typename Interrupter>
153 inline typename TreeType::Ptr
155  const TreeType&,
156  const BoundaryOp&,
158  Interrupter&,
159  bool staggered = false);
160
161 template<
162  typename PreconditionerType,
163  typename TreeType,
164  typename DomainTreeType,
165  typename BoundaryOp,
166  typename Interrupter>
167 inline typename TreeType::Ptr
169  const TreeType&,
170  const DomainTreeType&,
171  const BoundaryOp&,
173  Interrupter&,
174  bool staggered = false);
175 //@}
176
177
178 /// @name Low-level functions
179 //@{
180 // The following are low-level routines that can be used to assemble custom solvers.
181
182 /// @brief Overwrite each active voxel in the given scalar tree
183 /// with a sequential index, starting from zero.
184 template<typename VIndexTreeType>
185 inline void populateIndexTree(VIndexTreeType&);
186
187 /// @brief Iterate over the active voxels of the input tree and for each one
188 /// assign its index in the iteration sequence to the corresponding voxel
189 /// of an integer-valued output tree.
190 template<typename TreeType>
191 inline typename TreeType::template ValueConverter<VIndex>::Type::Ptr
192 createIndexTree(const TreeType&);
193
194
195 /// @brief Return a vector of the active voxel values of the scalar-valued @a source tree.
196 /// @details The <i>n</i>th element of the vector corresponds to the voxel whose value
197 /// in the @a index tree is @e n.
198 /// @param source a tree with a scalar value type
199 /// @param index a tree of the same configuration as @a source but with
200 /// value type VIndex that maps voxels to elements of the output vector
201 template<typename VectorValueType, typename SourceTreeType>
204  const SourceTreeType& source,
205  const typename SourceTreeType::template ValueConverter<VIndex>::Type& index);
206
207
208 /// @brief Return a tree with the same active voxel topology as the @a index tree
209 /// but whose voxel values are taken from the the given vector.
210 /// @details The voxel whose value in the @a index tree is @e n gets assigned
211 /// the <i>n</i>th element of the vector.
212 /// @param index a tree with value type VIndex that maps voxels to elements of @a values
213 /// @param values a vector of values with which to populate the active voxels of the output tree
214 /// @param background the value for the inactive voxels of the output tree
215 template<typename TreeValueType, typename VIndexTreeType, typename VectorValueType>
216 inline typename VIndexTreeType::template ValueConverter<TreeValueType>::Type::Ptr
219  const VIndexTreeType& index,
220  const TreeValueType& background);
221
222
223 /// @brief Generate a sparse matrix of the index-space (&Delta;<i>x</i> = 1) %Laplacian operator
224 /// using second-order finite differences.
225 /// @details This construction assumes homogeneous Dirichlet boundary conditions
226 /// (exterior grid points are zero).
227 template<typename BoolTreeType>
230  const typename BoolTreeType::template ValueConverter<VIndex>::Type& vectorIndexTree,
232  bool staggered = false);
233
234
235 /// @brief Generate a sparse matrix of the index-space (&Delta;<i>x</i> = 1) %Laplacian operator
236 /// with user-specified boundary conditions using second-order finite differences.
237 /// @details Each thread gets its own copy of @a boundaryOp, which should be
238 /// a functor of the form
239 /// @code
240 /// struct BoundaryOp {
241 /// using ValueType = LaplacianMatrix::ValueType;
242 /// void operator()(
243 /// const Coord& ijk, // coordinates of a boundary voxel
244 /// const Coord& ijkNeighbor, // coordinates of an exterior neighbor of ijk
245 /// ValueType& source, // element of source vector corresponding to ijk
246 /// ValueType& diagonal // element of Laplacian matrix corresponding to ijk
247 /// ) const;
248 /// };
249 /// @endcode
250 /// The functor is called for each of the exterior neighbors of each boundary voxel @ijk,
251 /// and it must specify a boundary condition for @ijk by modifying one or both of two
252 /// provided values: an entry in the given @a source vector corresponding to @ijk and
253 /// the weighting coefficient for @ijk in the %Laplacian matrix.
254 template<typename BoolTreeType, typename BoundaryOp>
257  const typename BoolTreeType::template ValueConverter<VIndex>::Type& vectorIndexTree,
259  const BoundaryOp& boundaryOp,
261  bool staggered = false);
262
263
264 /// @brief Dirichlet boundary condition functor
265 /// @details This is useful in describing fluid/air interfaces, where the pressure
266 /// of the air is assumed to be zero.
267 template<typename ValueType>
269  inline void operator()(const Coord&, const Coord&, ValueType&, ValueType& diag) const {
270  // Exterior neighbors are empty, so decrement the weighting coefficient
271  // as for interior neighbors but leave the source vector unchanged.
272  diag -= 1;
273  }
274 };
275
276 //@}
277
278
279 ////////////////////////////////////////
280
281
282 namespace internal {
283
284 /// @brief Functor for use with LeafManager::foreach() to populate an array
285 /// with per-leaf active voxel counts
286 template<typename LeafType>
288 {
290  LeafCountOp(VIndex* count_): count(count_) {}
291  void operator()(const LeafType& leaf, size_t leafIdx) const {
292  count[leafIdx] = static_cast<VIndex>(leaf.onVoxelCount());
293  }
294 };
295
296
297 /// @brief Functor for use with LeafManager::foreach() to populate
298 /// active leaf voxels with sequential indices
299 template<typename LeafType>
301 {
302  const VIndex* count;
303  LeafIndexOp(const VIndex* count_): count(count_) {}
304  void operator()(LeafType& leaf, size_t leafIdx) const {
305  VIndex idx = (leafIdx == 0) ? 0 : count[leafIdx - 1];
306  for (typename LeafType::ValueOnIter it = leaf.beginValueOn(); it; ++it) {
307  it.setValue(idx++);
308  }
309  }
310 };
311
312 } // namespace internal
313
314
315 template<typename VIndexTreeType>
316 inline void
317 populateIndexTree(VIndexTreeType& result)
318 {
319  using LeafT = typename VIndexTreeType::LeafNodeType;
320  using LeafMgrT = typename tree::LeafManager<VIndexTreeType>;
321
322  // Linearize the tree.
323  LeafMgrT leafManager(result);
324  const size_t leafCount = leafManager.leafCount();
325
326  if (leafCount == 0) return;
327
328  // Count the number of active voxels in each leaf node.
329  std::unique_ptr<VIndex[]> perLeafCount(new VIndex[leafCount]);
330  VIndex* perLeafCountPtr = perLeafCount.get();
331  leafManager.foreach(internal::LeafCountOp<LeafT>(perLeafCountPtr));
332
333  // The starting index for each leaf node is the total number
334  // of active voxels in all preceding leaf nodes.
335  for (size_t i = 1; i < leafCount; ++i) {
336  perLeafCount[i] += perLeafCount[i - 1];
337  }
338
339  // The last accumulated value should be the total of all active voxels.
340  assert(Index64(perLeafCount[leafCount-1]) == result.activeVoxelCount());
341
342  // Parallelize over the leaf nodes of the tree, storing a unique index
343  // in each active voxel.
344  leafManager.foreach(internal::LeafIndexOp<LeafT>(perLeafCountPtr));
345 }
346
347
348 template<typename TreeType>
349 inline typename TreeType::template ValueConverter<VIndex>::Type::Ptr
350 createIndexTree(const TreeType& tree)
351 {
352  using VIdxTreeT = typename TreeType::template ValueConverter<VIndex>::Type;
353
354  // Construct an output tree with the same active voxel topology as the input tree.
355  const VIndex invalidIdx = -1;
356  typename VIdxTreeT::Ptr result(
357  new VIdxTreeT(tree, /*background=*/invalidIdx, TopologyCopy()));
358
359  // All active voxels are degrees of freedom, including voxels contained in active tiles.
360  result->voxelizeActiveTiles();
361
362  populateIndexTree(*result);
363
364  return result;
365 }
366
367
368 ////////////////////////////////////////
369
370
371 namespace internal {
372
373 /// @brief Functor for use with LeafManager::foreach() to populate a vector
374 /// with the values of a tree's active voxels
375 template<typename VectorValueType, typename SourceTreeType>
377 {
378  using VIdxTreeT = typename SourceTreeType::template ValueConverter<VIndex>::Type;
379  using VIdxLeafT = typename VIdxTreeT::LeafNodeType;
380  using LeafT = typename SourceTreeType::LeafNodeType;
381  using TreeValueT = typename SourceTreeType::ValueType;
383
384  const SourceTreeType* tree;
386
387  CopyToVecOp(const SourceTreeType& t, VectorT& v): tree(&t), vector(&v) {}
388
389  void operator()(const VIdxLeafT& idxLeaf, size_t /*leafIdx*/) const
390  {
391  VectorT& vec = *vector;
392  if (const LeafT* leaf = tree->probeLeaf(idxLeaf.origin())) {
393  // If a corresponding leaf node exists in the source tree,
394  // copy voxel values from the source node to the output vector.
395  for (typename VIdxLeafT::ValueOnCIter it = idxLeaf.cbeginValueOn(); it; ++it) {
396  vec[*it] = leaf->getValue(it.pos());
397  }
398  } else {
399  // If no corresponding leaf exists in the source tree,
400  // fill the vector with a uniform value.
401  const TreeValueT& value = tree->getValue(idxLeaf.origin());
402  for (typename VIdxLeafT::ValueOnCIter it = idxLeaf.cbeginValueOn(); it; ++it) {
403  vec[*it] = value;
404  }
405  }
406  }
407 };
408
409 } // namespace internal
410
411
412 template<typename VectorValueType, typename SourceTreeType>
414 createVectorFromTree(const SourceTreeType& tree,
415  const typename SourceTreeType::template ValueConverter<VIndex>::Type& idxTree)
416 {
417  using VIdxTreeT = typename SourceTreeType::template ValueConverter<VIndex>::Type;
418  using VIdxLeafMgrT = tree::LeafManager<const VIdxTreeT>;
420
421  // Allocate the vector.
422  const size_t numVoxels = idxTree.activeVoxelCount();
423  typename VectorT::Ptr result(new VectorT(static_cast<math::pcg::SizeType>(numVoxels)));
424
425  // Parallelize over the leaf nodes of the index tree, filling the output vector
426  // with values from corresponding voxels of the source tree.
427  VIdxLeafMgrT leafManager(idxTree);
428  leafManager.foreach(internal::CopyToVecOp<VectorValueType, SourceTreeType>(tree, *result));
429
430  return result;
431 }
432
433
434 ////////////////////////////////////////
435
436
437 namespace internal {
438
439 /// @brief Functor for use with LeafManager::foreach() to populate a tree
440 /// with values from a vector
441 template<typename TreeValueType, typename VIndexTreeType, typename VectorValueType>
443 {
444  using OutTreeT = typename VIndexTreeType::template ValueConverter<TreeValueType>::Type;
445  using OutLeafT = typename OutTreeT::LeafNodeType;
446  using VIdxLeafT = typename VIndexTreeType::LeafNodeType;
448
449  const VectorT* vector;
451
452  CopyFromVecOp(const VectorT& v, OutTreeT& t): vector(&v), tree(&t) {}
453
454  void operator()(const VIdxLeafT& idxLeaf, size_t /*leafIdx*/) const
455  {
456  const VectorT& vec = *vector;
457  OutLeafT* leaf = tree->probeLeaf(idxLeaf.origin());
458  assert(leaf != nullptr);
459  for (typename VIdxLeafT::ValueOnCIter it = idxLeaf.cbeginValueOn(); it; ++it) {
460  leaf->setValueOnly(it.pos(), static_cast<TreeValueType>(vec[*it]));
461  }
462  }
463 };
464
465 } // namespace internal
466
467
468 template<typename TreeValueType, typename VIndexTreeType, typename VectorValueType>
469 inline typename VIndexTreeType::template ValueConverter<TreeValueType>::Type::Ptr
472  const VIndexTreeType& idxTree,
473  const TreeValueType& background)
474 {
475  using OutTreeT = typename VIndexTreeType::template ValueConverter<TreeValueType>::Type;
476  using VIdxLeafMgrT = typename tree::LeafManager<const VIndexTreeType>;
477
478  // Construct an output tree with the same active voxel topology as the index tree.
479  typename OutTreeT::Ptr result(new OutTreeT(idxTree, background, TopologyCopy()));
480  OutTreeT& tree = *result;
481
482  // Parallelize over the leaf nodes of the index tree, populating voxels
483  // of the output tree with values from the input vector.
484  VIdxLeafMgrT leafManager(idxTree);
485  leafManager.foreach(
487
488  return result;
489 }
490
491
492 ////////////////////////////////////////
493
494
495 namespace internal {
496
497 /// Functor for use with LeafManager::foreach() to populate a sparse %Laplacian matrix
498 template<typename BoolTreeType, typename BoundaryOp>
500 {
501  using VIdxTreeT = typename BoolTreeType::template ValueConverter<VIndex>::Type;
502  using VIdxLeafT = typename VIdxTreeT::LeafNodeType;
505
509  const BoundaryOp boundaryOp;
511
513  const BoolTreeType& mask, const BoundaryOp& op, VectorT& src):
515
516  void operator()(const VIdxLeafT& idxLeaf, size_t /*leafIdx*/) const
517  {
518  // Local accessors
520  typename tree::ValueAccessor<const VIdxTreeT> vectorIdx(*idxTree);
521
522  Coord ijk;
523  VIndex column;
524  const ValueT diagonal = -6.f, offDiagonal = 1.f;
525
526  // Loop over active voxels in this leaf.
527  for (typename VIdxLeafT::ValueOnCIter it = idxLeaf.cbeginValueOn(); it; ++it) {
528  assert(it.getValue() > -1);
529  const math::pcg::SizeType rowNum = static_cast<math::pcg::SizeType>(it.getValue());
530
532
533  ijk = it.getCoord();
534  if (interior.isValueOn(ijk)) {
535  // The current voxel is an interior voxel.
536  // All of its neighbors are in the solution domain.
537
538  // -x direction
539  row.setValue(vectorIdx.getValue(ijk.offsetBy(-1, 0, 0)), offDiagonal);
540  // -y direction
541  row.setValue(vectorIdx.getValue(ijk.offsetBy(0, -1, 0)), offDiagonal);
542  // -z direction
543  row.setValue(vectorIdx.getValue(ijk.offsetBy(0, 0, -1)), offDiagonal);
544  // diagonal
545  row.setValue(rowNum, diagonal);
546  // +z direction
547  row.setValue(vectorIdx.getValue(ijk.offsetBy(0, 0, 1)), offDiagonal);
548  // +y direction
549  row.setValue(vectorIdx.getValue(ijk.offsetBy(0, 1, 0)), offDiagonal);
550  // +x direction
551  row.setValue(vectorIdx.getValue(ijk.offsetBy(1, 0, 0)), offDiagonal);
552
553  } else {
554  // The current voxel is a boundary voxel.
555  // At least one of its neighbors is outside the solution domain.
556
557  ValueT modifiedDiagonal = 0.f;
558
559  // -x direction
560  if (vectorIdx.probeValue(ijk.offsetBy(-1, 0, 0), column)) {
561  row.setValue(column, offDiagonal);
562  modifiedDiagonal -= 1;
563  } else {
564  boundaryOp(ijk, ijk.offsetBy(-1, 0, 0), source->at(rowNum), modifiedDiagonal);
565  }
566  // -y direction
567  if (vectorIdx.probeValue(ijk.offsetBy(0, -1, 0), column)) {
568  row.setValue(column, offDiagonal);
569  modifiedDiagonal -= 1;
570  } else {
571  boundaryOp(ijk, ijk.offsetBy(0, -1, 0), source->at(rowNum), modifiedDiagonal);
572  }
573  // -z direction
574  if (vectorIdx.probeValue(ijk.offsetBy(0, 0, -1), column)) {
575  row.setValue(column, offDiagonal);
576  modifiedDiagonal -= 1;
577  } else {
578  boundaryOp(ijk, ijk.offsetBy(0, 0, -1), source->at(rowNum), modifiedDiagonal);
579  }
580  // +z direction
581  if (vectorIdx.probeValue(ijk.offsetBy(0, 0, 1), column)) {
582  row.setValue(column, offDiagonal);
583  modifiedDiagonal -= 1;
584  } else {
585  boundaryOp(ijk, ijk.offsetBy(0, 0, 1), source->at(rowNum), modifiedDiagonal);
586  }
587  // +y direction
588  if (vectorIdx.probeValue(ijk.offsetBy(0, 1, 0), column)) {
589  row.setValue(column, offDiagonal);
590  modifiedDiagonal -= 1;
591  } else {
592  boundaryOp(ijk, ijk.offsetBy(0, 1, 0), source->at(rowNum), modifiedDiagonal);
593  }
594  // +x direction
595  if (vectorIdx.probeValue(ijk.offsetBy(1, 0, 0), column)) {
596  row.setValue(column, offDiagonal);
597  modifiedDiagonal -= 1;
598  } else {
599  boundaryOp(ijk, ijk.offsetBy(1, 0, 0), source->at(rowNum), modifiedDiagonal);
600  }
601  // diagonal
602  row.setValue(rowNum, modifiedDiagonal);
603  }
604  } // end loop over voxels
605  }
606 };
607
608
609 // Stencil 1 is the correct stencil, but stencil 2 requires
610 // half as many comparisons and produces smoother results at boundaries.
611 //#define OPENVDB_TOOLS_POISSON_LAPLACIAN_STENCIL 1
612 #define OPENVDB_TOOLS_POISSON_LAPLACIAN_STENCIL 2
613
614 /// Functor for use with LeafManager::foreach() to populate a sparse %Laplacian matrix
615 template<typename VIdxTreeT, typename BoundaryOp>
617 {
618  using VIdxLeafT = typename VIdxTreeT::LeafNodeType;
621
623  const VIdxTreeT* idxTree;
624  const BoundaryOp boundaryOp;
626
627  ISLaplacianOp(LaplacianMatrix& m, const VIdxTreeT& idx, const BoundaryOp& op, VectorT& src):
628  laplacian(&m), idxTree(&idx), boundaryOp(op), source(&src) {}
629
630  void operator()(const VIdxLeafT& idxLeaf, size_t /*leafIdx*/) const
631  {
632  typename tree::ValueAccessor<const VIdxTreeT> vectorIdx(*idxTree);
633
634  const int kNumOffsets = 6;
635  const Coord ijkOffset[kNumOffsets] = {
636 #if OPENVDB_TOOLS_POISSON_LAPLACIAN_STENCIL == 1
637  Coord(-1,0,0), Coord(1,0,0), Coord(0,-1,0), Coord(0,1,0), Coord(0,0,-1), Coord(0,0,1)
638 #else
639  Coord(-2,0,0), Coord(2,0,0), Coord(0,-2,0), Coord(0,2,0), Coord(0,0,-2), Coord(0,0,2)
640 #endif
641  };
642
643  // For each active voxel in this leaf...
644  for (typename VIdxLeafT::ValueOnCIter it = idxLeaf.cbeginValueOn(); it; ++it) {
645  assert(it.getValue() > -1);
646
647  const Coord ijk = it.getCoord();
648  const math::pcg::SizeType rowNum = static_cast<math::pcg::SizeType>(it.getValue());
649
651
652  ValueT modifiedDiagonal = 0.f;
653
654  // For each of the neighbors of the voxel at (i,j,k)...
655  for (int dir = 0; dir < kNumOffsets; ++dir) {
656  const Coord neighbor = ijk + ijkOffset[dir];
657  VIndex column;
658  // For collocated vector grids, the central differencing stencil requires
659  // access to neighbors at a distance of two voxels in each direction
660  // (-x, +x, -y, +y, -z, +z).
661 #if OPENVDB_TOOLS_POISSON_LAPLACIAN_STENCIL == 1
662  const bool ijkIsInterior = (vectorIdx.probeValue(neighbor + ijkOffset[dir], column)
663  && vectorIdx.isValueOn(neighbor));
664 #else
665  const bool ijkIsInterior = vectorIdx.probeValue(neighbor, column);
666 #endif
667  if (ijkIsInterior) {
668  // If (i,j,k) is sufficiently far away from the exterior,
669  // set its weight to one and adjust the center weight accordingly.
670  row.setValue(column, 1.f);
671  modifiedDiagonal -= 1.f;
672  } else {
673  // If (i,j,k) is adjacent to or one voxel away from the exterior,
674  // invoke the boundary condition functor.
675  boundaryOp(ijk, neighbor, source->at(rowNum), modifiedDiagonal);
676  }
677  }
678  // Set the (possibly modified) weight for the voxel at (i,j,k).
679  row.setValue(rowNum, modifiedDiagonal);
680  }
681  }
682 };
683
684 } // namespace internal
685
686
687 template<typename BoolTreeType>
689 createISLaplacian(const typename BoolTreeType::template ValueConverter<VIndex>::Type& idxTree,
690  const BoolTreeType& interiorMask, bool staggered)
691 {
692  using ValueT = LaplacianMatrix::ValueType;
694  static_cast<math::pcg::SizeType>(idxTree.activeVoxelCount()));
696  return createISLaplacianWithBoundaryConditions(idxTree, interiorMask, op, unused, staggered);
697 }
698
699
700 template<typename BoolTreeType, typename BoundaryOp>
703  const typename BoolTreeType::template ValueConverter<VIndex>::Type& idxTree,
705  const BoundaryOp& boundaryOp,
707  bool staggered)
708 {
709  using VIdxTreeT = typename BoolTreeType::template ValueConverter<VIndex>::Type;
710  using VIdxLeafMgrT = typename tree::LeafManager<const VIdxTreeT>;
711
712  // The number of active voxels is the number of degrees of freedom.
713  const Index64 numDoF = idxTree.activeVoxelCount();
714
715  // Construct the matrix.
716  LaplacianMatrix::Ptr laplacianPtr(
717  new LaplacianMatrix(static_cast<math::pcg::SizeType>(numDoF)));
718  LaplacianMatrix& laplacian = *laplacianPtr;
719
720  // Populate the matrix using a second-order, 7-point CD stencil.
721  VIdxLeafMgrT idxLeafManager(idxTree);
722  if (staggered) {
724  laplacian, idxTree, interiorMask, boundaryOp, source));
725  } else {
726  idxLeafManager.foreach(internal::ISLaplacianOp<VIdxTreeT, BoundaryOp>(
727  laplacian, idxTree, boundaryOp, source));
728  }
729
730  return laplacianPtr;
731 }
732
733
734 ////////////////////////////////////////
735
736
737 template<typename TreeType>
738 inline typename TreeType::Ptr
739 solve(const TreeType& inTree, math::pcg::State& state, bool staggered)
740 {
741  util::NullInterrupter interrupter;
742  return solve(inTree, state, interrupter, staggered);
743 }
744
745
746 template<typename TreeType, typename Interrupter>
747 inline typename TreeType::Ptr
748 solve(const TreeType& inTree, math::pcg::State& state, Interrupter& interrupter, bool staggered)
749 {
751  return solveWithBoundaryConditions(inTree, boundaryOp, state, interrupter, staggered);
752 }
753
754
755 template<typename TreeType, typename BoundaryOp, typename Interrupter>
756 inline typename TreeType::Ptr
757 solveWithBoundaryConditions(const TreeType& inTree, const BoundaryOp& boundaryOp,
758  math::pcg::State& state, Interrupter& interrupter, bool staggered)
759 {
761  return solveWithBoundaryConditionsAndPreconditioner<DefaultPrecondT>(
762  inTree, boundaryOp, state, interrupter, staggered);
763 }
764
765
766 template<
767  typename PreconditionerType,
768  typename TreeType,
769  typename BoundaryOp,
770  typename Interrupter>
771 inline typename TreeType::Ptr
773  const TreeType& inTree,
774  const BoundaryOp& boundaryOp,
775  math::pcg::State& state,
776  Interrupter& interrupter,
777  bool staggered)
778 {
779  return solveWithBoundaryConditionsAndPreconditioner<PreconditionerType>(
780  /*source=*/inTree, /*domain mask=*/inTree, boundaryOp, state, interrupter, staggered);
781 }
782
783 template<
784  typename PreconditionerType,
785  typename TreeType,
786  typename DomainTreeType,
787  typename BoundaryOp,
788  typename Interrupter>
789 inline typename TreeType::Ptr
791  const TreeType& inTree,
793  const BoundaryOp& boundaryOp,
794  math::pcg::State& state,
795  Interrupter& interrupter,
796  bool staggered)
797 {
798  using TreeValueT = typename TreeType::ValueType;
799  using VecValueT = LaplacianMatrix::ValueType;
800  using VectorT = typename math::pcg::Vector<VecValueT>;
801  using VIdxTreeT = typename TreeType::template ValueConverter<VIndex>::Type;
802  using MaskTreeT = typename TreeType::template ValueConverter<bool>::Type;
803
804  // 1. Create a mapping from active voxels of the input tree to elements of a vector.
805  typename VIdxTreeT::ConstPtr idxTree = createIndexTree(domainMask);
806
807  // 2. Populate a vector with values from the input tree.
808  typename VectorT::Ptr b = createVectorFromTree<VecValueT>(inTree, *idxTree);
809
810  // 3. Create a mask of the interior voxels of the input tree (from the densified index tree).
811  /// @todo Is this really needed?
815
816  // 4. Create the Laplacian matrix.
818  *idxTree, *interiorMask, boundaryOp, *b, staggered);
819
820  // 5. Solve the Poisson equation.
821  laplacian->scale(-1.0); // matrix is negative-definite; solve -M x = -b
822  b->scale(-1.0);
823  typename VectorT::Ptr x(new VectorT(b->size(), zeroVal<VecValueT>()));
825  new PreconditionerType(*laplacian));
826  if (!precond->isValid()) {
827  precond.reset(new math::pcg::JacobiPreconditioner<LaplacianMatrix>(*laplacian));
828  }
829
830  state = math::pcg::solve(*laplacian, *b, *x, *precond, interrupter, state);
831
832  // 6. Populate the output tree with values from the solution vector.
833  /// @todo if (state.success) ... ?
834  return createTreeFromVector<TreeValueT>(*x, *idxTree, /*background=*/zeroVal<TreeValueT>());
835 }
836
837 } // namespace poisson
838 } // namespace tools
839 } // namespace OPENVDB_VERSION_NAME
840 } // namespace openvdb
841
842 #endif // OPENVDB_TOOLS_POISSONSOLVER_HAS_BEEN_INCLUDED
RowEditor getRowEditor(SizeType row)
Return a read/write view onto the given row of this matrix.
void operator()(const VIdxLeafT &idxLeaf, size_t) const
Lightweight, variable-length vector.
GLenum src
Definition: glew.h:2410
Functor for use with LeafManager::foreach() to populate an array with per-leaf active voxel counts...
Preconditioned conjugate gradient solver (solves Ax = b using the conjugate gradient method with one ...
GLenum GLenum void void * column
Definition: glew.h:4965
void operator()(LeafType &leaf, size_t leafIdx) const
GLuint index
Definition: glew.h:1814
Functor for use with LeafManager::foreach() to populate a tree with values from a vector...
Functor for use with LeafManager::foreach() to populate a sparse Laplacian matrix.
GLint GLsizei const GLuint64 * values
Definition: glew.h:3612
ISStaggeredLaplacianOp(LaplacianMatrix &m, const VIdxTreeT &idx, const BoolTreeType &mask, const BoundaryOp &op, VectorT &src)
GLsizei GLsizei GLchar * source
Definition: glew.h:1832
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:167
LaplacianMatrix::Ptr createISLaplacianWithBoundaryConditions(const typename BoolTreeType::template ValueConverter< VIndex >::Type &vectorIndexTree, const BoolTreeType &interiorMask, const BoundaryOp &boundaryOp, typename math::pcg::Vector< LaplacianMatrix::ValueType > &source, bool staggered=false)
Generate a sparse matrix of the index-space (Δx = 1) Laplacian operator with user-specified boundary ...
const GLdouble * m
Definition: glew.h:9124
const GLdouble * v
Definition: glew.h:1391
Definition: glew.h:1845
Dummy NOOP interrupter class defining interface.
Functor for use with LeafManager::foreach() to populate a vector with the values of a tree's active v...
Sparse, square matrix representing a 3D stencil operator of size STENCIL_SIZE.
typename VIndexTreeType::template ValueConverter< TreeValueType >::Type OutTreeT
math::pcg::SparseStencilMatrix< double, 7 > LaplacianMatrix
The type of a matrix used to represent a three-dimensional Laplacian operator.
Definition: PoissonSolver.h:82
ISLaplacianOp(LaplacianMatrix &m, const VIdxTreeT &idx, const BoundaryOp &op, VectorT &src)
void operator()(const VIdxLeafT &idxLeaf, size_t) const
GLclampf f
Definition: glew.h:3499
Preconditioner using incomplete Cholesky factorization.
GLint GLint GLint GLint GLint x
Definition: glew.h:1252
const ValueType & getValue(const Coord &xyz) const
Return the value of the voxel at the given coordinates.
State solve(const PositiveDefMatrix &A, const Vector< typename PositiveDefMatrix::ValueType > &b, Vector< typename PositiveDefMatrix::ValueType > &x, Preconditioner< typename PositiveDefMatrix::ValueType > &preconditioner, const State &termination=terminationDefaults< typename PositiveDefMatrix::ValueType >())
Solve Ax = b via the preconditioned conjugate gradient method.
VIndexTreeType::template ValueConverter< TreeValueType >::Type::Ptr createTreeFromVector(const math::pcg::Vector< VectorValueType > &values, const VIndexTreeType &index, const TreeValueType &background)
Return a tree with the same active voxel topology as the index tree but whose voxel values are taken ...
typename BoolTreeType::template ValueConverter< VIndex >::Type VIdxTreeT
This class manages a linear array of pointers to a given tree's leaf nodes, as well as optional auxil...
Definition: LeafManager.h:84
typename math::pcg::Vector< VectorValueType > VectorT
void operator()(const LeafType &leaf, size_t leafIdx) const
void operator()(const VIdxLeafT &idxLeaf, size_t) const
GridType::template ValueConverter< bool >::Type::Ptr interiorMask(const GridType &grid, const double isovalue=0.0)
Given an input grid of any type, return a new, boolean grid whose active voxel topology matches the i...
TreeType::Ptr solveWithBoundaryConditionsAndPreconditioner(const TreeType &, const BoundaryOp &, math::pcg::State &, Interrupter &, bool staggered=false)
Solve ∇2x = b for x with user-specified boundary conditions, where b is a vector comprising the value...
GridType::Ptr laplacian(const GridType &grid, bool threaded, InterruptT *interrupt)
Compute the Laplacian of the given scalar grid.
GLdouble GLdouble GLdouble b
Definition: glew.h:9122
bool isValueOn(const Coord &xyz) const
Return the active state of the voxel at the given coordinates.
math::pcg::Vector< VectorValueType >::Ptr createVectorFromTree(const SourceTreeType &source, const typename SourceTreeType::template ValueConverter< VIndex >::Type &index)
Return a vector of the active voxel values of the scalar-valued source tree.
UT_VectorT< T > VectorT
Definition: GU_UVUtils.h:35
LaplacianMatrix::Ptr createISLaplacian(const typename BoolTreeType::template ValueConverter< VIndex >::Type &vectorIndexTree, const BoolTreeType &interiorMask, bool staggered=false)
Generate a sparse matrix of the index-space (Δx = 1) Laplacian operator using second-order finite dif...
SizeType setValue(SizeType column, const ValueType &value)
Set the value of the entry in the specified column.
void populateIndexTree(VIndexTreeType &)
Overwrite each active voxel in the given scalar tree with a sequential index, starting from zero...
GLuint GLuint GLsizei count
Definition: glew.h:1253
Implementation of morphological dilation and erosion.
GLuint64EXT * result
Definition: glew.h:14007
Tag dispatch class that distinguishes topology copy constructors from deep copy constructors.
Definition: Types.h:542
void erodeVoxels(TreeType &tree, int iterations=1, NearestNeighbors nn=NN_FACE)
Topologically erode all leaf-level active voxels in the given tree.
Definition: Morphology.h:847
A LeafManager manages a linear array of pointers to a given tree's leaf nodes, as well as optional au...
typename SourceTreeType::template ValueConverter< VIndex >::Type VIdxTreeT
TreeType::Ptr solve(const TreeType &, math::pcg::State &, bool staggered=false)
Solve ∇2x = b for x, where b is a vector comprising the values of all of the active voxels in the inp...
Functor for use with LeafManager::foreach() to populate active leaf voxels with sequential indices...
TreeType::template ValueConverter< VIndex >::Type::Ptr createIndexTree(const TreeType &)
Iterate over the active voxels of the input tree and for each one assign its index in the iteration s...
GLenum GLenum void * row
Definition: glew.h:4965
TreeType::Ptr solveWithBoundaryConditions(const TreeType &, const BoundaryOp &, math::pcg::State &, Interrupter &, bool staggered=false)
Solve ∇2x = b for x with user-specified boundary conditions, where b is a vector comprising the value...
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition: version.h:113
GLsizei const GLfloat * value
Definition: glew.h:1849
GLdouble GLdouble t
Definition: glew.h:1398
bool probeValue(const Coord &xyz, ValueType &value) const
Return the active state of the voxel as well as its value.
Functor for use with LeafManager::foreach() to populate a sparse Laplacian matrix.
void operator()(const Coord &, const Coord &, ValueType &, ValueType &diag) const