This file is indexed.

/usr/include/openvdb/tree/TreeIterator.h is in libopenvdb-dev 3.2.0-2.1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2016 DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// *     Neither the name of DreamWorks Animation nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////
//
/// @file TreeIterator.h

#ifndef OPENVDB_TREE_TREEITERATOR_HAS_BEEN_INCLUDED
#define OPENVDB_TREE_TREEITERATOR_HAS_BEEN_INCLUDED

#include <boost/mpl/front.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <openvdb/version.h>
#include <openvdb/Types.h>

// Prior to 0.96.1, depth-bounded value iterators always descended to the leaf level
// and iterated past leaf nodes.  Now, they never descend past the maximum depth.
// Comment out the following line to restore the older, less-efficient behavior:
#define ENABLE_TREE_VALUE_DEPTH_BOUND_OPTIMIZATION


namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace tree {

/// CopyConstness<T1, T2>::Type is either const T2 or T2 with no const qualifier,
/// depending on whether T1 is const.  For example,
/// - CopyConstness<int, int>::Type is int
/// - CopyConstness<int, const int>::Type is int
/// - CopyConstness<const int, int>::Type is const int
/// - CopyConstness<const int, const int>::Type is const int
template<typename FromType, typename ToType> struct CopyConstness {
    typedef typename boost::remove_const<ToType>::type Type;
};
template<typename FromType, typename ToType> struct CopyConstness<const FromType, ToType> {
    typedef const ToType Type;
};


////////////////////////////////////////


namespace iter {

template<typename HeadT, int HeadLevel>
struct InvertedTree {
    typedef typename InvertedTree<typename HeadT::ChildNodeType, HeadLevel-1>::Type SubtreeT;
    typedef typename boost::mpl::push_back<SubtreeT, HeadT>::type Type;
};
template<typename HeadT>
struct InvertedTree<HeadT, /*HeadLevel=*/1> {
    typedef typename boost::mpl::vector<typename HeadT::ChildNodeType, HeadT>::type Type;
};

} // namespace iter


////////////////////////////////////////


/// IterTraits provides the following for iterators of the standard types,
/// i.e., for {Child,Value}{On,Off,All}{Iter,CIter}:
/// - a NodeConverter template to convert an iterator for one type of node
///   to an iterator of the same type for another type of node; for example,
///   IterTraits<RootNode, RootNode::ValueOnIter>::NodeConverter<LeafNode>::Type
///   is synonymous with LeafNode::ValueOnIter.
/// - a begin(node) function that returns a begin iterator for a node of arbitrary type;
///   for example, IterTraits<LeafNode, LeafNode::ValueOnIter>::begin(leaf) returns
///   leaf.beginValueOn()
/// - a getChild() function that returns a pointer to the child node to which the iterator
///   is currently pointing (always NULL if the iterator is a Value iterator)
template<typename NodeT, typename IterT>
struct IterTraits
{
    template<typename ChildT> static ChildT* getChild(const IterT&) { return NULL; }
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ChildOnIter>
{
    typedef typename NodeT::ChildOnIter IterT;
    static IterT begin(NodeT& node) { return node.beginChildOn(); }
    template<typename ChildT> static ChildT* getChild(const IterT& iter) {
        return &iter.getValue();
    }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ChildOnIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ChildOnCIter>
{
    typedef typename NodeT::ChildOnCIter IterT;
    static IterT begin(const NodeT& node) { return node.cbeginChildOn(); }
    template<typename ChildT> static const ChildT* getChild(const IterT& iter) {
        return &iter.getValue();
    }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ChildOnCIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ChildOffIter>
{
    typedef typename NodeT::ChildOffIter IterT;
    static IterT begin(NodeT& node) { return node.beginChildOff(); }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ChildOffIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ChildOffCIter>
{
    typedef typename NodeT::ChildOffCIter IterT;
    static IterT begin(const NodeT& node) { return node.cbeginChildOff(); }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ChildOffCIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ChildAllIter>
{
    typedef typename NodeT::ChildAllIter IterT;
    static IterT begin(NodeT& node) { return node.beginChildAll(); }
    template<typename ChildT> static ChildT* getChild(const IterT& iter) {
        typename IterT::NonConstValueType val;
        return iter.probeChild(val);
    }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ChildAllIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ChildAllCIter>
{
    typedef typename NodeT::ChildAllCIter IterT;
    static IterT begin(const NodeT& node) { return node.cbeginChildAll(); }
    template<typename ChildT> static ChildT* getChild(const IterT& iter) {
        typename IterT::NonConstValueType val;
        return iter.probeChild(val);
    }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ChildAllCIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ValueOnIter>
{
    typedef typename NodeT::ValueOnIter IterT;
    static IterT begin(NodeT& node) { return node.beginValueOn(); }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ValueOnIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ValueOnCIter>
{
    typedef typename NodeT::ValueOnCIter IterT;
    static IterT begin(const NodeT& node) { return node.cbeginValueOn(); }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ValueOnCIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ValueOffIter>
{
    typedef typename NodeT::ValueOffIter IterT;
    static IterT begin(NodeT& node) { return node.beginValueOff(); }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ValueOffIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ValueOffCIter>
{
    typedef typename NodeT::ValueOffCIter IterT;
    static IterT begin(const NodeT& node) { return node.cbeginValueOff(); }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ValueOffCIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ValueAllIter>
{
    typedef typename NodeT::ValueAllIter IterT;
    static IterT begin(NodeT& node) { return node.beginValueAll(); }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ValueAllIter Type;
    };
};

template<typename NodeT>
struct IterTraits<NodeT, typename NodeT::ValueAllCIter>
{
    typedef typename NodeT::ValueAllCIter IterT;
    static IterT begin(const NodeT& node) { return node.cbeginValueAll(); }
    template<typename OtherNodeT> struct NodeConverter {
        typedef typename OtherNodeT::ValueAllCIter Type;
    };
};


////////////////////////////////////////


/// @brief An IterListItem is an element of a compile-time linked list of iterators
/// to nodes of different types.
///
/// The list is constructed by traversing the template hierarchy of a Tree in reverse order,
/// so typically the elements will be a LeafNode iterator of some type (e.g., ValueOnCIter),
/// followed by one or more InternalNode iterators of the same type, followed by a RootNode
/// iterator of the same type.
///
/// The length of the list is fixed at compile time, and because it is implemented using
/// nested, templated classes, much of the list traversal logic can be optimized away.
template<typename PrevItemT, typename NodeVecT, size_t VecSize, Index _Level>
class IterListItem
{
public:
    /// The type of iterator stored in the previous list item
    typedef typename PrevItemT::IterT PrevIterT;
    /// The type of node (non-const) whose iterator is stored in this list item
    typedef typename boost::mpl::front<NodeVecT>::type _NodeT;
    /// The type of iterator stored in this list item (e.g., InternalNode::ValueOnCIter)
    typedef typename IterTraits<typename PrevIterT::NonConstNodeType, PrevIterT>::template
        NodeConverter<_NodeT>::Type IterT;

    /// The type of node (const or non-const) over which IterT iterates (e.g., const RootNode<...>)
    typedef typename IterT::NodeType NodeT;
    /// The type of the node with const qualifiers removed ("Non-Const")
    typedef typename IterT::NonConstNodeType NCNodeT;
    /// The type of value (with const qualifiers removed) to which the iterator points
    typedef typename IterT::NonConstValueType NCValueT;
    /// NodeT's child node type, with the same constness (e.g., const InternalNode<...>)
    typedef typename CopyConstness<NodeT, typename NodeT::ChildNodeType>::Type ChildT;
    /// NodeT's child node type with const qualifiers removed
    typedef typename CopyConstness<NCNodeT, typename NCNodeT::ChildNodeType>::Type NCChildT;
    typedef IterTraits<NCNodeT, IterT> ITraits;
    /// NodeT's level in its tree (0 = LeafNode)
    static const Index Level = _Level;

    IterListItem(PrevItemT* prev): mNext(this), mPrev(prev) {}

    IterListItem(const IterListItem& other): mIter(other.mIter), mNext(other.mNext), mPrev(NULL) {}
    IterListItem& operator=(const IterListItem& other)
    {
        if (&other != this) {
            mIter = other.mIter;
            mNext = other.mNext;
            mPrev = NULL; ///< @note external call to updateBackPointers() required
        }
        return *this;
    }

    void updateBackPointers(PrevItemT* prev) { mPrev = prev; mNext.updateBackPointers(this); }

    void setIter(const IterT& iter) { mIter = iter; }
    template<typename OtherIterT>
    void setIter(const OtherIterT& iter) { mNext.setIter(iter); }

    /// Return the node over which this list element's iterator iterates.
    void getNode(Index lvl, NodeT*& node) const
    {
        node = (lvl <= Level) ? mIter.getParentNode() : NULL;
    }
    /// Return the node over which one of the following list elements' iterator iterates.
    template<typename OtherNodeT>
    void getNode(Index lvl, OtherNodeT*& node) const { mNext.getNode(lvl, node); }

    /// @brief Initialize the iterator for level @a lvl of the tree with the node
    /// over which the corresponding iterator of @a otherListItem is iterating.
    ///
    /// For example, if @a otherListItem contains a LeafNode::ValueOnIter,
    /// initialize this list's leaf iterator with the same LeafNode.
    template<typename OtherIterListItemT>
    void initLevel(Index lvl, OtherIterListItemT& otherListItem)
    {
        if (lvl == Level) {
            const NodeT* node = NULL;
            otherListItem.getNode(lvl, node);
            mIter = (node == NULL) ? IterT() : ITraits::begin(*const_cast<NodeT*>(node));
        } else {
            // Forward to one of the following list elements.
            mNext.initLevel(lvl, otherListItem);
        }
    }

    /// Return The table offset of the iterator at level @a lvl of the tree.
    Index pos(Index lvl) const { return (lvl == Level) ? mIter.pos() : mNext.pos(lvl); }

    /// Return @c true if the iterator at level @a lvl of the tree has not yet reached its end.
    bool test(Index lvl) const { return (lvl == Level) ? mIter.test() : mNext.test(lvl); }

    /// Increment the iterator at level @a lvl of the tree.
    bool next(Index lvl) { return (lvl == Level) ? mIter.next() : mNext.next(lvl); }

    /// @brief If the iterator at level @a lvl of the tree points to a child node,
    /// initialize the next iterator in this list with that child node.
    bool down(Index lvl)
    {
        if (lvl == Level && mPrev != NULL && mIter) {
            if (ChildT* child = ITraits::template getChild<ChildT>(mIter)) {
                mPrev->setIter(PrevItemT::ITraits::begin(*child));
                return true;
            }
        }
        return (lvl > Level) ? mNext.down(lvl) : false;
    }

    /// @brief Return the global coordinates of the voxel or tile to which the iterator
    /// at level @a lvl of the tree is currently pointing.
    Coord getCoord(Index lvl) const
    {
        return (lvl == Level) ? mIter.getCoord() : mNext.getCoord(lvl);
    }
    Index getChildDim(Index lvl) const
    {
        return (lvl == Level) ? NodeT::getChildDim() : mNext.getChildDim(lvl);
    }
    /// Return the number of (virtual) voxels spanned by a tile value or child node
    Index64 getVoxelCount(Index lvl) const
    {
        return (lvl == Level) ? ChildT::NUM_VOXELS : mNext.getVoxelCount(lvl);
    }

    /// Return @c true if the iterator at level @a lvl of the tree points to an active value.
    bool isValueOn(Index lvl) const
    {
        return (lvl == Level) ? mIter.isValueOn() : mNext.isValueOn(lvl);
    }

    /// Return the value to which the iterator at level @a lvl of the tree points.
    const NCValueT& getValue(Index lvl) const
    {
        if (lvl == Level) return mIter.getValue();
        return mNext.getValue(lvl);
    }

    /// @brief Set the value (to @a val) to which the iterator at level @a lvl
    /// of the tree points and mark the value as active.
    /// @note Not valid when @c IterT is a const iterator type
    void setValue(Index lvl, const NCValueT& val) const
    {
        if (lvl == Level) mIter.setValue(val); else mNext.setValue(lvl, val);
    }
    /// @brief Set the value (to @a val) to which the iterator at level @a lvl of the tree
    /// points and mark the value as active if @a on is @c true, or inactive otherwise.
    /// @note Not valid when @c IterT is a const iterator type
    void setValueOn(Index lvl, bool on = true) const
    {
        if (lvl == Level) mIter.setValueOn(on); else mNext.setValueOn(lvl, on);
    }
    /// @brief Mark the value to which the iterator at level @a lvl of the tree points
    /// as inactive.
    /// @note Not valid when @c IterT is a const iterator type
    void setValueOff(Index lvl) const
    {
        if (lvl == Level) mIter.setValueOff(); else mNext.setValueOff(lvl);
    }

    /// @brief Apply a functor to the item to which this iterator is pointing.
    /// @note Not valid when @c IterT is a const iterator type
    template<typename ModifyOp>
    void modifyValue(Index lvl, const ModifyOp& op) const
    {
        if (lvl == Level) mIter.modifyValue(op); else mNext.modifyValue(lvl, op);
    }

private:
    typedef typename boost::mpl::pop_front<NodeVecT>::type RestT; // NodeVecT minus its first item
    typedef IterListItem<IterListItem, RestT, VecSize - 1, Level + 1> NextItem;

    IterT mIter;
    NextItem mNext;
    PrevItemT* mPrev;
};


/// The initial element of a compile-time linked list of iterators to nodes of different types
template<typename PrevItemT, typename NodeVecT, size_t VecSize>
class IterListItem<PrevItemT, NodeVecT, VecSize, /*Level=*/0U>
{
public:
    /// The type of iterator stored in the previous list item
    typedef typename PrevItemT::IterT PrevIterT;
    /// The type of node (non-const) whose iterator is stored in this list item
    typedef typename boost::mpl::front<NodeVecT>::type _NodeT;
    /// The type of iterator stored in this list item (e.g., InternalNode::ValueOnCIter)
    typedef typename IterTraits<typename PrevIterT::NonConstNodeType, PrevIterT>::template
        NodeConverter<_NodeT>::Type IterT;

    /// The type of node (const or non-const) over which IterT iterates (e.g., const RootNode<...>)
    typedef typename IterT::NodeType NodeT;
    /// The type of the node with const qualifiers removed ("Non-Const")
    typedef typename IterT::NonConstNodeType NCNodeT;
    /// The type of value (with const qualifiers removed) to which the iterator points
    typedef typename IterT::NonConstValueType NCValueT;
    typedef IterTraits<NCNodeT, IterT> ITraits;
    /// NodeT's level in its tree (0 = LeafNode)
    static const Index Level = 0;

    IterListItem(PrevItemT*): mNext(this), mPrev(NULL) {}

    IterListItem(const IterListItem& other): mIter(other.mIter), mNext(other.mNext), mPrev(NULL) {}
    IterListItem& operator=(const IterListItem& other)
    {
        if (&other != this) {
            mIter = other.mIter;
            mNext = other.mNext;
            mPrev = NULL;
        }
        return *this;
    }

    void updateBackPointers(PrevItemT* = NULL) { mPrev = NULL; mNext.updateBackPointers(this); }

    void setIter(const IterT& iter) { mIter = iter; }
    template<typename OtherIterT>
    void setIter(const OtherIterT& iter) { mNext.setIter(iter); }

    void getNode(Index lvl, NodeT*& node) const
    {
        node = (lvl == 0) ? mIter.getParentNode() : NULL;
    }
    template<typename OtherNodeT>
    void getNode(Index lvl, OtherNodeT*& node) const { mNext.getNode(lvl, node); }

    template<typename OtherIterListItemT>
    void initLevel(Index lvl, OtherIterListItemT& otherListItem)
    {
        if (lvl == 0) {
            const NodeT* node = NULL;
            otherListItem.getNode(lvl, node);
            mIter = (node == NULL) ? IterT() : ITraits::begin(*const_cast<NodeT*>(node));
        } else {
            mNext.initLevel(lvl, otherListItem);
        }
    }

    Index pos(Index lvl) const { return (lvl == 0) ? mIter.pos() : mNext.pos(lvl); }

    bool test(Index lvl) const { return (lvl == 0) ? mIter.test() : mNext.test(lvl); }

    bool next(Index lvl) { return (lvl == 0) ? mIter.next() : mNext.next(lvl); }

    bool down(Index lvl) { return (lvl == 0) ? false : mNext.down(lvl); }

    Coord getCoord(Index lvl) const
    {
        return (lvl == 0) ?  mIter.getCoord() : mNext.getCoord(lvl);
    }
    Index getChildDim(Index lvl) const
    {
        return (lvl == 0) ? NodeT::getChildDim() : mNext.getChildDim(lvl);
    }

    Index64 getVoxelCount(Index lvl) const
    {
        return (lvl == 0) ? 1 : mNext.getVoxelCount(lvl);
    }

    bool isValueOn(Index lvl) const
    {
        return (lvl == 0) ? mIter.isValueOn() : mNext.isValueOn(lvl);
    }

    const NCValueT& getValue(Index lvl) const
    {
        if (lvl == 0) return mIter.getValue();
        return mNext.getValue(lvl);
    }

    void setValue(Index lvl, const NCValueT& val) const
    {
        if (lvl == 0) mIter.setValue(val); else mNext.setValue(lvl, val);
    }
    void setValueOn(Index lvl, bool on = true) const
    {
        if (lvl == 0) mIter.setValueOn(on); else mNext.setValueOn(lvl, on);
    }
    void setValueOff(Index lvl) const
    {
        if (lvl == 0) mIter.setValueOff(); else mNext.setValueOff(lvl);
    }

    template<typename ModifyOp>
    void modifyValue(Index lvl, const ModifyOp& op) const
    {
        if (lvl == 0) mIter.modifyValue(op); else mNext.modifyValue(lvl, op);
    }

private:
    typedef typename boost::mpl::pop_front<NodeVecT>::type RestT; // NodeVecT minus its first item
    typedef IterListItem<IterListItem, RestT, VecSize - 1, /*Level=*/1> NextItem;

    IterT mIter;
    NextItem mNext;
    PrevItemT* mPrev;
};


/// The final element of a compile-time linked list of iterators to nodes of different types
template<typename PrevItemT, typename NodeVecT, Index _Level>
class IterListItem<PrevItemT, NodeVecT, /*VecSize=*/1, _Level>
{
public:
    typedef typename boost::mpl::front<NodeVecT>::type _NodeT;
    /// The type of iterator stored in the previous list item
    typedef typename PrevItemT::IterT PrevIterT;
    /// The type of iterator stored in this list item (e.g., RootNode::ValueOnCIter)
    typedef typename IterTraits<typename PrevIterT::NonConstNodeType, PrevIterT>::template
        NodeConverter<_NodeT>::Type IterT;

    /// The type of node over which IterT iterates (e.g., const RootNode<...>)
    typedef typename IterT::NodeType NodeT;
    /// The type of the node with const qualifiers removed ("Non-Const")
    typedef typename IterT::NonConstNodeType NCNodeT;
    /// The type of value (with const qualifiers removed) to which the iterator points
    typedef typename IterT::NonConstValueType NCValueT;
    /// NodeT's child node type, with the same constness (e.g., const InternalNode<...>)
    typedef typename CopyConstness<NodeT, typename NodeT::ChildNodeType>::Type ChildT;
    /// NodeT's child node type with const qualifiers removed
    typedef typename CopyConstness<NCNodeT, typename NCNodeT::ChildNodeType>::Type NCChildT;
    typedef IterTraits<NCNodeT, IterT> ITraits;
    /// NodeT's level in its tree (0 = LeafNode)
    static const Index Level = _Level;

    IterListItem(PrevItemT* prev): mPrev(prev) {}

    IterListItem(const IterListItem& other): mIter(other.mIter), mPrev(NULL) {}
    IterListItem& operator=(const IterListItem& other)
    {
        if (&other != this) {
            mIter = other.mIter;
            mPrev = NULL; ///< @note external call to updateBackPointers() required
        }
        return *this;
    }

    void updateBackPointers(PrevItemT* prev) { mPrev = prev; }

    // The following method specializations differ from the default template
    // implementations mainly in that they don't forward.

    void setIter(const IterT& iter) { mIter = iter; }

    void getNode(Index lvl, NodeT*& node) const
    {
        node = (lvl <= Level) ? mIter.getParentNode() : NULL;
    }

    template<typename OtherIterListItemT>
    void initLevel(Index lvl, OtherIterListItemT& otherListItem)
    {
        if (lvl == Level) {
            const NodeT* node = NULL;
            otherListItem.getNode(lvl, node);
            mIter = (node == NULL) ? IterT() : ITraits::begin(*const_cast<NodeT*>(node));
        }
    }

    Index pos(Index lvl) const { return (lvl == Level) ? mIter.pos() : Index(-1); }

    bool test(Index lvl) const { return (lvl == Level) ? mIter.test() : false; }

    bool next(Index lvl) { return (lvl == Level) ? mIter.next() : false; }

    bool down(Index lvl)
    {
        if (lvl == Level && mPrev != NULL && mIter) {
            if (ChildT* child = ITraits::template getChild<ChildT>(mIter)) {
                mPrev->setIter(PrevItemT::ITraits::begin(*child));
                return true;
            }
        }
        return false;
    }

    Coord getCoord(Index lvl) const { return (lvl == Level) ? mIter.getCoord() : Coord(); }
    Index getChildDim(Index lvl) const { return (lvl == Level) ? NodeT::getChildDim() : 0; }
    Index64 getVoxelCount(Index lvl) const { return (lvl == Level) ? ChildT::NUM_VOXELS : 0; }

    bool isValueOn(Index lvl) const { return (lvl == Level) ? mIter.isValueOn() : false; }

    const NCValueT& getValue(Index lvl) const
    {
        assert(lvl == Level);
        (void)lvl; // avoid unused variable warning in optimized builds
        return mIter.getValue();
    }

    void setValue(Index lvl, const NCValueT& val) const { if (lvl == Level) mIter.setValue(val); }
    void setValueOn(Index lvl, bool on = true) const { if (lvl == Level) mIter.setValueOn(on); }
    void setValueOff(Index lvl) const { if (lvl == Level) mIter.setValueOff(); }

    template<typename ModifyOp>
    void modifyValue(Index lvl, const ModifyOp& op) const
    {
        if (lvl == Level) mIter.modifyValue(op);
    }

private:
    IterT mIter;
    PrevItemT* mPrev;
};


////////////////////////////////////////


//#define DEBUG_TREE_VALUE_ITERATOR

/// @brief Base class for tree-traversal iterators over tile and voxel values
template<typename _TreeT, typename _ValueIterT>
class TreeValueIteratorBase
{
public:
    typedef _TreeT TreeT;
    typedef _ValueIterT ValueIterT;
    typedef typename ValueIterT::NodeType NodeT;
    typedef typename ValueIterT::NonConstValueType ValueT;
    typedef typename NodeT::ChildOnCIter ChildOnIterT;
    static const Index ROOT_LEVEL = NodeT::LEVEL;
    BOOST_STATIC_ASSERT(ValueIterT::NodeType::LEVEL == ROOT_LEVEL);
    static const Index LEAF_LEVEL = 0, ROOT_DEPTH = 0, LEAF_DEPTH = ROOT_LEVEL;

    TreeValueIteratorBase(TreeT&);

    TreeValueIteratorBase(const TreeValueIteratorBase& other);
    TreeValueIteratorBase& operator=(const TreeValueIteratorBase& other);

    /// Specify the depth of the highest level of the tree to which to ascend (depth 0 = root).
    void setMinDepth(Index minDepth);
    /// Return the depth of the highest level of the tree to which this iterator ascends.
    Index getMinDepth() const { return ROOT_LEVEL - Index(mMaxLevel); }
    /// Specify the depth of the lowest level of the tree to which to descend (depth 0 = root).
    void setMaxDepth(Index maxDepth);
    /// Return the depth of the lowest level of the tree to which this iterator ascends.
    Index getMaxDepth() const { return ROOT_LEVEL - Index(mMinLevel); }

    //@{
    /// Return @c true if this iterator is not yet exhausted.
    bool test() const { return mValueIterList.test(mLevel); }
    operator bool() const { return this->test(); }
    //@}

    /// @brief Advance to the next tile or voxel value.
    /// Return @c true if this iterator is not yet exhausted.
    bool next();
    /// Advance to the next tile or voxel value.
    TreeValueIteratorBase& operator++() { this->next(); return *this; }

    /// @brief Return the level in the tree (0 = leaf) of the node to which
    /// this iterator is currently pointing.
    Index getLevel() const { return mLevel; }
    /// @brief Return the depth in the tree (0 = root) of the node to which
    /// this iterator is currently pointing.
    Index getDepth() const { return ROOT_LEVEL - mLevel; }
    static Index getLeafDepth() { return LEAF_DEPTH; }

    /// @brief Return in @a node a pointer to the node over which this iterator is
    /// currently iterating or one of that node's parents, as determined by @a NodeType.
    /// @return a null pointer if @a NodeType specifies a node at a lower level
    /// of the tree than that given by getLevel().
    template<typename NodeType>
    void getNode(NodeType*& node) const { mValueIterList.getNode(mLevel, node); }

    /// @brief Return the global coordinates of the voxel or tile to which
    /// this iterator is currently pointing.
    Coord getCoord() const { return mValueIterList.getCoord(mLevel); }
    /// @brief Return in @a bbox the axis-aligned bounding box of
    /// the voxel or tile to which this iterator is currently pointing.
    /// @return false if the bounding box is empty.
    bool getBoundingBox(CoordBBox&) const;
    /// @brief Return the axis-aligned bounding box of the voxel or tile to which
    /// this iterator is currently pointing.
    CoordBBox getBoundingBox() const { CoordBBox b; this->getBoundingBox(b); return b; }

    /// Return the number of (virtual) voxels corresponding to the value
    Index64 getVoxelCount() const { return mValueIterList.getVoxelCount(mLevel);}

    /// Return @c true if this iterator is currently pointing to a (non-leaf) tile value.
    bool isTileValue() const { return mLevel != 0 && this->test(); }
    /// Return @c true if this iterator is currently pointing to a (leaf) voxel value.
    bool isVoxelValue() const { return mLevel == 0 && this->test(); }
    /// Return @c true if the value to which this iterator is currently pointing is active.
    bool isValueOn() const { return mValueIterList.isValueOn(mLevel); }

    //@{
    /// Return the tile or voxel value to which this iterator is currently pointing.
    const ValueT& getValue() const { return mValueIterList.getValue(mLevel); }
    const ValueT& operator*() const { return this->getValue(); }
    const ValueT* operator->() const { return &(this->operator*()); }
    //@}

    /// @brief Change the tile or voxel value to which this iterator is currently pointing
    /// and mark it as active.
    void setValue(const ValueT& val) const { mValueIterList.setValue(mLevel, val); }
    /// @brief Change the active/inactive state of the tile or voxel value to which
    /// this iterator is currently pointing.
    void setActiveState(bool on) const { mValueIterList.setValueOn(mLevel, on); }
    /// Mark the tile or voxel value to which this iterator is currently pointing as inactive.
    void setValueOff() const { mValueIterList.setValueOff(mLevel); }

    /// @brief Apply a functor to the item to which this iterator is pointing.
    /// (Not valid for const iterators.)
    /// @param op  a functor of the form <tt>void op(ValueType&) const</tt> that modifies
    ///            its argument in place
    /// @see Tree::modifyValue()
    template<typename ModifyOp>
    void modifyValue(const ModifyOp& op) const { mValueIterList.modifyValue(mLevel, op); }

    /// Return a pointer to the tree over which this iterator is iterating.
    TreeT* getTree() const { return mTree; }

    /// Return a string (for debugging, mainly) describing this iterator's current state.
    std::string summary() const;

private:
    bool advance(bool dontIncrement = false);

    typedef typename iter::InvertedTree<NodeT, NodeT::LEVEL>::Type InvTreeT;
    struct PrevChildItem { typedef ChildOnIterT IterT; };
    struct PrevValueItem { typedef ValueIterT IterT; };

    IterListItem<PrevChildItem, InvTreeT, /*VecSize=*/ROOT_LEVEL+1, /*Level=*/0> mChildIterList;
    IterListItem<PrevValueItem, InvTreeT, /*VecSize=*/ROOT_LEVEL+1, /*Level=*/0> mValueIterList;
    Index mLevel;
    int mMinLevel, mMaxLevel;
    TreeT* mTree;
}; // class TreeValueIteratorBase


template<typename TreeT, typename ValueIterT>
inline
TreeValueIteratorBase<TreeT, ValueIterT>::TreeValueIteratorBase(TreeT& tree):
    mChildIterList(NULL),
    mValueIterList(NULL),
    mLevel(ROOT_LEVEL),
    mMinLevel(int(LEAF_LEVEL)),
    mMaxLevel(int(ROOT_LEVEL)),
    mTree(&tree)
{
    mChildIterList.setIter(IterTraits<NodeT, ChildOnIterT>::begin(tree.root()));
    mValueIterList.setIter(IterTraits<NodeT, ValueIterT>::begin(tree.root()));
    this->advance(/*dontIncrement=*/true);
}


template<typename TreeT, typename ValueIterT>
inline
TreeValueIteratorBase<TreeT, ValueIterT>::TreeValueIteratorBase(const TreeValueIteratorBase& other):
    mChildIterList(other.mChildIterList),
    mValueIterList(other.mValueIterList),
    mLevel(other.mLevel),
    mMinLevel(other.mMinLevel),
    mMaxLevel(other.mMaxLevel),
    mTree(other.mTree)
{
    mChildIterList.updateBackPointers();
    mValueIterList.updateBackPointers();
}


template<typename TreeT, typename ValueIterT>
inline TreeValueIteratorBase<TreeT, ValueIterT>&
TreeValueIteratorBase<TreeT, ValueIterT>::operator=(const TreeValueIteratorBase& other)
{
    if (&other != this) {
        mChildIterList = other.mChildIterList;
        mValueIterList = other.mValueIterList;
        mLevel = other.mLevel;
        mMinLevel = other.mMinLevel;
        mMaxLevel = other.mMaxLevel;
        mTree = other.mTree;
        mChildIterList.updateBackPointers();
        mValueIterList.updateBackPointers();
    }
    return *this;
}


template<typename TreeT, typename ValueIterT>
inline void
TreeValueIteratorBase<TreeT, ValueIterT>::setMinDepth(Index minDepth)
{
    mMaxLevel = int(ROOT_LEVEL - minDepth); // level = ROOT_LEVEL - depth
    if (int(mLevel) > mMaxLevel) this->next();
}


template<typename TreeT, typename ValueIterT>
inline void
TreeValueIteratorBase<TreeT, ValueIterT>::setMaxDepth(Index maxDepth)
{
    // level = ROOT_LEVEL - depth
    mMinLevel = int(ROOT_LEVEL - std::min(maxDepth, this->getLeafDepth()));
    if (int(mLevel) < mMinLevel) this->next();
}


template<typename TreeT, typename ValueIterT>
inline bool
TreeValueIteratorBase<TreeT, ValueIterT>::next()
{
    do {
        if (!this->advance()) return false;
    } while (int(mLevel) < mMinLevel || int(mLevel) > mMaxLevel);
    return true;
}


template<typename TreeT, typename ValueIterT>
inline bool
TreeValueIteratorBase<TreeT, ValueIterT>::advance(bool dontIncrement)
{
    bool recurse = false;
    do {
        recurse = false;
        Index
            vPos = mValueIterList.pos(mLevel),
            cPos = mChildIterList.pos(mLevel);
        if (vPos == cPos && mChildIterList.test(mLevel)) {
            /// @todo Once ValueOff iterators properly skip child pointers, remove this block.
            mValueIterList.next(mLevel);
            vPos = mValueIterList.pos(mLevel);
        }
        if (vPos < cPos) {
            if (dontIncrement) return true;
            if (mValueIterList.next(mLevel)) {
                if (mValueIterList.pos(mLevel) == cPos && mChildIterList.test(mLevel)) {
                    /// @todo Once ValueOff iterators properly skip child pointers,
                    /// remove this block.
                    mValueIterList.next(mLevel);
                }
                // If there is a next value and it precedes the next child, return.
                if (mValueIterList.pos(mLevel) < cPos) return true;
            }
        } else {
            // Advance to the next child, which may or may not precede the next value.
            if (!dontIncrement) mChildIterList.next(mLevel);
        }
#ifdef DEBUG_TREE_VALUE_ITERATOR
        std::cout << "\n" << this->summary() << std::flush;
#endif

        // Descend to the lowest level at which the next value precedes the next child.
        while (mChildIterList.pos(mLevel) < mValueIterList.pos(mLevel)) {
#ifdef ENABLE_TREE_VALUE_DEPTH_BOUND_OPTIMIZATION
            if (int(mLevel) == mMinLevel) {
                // If the current node lies at the lowest allowed level, none of its
                // children can be visited, so just advance its child iterator.
                mChildIterList.next(mLevel);
                if (mValueIterList.pos(mLevel) == mChildIterList.pos(mLevel)
                    && mChildIterList.test(mLevel))
                {
                    /// @todo Once ValueOff iterators properly skip child pointers,
                    /// remove this block.
                    mValueIterList.next(mLevel);
                }
            } else
#endif
                if (mChildIterList.down(mLevel)) {
                    --mLevel; // descend one level
                    mValueIterList.initLevel(mLevel, mChildIterList);
                    if (mValueIterList.pos(mLevel) == mChildIterList.pos(mLevel)
                        && mChildIterList.test(mLevel))
                    {
                        /// @todo Once ValueOff iterators properly skip child pointers,
                        /// remove this block.
                        mValueIterList.next(mLevel);
                    }
                } else break;
#ifdef DEBUG_TREE_VALUE_ITERATOR
            std::cout << "\n" << this->summary() << std::flush;
#endif
        }
        // Ascend to the nearest level at which one of the iterators is not yet exhausted.
        while (!mChildIterList.test(mLevel) && !mValueIterList.test(mLevel)) {
            if (mLevel == ROOT_LEVEL) return false;
            ++mLevel;
            mChildIterList.next(mLevel);
            dontIncrement = true;
            recurse = true;
        }
    } while (recurse);
    return true;
}


template<typename TreeT, typename ValueIterT>
inline bool
TreeValueIteratorBase<TreeT, ValueIterT>::getBoundingBox(CoordBBox& bbox) const
{
    if (!this->test()) {
        bbox = CoordBBox();
        return false;
    }
    bbox.min() = mValueIterList.getCoord(mLevel);
    bbox.max() = bbox.min().offsetBy(mValueIterList.getChildDim(mLevel) - 1);
    return true;
}


template<typename TreeT, typename ValueIterT>
inline std::string
TreeValueIteratorBase<TreeT, ValueIterT>::summary() const
{
    std::ostringstream ostr;
    for (int lvl = int(ROOT_LEVEL); lvl >= 0 && lvl >= int(mLevel); --lvl) {
        if (lvl == 0) ostr << "leaf";
        else if (lvl == int(ROOT_LEVEL)) ostr << "root";
        else ostr << "int" << (ROOT_LEVEL - lvl);
        ostr << " v" << mValueIterList.pos(lvl)
            << " c" << mChildIterList.pos(lvl);
        if (lvl > int(mLevel)) ostr << " / ";
    }
    if (this->test() && mValueIterList.pos(mLevel) < mChildIterList.pos(mLevel)) {
        if (mLevel == 0) {
            ostr << " " << this->getCoord();
        } else {
            ostr << " " << this->getBoundingBox();
        }
    }
    return ostr.str();
}


////////////////////////////////////////


/// @brief Base class for tree-traversal iterators over all nodes
template<typename _TreeT, typename RootChildOnIterT>
class NodeIteratorBase
{
public:
    typedef _TreeT TreeT;
    typedef RootChildOnIterT RootIterT;
    typedef typename RootIterT::NodeType RootNodeT;
    typedef typename RootIterT::NonConstNodeType NCRootNodeT;
    static const Index ROOT_LEVEL = RootNodeT::LEVEL;
    typedef typename iter::InvertedTree<NCRootNodeT, ROOT_LEVEL>::Type InvTreeT;
    static const Index LEAF_LEVEL = 0, ROOT_DEPTH = 0, LEAF_DEPTH = ROOT_LEVEL;

    typedef IterTraits<NCRootNodeT, RootIterT> RootIterTraits;

    NodeIteratorBase();
    NodeIteratorBase(TreeT&);

    NodeIteratorBase(const NodeIteratorBase& other);
    NodeIteratorBase& operator=(const NodeIteratorBase& other);

    /// Specify the depth of the highest level of the tree to which to ascend (depth 0 = root).
    void setMinDepth(Index minDepth);
    /// Return the depth of the highest level of the tree to which this iterator ascends.
    Index getMinDepth() const { return ROOT_LEVEL - Index(mMaxLevel); }
    /// Specify the depth of the lowest level of the tree to which to descend (depth 0 = root).
    void setMaxDepth(Index maxDepth);
    /// Return the depth of the lowest level of the tree to which this iterator ascends.
    Index getMaxDepth() const { return ROOT_LEVEL - Index(mMinLevel); }

    //@{
    /// Return @c true if this iterator is not yet exhausted.
    bool test() const { return !mDone; }
    operator bool() const { return this->test(); }
    //@}

    /// @brief Advance to the next tile or voxel value.
    /// @return @c true if this iterator is not yet exhausted.
    bool next();
    /// Advance the iterator to the next leaf node.
    void increment() { this->next(); }
    NodeIteratorBase& operator++() { this->increment(); return *this; }
    /// Increment the iterator n times.
    void increment(Index n) { for (Index i = 0; i < n && this->next(); ++i) {} }

    /// @brief Return the level in the tree (0 = leaf) of the node to which
    /// this iterator is currently pointing.
    Index getLevel() const { return mLevel; }
    /// @brief Return the depth in the tree (0 = root) of the node to which
    /// this iterator is currently pointing.
    Index getDepth() const { return ROOT_LEVEL - mLevel; }
    static Index getLeafDepth() { return LEAF_DEPTH; }

    /// @brief Return the global coordinates of the voxel or tile to which
    /// this iterator is currently pointing.
    Coord getCoord() const;
    /// @brief Return in @a bbox the axis-aligned bounding box of
    /// the voxel or tile to which this iterator is currently pointing.
    /// @return false if the bounding box is empty.
    bool getBoundingBox(CoordBBox& bbox) const;
    /// @brief Return the axis-aligned bounding box of the voxel or tile to which
    /// this iterator is currently pointing.
    CoordBBox getBoundingBox() const { CoordBBox b; this->getBoundingBox(b); return b; }

    //@{
    /// @brief Return the node to which the iterator is pointing.
    /// @note This iterator doesn't have the usual dereference operators (* and ->),
    /// because they would have to be overloaded by the returned node type.
    template<typename NodeT>
    void getNode(NodeT*& node) const { node = NULL; mIterList.getNode(mLevel, node); }
    template<typename NodeT>
    void getNode(const NodeT*& node) const { node = NULL; mIterList.getNode(mLevel, node); }
    //@}

    TreeT* getTree() const { return mTree; }

    std::string summary() const;

private:
    struct PrevItem { typedef RootIterT IterT; };

    IterListItem<PrevItem, InvTreeT, /*VecSize=*/ROOT_LEVEL+1, LEAF_LEVEL> mIterList;
    Index mLevel;
    int mMinLevel, mMaxLevel;
    bool mDone;
    TreeT* mTree;
}; // class NodeIteratorBase


template<typename TreeT, typename RootChildOnIterT>
inline
NodeIteratorBase<TreeT, RootChildOnIterT>::NodeIteratorBase():
    mIterList(NULL),
    mLevel(ROOT_LEVEL),
    mMinLevel(int(LEAF_LEVEL)),
    mMaxLevel(int(ROOT_LEVEL)),
    mDone(true),
    mTree(NULL)
{
}


template<typename TreeT, typename RootChildOnIterT>
inline
NodeIteratorBase<TreeT, RootChildOnIterT>::NodeIteratorBase(TreeT& tree):
    mIterList(NULL),
    mLevel(ROOT_LEVEL),
    mMinLevel(int(LEAF_LEVEL)),
    mMaxLevel(int(ROOT_LEVEL)),
    mDone(false),
    mTree(&tree)
{
    mIterList.setIter(RootIterTraits::begin(tree.root()));
}


template<typename TreeT, typename RootChildOnIterT>
inline
NodeIteratorBase<TreeT, RootChildOnIterT>::NodeIteratorBase(const NodeIteratorBase& other):
    mIterList(other.mIterList),
    mLevel(other.mLevel),
    mMinLevel(other.mMinLevel),
    mMaxLevel(other.mMaxLevel),
    mDone(other.mDone),
    mTree(other.mTree)
{
    mIterList.updateBackPointers();
}


template<typename TreeT, typename RootChildOnIterT>
inline NodeIteratorBase<TreeT, RootChildOnIterT>&
NodeIteratorBase<TreeT, RootChildOnIterT>::operator=(const NodeIteratorBase& other)
{
    if (&other != this) {
        mLevel = other.mLevel;
        mMinLevel = other.mMinLevel;
        mMaxLevel = other.mMaxLevel;
        mDone = other.mDone;
        mTree = other.mTree;
        mIterList = other.mIterList;
        mIterList.updateBackPointers();
    }
    return *this;
}


template<typename TreeT, typename RootChildOnIterT>
inline void
NodeIteratorBase<TreeT, RootChildOnIterT>::setMinDepth(Index minDepth)
{
    mMaxLevel = int(ROOT_LEVEL - minDepth); // level = ROOT_LEVEL - depth
    if (int(mLevel) > mMaxLevel) this->next();
}


template<typename TreeT, typename RootChildOnIterT>
inline void
NodeIteratorBase<TreeT, RootChildOnIterT>::setMaxDepth(Index maxDepth)
{
    // level = ROOT_LEVEL - depth
    mMinLevel = int(ROOT_LEVEL - std::min(maxDepth, this->getLeafDepth()));
    if (int(mLevel) < mMinLevel) this->next();
}


template<typename TreeT, typename RootChildOnIterT>
inline bool
NodeIteratorBase<TreeT, RootChildOnIterT>::next()
{
    do {
        if (mDone) return false;

        // If the iterator over the current node points to a child,
        // descend to the child (depth-first traversal).
        if (int(mLevel) > mMinLevel && mIterList.test(mLevel)) {
            if (!mIterList.down(mLevel)) return false;
            --mLevel;
        } else {
            // Ascend to the nearest ancestor that has other children.
            while (!mIterList.test(mLevel)) {
                if (mLevel == ROOT_LEVEL) {
                    // Can't ascend higher than the root.
                    mDone = true;
                    return false;
                }
                ++mLevel; // ascend one level
                mIterList.next(mLevel); // advance to the next child, if there is one
            }
            // Descend to the child.
            if (!mIterList.down(mLevel)) return false;
            --mLevel;
        }
    } while (int(mLevel) < mMinLevel || int(mLevel) > mMaxLevel);
    return true;
}


template<typename TreeT, typename RootChildOnIterT>
inline Coord
NodeIteratorBase<TreeT, RootChildOnIterT>::getCoord() const
{
    if (mLevel != ROOT_LEVEL) return  mIterList.getCoord(mLevel + 1);
    RootNodeT* root = NULL;
    this->getNode(root);
    return root ? root->getMinIndex() : Coord::min();
}


template<typename TreeT, typename RootChildOnIterT>
inline bool
NodeIteratorBase<TreeT, RootChildOnIterT>::getBoundingBox(CoordBBox& bbox) const
{
    if (mLevel == ROOT_LEVEL) {
        RootNodeT* root = NULL;
        this->getNode(root);
        if (root == NULL) {
            bbox = CoordBBox();
            return false;
        }
        root->getIndexRange(bbox);
        return true;
    }
    bbox.min() = mIterList.getCoord(mLevel + 1);
    bbox.max() = bbox.min().offsetBy(mIterList.getChildDim(mLevel + 1) - 1);
    return true;
}


template<typename TreeT, typename RootChildOnIterT>
inline std::string
NodeIteratorBase<TreeT, RootChildOnIterT>::summary() const
{
    std::ostringstream ostr;
    for (int lvl = int(ROOT_LEVEL); lvl >= 0 && lvl >= int(mLevel); --lvl) {
        if (lvl == 0) ostr << "leaf";
        else if (lvl == int(ROOT_LEVEL)) ostr << "root";
        else ostr << "int" << (ROOT_LEVEL - lvl);
        ostr << " c" << mIterList.pos(lvl);
        if (lvl > int(mLevel)) ostr << " / ";
    }
    CoordBBox bbox;
    this->getBoundingBox(bbox);
    ostr << " " << bbox;
    return ostr.str();
}


////////////////////////////////////////


/// @brief Base class for tree-traversal iterators over all leaf nodes (but not leaf voxels)
template<typename TreeT, typename RootChildOnIterT>
class LeafIteratorBase
{
public:
    typedef RootChildOnIterT RootIterT;
    typedef typename RootIterT::NodeType RootNodeT;
    typedef typename RootIterT::NonConstNodeType NCRootNodeT;
    static const Index ROOT_LEVEL = RootNodeT::LEVEL;
    typedef typename iter::InvertedTree<NCRootNodeT, ROOT_LEVEL>::Type InvTreeT;
    typedef typename boost::mpl::front<InvTreeT>::type NCLeafNodeT;
    typedef typename CopyConstness<RootNodeT, NCLeafNodeT>::Type LeafNodeT;
    static const Index LEAF_LEVEL = 0, LEAF_PARENT_LEVEL = LEAF_LEVEL + 1;

    typedef IterTraits<NCRootNodeT, RootIterT> RootIterTraits;

    LeafIteratorBase(): mIterList(NULL), mTree(NULL) {}

    LeafIteratorBase(TreeT& tree): mIterList(NULL), mTree(&tree)
    {
        // Initialize the iterator list with a root node iterator.
        mIterList.setIter(RootIterTraits::begin(tree.root()));
        // Descend along the first branch, initializing the node iterator at each level.
        Index lvl = ROOT_LEVEL;
        for ( ; lvl > 0 && mIterList.down(lvl); --lvl) {}
        // If the first branch terminated above the leaf level, backtrack to the next branch.
        if (lvl > 0) this->next();
    }

    LeafIteratorBase(const LeafIteratorBase& other): mIterList(other.mIterList), mTree(other.mTree)
    {
        mIterList.updateBackPointers();
    }
    LeafIteratorBase& operator=(const LeafIteratorBase& other)
    {
        if (&other != this) {
            mTree = other.mTree;
            mIterList = other.mIterList;
            mIterList.updateBackPointers();
        }
        return *this;
    }

    //@{
    /// Return the leaf node to which the iterator is pointing.
    LeafNodeT* getLeaf() const { LeafNodeT* n = NULL; mIterList.getNode(LEAF_LEVEL, n); return n; }
    LeafNodeT& operator*() const { return *this->getLeaf(); }
    LeafNodeT* operator->() const { return this->getLeaf(); }
    //@}

    bool test() const { return mIterList.test(LEAF_PARENT_LEVEL); }
    operator bool() const { return this->test(); }

    //@{
    /// Advance the iterator to the next leaf node.
    bool next();
    void increment() { this->next(); }
    LeafIteratorBase& operator++() { this->increment(); return *this; }
    //@}
    /// Increment the iterator n times.
    void increment(Index n) { for (Index i = 0; i < n && this->next(); ++i) {} }

    TreeT* getTree() const { return mTree; }

private:
    struct PrevItem { typedef RootIterT IterT; };

    /// @note Even though a LeafIterator doesn't iterate over leaf voxels,
    /// the first item of this linked list of node iterators is a leaf node iterator,
    /// whose purpose is only to provide access to its parent leaf node.
    IterListItem<PrevItem, InvTreeT, /*VecSize=*/ROOT_LEVEL+1, LEAF_LEVEL> mIterList;
    TreeT* mTree;
}; // class LeafIteratorBase


template<typename TreeT, typename RootChildOnIterT>
inline bool
LeafIteratorBase<TreeT, RootChildOnIterT>::next()
{
    // If the iterator is valid for the current node one level above the leaf level,
    // advance the iterator to the node's next child.
    if (mIterList.test(LEAF_PARENT_LEVEL) && mIterList.next(LEAF_PARENT_LEVEL)) {
        mIterList.down(LEAF_PARENT_LEVEL); // initialize the leaf iterator
        return true;
    }

    Index lvl = LEAF_PARENT_LEVEL;
    while (!mIterList.test(LEAF_PARENT_LEVEL)) {
        if (mIterList.test(lvl)) {
            mIterList.next(lvl);
        } else {
            do {
                // Ascend to the nearest level at which
                // one of the iterators is not yet exhausted.
                if (lvl == ROOT_LEVEL) return false;
                ++lvl;
                if (mIterList.test(lvl)) mIterList.next(lvl);
            } while (!mIterList.test(lvl));
        }
        // Descend to the lowest child, but not as far as the leaf iterator.
        while (lvl > LEAF_PARENT_LEVEL && mIterList.down(lvl)) --lvl;
    }
    mIterList.down(LEAF_PARENT_LEVEL); // initialize the leaf iterator
    return true;
}


////////////////////////////////////////


/// An IteratorRange wraps a tree or node iterator, giving the iterator TBB
/// splittable range semantics.
template<typename IterT>
class IteratorRange
{
public:
    IteratorRange(const IterT& iter, size_t grainSize = 8):
        mIter(iter),
        mGrainSize(grainSize),
        mSize(0)
    {
        mSize = this->size();
    }
    IteratorRange(IteratorRange& other, tbb::split):
        mIter(other.mIter),
        mGrainSize(other.mGrainSize),
        mSize(other.mSize >> 1)
    {
        other.increment(mSize);
    }

    /// @brief Return a reference to this range's iterator.
    /// @note The reference is const, because the iterator should not be
    /// incremented directly.  Use this range object's increment() instead.
    const IterT& iterator() const { return mIter; }

    bool empty() const { return mSize == 0 || !mIter.test(); }
    bool test() const { return !this->empty(); }
    operator bool() const { return !this->empty(); }

    /// @brief Return @c true if this range is splittable (i.e., if the iterator
    /// can be advanced more than mGrainSize times).
    bool is_divisible() const { return mSize > mGrainSize; }

    /// Advance the iterator @a n times.
    void increment(Index n = 1) { for ( ; n > 0 && mSize > 0; --n, --mSize, ++mIter) {} }
    /// Advance the iterator to the next item.
    IteratorRange& operator++() { this->increment(); return *this; }
    /// @brief Advance the iterator to the next item.
    /// @return @c true if the iterator is not yet exhausted.
    bool next() { this->increment(); return this->test(); }

private:
    Index size() const { Index n = 0; for (IterT it(mIter); it.test(); ++n, ++it) {} return n; }

    IterT mIter;
    size_t mGrainSize;
    /// @note mSize is only an estimate of the number of times mIter can be incremented
    /// before it is exhausted (because the topology of the underlying tree could change
    /// during iteration).  For the purpose of range splitting, though, that should be
    /// sufficient, since the two halves need not be of exactly equal size.
    Index mSize;
};


////////////////////////////////////////


/// @brief Base class for tree-traversal iterators over real and virtual voxel values
/// @todo class TreeVoxelIteratorBase;

} // namespace tree
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb

#endif // OPENVDB_TREE_TREEITERATOR_HAS_BEEN_INCLUDED

// Copyright (c) 2012-2016 DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )