OpenVDB 14.0.0
Loading...
Searching...
No Matches
Merge.h
Go to the documentation of this file.
1// Copyright Contributors to the OpenVDB Project
2// SPDX-License-Identifier: Apache-2.0
3//
4/// @file Merge.h
5///
6/// @brief Functions to efficiently merge grids
7///
8/// @author Dan Bailey
9
10#ifndef OPENVDB_TOOLS_MERGE_HAS_BEEN_INCLUDED
11#define OPENVDB_TOOLS_MERGE_HAS_BEEN_INCLUDED
12
13#include <openvdb/Platform.h>
14#include <openvdb/Exceptions.h>
15#include <openvdb/Types.h>
16#include <openvdb/Grid.h>
18#include <openvdb/openvdb.h>
19#include <openvdb/util/Assert.h>
20
21#include "NodeVisitor.h"
22
23#include <memory>
24#include <unordered_map>
25#include <unordered_set>
26
27namespace openvdb {
29namespace OPENVDB_VERSION_NAME {
30namespace tools {
31
32
33/// @brief Convenience class that contains a pointer to a tree to be stolen or
34/// deep copied depending on the tag dispatch class used and a subset of
35/// methods to retrieve data from the tree.
36///
37/// @details The primary purpose of this class is to be able to create an array
38/// of TreeToMerge objects that each store a tree to be stolen or a tree to be
39/// deep-copied in an arbitrary order. Certain operations such as floating-point
40/// addition are non-associative so the order in which they are merged is
41/// important for the operation to remain deterministic regardless of how the
42/// data is being extracted from the tree.
43///
44/// @note Stealing data requires a non-const tree pointer. There is a constructor
45/// to pass in a tree shared pointer for cases where it is desirable for this class
46/// to maintain shared ownership.
47template <typename TreeT>
49{
50 using TreeType = std::remove_const_t<TreeT>;
51 using RootNodeType = typename TreeType::RootNodeType;
52 using ValueType = typename TreeType::ValueType;
53 using MaskTreeType = typename TreeT::template ValueConverter<ValueMask>::Type;
54
55 TreeToMerge() = delete;
56
57 /// @brief Non-const pointer tree constructor for stealing data.
59 : mTree(&tree), mSteal(true) { }
60 /// @brief Non-const shared pointer tree constructor for stealing data.
61 TreeToMerge(typename TreeType::Ptr treePtr, Steal)
62 : mTreePtr(treePtr), mTree(mTreePtr.get()), mSteal(true) { }
63
64 /// @brief Const tree pointer constructor for deep-copying data. As the
65 /// tree is not mutable and thus cannot be pruned, a lightweight mask tree
66 /// with the same topology is created that can be pruned to use as a
67 /// reference. Initialization of this mask tree can optionally be disabled
68 /// for delayed construction.
70 : mTree(&tree), mSteal(false)
71 {
72 if (mTree && initialize) this->initializeMask();
73 }
74
75 /// @brief Non-const tree pointer constructor for deep-copying data. The
76 /// tree is not intended to be modified so is not pruned, instead a
77 /// lightweight mask tree with the same topology is created that can be
78 /// pruned to use as a reference. Initialization of this mask tree can
79 /// optionally be disabled for delayed construction.
81 : TreeToMerge(static_cast<const TreeType&>(tree), tag, initialize) { }
82
83 /// @brief Reset the non-const tree shared pointer. This is primarily
84 /// used to preserve the order of trees to merge in a container but have
85 /// the data in the tree be lazily loaded or resampled.
86 void reset(typename TreeType::Ptr treePtr, Steal);
87
88 /// @brief Return a pointer to the tree to be stolen.
89 TreeType* treeToSteal() { return mSteal ? const_cast<TreeType*>(mTree) : nullptr; }
90 /// @brief Return a pointer to the tree to be deep-copied.
91 const TreeType* treeToDeepCopy() { return mSteal ? nullptr : mTree; }
92
93 /// @brief Retrieve a const pointer to the root node.
94 const RootNodeType* rootPtr() const;
95
96 /// @brief Return a pointer to the node of type @c NodeT that contains
97 /// voxel (x, y, z). If no such node exists, return @c nullptr.
98 template<typename NodeT>
99 const NodeT* probeConstNode(const Coord& ijk) const;
100
101 /// @brief Prune the mask and remove the node associated with this coord.
102 void pruneMask(Index level, const Coord& ijk);
103
104 /// @brief Return a pointer to the node of type @c NodeT that contains voxel (x, y, z).
105 /// If the tree is non-const, steal the node and replace it with the value provided.
106 /// If the tree is const, deep-copy the node and modify the mask tree to prune the node.
107 template <typename NodeT>
108 std::unique_ptr<NodeT> stealOrDeepCopyNode(const Coord& ijk, const ValueType& value);
109
110 /// @brief Return a pointer to the node of type @c NodeT that contains voxel (x, y, z).
111 /// If the tree is non-const, steal the node and replace it with an inactive
112 /// background-value tile.
113 /// If the tree is const, deep-copy the node and modify the mask tree to prune the node.
114 template <typename NodeT>
115 std::unique_ptr<NodeT> stealOrDeepCopyNode(const Coord& ijk);
116
117 /// @brief Add a tile containing voxel (x, y, z) at the level of NodeT,
118 /// deleting the existing branch if necessary.
119 template <typename NodeT>
120 void addTile(const Coord& ijk, const ValueType& value, bool active);
121
122 // build a lightweight mask using a union of the const tree where leaf nodes
123 // are converted into active tiles
124 void initializeMask();
125
126 // returns true if mask has been initialized
127 bool hasMask() const;
128
129 // returns MaskTree pointer or nullptr
130 MaskTreeType* mask() { return mMaskTree.ptr.get(); }
131 const MaskTreeType* mask() const { return mMaskTree.ptr.get(); }
132
133private:
134 struct MaskPtr;
135 struct MaskUnionOp;
136
137 typename TreeType::Ptr mTreePtr;
138 const TreeType* mTree;
139 MaskPtr mMaskTree;
140 bool mSteal;
141}; // struct TreeToMerge
142
143
144/// @brief Wrapper around unique_ptr that deep-copies mask on copy construction
145template <typename TreeT>
146struct TreeToMerge<TreeT>::MaskPtr
147{
148 std::unique_ptr<MaskTreeType> ptr;
149
150 MaskPtr() = default;
151 ~MaskPtr() = default;
152 MaskPtr(MaskPtr&& other) = default;
153 MaskPtr& operator=(MaskPtr&& other) = default;
154 MaskPtr(const MaskPtr& other)
155 : ptr(bool(other.ptr) ? std::make_unique<MaskTreeType>(*other.ptr) : nullptr) { }
156 MaskPtr& operator=(const MaskPtr& other)
157 {
158 if (bool(other.ptr)) ptr = std::make_unique<MaskTreeType>(*other.ptr);
159 else ptr.reset();
160 return *this;
161 }
162};
163
164/// @brief DynamicNodeManager operator used to generate a mask of the input
165/// tree, but with dense leaf nodes replaced with active tiles for compactness
166template <typename TreeT>
168{
170 using RootT = typename MaskT::RootNodeType;
171 using LeafT = typename MaskT::LeafNodeType;
172
173 explicit MaskUnionOp(const TreeT& tree) : mTree(tree) { }
174 bool operator()(RootT& root, size_t) const;
175 template<typename NodeT>
176 bool operator()(NodeT& node, size_t) const;
177 bool operator()(LeafT&, size_t) const { return false; }
178private:
179 const TreeT& mTree;
180}; // struct TreeToMerge<TreeT>::MaskUnionOp
181
182
183////////////////////////////////////////
184
185
186/// @brief DynamicNodeManager operator to merge trees using a CSG union or intersection.
187/// @note This class modifies the topology of the tree so is designed to be used
188/// from DynamicNodeManager::foreachTopDown().
189/// @details A union and an intersection are opposite operations to each other so
190/// implemented in a combined class. Use the CsgUnionOp and CsgIntersectionOp aliases
191/// for convenience.
192template<typename TreeT, bool Union>
194{
195 using ValueT = typename TreeT::ValueType;
196 using RootT = typename TreeT::RootNodeType;
197 using LeafT = typename TreeT::LeafNodeType;
198
199 /// @brief Convenience constructor to CSG union or intersect a single
200 /// non-const tree with another. This constructor takes a Steal or DeepCopy
201 /// tag dispatch class.
202 template <typename TagT>
203 CsgUnionOrIntersectionOp(TreeT& tree, TagT tag) { mTreesToMerge.emplace_back(tree, tag); }
204
205 /// @brief Convenience constructor to CSG union or intersect a single
206 /// const tree with another. This constructor requires a DeepCopy tag
207 /// dispatch class.
208 CsgUnionOrIntersectionOp(const TreeT& tree, DeepCopy tag) { mTreesToMerge.emplace_back(tree, tag); }
209
210 /// @brief Constructor to CSG union or intersect a container of multiple
211 /// const or non-const tree pointers. A Steal tag requires a container of
212 /// non-const trees, a DeepCopy tag will accept either const or non-const
213 /// trees.
214 template <typename TreesT, typename TagT>
215 CsgUnionOrIntersectionOp(TreesT& trees, TagT tag)
216 {
217 for (auto* tree : trees) {
218 if (tree) {
219 mTreesToMerge.emplace_back(*tree, tag);
220 }
221 }
222 }
223
224 /// @brief Constructor to accept a vector of TreeToMerge objects, primarily
225 /// used when mixing const/non-const trees.
226 /// @note Union/intersection order is preserved.
227 explicit CsgUnionOrIntersectionOp(const std::vector<TreeToMerge<TreeT>>& trees)
228 : mTreesToMerge(trees) { }
229
230 /// @brief Constructor to accept a deque of TreeToMerge objects, primarily
231 /// used when mixing const/non-const trees.
232 /// @note Union/intersection order is preserved.
233 explicit CsgUnionOrIntersectionOp(const std::deque<TreeToMerge<TreeT>>& trees)
234 : mTreesToMerge(trees.cbegin(), trees.cend()) { }
235
236 /// @brief Return true if no trees being merged
237 bool empty() const { return mTreesToMerge.empty(); }
238
239 /// @brief Return the number of trees being merged
240 size_t size() const { return mTreesToMerge.size(); }
241
242 /// Enables immediate pruning of tiles that cancel each other out.
243 void setPruneCancelledTiles(bool doprune) { mPruneCancelledTiles = doprune; }
244
245 // Processes the root node. Required by the NodeManager
246 bool operator()(RootT& root, size_t idx) const;
247
248 // Processes the internal nodes. Required by the NodeManager
249 template<typename NodeT>
250 bool operator()(NodeT& node, size_t idx) const;
251
252 // Processes the leaf nodes. Required by the NodeManager
253 bool operator()(LeafT& leaf, size_t idx) const;
254
255private:
256 // on processing the root node, the background value is stored, retrieve it
257 // and check that the root node has already been processed
258 const ValueT& background() const;
259
260 mutable std::vector<TreeToMerge<TreeT>> mTreesToMerge;
261 mutable const ValueT* mBackground = nullptr;
262 bool mPruneCancelledTiles = false;
263}; // struct CsgUnionOrIntersectionOp
264
265
266template <typename TreeT>
267using CsgUnionOp = CsgUnionOrIntersectionOp<TreeT, /*Union=*/true>;
268
269template <typename TreeT>
270using CsgIntersectionOp = CsgUnionOrIntersectionOp<TreeT, /*Union=*/false>;
271
272
273/// @brief DynamicNodeManager operator to merge two trees using a CSG difference.
274/// @note This class modifies the topology of the tree so is designed to be used
275/// from DynamicNodeManager::foreachTopDown().
276/// PruneCancelledTiles will set to background any leaf tile that matches
277/// in the two trees, thus minimizing ghost banding when common borders
278/// are differenced.
279template<typename TreeT>
281{
282 using ValueT = typename TreeT::ValueType;
283 using RootT = typename TreeT::RootNodeType;
284 using LeafT = typename TreeT::LeafNodeType;
285
286 /// @brief Convenience constructor to CSG difference a single non-const
287 /// tree from another. This constructor takes a Steal or DeepCopy tag
288 /// dispatch class.
289 template <typename TagT>
290 CsgDifferenceOp(TreeT& tree, TagT tag) : mTree(tree, tag) { }
291 /// @brief Convenience constructor to CSG difference a single const
292 /// tree from another. This constructor requires an explicit DeepCopy tag
293 /// dispatch class.
294 CsgDifferenceOp(const TreeT& tree, DeepCopy tag) : mTree(tree, tag) { }
295
296 /// @brief Constructor to CSG difference the tree in a TreeToMerge object
297 /// from another.
299
300 /// Enables immediate pruning of tiles that cancel each other out.
301 void setPruneCancelledTiles(bool doprune) { mPruneCancelledTiles = doprune; }
302
303 /// @brief Return the number of trees being merged (only ever 1)
304 size_t size() const { return 1; }
305
306 // Processes the root node. Required by the NodeManager
307 bool operator()(RootT& root, size_t idx) const;
308
309 // Processes the internal nodes. Required by the NodeManager
310 template<typename NodeT>
311 bool operator()(NodeT& node, size_t idx) const;
312
313 // Processes the leaf nodes. Required by the NodeManager
314 bool operator()(LeafT& leaf, size_t idx) const;
315
316private:
317 // on processing the root node, the background values are stored, retrieve them
318 // and check that the root nodes have already been processed
319 const ValueT& background() const;
320 const ValueT& otherBackground() const;
321
322 // note that this vector is copied in NodeTransformer every time a foreach call is made,
323 // however in typical use cases this cost will be dwarfed by the actual merge algorithm
324 mutable TreeToMerge<TreeT> mTree;
325 mutable const ValueT* mBackground = nullptr;
326 mutable const ValueT* mOtherBackground = nullptr;
327 bool mPruneCancelledTiles = false;
328}; // struct CsgDifferenceOp
329
330
331/// @brief DynamicNodeManager operator to merge trees using a sum operation.
332/// @note This class modifies the topology of the tree so is designed to be used
333/// from DynamicNodeManager::foreachTopDown().
334template<typename TreeT>
336{
337 using ValueT = typename TreeT::ValueType;
338 using RootT = typename TreeT::RootNodeType;
339 using LeafT = typename TreeT::LeafNodeType;
340
341 /// @brief Convenience constructor to sum a single non-const tree with another.
342 /// This constructor takes a Steal or DeepCopy tag dispatch class.
343 template <typename TagT>
344 SumMergeOp(TreeT& tree, TagT tag) { mTreesToMerge.emplace_back(tree, tag); }
345
346 /// @brief Convenience constructor to sum a single const tree with another.
347 /// This constructor requires a DeepCopy tag dispatch class.
348 SumMergeOp(const TreeT& tree, DeepCopy tag) { mTreesToMerge.emplace_back(tree, tag); }
349
350 /// @brief Constructor to sum a container of multiple const or non-const tree pointers.
351 /// A Steal tag requires a container of non-const trees, a DeepCopy tag will accept
352 /// either const or non-const trees.
353 template <typename TreesT, typename TagT>
354 SumMergeOp(TreesT& trees, TagT tag)
355 {
356 for (auto* tree : trees) {
357 if (tree) {
358 mTreesToMerge.emplace_back(*tree, tag);
359 }
360 }
361 }
362
363 /// @brief Constructor to accept a vector of TreeToMerge objects, primarily
364 /// used when mixing const/non-const trees.
365 /// @note Sum order is preserved.
366 explicit SumMergeOp(const std::vector<TreeToMerge<TreeT>>& trees)
367 : mTreesToMerge(trees) { }
368
369 /// @brief Constructor to accept a deque of TreeToMerge objects, primarily
370 /// used when mixing const/non-const trees.
371 /// @note Sum order is preserved.
372 explicit SumMergeOp(const std::deque<TreeToMerge<TreeT>>& trees)
373 : mTreesToMerge(trees.cbegin(), trees.cend()) { }
374
375 /// @brief Return true if no trees being merged
376 bool empty() const { return mTreesToMerge.empty(); }
377
378 /// @brief Return the number of trees being merged
379 size_t size() const { return mTreesToMerge.size(); }
380
381 // Processes the root node. Required by the NodeManager
382 bool operator()(RootT& root, size_t idx) const;
383
384 // Processes the internal nodes. Required by the NodeManager
385 template<typename NodeT>
386 bool operator()(NodeT& node, size_t idx) const;
387
388 // Processes the leaf nodes. Required by the NodeManager
389 bool operator()(LeafT& leaf, size_t idx) const;
390
391private:
392 // on processing the root node, the background value is stored, retrieve it
393 // and check that the root node has already been processed
394 const ValueT& background() const;
395
396 mutable std::vector<TreeToMerge<TreeT>> mTreesToMerge;
397 mutable const ValueT* mBackground = nullptr;
398}; // struct SumMergeOp
399
400
401////////////////////////////////////////
402
403
404template<typename TreeT>
406{
407 if (mSteal) return;
408 mMaskTree.ptr.reset(new MaskTreeType);
409 MaskUnionOp op(*mTree);
410 tree::DynamicNodeManager<MaskTreeType, MaskTreeType::RootNodeType::LEVEL-1> manager(*this->mask());
411 manager.foreachTopDown(op);
412}
413
414template<typename TreeT>
416{
417 return bool(mMaskTree.ptr);
418}
419
420template<typename TreeT>
421void TreeToMerge<TreeT>::reset(typename TreeType::Ptr treePtr, Steal)
422{
423 if (!treePtr) {
424 OPENVDB_THROW(RuntimeError, "Cannot reset with empty Tree shared pointer.");
425 }
426 mSteal = true;
427 mTreePtr = treePtr;
428 mTree = mTreePtr.get();
429}
430
431template<typename TreeT>
434{
435 return &mTree->root();
436}
437
438template<typename TreeT>
439template<typename NodeT>
440const NodeT*
442{
443 // test mutable mask first, node may have already been pruned
444 if (!mSteal && !this->mask()->isValueOn(ijk)) return nullptr;
445 return mTree->template probeConstNode<NodeT>(ijk);
446}
447
448template<typename TreeT>
449void
451{
452 if (!mSteal) {
453 OPENVDB_ASSERT(this->hasMask());
454 this->mask()->addTile(level, ijk, false, false);
455 }
456}
457
458template<typename TreeT>
459template<typename NodeT>
460std::unique_ptr<NodeT>
462{
463 if (mSteal) {
464 TreeType* tree = const_cast<TreeType*>(mTree);
465 return std::unique_ptr<NodeT>(
466 tree->root().template stealNode<NodeT>(ijk, value, false)
467 );
468 } else {
469 auto* child = this->probeConstNode<NodeT>(ijk);
470 if (child) {
471 auto result = std::make_unique<NodeT>(*child);
472 this->pruneMask(NodeT::LEVEL+1, ijk);
473 return result;
474 }
475 }
476 return std::unique_ptr<NodeT>();
477}
478
479template<typename TreeT>
480template<typename NodeT>
481std::unique_ptr<NodeT>
483{
484 return this->stealOrDeepCopyNode<NodeT>(ijk, mTree->root().background());
485}
486
487template<typename TreeT>
488template<typename NodeT>
489void
490TreeToMerge<TreeT>::addTile(const Coord& ijk, const ValueType& value, bool active)
491{
492 // ignore leaf node tiles (values)
493 if (NodeT::LEVEL == 0) return;
494
495 if (mSteal) {
496 TreeType* tree = const_cast<TreeType*>(mTree);
497 auto* node = tree->template probeNode<NodeT>(ijk);
498 if (node) {
499 const Index pos = NodeT::coordToOffset(ijk);
500 node->addTile(pos, value, active);
501 }
502 } else {
503 auto* node = mTree->template probeConstNode<NodeT>(ijk);
504 if (node) this->pruneMask(NodeT::LEVEL, ijk);
505 }
506}
507
508
509////////////////////////////////////////
510
511
512template <typename TreeT>
513bool TreeToMerge<TreeT>::MaskUnionOp::operator()(RootT& root, size_t /*idx*/) const
514{
515 using ChildT = typename RootT::ChildNodeType;
516
517 const Index count = mTree.root().childCount();
518
519 std::vector<std::unique_ptr<ChildT>> children(count);
520
521 // allocate new root children
522
523 tbb::parallel_for(
524 tbb::blocked_range<Index>(0, count),
525 [&](tbb::blocked_range<Index>& range)
526 {
527 for (Index i = range.begin(); i < range.end(); i++) {
528 children[i] = std::make_unique<ChildT>(Coord::max(), true, true);
529 }
530 }
531 );
532
533 // apply origins and add root children to new root node
534
535 size_t i = 0;
536 for (auto iter = mTree.root().cbeginChildOn(); iter; ++iter) {
537 children[i]->setOrigin(iter->origin());
538 root.addChild(children[i].release());
539 i++;
540 }
541
542 return true;
543}
544
545template <typename TreeT>
546template <typename NodeT>
547bool TreeToMerge<TreeT>::MaskUnionOp::operator()(NodeT& node, size_t /*idx*/) const
548{
549 using ChildT = typename NodeT::ChildNodeType;
550
551 const auto* otherNode = mTree.template probeConstNode<NodeT>(node.origin());
552 if (!otherNode) return false;
553
554 // this mask tree stores active tiles in place of leaf nodes for compactness
555
556 if (NodeT::LEVEL == 1) {
557 for (auto iter = otherNode->cbeginChildOn(); iter; ++iter) {
558 node.addTile(iter.pos(), true, true);
559 }
560 } else {
561 for (auto iter = otherNode->cbeginChildOn(); iter; ++iter) {
562 auto* child = new ChildT(iter->origin(), true, true);
563 node.addChild(child);
564 }
565 }
566
567 return true;
568}
569
570
571////////////////////////////////////////
572
573/// @cond OPENVDB_DOCS_INTERNAL
574
575namespace merge_internal {
576
577
578template <typename BufferT, typename ValueT>
579struct UnallocatedBuffer
580{
581 static void allocateAndFill(BufferT& buffer, const ValueT& background)
582 {
583 if (buffer.empty()) {
584 buffer.allocate();
585 buffer.fill(background);
586 }
587 }
588
589 static bool isPartiallyConstructed(const BufferT& buffer)
590 {
591 return buffer.empty();
592 }
593}; // struct AllocateAndFillBuffer
594
595template <typename BufferT>
596struct UnallocatedBuffer<BufferT, bool>
597{
598 // do nothing for bool buffers as they cannot be unallocated
599 static void allocateAndFill(BufferT&, const bool&) { }
600 static bool isPartiallyConstructed(const BufferT&) { return false; }
601}; // struct AllocateAndFillBuffer
602
603
604// a convenience class that combines nested parallelism with the depth-visit
605// node visitor which can result in increased performance with large sub-trees
606template <Index LEVEL>
607struct Dispatch
608{
609 template <typename NodeT, typename OpT>
610 static void run(NodeT& node, OpT& op)
611 {
612 using NonConstChildT = typename NodeT::ChildNodeType;
613 using ChildT = typename CopyConstness<NodeT, NonConstChildT>::Type;
614
615 // use nested parallelism if there is more than one child
616
617 Index32 childCount = node.childCount();
618 if (childCount > 0) {
619 op(node, size_t(0));
620
621 // build linear list of child pointers
622 std::vector<ChildT*> children;
623 children.reserve(childCount);
624 for (auto iter = node.beginChildOn(); iter; ++iter) {
625 children.push_back(&(*iter));
626 }
627
628 // parallelize across children
629 tbb::parallel_for(
630 tbb::blocked_range<Index32>(0, childCount),
631 [&](tbb::blocked_range<Index32>& range) {
632 for (Index32 n = range.begin(); n < range.end(); n++) {
633 DepthFirstNodeVisitor<ChildT>::visit(*children[n], op);
634 }
635 }
636 );
637 } else {
638 DepthFirstNodeVisitor<NodeT>::visit(node, op);
639 }
640 }
641}; // struct Dispatch
642
643// when LEVEL = 0, do not attempt nested parallelism
644template <>
645struct Dispatch<0>
646{
647 template <typename NodeT, typename OpT>
648 static void run(NodeT& node, OpT& op)
649 {
650 DepthFirstNodeVisitor<NodeT>::visit(node, op);
651 }
652};
653
654
655// an DynamicNodeManager operator to add a value and modify active state
656// for every tile and voxel in a given subtree
657template <typename TreeT>
658struct ApplyTileSumToNodeOp
659{
660 using LeafT = typename TreeT::LeafNodeType;
661 using ValueT = typename TreeT::ValueType;
662
663 ApplyTileSumToNodeOp(const ValueT& value, const bool active):
664 mValue(value), mActive(active) { }
665
666 template <typename NodeT>
667 void operator()(NodeT& node, size_t) const
668 {
669 // TODO: Need to add an InternalNode::setValue(Index offset, ...) to
670 // avoid the cost of using a value iterator or coordToOffset() in the case
671 // where node.isChildMaskOff() is true
672
673 for (auto iter = node.beginValueAll(); iter; ++iter) {
674 iter.setValue(mValue + *iter);
675 }
676 if (mActive) node.setValuesOn();
677 }
678
679 void operator()(LeafT& leaf, size_t) const
680 {
681 auto* data = leaf.buffer().data();
682
683 if (mValue != zeroVal<ValueT>()) {
684 for (Index i = 0; i < LeafT::SIZE; ++i) {
685 data[i] += mValue;
686 }
687 }
688 if (mActive) leaf.setValuesOn();
689 }
690
691 template <typename NodeT>
692 void run(NodeT& node)
693 {
694 Dispatch<NodeT::LEVEL>::run(node, *this);
695 }
696
697private:
698 ValueT mValue;
699 bool mActive;
700}; // struct ApplyTileSumToNodeOp
701
702
703
704} // namespace merge_internal
705
706
707/// @endcond
708
709////////////////////////////////////////
710
711
712template <typename TreeT, bool Union>
714{
715 const bool Intersect = !Union;
716
717 if (this->empty()) return false;
718
719 // store the background value
720 if (!mBackground) mBackground = &root.background();
721
722 // does the key exist in the root node?
723 auto keyExistsInRoot = [&](const Coord& key) -> bool
724 {
725 return root.getValueDepth(key) > -1;
726 };
727
728 // does the key exist in all merge tree root nodes?
729 auto keyExistsInAllTrees = [&](const Coord& key) -> bool
730 {
731 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
732 const auto* mergeRoot = mergeTree.rootPtr();
733 if (!mergeRoot) return false;
734 if (mergeRoot->getValueDepth(key) == -1) return false;
735 }
736 return true;
737 };
738
739 // delete any background tiles
740 root.eraseBackgroundTiles();
741
742 // for intersection, delete any root node keys that are not present in all trees
743 if (Intersect) {
744 // find all tile coordinates to delete
745 std::vector<Coord> toDelete;
746 for (auto valueIter = root.cbeginValueAll(); valueIter; ++valueIter) {
747 const Coord& key = valueIter.getCoord();
748 if (!keyExistsInAllTrees(key)) toDelete.push_back(key);
749 }
750 // find all child coordinates to delete
751 for (auto childIter = root.cbeginChildOn(); childIter; ++childIter) {
752 const Coord& key = childIter.getCoord();
753 if (!keyExistsInAllTrees(key)) toDelete.push_back(key);
754 }
755 // only mechanism to delete elements in root node is to delete background tiles,
756 // so insert background tiles (which will replace any child nodes) and then delete
757 for (Coord& key : toDelete) root.addTile(key, *mBackground, false);
758 root.eraseBackgroundTiles();
759 }
760
761 // find all tile values in this root and track inside/outside and active state
762 // note that level sets should never contain active tiles, but we handle them anyway
763
764 constexpr uint8_t ACTIVE_TILE = 0x1;
765 constexpr uint8_t INSIDE_TILE = 0x2;
766 constexpr uint8_t OUTSIDE_TILE = 0x4;
767
768 constexpr uint8_t INSIDE_STATE = Union ? INSIDE_TILE : OUTSIDE_TILE;
769 constexpr uint8_t OUTSIDE_STATE = Union ? OUTSIDE_TILE : INSIDE_TILE;
770
771 const ValueT insideBackground = Union ? -this->background() : this->background();
772 const ValueT outsideBackground = -insideBackground;
773
774 auto getTileFlag = [&](auto& valueIter) -> uint8_t
775 {
776 uint8_t flag(0);
777 const ValueT& value = valueIter.getValue();
778 if (value < zeroVal<ValueT>()) flag |= INSIDE_TILE;
779 else if (value > zeroVal<ValueT>()) flag |= OUTSIDE_TILE;
780 if (valueIter.isValueOn()) flag |= ACTIVE_TILE;
781 return flag;
782 };
783
784 std::unordered_map<Coord, /*flags*/uint8_t> tiles;
785
786 if (root.getTableSize() > 0) {
787 for (auto valueIter = root.cbeginValueAll(); valueIter; ++valueIter) {
788 const Coord& key = valueIter.getCoord();
789 tiles.insert({key, getTileFlag(valueIter)});
790 }
791 }
792
793 // find all tiles values in other roots and replace outside tiles with inside tiles
794
795 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
796 const auto* mergeRoot = mergeTree.rootPtr();
797 if (!mergeRoot) continue;
798 for (auto valueIter = mergeRoot->cbeginValueAll(); valueIter; ++valueIter) {
799 const Coord& key = valueIter.getCoord();
800 auto it = tiles.find(key);
801 if (it == tiles.end()) {
802 // if no tile with this key, insert it
803 tiles.insert({key, getTileFlag(valueIter)});
804 } else {
805 // replace an outside tile with an inside tile
806 const uint8_t flag = it->second;
807 if (flag & OUTSIDE_STATE) {
808 const uint8_t newFlag = getTileFlag(valueIter);
809 if (newFlag & INSIDE_STATE) {
810 it->second = newFlag;
811 }
812 }
813 }
814 }
815 }
816
817 // insert all inside tiles
818
819 for (auto it : tiles) {
820 const uint8_t flag = it.second;
821 if (flag & INSIDE_STATE) {
822 const Coord& key = it.first;
823 const bool state = flag & ACTIVE_TILE;
824 // for intersection, only add the tile if the key already exists in the tree
825 if (Union || keyExistsInRoot(key)) {
826 root.addTile(key, insideBackground, state);
827 }
828 }
829 }
830
831 std::unordered_set<Coord> children;
832
833 if (root.getTableSize() > 0) {
834 for (auto childIter = root.cbeginChildOn(); childIter; ++childIter) {
835 const Coord& key = childIter.getCoord();
836 children.insert(key);
837 }
838 }
839
840 bool continueRecurse = false;
841
842 // find all children in other roots and insert them if a child or tile with this key
843 // does not already exist or if the child will replace an outside tile
844
845 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
846 const auto* mergeRoot = mergeTree.rootPtr();
847 if (!mergeRoot) continue;
848 for (auto childIter = mergeRoot->cbeginChildOn(); childIter; ++childIter) {
849 const Coord& key = childIter.getCoord();
850
851 // for intersection, only add child nodes if the key already exists in the tree
852 if (Intersect && !keyExistsInRoot(key)) continue;
853
854 // if child already exists, merge recursion will need to continue to resolve conflict
855 if (children.count(key)) {
856 continueRecurse = true;
857 continue;
858 }
859
860 // if an inside tile exists, do nothing
861 auto it = tiles.find(key);
862 if (it != tiles.end() && it->second == INSIDE_STATE) continue;
863
864 auto childPtr = mergeTree.template stealOrDeepCopyNode<typename RootT::ChildNodeType>(key);
865 childPtr->resetBackground(mergeRoot->background(), root.background());
866 if (childPtr) root.addChild(childPtr.release());
867
868 children.insert(key);
869 }
870 }
871
872 // insert all outside tiles that don't replace an inside tile or a child node
873
874 for (auto it : tiles) {
875 const uint8_t flag = it.second;
876 if (flag & OUTSIDE_STATE) {
877 const Coord& key = it.first;
878 if (!children.count(key)) {
879 const bool state = flag & ACTIVE_TILE;
880 // for intersection, only add the tile if the key already exists in the tree
881 if (Union || keyExistsInRoot(key)) {
882 root.addTile(key, outsideBackground, state);
883 }
884 }
885 }
886 }
887
888 // finish by removing any background tiles
889 root.eraseBackgroundTiles();
890
891 return continueRecurse;
892}
893
894template<typename TreeT, bool Union>
895template<typename NodeT>
897{
898 using NonConstNodeT = typename std::remove_const<NodeT>::type;
899
900 if (this->empty()) return false;
901
902 const ValueT insideBackground = Union ? -this->background() : this->background();
903 const ValueT outsideBackground = -insideBackground;
904
905 using NodeMaskT = typename NodeT::NodeMaskType;
906
907 // store temporary masks to track inside and outside tile states
908 NodeMaskT validTile;
909 NodeMaskT invalidTile;
910
911 auto isValid = [](const ValueT& value)
912 {
913 return Union ? value < zeroVal<ValueT>() : value > zeroVal<ValueT>();
914 };
915
916 auto isInvalid = [](const ValueT& value)
917 {
918 return Union ? value > zeroVal<ValueT>() : value < zeroVal<ValueT>();
919 };
920
921 for (auto iter = node.cbeginValueAll(); iter; ++iter) {
922 if (isValid(iter.getValue())) {
923 validTile.setOn(iter.pos());
924 } else if (isInvalid(iter.getValue())) {
925 invalidTile.setOn(iter.pos());
926 }
927 }
928
929 bool continueRecurse = false;
930
931 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
932
933 auto* mergeNode = mergeTree.template probeConstNode<NonConstNodeT>(node.origin());
934
935 if (!mergeNode) continue;
936
937 // iterate over all tiles
938
939 for (auto iter = mergeNode->cbeginValueAll(); iter; ++iter) {
940 Index pos = iter.pos();
941 // source node contains an inside tile, so ignore
942 if (validTile.isOn(pos)) continue;
943 // this node contains an inside tile, so turn into an inside tile
944 if (isValid(iter.getValue())) {
945 node.addTile(pos, insideBackground, iter.isValueOn());
946 validTile.setOn(pos);
947 }
948 }
949
950 // iterate over all child nodes
951
952 for (auto iter = mergeNode->cbeginChildOn(); iter; ++iter) {
953 Index pos = iter.pos();
954 const Coord& ijk = iter.getCoord();
955 // source node contains an inside tile, so ensure other node has no child
956 if (validTile.isOn(pos)) {
957 mergeTree.template addTile<NonConstNodeT>(ijk, outsideBackground, false);
958 } else if (invalidTile.isOn(pos)) {
959 auto childPtr = mergeTree.template stealOrDeepCopyNode<typename NodeT::ChildNodeType>(ijk);
960 if (childPtr) {
961 childPtr->resetBackground(mergeTree.rootPtr()->background(), this->background());
962 node.addChild(childPtr.release());
963 }
964 invalidTile.setOff(pos);
965 } else {
966 // if both source and target are child nodes, merge recursion needs to continue
967 // along this branch to resolve the conflict
968 continueRecurse = true;
969 }
970 }
971 }
972
973 return continueRecurse;
974}
975
976template <typename TreeT, bool Union>
978{
979 using LeafT = typename TreeT::LeafNodeType;
980 using ValueT = typename LeafT::ValueType;
981 using BufferT = typename LeafT::Buffer;
982
983 if (this->empty()) return false;
984
985 const ValueT background = Union ? this->background() : -this->background();
986
987 // if buffer is not out-of-core and empty, leaf node must have only been
988 // partially constructed, so allocate and fill with background value
989
990 merge_internal::UnallocatedBuffer<BufferT, ValueT>::allocateAndFill(
991 leaf.buffer(), background);
992
993 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
994 const LeafT* mergeLeaf = mergeTree.template probeConstNode<LeafT>(leaf.origin());
995 if (!mergeLeaf) continue;
996 // if buffer is not out-of-core yet empty, leaf node must have only been
997 // partially constructed, so skip merge
998 if (merge_internal::UnallocatedBuffer<BufferT, ValueT>::isPartiallyConstructed(
999 mergeLeaf->buffer())) {
1000 continue;
1001 }
1002
1003 if (mPruneCancelledTiles) {
1004 bool allnegequal = true;
1005 for (Index i = 0 ; i < LeafT::SIZE; i++) {
1006 const ValueT& newValue = mergeLeaf->getValue(i);
1007 const ValueT& oldValue = leaf.getValue(i);
1008 allnegequal &= oldValue == math::negative(newValue);
1009 const bool doMerge = Union ? newValue < oldValue : newValue > oldValue;
1010 if (doMerge) {
1011 leaf.setValueOnly(i, newValue);
1012 leaf.setActiveState(i, mergeLeaf->isValueOn(i));
1013 }
1014 }
1015 if (allnegequal) {
1016 // If two diffed tiles have the same values of opposite signs,
1017 // we know they have both the same distances and gradients.
1018 // Thus they will cancel out.
1019 if (Union) { leaf.fill(math::negative(this->background()), false); }
1020 else { leaf.fill(this->background(), false); }
1021 }
1022
1023 } else {
1024 for (Index i = 0 ; i < LeafT::SIZE; i++) {
1025 const ValueT& newValue = mergeLeaf->getValue(i);
1026 const ValueT& oldValue = leaf.getValue(i);
1027 const bool doMerge = Union ? newValue < oldValue : newValue > oldValue;
1028 if (doMerge) {
1029 leaf.setValueOnly(i, newValue);
1030 leaf.setActiveState(i, mergeLeaf->isValueOn(i));
1031 }
1032 }
1033 }
1034 }
1035
1036 return false;
1037}
1038
1039template <typename TreeT, bool Union>
1041CsgUnionOrIntersectionOp<TreeT, Union>::background() const
1042{
1043 // this operator is only intended to be used with foreachTopDown()
1044 OPENVDB_ASSERT(mBackground);
1045 return *mBackground;
1046}
1047
1048
1049////////////////////////////////////////
1050
1051
1052template <typename TreeT>
1054{
1055 // store the background values
1056 if (!mBackground) mBackground = &root.background();
1057 if (!mOtherBackground) mOtherBackground = &mTree.rootPtr()->background();
1058
1059 // find all tile values in this root and track inside/outside and active state
1060 // note that level sets should never contain active tiles, but we handle them anyway
1061
1062 constexpr uint8_t ACTIVE_TILE = 0x1;
1063 constexpr uint8_t INSIDE_TILE = 0x2;
1064 constexpr uint8_t CHILD = 0x4;
1065
1066 auto getTileFlag = [&](auto& valueIter) -> uint8_t
1067 {
1068 uint8_t flag(0);
1069 const ValueT& value = valueIter.getValue();
1070 if (value < zeroVal<ValueT>()) flag |= INSIDE_TILE;
1071 if (valueIter.isValueOn()) flag |= ACTIVE_TILE;
1072 return flag;
1073 };
1074
1075 // delete any background tiles
1076 root.eraseBackgroundTiles();
1077
1078 std::unordered_map<Coord, /*flags*/uint8_t> flags;
1079
1080 if (root.getTableSize() > 0) {
1081 for (auto valueIter = root.cbeginValueAll(); valueIter; ++valueIter) {
1082 const Coord& key = valueIter.getCoord();
1083 const uint8_t flag = getTileFlag(valueIter);
1084 if (flag & INSIDE_TILE) {
1085 flags.insert({key, getTileFlag(valueIter)});
1086 }
1087 }
1088
1089 for (auto childIter = root.cbeginChildOn(); childIter; ++childIter) {
1090 const Coord& key = childIter.getCoord();
1091 flags.insert({key, CHILD});
1092 }
1093 }
1094
1095 bool continueRecurse = false;
1096
1097 const auto* mergeRoot = mTree.rootPtr();
1098
1099 if (mergeRoot) {
1100 for (auto valueIter = mergeRoot->cbeginValueAll(); valueIter; ++valueIter) {
1101 const Coord& key = valueIter.getCoord();
1102 const uint8_t flag = getTileFlag(valueIter);
1103 if (flag & INSIDE_TILE) {
1104 auto it = flags.find(key);
1105 if (it != flags.end()) {
1106 const bool state = flag & ACTIVE_TILE;
1107 root.addTile(key, this->background(), state);
1108 }
1109 }
1110 }
1111
1112 for (auto childIter = mergeRoot->cbeginChildOn(); childIter; ++childIter) {
1113 const Coord& key = childIter.getCoord();
1114 auto it = flags.find(key);
1115 if (it != flags.end()) {
1116 const uint8_t otherFlag = it->second;
1117 if (otherFlag & CHILD) {
1118 // if child already exists, merge recursion will need to continue to resolve conflict
1119 continueRecurse = true;
1120 } else if (otherFlag & INSIDE_TILE) {
1121 auto childPtr = mTree.template stealOrDeepCopyNode<typename RootT::ChildNodeType>(key);
1122 if (childPtr) {
1123 childPtr->resetBackground(this->otherBackground(), this->background());
1124 childPtr->negate();
1125 root.addChild(childPtr.release());
1126 }
1127 }
1128 }
1129 }
1130 }
1131
1132 // finish by removing any background tiles
1133 root.eraseBackgroundTiles();
1134
1135 return continueRecurse;
1136}
1137
1138template<typename TreeT>
1139template<typename NodeT>
1140bool CsgDifferenceOp<TreeT>::operator()(NodeT& node, size_t) const
1141{
1142 using NonConstNodeT = typename std::remove_const<NodeT>::type;
1143
1144 using NodeMaskT = typename NodeT::NodeMaskType;
1145
1146 // store temporary mask to track inside tile state
1147
1148 NodeMaskT insideTile;
1149 for (auto iter = node.cbeginValueAll(); iter; ++iter) {
1150 if (iter.getValue() < zeroVal<ValueT>()) {
1151 insideTile.setOn(iter.pos());
1152 }
1153 }
1154
1155 bool continueRecurse = false;
1156
1157 auto* mergeNode = mTree.template probeConstNode<NonConstNodeT>(node.origin());
1158
1159 if (!mergeNode) return continueRecurse;
1160
1161 // iterate over all tiles
1162
1163 for (auto iter = mergeNode->cbeginValueAll(); iter; ++iter) {
1164 Index pos = iter.pos();
1165 if (iter.getValue() < zeroVal<ValueT>()) {
1166 if (insideTile.isOn(pos) || node.isChildMaskOn(pos)) {
1167 node.addTile(pos, this->background(), iter.isValueOn());
1168 }
1169 }
1170 }
1171
1172 // iterate over all children
1173
1174 for (auto iter = mergeNode->cbeginChildOn(); iter; ++iter) {
1175 Index pos = iter.pos();
1176 const Coord& ijk = iter.getCoord();
1177 if (insideTile.isOn(pos)) {
1178 auto childPtr = mTree.template stealOrDeepCopyNode<typename NodeT::ChildNodeType>(ijk);
1179 if (childPtr) {
1180 childPtr->resetBackground(this->otherBackground(), this->background());
1181 childPtr->negate();
1182 node.addChild(childPtr.release());
1183 }
1184 } else if (node.isChildMaskOn(pos)) {
1185 // if both source and target are child nodes, merge recursion needs to continue
1186 // along this branch to resolve the conflict
1187 continueRecurse = true;
1188 }
1189 }
1190
1191 return continueRecurse;
1192}
1193
1194template <typename TreeT>
1196{
1197 using LeafT = typename TreeT::LeafNodeType;
1198 using ValueT = typename LeafT::ValueType;
1199 using BufferT = typename LeafT::Buffer;
1200
1201 // if buffer is not out-of-core and empty, leaf node must have only been
1202 // partially constructed, so allocate and fill with background value
1203
1204 merge_internal::UnallocatedBuffer<BufferT, ValueT>::allocateAndFill(
1205 leaf.buffer(), this->background());
1206
1207 const LeafT* mergeLeaf = mTree.template probeConstNode<LeafT>(leaf.origin());
1208 if (!mergeLeaf) return false;
1209
1210 // if buffer is not out-of-core yet empty, leaf node must have only been
1211 // partially constructed, so skip merge
1212
1213 if (merge_internal::UnallocatedBuffer<BufferT, ValueT>::isPartiallyConstructed(
1214 mergeLeaf->buffer())) {
1215 return false;
1216 }
1217
1218 if (mPruneCancelledTiles) {
1219 bool allequal = true;
1220 for (Index i = 0 ; i < LeafT::SIZE; i++) {
1221 const ValueT& aValue = leaf.getValue(i);
1222 ValueT bValue = mergeLeaf->getValue(i);
1223 allequal &= aValue == bValue;
1224 bValue = math::negative(bValue);
1225 if (aValue < bValue) { // a = max(a, -b)
1226 leaf.setValueOnly(i, bValue);
1227 leaf.setActiveState(i, mergeLeaf->isValueOn(i));
1228 }
1229 }
1230 if (allequal) {
1231 // If two diffed tiles have the same values, we know they
1232 // have both the same distances and gradients. Thus they will
1233 // cancel out.
1234 leaf.fill(background(), false);
1235 }
1236 } else {
1237 for (Index i = 0 ; i < LeafT::SIZE; i++) {
1238 const ValueT& aValue = leaf.getValue(i);
1239 ValueT bValue = mergeLeaf->getValue(i);
1240 bValue = math::negative(bValue);
1241 if (aValue < bValue) { // a = max(a, -b)
1242 leaf.setValueOnly(i, bValue);
1243 leaf.setActiveState(i, mergeLeaf->isValueOn(i));
1244 }
1245 }
1246 }
1247
1248 return false;
1249}
1250
1251template <typename TreeT>
1252const typename CsgDifferenceOp<TreeT>::ValueT&
1253CsgDifferenceOp<TreeT>::background() const
1254{
1255 // this operator is only intended to be used with foreachTopDown()
1256 OPENVDB_ASSERT(mBackground);
1257 return *mBackground;
1258}
1259
1260template <typename TreeT>
1261const typename CsgDifferenceOp<TreeT>::ValueT&
1262CsgDifferenceOp<TreeT>::otherBackground() const
1263{
1264 // this operator is only intended to be used with foreachTopDown()
1265 OPENVDB_ASSERT(mOtherBackground);
1266 return *mOtherBackground;
1267}
1268
1269
1270////////////////////////////////////////
1271
1272
1273template <typename TreeT>
1274bool SumMergeOp<TreeT>::operator()(RootT& root, size_t) const
1275{
1276 using ValueT = typename RootT::ValueType;
1277 using ChildT = typename RootT::ChildNodeType;
1278 using NonConstChildT = typename std::remove_const<ChildT>::type;
1279
1280 if (this->empty()) return false;
1281
1282 // store the background value
1283 if (!mBackground) mBackground = &root.background();
1284
1285 // does the key exist in the root node?
1286 auto keyExistsInRoot = [](const auto& rootToTest, const Coord& key) -> bool
1287 {
1288 return rootToTest.getValueDepth(key) > -1;
1289 };
1290
1291 constexpr uint8_t TILE = 0x1;
1292 constexpr uint8_t CHILD = 0x2;
1293 constexpr uint8_t TARGET_CHILD = 0x4; // child already exists in the target tree
1294
1295 std::unordered_map<Coord, /*flags*/uint8_t> children;
1296
1297 // find all tiles and child nodes in our root
1298
1299 if (root.getTableSize() > 0) {
1300 for (auto valueIter = root.cbeginValueAll(); valueIter; ++valueIter) {
1301 const Coord& key = valueIter.getCoord();
1302 children.insert({key, TILE});
1303 }
1304
1305 for (auto childIter = root.cbeginChildOn(); childIter; ++childIter) {
1306 const Coord& key = childIter.getCoord();
1307 children.insert({key, CHILD | TARGET_CHILD});
1308 }
1309 }
1310
1311 // find all tiles and child nodes in other roots
1312
1313 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
1314 const auto* mergeRoot = mergeTree.rootPtr();
1315 if (!mergeRoot) continue;
1316
1317 for (auto valueIter = mergeRoot->cbeginValueAll(); valueIter; ++valueIter) {
1318 const Coord& key = valueIter.getCoord();
1319 auto it = children.find(key);
1320 if (it == children.end()) {
1321 // if no element with this key, insert it
1322 children.insert({key, TILE});
1323 } else {
1324 // mark as tile
1325 it->second |= TILE;
1326 }
1327 }
1328
1329 for (auto childIter = mergeRoot->cbeginChildOn(); childIter; ++childIter) {
1330 const Coord& key = childIter.getCoord();
1331 auto it = children.find(key);
1332 if (it == children.end()) {
1333 // if no element with this key, insert it
1334 children.insert({key, CHILD});
1335 } else {
1336 // mark as child
1337 it->second |= CHILD;
1338 }
1339 }
1340 }
1341
1342 // if any coords do not already exist in the root, insert an inactive background tile
1343
1344 for (const auto& it : children) {
1345 if (!keyExistsInRoot(root, it.first)) {
1346 root.addTile(it.first, root.background(), false);
1347 }
1348 }
1349
1350 // for each coord, merge each tile into the root until a child is found, then steal it
1351
1352 for (const auto& it : children) {
1353
1354 const Coord& key = it.first;
1355
1356 // do nothing if the target root already contains a child node,
1357 // merge recursion will need to continue to resolve conflict
1358 if (it.second & TARGET_CHILD) continue;
1359
1360 ValueT value;
1361 const bool active = root.probeValue(key, value);
1362
1363 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
1364 const auto* mergeRoot = mergeTree.rootPtr();
1365 if (!mergeRoot) continue;
1366
1367 // steal or deep-copy the first child node that is encountered,
1368 // then cease processing of this root node coord as merge recursion
1369 // will need to continue to resolve conflict
1370
1371 const auto* mergeNode = mergeRoot->template probeConstNode<ChildT>(key);
1372 if (mergeNode) {
1373 auto childPtr = mergeTree.template stealOrDeepCopyNode<ChildT>(key);
1374 if (childPtr) {
1375 // apply tile value and active state to the sub-tree
1376 merge_internal::ApplyTileSumToNodeOp<TreeT> applyOp(value, active);
1377 applyOp.run(*childPtr);
1378 root.addChild(childPtr.release());
1379 }
1380 break;
1381 }
1382
1383 ValueT mergeValue;
1384 const bool mergeActive = mergeRoot->probeValue(key, mergeValue);
1385
1386 if (active || mergeActive) {
1387 value += mergeValue;
1388 root.addTile(key, value, true);
1389 } else {
1390 value += mergeValue;
1391 root.addTile(key, value, false);
1392 }
1393
1394 // reset tile value to zero to prevent it being merged twice
1395 mergeTree.template addTile<NonConstChildT>(key, zeroVal<ValueT>(), false);
1396 }
1397 }
1398
1399 // set root background to be the sum of all other root backgrounds
1400
1401 ValueT background = root.background();
1402
1403 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
1404 const auto* mergeRoot = mergeTree.rootPtr();
1405 if (!mergeRoot) continue;
1406 background += mergeRoot->background();
1407 }
1408
1409 root.setBackground(background, /*updateChildNodes=*/false);
1410
1411 return true;
1412}
1413
1414template<typename TreeT>
1415template<typename NodeT>
1416bool SumMergeOp<TreeT>::operator()(NodeT& node, size_t) const
1417{
1418 using ChildT = typename NodeT::ChildNodeType;
1419 using NonConstNodeT = typename std::remove_const<NodeT>::type;
1420
1421 if (this->empty()) return false;
1422
1423 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
1424 const auto* mergeRoot = mergeTree.rootPtr();
1425 if (!mergeRoot) continue;
1426
1427 const auto* mergeNode = mergeTree.template probeConstNode<NonConstNodeT>(node.origin());
1428 if (mergeNode) {
1429 // merge node
1430
1431 for (auto iter = node.beginValueAll(); iter; ++iter) {
1432 if (mergeNode->isChildMaskOn(iter.pos())) {
1433 // steal child node
1434 auto childPtr = mergeTree.template stealOrDeepCopyNode<ChildT>(iter.getCoord());
1435 if (childPtr) {
1436 // apply tile value and active state to the sub-tree
1437 merge_internal::ApplyTileSumToNodeOp<TreeT> applyOp(*iter, iter.isValueOn());
1438 applyOp.run(*childPtr);
1439 node.addChild(childPtr.release());
1440 }
1441 } else {
1442 ValueT mergeValue;
1443 const bool mergeActive = mergeNode->probeValue(iter.getCoord(), mergeValue);
1444 iter.setValue(*iter + mergeValue);
1445 if (mergeActive && !iter.isValueOn()) iter.setValueOn();
1446 }
1447 }
1448
1449 } else {
1450 // merge tile or background value
1451
1452 if (mergeTree.hasMask()) {
1453 // if not stealing, test the original tree and if the node exists there, it means it
1454 // has been stolen so don't merge the tile value with this node
1455 const ChildT* originalMergeNode = mergeRoot->template probeConstNode<ChildT>(node.origin());
1456 if (originalMergeNode) continue;
1457 }
1458
1459 ValueT mergeValue;
1460 const bool mergeActive = mergeRoot->probeValue(node.origin(), mergeValue);
1461 for (auto iter = node.beginValueAll(); iter; ++iter) {
1462 iter.setValue(*iter + mergeValue);
1463 if (mergeActive && !iter.isValueOn()) iter.setValueOn();
1464 }
1465 }
1466 }
1467
1468 return true;
1469}
1470
1471template <typename TreeT>
1472bool SumMergeOp<TreeT>::operator()(LeafT& leaf, size_t) const
1473{
1474 using RootT = typename TreeT::RootNodeType;
1475 using RootChildT = typename RootT::ChildNodeType;
1476 using NonConstRootChildT = typename std::remove_const<RootChildT>::type;
1477 using LeafT = typename TreeT::LeafNodeType;
1478 using ValueT = typename LeafT::ValueType;
1479 using BufferT = typename LeafT::Buffer;
1480 using NonConstLeafT = typename std::remove_const<LeafT>::type;
1481
1482 if (this->empty()) return false;
1483
1484 const Coord& ijk = leaf.origin();
1485
1486 // if buffer is not out-of-core and empty, leaf node must have only been
1487 // partially constructed, so allocate and fill with background value
1488
1489 merge_internal::UnallocatedBuffer<BufferT, ValueT>::allocateAndFill(
1490 leaf.buffer(), this->background());
1491
1492 auto* data = leaf.buffer().data();
1493
1494 for (TreeToMerge<TreeT>& mergeTree : mTreesToMerge) {
1495 const RootT* mergeRoot = mergeTree.rootPtr();
1496 if (!mergeRoot) continue;
1497
1498 const LeafT* mergeLeaf = mergeTree.template probeConstNode<NonConstLeafT>(ijk);
1499 if (mergeLeaf) {
1500 // merge leaf
1501
1502 // if buffer is not out-of-core yet empty, leaf node must have only been
1503 // partially constructed, so skip merge
1504
1505 if (merge_internal::UnallocatedBuffer<BufferT, ValueT>::isPartiallyConstructed(
1506 mergeLeaf->buffer())) {
1507 return false;
1508 }
1509
1510 for (Index i = 0; i < LeafT::SIZE; ++i) {
1511 data[i] += mergeLeaf->getValue(i);
1512 }
1513
1514 leaf.getValueMask() |= mergeLeaf->getValueMask();
1515 } else {
1516 // merge root tile or background value (as the merge leaf does not exist)
1517
1518 if (mergeTree.hasMask()) {
1519 // if not stealing, test the original tree and if the leaf exists there, it means it
1520 // has been stolen so don't merge the tile value with this leaf
1521 const LeafT* originalMergeLeaf = mergeRoot->template probeConstNode<NonConstLeafT>(ijk);
1522 if (originalMergeLeaf) continue;
1523 }
1524
1525 const RootChildT* mergeRootChild = mergeRoot->template probeConstNode<NonConstRootChildT>(ijk);
1526
1527 ValueT mergeValue;
1528 bool mergeActive = mergeRootChild ?
1529 mergeRootChild->probeValue(ijk, mergeValue) : mergeRoot->probeValue(ijk, mergeValue);
1530
1531 if (mergeValue != zeroVal<ValueT>()) {
1532 for (Index i = 0; i < LeafT::SIZE; ++i) {
1533 data[i] += mergeValue;
1534 }
1535 }
1536
1537 if (mergeActive) leaf.setValuesOn();
1538 }
1539 }
1540
1541 return false;
1542}
1543
1544template <typename TreeT>
1545const typename SumMergeOp<TreeT>::ValueT&
1546SumMergeOp<TreeT>::background() const
1547{
1548 // this operator is only intended to be used with foreachTopDown()
1549 OPENVDB_ASSERT(mBackground);
1550 return *mBackground;
1551}
1552
1553
1554////////////////////////////////////////
1555
1556// Explicit Template Instantiation
1557
1558#ifdef OPENVDB_USE_EXPLICIT_INSTANTIATION
1559
1560#ifdef OPENVDB_INSTANTIATE_MERGE
1562#endif
1563
1564OPENVDB_INSTANTIATE_STRUCT TreeToMerge<MaskTree>;
1565OPENVDB_INSTANTIATE_STRUCT TreeToMerge<BoolTree>;
1566OPENVDB_INSTANTIATE_STRUCT TreeToMerge<FloatTree>;
1567OPENVDB_INSTANTIATE_STRUCT TreeToMerge<DoubleTree>;
1568OPENVDB_INSTANTIATE_STRUCT TreeToMerge<Int32Tree>;
1569OPENVDB_INSTANTIATE_STRUCT TreeToMerge<Int64Tree>;
1570OPENVDB_INSTANTIATE_STRUCT TreeToMerge<Vec3STree>;
1571OPENVDB_INSTANTIATE_STRUCT TreeToMerge<Vec3DTree>;
1572OPENVDB_INSTANTIATE_STRUCT TreeToMerge<Vec3ITree>;
1573
1574OPENVDB_INSTANTIATE_STRUCT SumMergeOp<MaskTree>;
1575OPENVDB_INSTANTIATE_STRUCT SumMergeOp<BoolTree>;
1576OPENVDB_INSTANTIATE_STRUCT SumMergeOp<FloatTree>;
1577OPENVDB_INSTANTIATE_STRUCT SumMergeOp<DoubleTree>;
1578OPENVDB_INSTANTIATE_STRUCT SumMergeOp<Int32Tree>;
1579OPENVDB_INSTANTIATE_STRUCT SumMergeOp<Int64Tree>;
1580OPENVDB_INSTANTIATE_STRUCT SumMergeOp<Vec3STree>;
1581OPENVDB_INSTANTIATE_STRUCT SumMergeOp<Vec3DTree>;
1582OPENVDB_INSTANTIATE_STRUCT SumMergeOp<Vec3ITree>;
1583
1584OPENVDB_INSTANTIATE_STRUCT CsgUnionOrIntersectionOp<FloatTree, true>;
1585OPENVDB_INSTANTIATE_STRUCT CsgUnionOrIntersectionOp<DoubleTree, true>;
1586
1587OPENVDB_INSTANTIATE_STRUCT CsgUnionOrIntersectionOp<FloatTree, false>;
1588OPENVDB_INSTANTIATE_STRUCT CsgUnionOrIntersectionOp<DoubleTree, false>;
1589
1590OPENVDB_INSTANTIATE_STRUCT CsgDifferenceOp<FloatTree>;
1591OPENVDB_INSTANTIATE_STRUCT CsgDifferenceOp<DoubleTree>;
1592
1593#endif // OPENVDB_USE_EXPLICIT_INSTANTIATION
1594
1595
1596} // namespace tools
1597} // namespace OPENVDB_VERSION_NAME
1598} // namespace openvdb
1599
1600#endif // OPENVDB_TOOLS_MERGE_HAS_BEEN_INCLUDED
#define OPENVDB_ASSERT(X)
Definition Assert.h:41
Implementation of a depth-first node visitor.
static Coord max()
Return the largest possible coordinate.
Definition Coord.h:47
Tag dispatch class that distinguishes constructors that deep copy.
Definition Types.h:756
Definition Exceptions.h:63
Tag dispatch class that distinguishes constructors that steal.
Definition Types.h:758
Signed (x, y, z) 32-bit integer coordinates.
Definition Coord.h:26
Definition NodeManager.h:891
OPENVDB_AX_API void run(const char *ax, openvdb::GridBase &grid, const AttributeBindings &bindings={})
Run a full AX pipeline (parse, compile and execute) on a single OpenVDB Grid.
T negative(const T &val)
Return the unary negation of the given value.
Definition Math.h:139
CsgUnionOrIntersectionOp< TreeT, false > CsgIntersectionOp
Definition Merge.h:270
CsgUnionOrIntersectionOp< TreeT, true > CsgUnionOp
Definition Merge.h:267
Definition PointDataGrid.h:48
Index32 Index
Definition Types.h:34
void initialize()
Global registration of native Grid, Transform, Metadata and Point attribute types.
constexpr T zeroVal()
Return the value of type T that corresponds to zero.
Definition Math.h:71
uint32_t Index32
Definition Types.h:32
Definition Exceptions.h:13
Definition Coord.h:590
#define OPENVDB_THROW(exception, message)
Definition Exceptions.h:74
NodeManager produces linear arrays of all tree nodes allowing for efficient threading and bottom-up p...
CsgDifferenceOp(TreeToMerge< TreeT > &tree)
Constructor to CSG difference the tree in a TreeToMerge object from another.
Definition Merge.h:298
size_t size() const
Return the number of trees being merged (only ever 1)
Definition Merge.h:304
bool operator()(RootT &root, size_t idx) const
Definition Merge.h:1053
typename TreeT::RootNodeType RootT
Definition Merge.h:283
typename TreeT::LeafNodeType LeafT
Definition Merge.h:284
typename TreeT::ValueType ValueT
Definition Merge.h:282
CsgDifferenceOp(const TreeT &tree, DeepCopy tag)
Convenience constructor to CSG difference a single const tree from another. This constructor requires...
Definition Merge.h:294
CsgDifferenceOp(TreeT &tree, TagT tag)
Convenience constructor to CSG difference a single non-const tree from another. This constructor take...
Definition Merge.h:290
void setPruneCancelledTiles(bool doprune)
Enables immediate pruning of tiles that cancel each other out.
Definition Merge.h:301
DynamicNodeManager operator to merge trees using a CSG union or intersection.
Definition Merge.h:194
bool operator()(LeafT &leaf, size_t idx) const
Definition Merge.h:977
CsgUnionOrIntersectionOp(const TreeT &tree, DeepCopy tag)
Convenience constructor to CSG union or intersect a single const tree with another....
Definition Merge.h:208
bool operator()(NodeT &node, size_t idx) const
Definition Merge.h:896
size_t size() const
Return the number of trees being merged.
Definition Merge.h:240
bool operator()(RootT &root, size_t idx) const
Definition Merge.h:713
typename TreeT::RootNodeType RootT
Definition Merge.h:196
typename TreeT::LeafNodeType LeafT
Definition Merge.h:197
CsgUnionOrIntersectionOp(const std::vector< TreeToMerge< TreeT > > &trees)
Constructor to accept a vector of TreeToMerge objects, primarily used when mixing const/non-const tre...
Definition Merge.h:227
bool empty() const
Return true if no trees being merged.
Definition Merge.h:237
CsgUnionOrIntersectionOp(const std::deque< TreeToMerge< TreeT > > &trees)
Constructor to accept a deque of TreeToMerge objects, primarily used when mixing const/non-const tree...
Definition Merge.h:233
CsgUnionOrIntersectionOp(TreeT &tree, TagT tag)
Convenience constructor to CSG union or intersect a single non-const tree with another....
Definition Merge.h:203
typename TreeT::ValueType ValueT
Definition Merge.h:195
CsgUnionOrIntersectionOp(TreesT &trees, TagT tag)
Constructor to CSG union or intersect a container of multiple const or non-const tree pointers....
Definition Merge.h:215
void setPruneCancelledTiles(bool doprune)
Enables immediate pruning of tiles that cancel each other out.
Definition Merge.h:243
SumMergeOp(const std::deque< TreeToMerge< TreeT > > &trees)
Constructor to accept a deque of TreeToMerge objects, primarily used when mixing const/non-const tree...
Definition Merge.h:372
size_t size() const
Return the number of trees being merged.
Definition Merge.h:379
SumMergeOp(TreesT &trees, TagT tag)
Constructor to sum a container of multiple const or non-const tree pointers. A Steal tag requires a c...
Definition Merge.h:354
bool operator()(RootT &root, size_t idx) const
Definition Merge.h:1274
typename TreeT::RootNodeType RootT
Definition Merge.h:338
typename TreeT::LeafNodeType LeafT
Definition Merge.h:339
SumMergeOp(const TreeT &tree, DeepCopy tag)
Convenience constructor to sum a single const tree with another. This constructor requires a DeepCopy...
Definition Merge.h:348
bool empty() const
Return true if no trees being merged.
Definition Merge.h:376
SumMergeOp(TreeT &tree, TagT tag)
Convenience constructor to sum a single non-const tree with another. This constructor takes a Steal o...
Definition Merge.h:344
typename TreeT::ValueType ValueT
Definition Merge.h:337
SumMergeOp(const std::vector< TreeToMerge< TreeT > > &trees)
Constructor to accept a vector of TreeToMerge objects, primarily used when mixing const/non-const tre...
Definition Merge.h:366
std::unique_ptr< MaskTreeType > ptr
Definition Merge.h:148
MaskPtr & operator=(MaskPtr &&other)=default
MaskPtr(const MaskPtr &other)
Definition Merge.h:154
MaskPtr & operator=(const MaskPtr &other)
Definition Merge.h:156
DynamicNodeManager operator used to generate a mask of the input tree, but with dense leaf nodes repl...
Definition Merge.h:168
typename MaskT::LeafNodeType LeafT
Definition Merge.h:171
MaskUnionOp(const TreeT &tree)
Definition Merge.h:173
bool operator()(LeafT &, size_t) const
Definition Merge.h:177
MaskTreeType MaskT
Definition Merge.h:169
typename MaskT::RootNodeType RootT
Definition Merge.h:170
bool operator()(RootT &root, size_t) const
Definition Merge.h:513
Convenience class that contains a pointer to a tree to be stolen or deep copied depending on the tag ...
Definition Merge.h:49
TreeToMerge(typename TreeType::Ptr treePtr, Steal)
Non-const shared pointer tree constructor for stealing data.
Definition Merge.h:61
std::remove_const_t< TreeT > TreeType
Definition Merge.h:50
typename TreeType::ValueType ValueType
Definition Merge.h:52
bool hasMask() const
Definition Merge.h:415
MaskTreeType * mask()
Definition Merge.h:130
void addTile(const Coord &ijk, const ValueType &value, bool active)
Add a tile containing voxel (x, y, z) at the level of NodeT, deleting the existing branch if necessar...
Definition Merge.h:490
typename TreeType::RootNodeType RootNodeType
Definition Merge.h:51
typename TreeT::template ValueConverter< ValueMask >::Type MaskTreeType
Definition Merge.h:53
void initializeMask()
Definition Merge.h:405
std::unique_ptr< NodeT > stealOrDeepCopyNode(const Coord &ijk, const ValueType &value)
Return a pointer to the node of type NodeT that contains voxel (x, y, z). If the tree is non-const,...
Definition Merge.h:461
const MaskTreeType * mask() const
Definition Merge.h:131
void pruneMask(Index level, const Coord &ijk)
Prune the mask and remove the node associated with this coord.
Definition Merge.h:450
const TreeType * treeToDeepCopy()
Return a pointer to the tree to be deep-copied.
Definition Merge.h:91
TreeToMerge(const TreeType &tree, DeepCopy, bool initialize=true)
Const tree pointer constructor for deep-copying data. As the tree is not mutable and thus cannot be p...
Definition Merge.h:69
const RootNodeType * rootPtr() const
Retrieve a const pointer to the root node.
Definition Merge.h:433
TreeToMerge(TreeType &tree, DeepCopy tag, bool initialize=true)
Non-const tree pointer constructor for deep-copying data. The tree is not intended to be modified so ...
Definition Merge.h:80
const NodeT * probeConstNode(const Coord &ijk) const
Return a pointer to the node of type NodeT that contains voxel (x, y, z). If no such node exists,...
Definition Merge.h:441
void reset(typename TreeType::Ptr treePtr, Steal)
Reset the non-const tree shared pointer. This is primarily used to preserve the order of trees to mer...
Definition Merge.h:421
TreeToMerge(TreeType &tree, Steal)
Non-const pointer tree constructor for stealing data.
Definition Merge.h:58
TreeType * treeToSteal()
Return a pointer to the tree to be stolen.
Definition Merge.h:89
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition version.h.in:121
#define OPENVDB_INSTANTIATE_STRUCT
Definition version.h.in:232
#define OPENVDB_USE_VERSION_NAMESPACE
Definition version.h.in:291