This file is indexed.

/usr/include/Field3D/Field.h is in libfield3d-dev 1.7.2-1build2.

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
//----------------------------------------------------------------------------//

/*
 * Copyright (c) 2009 Sony Pictures Imageworks Inc
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.  Neither the name of Sony Pictures Imageworks 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 DIRECT, 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.
 */

//----------------------------------------------------------------------------//

/*! \file Field.h
  \brief Contains Field, WritableField and ResizableField classes.
  \ingroup field
*/

//----------------------------------------------------------------------------//

#ifndef _INCLUDED_Field3D_Field_H_
#define _INCLUDED_Field3D_Field_H_

#include <cmath>
#include <vector>
#include <map>

#include <boost/intrusive_ptr.hpp> 
#include <boost/thread/mutex.hpp>

#include "Traits.h"
#include "Exception.h"
#include "FieldMapping.h"
#include "FieldMetadata.h"
#include "Log.h"
#include "RefCount.h"
#include "Types.h"

//----------------------------------------------------------------------------//

#include "ns.h"

FIELD3D_NAMESPACE_OPEN

//----------------------------------------------------------------------------//
// Exceptions
//----------------------------------------------------------------------------//

namespace Exc {

DECLARE_FIELD3D_GENERIC_EXCEPTION(MemoryException, Exception)
DECLARE_FIELD3D_GENERIC_EXCEPTION(ResizeException, Exception)

} // namespace Exc

//----------------------------------------------------------------------------//
// FieldBase
//----------------------------------------------------------------------------//

/*! \class FieldBase
  \ingroup field
  This class provides a common base for all Field objects. It serves the 
  purpose of providing the className() virtual function and as a container
  for the metadata map
*/

class FIELD3D_API FieldBase : public RefBase, public MetadataCallback
{
public:

  // Typedefs ------------------------------------------------------------------

  typedef boost::intrusive_ptr<FieldBase> Ptr;
  typedef FieldBase class_type;

  // Constructors --------------------------------------------------------------

  //! \name Constructors, destructors, copying
  //! \{

  //! Constructor
  FieldBase();

  //! Copy Constructor
  FieldBase(const FieldBase &);

  //! Destructor
  virtual ~FieldBase();

  //! \}

  // RTTI replacement ----------------------------------------------------------

  static const char *staticClassName()
  {
    return "FieldBase";
  }

  static const char* staticClassType()
  {
    return staticClassName();
  }
  
  // To be implemented by subclasses -------------------------------------------

  //! \name To be implemented by subclasses
  //! \{

  //! Returns the class name of the object. Used by the class pool and when
  //! writing the data to disk.
  //! \note This is different from classType for any templated class,
  //! as staticClassType() will include the template parameter(s) but className
  //! remains just the name of the template itself.
  virtual std::string className() const = 0;

  //! Returns the full class type string. 
  virtual std::string classType() const = 0;

  //! Returns a pointer to a copy of the field, pure virtual so ensure
  //! derived classes properly implement it
  virtual Ptr clone() const = 0;

  //! \}

  // Access to metadata --------------------------------------------------------

  //! \name Metadata
  //! \{

  //! accessor to the m_metadata class
  FieldMetadata& metadata()
  { return m_metadata; }

  //! Read only access to the m_metadata class
  const FieldMetadata& metadata() const
  { return m_metadata; }

  //! Copies the metadata from a second field
  void copyMetadata(const FieldBase &field)
  { m_metadata = field.metadata(); }

  //! \}

  // Public data members -------------------------------------------------------

  //! Optional name of the field
  std::string name;
  //! Optional name of the attribute the field represents
  std::string attribute;

 private:

  // Private data members ------------------------------------------------------

  //! metadata
  FieldMetadata m_metadata;

};

//----------------------------------------------------------------------------//
// FieldRes
//----------------------------------------------------------------------------//

/*! \class FieldRes
  \ingroup field
  This class serves to isolate the extents and data window from its
  templated subclasses. Thus, anything that needs to access the extents or
  data window don't need to know about what data type the subclass is
  templated on.

  It also owns the field's mapping.

  Why do we have both an extent and a data window? The extents are used
  to define which range of voxels define the [0..1] local coordinate system.
  The data window in turn defines the voxels that are legal to read/write
  from. Thus, for optimization we may have a large extents but a small data
  window, or a small extents and a larger data window which would let us
  apply large-kernel filters without having to deal with boundary conditions.
*/

//----------------------------------------------------------------------------//

class FieldRes : public FieldBase
{
public:

  // Typedefs ------------------------------------------------------------------

  typedef boost::intrusive_ptr<FieldRes> Ptr;
  typedef std::vector<Ptr> Vec;

  // RTTI replacement ----------------------------------------------------------

  typedef FieldRes class_type;
  DEFINE_FIELD_RTTI_ABSTRACT_CLASS;

  virtual std::string dataTypeString() const
  { return std::string("FieldRes"); }

  static const char *staticClassName()
  {
    return "FieldRes";
  }

  static const char *staticClassType()
  {
    return staticClassName();
  }
  
  // Ctor, dtor ----------------------------------------------------------------

  //! This constructor ensures that we have a valid mapping at all times
  FieldRes();

  //! Base class copy constructor
  //! \todo OSS Go over the copy constructing - is it implemented right? 8hr
  FieldRes(const FieldRes &src);

  // Main methods --------------------------------------------------------------

  //! Returns the extents of the data. This signifies the relevant area that
  //! the data exists over. However, the data window (below) may be smaller
  //! than the extents, in which case it is only safe to call value() for
  //! those coordinate inside the data window.
  inline const Box3i& extents() const
  { return m_extents; }
  //! Returns the data window. Any coordinate inside this window is safe to
  //! pass to value() in the Field subclass.
  inline const Box3i& dataWindow() const
  { return m_dataWindow; }

  inline V3i const dataResolution() const
  { return m_dataWindow.max - m_dataWindow.min + V3i(1); }

  //! Sets the field's mapping
  void setMapping(FieldMapping::Ptr mapping);

  //! Returns a pointer to the mapping
  FieldMapping::Ptr mapping()
  { return m_mapping; }

  //! Returns a pointer to the mapping
  const FieldMapping::Ptr mapping() const
  { return m_mapping; }

  //! Returns true is the indicies are in bounds of the data window
  bool isInBounds(int i, int j, int k) const;

  // To be implemented by subclasses -------------------------------------------

  //! Returns the memory usage (in bytes)
  //! \note This needs to be re-implemented for any subclass that adds data
  //! members. Those classes should also call their superclass and add the 
  //! combined memory use.
  virtual long long int memSize() const
  { return sizeof(*this); }

  //! Tells the subclass that the mapping changed
  virtual void mappingChanged()
  { /* Empty */ }

  //! Counts the number of voxels. For most fields, this is just the volume
  //! of the data window, but sparse data structures can override this to 
  //! return a better value
  virtual size_t voxelCount() const
  { 
    V3i res = m_dataWindow.size() + V3i(1);
    return res.x * res.y * res.z;
  }

protected:

  // Typedefs ------------------------------------------------------------------

  typedef MatrixFieldMapping default_mapping;

  // Data members --------------------------------------------------------------

  //! Defines the extents of the the storage. This may be larger or smaller 
  //! than the data window, and in the case where it is larger, care must be
  //! taken not to access voxels outside the data window. This should be treated 
  //! as a closed (i.e. inclusive) interval.
  Box3i m_extents;
  //! Defines the area where data is allocated. This should be treated as a
  //! closed (i.e. inclusive) interval.
  Box3i m_dataWindow;
  //! Pointer to the field's mapping
  FieldMapping::Ptr m_mapping;

private:

  // Typedefs ------------------------------------------------------------------

  //! Convenience typedef for referring to base class
  typedef FieldBase base;

};

//----------------------------------------------------------------------------//

inline FieldRes::FieldRes()
  : m_mapping(new default_mapping)
{ 
  m_extents = Box3i(V3i(0), V3i(-1));
  m_dataWindow = m_extents;
  m_mapping->setExtents(m_extents); 
}

//----------------------------------------------------------------------------//

inline FieldRes::FieldRes(const FieldRes &src) 
  : FieldBase(src)
{
  // Call base class first
  // FieldBase(src);
  // Copy self
  *this = src;
  m_mapping = src.mapping()->clone();
}

//----------------------------------------------------------------------------//

inline void FieldRes::setMapping(FieldMapping::Ptr mapping)
{ 
  if (mapping) {
    m_mapping = mapping->clone(); 
    m_mapping->setExtents(m_extents); 
  } else {
    Msg::print(Msg::SevWarning, 
               "Tried to call FieldRes::setMapping with null pointer");
  }
  // Tell subclasses about the mapping change
  mappingChanged();
}

//----------------------------------------------------------------------------//

inline bool FieldRes::isInBounds(int i, int j, int k) const
{
  // Check bounds
  if (i < m_dataWindow.min.x || i > m_dataWindow.max.x ||
      j < m_dataWindow.min.y || j > m_dataWindow.max.y ||
      k < m_dataWindow.min.z || k > m_dataWindow.max.z) {
    return false;
  }

  return true;
}

//----------------------------------------------------------------------------//
// Field
//----------------------------------------------------------------------------//

/*! \class Field
  \ingroup field
  This class provides read-only access to voxels. A read-only buffer can not be
  resized. Resizing is added by ResizableField. The object still has a 
  size of course, but it can only be set by subclass-specific methods.
  \note Regarding the template type Data_T. This does not necessarily have
  to be the internal data storage format, it only defines the -return type-
  that the particular Field instance provides.
*/

template <class Data_T>
class Field : public FieldRes
{
public:

  // Typedefs ------------------------------------------------------------------
  
  typedef boost::intrusive_ptr<Field> Ptr;

  //! Allows us to reference the template class
  typedef Data_T value_type;

  //! This is a convenience typedef for the list that 
  //! Field3DInputFile::readScalarLayers() and 
  //! Field3DInputFile::readVectorLayers() will return its data in
  typedef std::vector<Ptr> Vec;

  // RTTI replacement ----------------------------------------------------------

  typedef Field<Data_T> class_type;
  DEFINE_FIELD_RTTI_ABSTRACT_CLASS;

  static const char *staticClassName()
  {
    return "Field";
  }

  static const char* staticClassType()
  {
    return Field<Data_T>::ms_classType.name();
  }

  // Constructors --------------------------------------------------------------

  //! Dtor
  virtual ~Field()
  { /* Empty */ }

  // Iterators -----------------------------------------------------------------

  //! Const iterator for traversing the values in a Field object.
  //! \ingroup field
  class const_iterator;

  //! Const iterator to first element. "cbegin" matches the tr1 c++ standard.
  const_iterator cbegin() const;
  //! Const iterator to first element of specific subset
  const_iterator cbegin(const Box3i &subset) const;
  //! Const iterator pointing one element past the last valid one.
  const_iterator cend() const;
  //! Const iterator pointing one element past the last valid one (for a 
  //! subset)
  const_iterator cend(const Box3i &subset) const;

  // To be implemented by subclasses -------------------------------------------

  //! Read access to a voxel. The coordinates are in integer voxel space . 
  //! \note Before the internal storage is accessed, the subclass must compute 
  //! the data window coordinates by looking at Field::m_dataWindow.
  //! \note Virtual functions are known not to play nice with threading.
  //! Therefor, concrete classes can implement (by convention) fastValue()
  //! as a non-virtual function.
  virtual Data_T value(int i, int j, int k) const = 0;

  // Other member functions ----------------------------------------------------

  virtual std::string dataTypeString() const 
  { return DataTypeTraits<Data_T>::name(); }


private:

  // Static data members -------------------------------------------------------

  static TemplatedFieldType<Field<Data_T> > ms_classType;

  // Typedefs ------------------------------------------------------------------

  //! Convenience typedef for referring to base class
  typedef FieldRes base;

};

//----------------------------------------------------------------------------//

#define FIELD3D_CLASSNAME_CLASSTYPE_IMPLEMENTATION  \
  virtual std::string className() const             \
  { return staticClassName(); }                     \
  virtual std::string classType() const             \
  { return staticClassType(); }                     \
  
#define FIELD3D_CLASSTYPE_TEMPL_INSTANTIATION(field)                  \
  template <typename Data_T>                                          \
  TemplatedFieldType<field<Data_T> > field<Data_T>::ms_classType =    \
    TemplatedFieldType<field<Data_T> >();                             \
  
FIELD3D_CLASSTYPE_TEMPL_INSTANTIATION(Field);

//----------------------------------------------------------------------------//
// Field::const_iterator
//----------------------------------------------------------------------------//

template <class Data_T>
class Field<Data_T>::const_iterator
{

public:
#if defined(WIN32) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
  typedef std::forward_iterator_tag iterator_category;
  typedef Data_T value_type;
  typedef ptrdiff_t difference_type;
  typedef ptrdiff_t distance_type;
  typedef Data_T *pointer;
  typedef Data_T& reference;
#endif

  // Constructors --------------------------------------------------------------

  const_iterator(const const_iterator &i) 
    :  x(i.x), y(i.y), z(i.z), 
       m_window(i.m_window), m_field(i.m_field) 
  { }

  const_iterator(const Field<Data_T> &field, const Box3i &window,
                 const V3i &currentPos)
    : x(currentPos.x), y(currentPos.y), z(currentPos.z), 
      m_window(window), m_field(field)
  { }

  // Operators -----------------------------------------------------------------

  inline const const_iterator& operator ++ ()
  {
    if (x == m_window.max.x) {
      if (y == m_window.max.y) {
        x = m_window.min.x;
        y = m_window.min.y;
        ++z;
      } else {
        x = m_window.min.x;
        ++y;
      }
    } else {
      ++x;
    }
    return *this;
  }
  template <class Iter_T>
  bool operator == (const Iter_T &rhs) const
  {
    return x == rhs.x && y == rhs.y && z == rhs.z;
  }
  template <class Iter_T>
  bool operator != (const Iter_T &rhs) const
  {
    return x != rhs.x || y != rhs.y || z != rhs.z;
  }
  inline Data_T operator * () const
  {
    return m_field.value(x, y, z);
  }
  // Public data members -------------------------------------------------------

  //! Current position
  int x, y, z;

private:

  // Private data members ------------------------------------------------------

  //! Window to traverse
  Box3i m_window;
  //! Reference to field being iterated over
  const Field<Data_T> &m_field;

};

//----------------------------------------------------------------------------//

template <class Data_T> 
typename Field<Data_T>::const_iterator 
Field<Data_T>::cbegin() const
{
  if (FieldRes::dataResolution() == V3i(0))
    return cend();
  return const_iterator(*this, m_dataWindow, m_dataWindow.min);
}

//----------------------------------------------------------------------------//

template <class Data_T> 
typename Field<Data_T>::const_iterator
Field<Data_T>::cbegin(const Box3i &subset) const
{
  if (subset.isEmpty())
    return cend(subset);
  return const_iterator(*this, subset, subset.min);
}

//----------------------------------------------------------------------------//

template <class Data_T>
typename Field<Data_T>::const_iterator 
Field<Data_T>::cend() const
{ 
  return const_iterator(*this, m_dataWindow, 
                        V3i(m_dataWindow.min.x, 
                            m_dataWindow.min.y,
                            m_dataWindow.max.z + 1));
}

//----------------------------------------------------------------------------//

template <class Data_T>
typename Field<Data_T>::const_iterator 
Field<Data_T>::cend(const Box3i &subset) const
{ 
  return const_iterator(*this, subset, V3i(subset.min.x, 
                                           subset.min.y,
                                           subset.max.z + 1));
}

//----------------------------------------------------------------------------//
// WritableField
//----------------------------------------------------------------------------//

/*! \class WritableField
  \ingroup field
  This class brings together both read- and write-access to voxels. The
  buffer can not be resized. Resizing is added by ResizableField.
*/

//----------------------------------------------------------------------------//

template <class Data_T>
class WritableField 
  : public Field<Data_T>
{
public:

  // Typedefs ------------------------------------------------------------------
  
  typedef boost::intrusive_ptr<WritableField> Ptr;

  // RTTI replacement ----------------------------------------------------------

  typedef WritableField<Data_T> class_type;
  DEFINE_FIELD_RTTI_ABSTRACT_CLASS;

  static const char *staticClassName()
  {
    return "WritableField";
  }

  static const char* staticClassType()
  {
    return WritableField<Data_T>::ms_classType.name();
  }
  
  // Iterators -----------------------------------------------------------------

  //! Non-const iterator for traversing the values in a Field object.
  //! \ingroup field
  class iterator;

  //! Iterator to first element.
  inline iterator begin();
  //! Iterator to first element of specific subset
  inline iterator begin(const Box3i &subset);
  //! Iterator pointing one element past the last valid one.
  inline iterator end();
  //! Iterator pointing one element past the last valid one (for a 
  //! subset)
  inline iterator end(const Box3i &subset);

  // To be implemented by subclasses ------------------------------------------- 

  //! Write access to a voxel. The coordinates are global coordinates. 
  //! \note Before the internal storage is accessed, the subclass must compute 
  //! the crop window coordinates by looking at Field::m_dataWindow.
  //! \note This is named differently from the const value so that non-const
  //! objects still have a clear way of accessing data in a const way.
  //! \note Virtual functions are known not to play nice with threading.
  //! Therefor, concrete classes can implement (by convention) fastLValue()
  //! as a non-virtual function.
  virtual Data_T& lvalue(int i, int j, int k) = 0;

  // Main methods --------------------------------------------------------------

  //! Clears all the voxels in the storage. Should be re-implemented by
  //! subclasses that can provide a more efficient version.
  virtual void clear(const Data_T &value)
  { std::fill(begin(), end(), value); }

private:

  // Static data members -------------------------------------------------------

  static TemplatedFieldType<WritableField<Data_T> > ms_classType;

  // Typedefs ------------------------------------------------------------------

  typedef Field<Data_T> base;

};

//----------------------------------------------------------------------------//

FIELD3D_CLASSTYPE_TEMPL_INSTANTIATION(WritableField);

//----------------------------------------------------------------------------//
// WritableField::iterator
//----------------------------------------------------------------------------//

template <class Data_T>
class WritableField<Data_T>::iterator
{
public:
#if defined(WIN32) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
  typedef std::forward_iterator_tag iterator_category;
  typedef Data_T value_type;
  typedef ptrdiff_t difference_type;
  typedef ptrdiff_t distance_type;
  typedef Data_T *pointer;
  typedef Data_T& reference;
#endif

  // Constructors --------------------------------------------------------------

  iterator(WritableField<Data_T> &field, const Box3i &window,
           const V3i &currentPos)
    : x(currentPos.x), y(currentPos.y), z(currentPos.z), 
      m_window(window), m_field(field)
  { }

  // Operators -----------------------------------------------------------------

  inline const iterator& operator ++ ()
  {
    if (x == m_window.max.x) {
      if (y == m_window.max.y) {
        x = m_window.min.x;
        y = m_window.min.y;
        ++z;
      } else {
        x = m_window.min.x;
        ++y;
      }
    } else {
      ++x;
    }
    return *this;
  }

  template <class Iter_T>
  bool operator == (const Iter_T &rhs) const
  {
    return x == rhs.x && y == rhs.y && z == rhs.z;
  }

  template <class Iter_T>
  bool operator != (const Iter_T &rhs) const
  {
    return x != rhs.x || y != rhs.y || z != rhs.z;
  }

  inline Data_T& operator * () const
  {
    return m_field.lvalue(x, y, z);
  }

  // Public data members -------------------------------------------------------

  //! Current position
  int x, y, z;

private:

  // Private data members ------------------------------------------------------

  //! Window to traverse
  Box3i m_window;
  //! Reference to field being iterated over
  WritableField<Data_T> &m_field;

};

//----------------------------------------------------------------------------//

template <class Data_T>
inline typename WritableField<Data_T>::iterator 
WritableField<Data_T>::begin()
{
  if (FieldRes::dataResolution() == V3i(0))
    return end();
  return iterator(*this, Field<Data_T>::m_dataWindow, 
                  Field<Data_T>::m_dataWindow.min);
}

//----------------------------------------------------------------------------//

template <class Data_T>
inline typename WritableField<Data_T>::iterator 
WritableField<Data_T>::begin(const Box3i &subset)
{
  if (subset.isEmpty())
    return end(subset);
  return iterator(*this, subset, subset.min);
}

//----------------------------------------------------------------------------//

template <class Data_T>
inline typename WritableField<Data_T>::iterator 
WritableField<Data_T>::end()
{ return iterator(*this, Field<Data_T>::m_dataWindow, 
                  V3i(Field<Data_T>::m_dataWindow.min.x, 
                      Field<Data_T>::m_dataWindow.min.y,
                      Field<Data_T>::m_dataWindow.max.z + 1));
}

//----------------------------------------------------------------------------//

template <class Data_T>
inline typename WritableField<Data_T>::iterator 
WritableField<Data_T>::end(const Box3i &subset)
{ return iterator(*this, subset, 
                  V3i(subset.min.x, subset.min.y, subset.max.z + 1));
}

//----------------------------------------------------------------------------//
// ResizableField
//----------------------------------------------------------------------------//

/*! \class ResizableField
  \ingroup field
  This class adds the ability to resize the data storage object. Most Field
  subclasses will derive from this class. Only classes that cannot implement
  sizeChanged() in a reasonable manner should derive from Field or 
  WritableField.
*/

//----------------------------------------------------------------------------//

template <class Data_T>
class ResizableField
  : public WritableField<Data_T>
{
public:

  // Typedefs ------------------------------------------------------------------

  typedef boost::intrusive_ptr<ResizableField> Ptr;

  // RTTI replacement ----------------------------------------------------------

  typedef ResizableField<Data_T> class_type;
  DEFINE_FIELD_RTTI_ABSTRACT_CLASS;

  static const char *staticClassName()
  {
    return "ResizableField";
  }
  
  static const char* staticClassType()
  {
    return ResizableField<Data_T>::ms_classType.name();
  }
  
  // Main methods --------------------------------------------------------------

  //! Resizes the object
  //! \warning Never call this from a constructor. It calls the virtual
  //! function sizeChanged().
  void setSize(const V3i &size);
  //! Resizes the object
  //! \warning Never call this from a constructor. It calls the virtual
  //! function sizeChanged().
  void setSize(const Box3i &extents);
  //! Resizes the object
  //! \warning Never call this from a constructor. It calls the virtual
  //! function sizeChanged().
  void setSize(const Box3i &extents, const Box3i &dataWindow);
  //! Resizes the object with padding
  //! \warning Never call this from a constructor. It calls the virtual
  //! function sizeChanged().
  void setSize(const V3i &size, int padding);

  //! Copies the data from another Field, also resizes
  void copyFrom(typename Field<Data_T>::Ptr other);
  //! Copies the data from another Field of another template class, 
  //! also resizes
  template <class Data_T2>
  void copyFrom(typename Field<Data_T2>::Ptr other);

  //! Sets up this field so that resolution and mapping matches the other
  void matchDefinition(FieldRes::Ptr fieldToMatch);

protected:

  // Static data members -------------------------------------------------------

  static TemplatedFieldType<ResizableField<Data_T> > ms_classType;

  // Typedefs ------------------------------------------------------------------

  typedef WritableField<Data_T> base;

  // To be implemented by subclasses -------------------------------------------

  //! Subclasses should re-implement this if they need to perform memory 
  //! allocations, etc. every time the size of the storage changes.
  //! \note Make sure to call the base class version in subclasses!
  virtual void sizeChanged()
  { base::m_mapping->setExtents(base::m_extents); }

};

//----------------------------------------------------------------------------//

FIELD3D_CLASSTYPE_TEMPL_INSTANTIATION(ResizableField);

//----------------------------------------------------------------------------//

template <class Data_T>
void ResizableField<Data_T>::setSize(const V3i &size)
{
  assert(size.x >= 0);
  assert(size.y >= 0);
  assert(size.z >= 0);

  Field<Data_T>::m_extents.min = V3i(0);
  Field<Data_T>::m_extents.max = size - V3i(1);
  Field<Data_T>::m_dataWindow = Field<Data_T>::m_extents;

  // Tell subclasses that the size changed so they can update themselves.
  sizeChanged();
}

//----------------------------------------------------------------------------//

template <class Data_T>
void ResizableField<Data_T>::setSize(const Box3i &extents)
{ 
  Field<Data_T>::m_extents = extents;
  Field<Data_T>::m_dataWindow = extents;
  // Tell subclasses that the size changed so they can update themselves.
  sizeChanged();
}

//----------------------------------------------------------------------------//

template <class Data_T>
void ResizableField<Data_T>::setSize(const Box3i &extents, 
                                     const Box3i &dataWindow)
{ 
  Field<Data_T>::m_extents = extents;
  Field<Data_T>::m_dataWindow = dataWindow;
  // Tell subclasses that the size changed so they can update themselves.
  sizeChanged();
}

//----------------------------------------------------------------------------//

template <class Data_T>
void ResizableField<Data_T>::setSize(const V3i &size, int padding)
{ 
  assert(size.x >= 0);
  assert(size.y >= 0);
  assert(size.z >= 0);
  assert(padding >= 0);

  setSize(Box3i(V3i(0), size - V3i(1)),
          Box3i(V3i(-padding), size + V3i(padding - 1))); 
}

//----------------------------------------------------------------------------//

template <class Data_T>
void ResizableField<Data_T>::copyFrom(typename Field<Data_T>::Ptr other)
{
  // Set mapping
  FieldRes::setMapping(other->mapping());
  // Set size to match
  setSize(other->extents(), other->dataWindow());

  // Copy over the data
  typename base::iterator i = base::begin();
  typename base::iterator end = base::end();
  typename Field<Data_T>::const_iterator c = other->cbegin();
  for (; i != end; ++i, ++c)
    *i = *c;
}

//----------------------------------------------------------------------------//

template <class Data_T>
template <class Data_T2>
void ResizableField<Data_T>::copyFrom(typename Field<Data_T2>::Ptr other) 
{
  // Set mapping
  FieldRes::setMapping(other->mapping());
  // Set size to match
  setSize(other->extents(), other->dataWindow());
  // Copy over the data
  typename base::iterator i = base::begin();
  typename base::iterator end = base::end();
  typename Field<Data_T2>::const_iterator c = other->cbegin();
  for (; i != end; ++i, ++c)
    *i = *c;
}

//----------------------------------------------------------------------------//

template <class Data_T>
void ResizableField<Data_T>::matchDefinition(FieldRes::Ptr fieldToMatch)
{
  setSize(fieldToMatch->extents(), fieldToMatch->dataWindow());
  FieldRes::setMapping(fieldToMatch->mapping());
}

//----------------------------------------------------------------------------//
// Field-related utility functions
//----------------------------------------------------------------------------//

//! Checks whether the mapping and resolution in two different fields are
//! identical
template <class Data_T, class Data_T2>
bool sameDefinition(typename Field<Data_T>::Ptr a, 
                    typename Field<Data_T2>::Ptr b,
                    double tolerance = 0.0)
{
  if (a->extents() != b->extents()) {
    return false;
  } 
  if (a->dataWindow() != b->dataWindow()) {
    return false;
  }
  if (!a->mapping()->isIdentical(b->mapping(), tolerance)) {
    return false;
  }
  return true;
}

//----------------------------------------------------------------------------//

//! Checks whether the span and data in two different fields are identical
//! \todo This should also check the mapping
template <class Data_T>
bool isIdentical(typename Field<Data_T>::Ptr a, typename Field<Data_T>::Ptr b)
{
  if (!sameDefinition<Data_T, Data_T>(a, b)) {
    return false;
  }
  // If data window is the same, we can safely assume that the range of
  // both fields' iterators are the same.
  typename Field<Data_T>::const_iterator is1 = a->cbegin();
  typename Field<Data_T>::const_iterator is2 = b->cbegin();
  typename Field<Data_T>::const_iterator ie1 = a->cend();
  bool same = true;
  for (; is1 != ie1; ++is1, ++is2) {
    if (*is1 != *is2) {
      same = false;
      break;
    }
  }
  return same;
}

//----------------------------------------------------------------------------//

//! Goes from continuous coordinates to discrete coordinates
//! See Graphics Gems - What is a pixel
inline int contToDisc(double contCoord)
{
  return static_cast<int>(std::floor(contCoord));
}

//----------------------------------------------------------------------------//

//! Goes from discrete coordinates to continuous coordinates
//! See Graphics Gems - What is a pixel
inline double discToCont(int discCoord)
{
  return static_cast<double>(discCoord) + 0.5;
}

//----------------------------------------------------------------------------//

//! Goes from continuous coords to discrete for a 2-vector
inline V2i contToDisc(const V2d &contCoord)
{
  return V2i(contToDisc(contCoord.x), contToDisc(contCoord.y));  
}

//----------------------------------------------------------------------------//

//! Goes from discrete coords to continuous for a 2-vector
inline V2d discToCont(const V2i &discCoord)
{
  return V2d(discToCont(discCoord.x), discToCont(discCoord.y));  
}

//----------------------------------------------------------------------------//

//! Goes from continuous coords to discrete for a 3-vector
inline V3i contToDisc(const V3d &contCoord)
{
  return V3i(contToDisc(contCoord.x), contToDisc(contCoord.y),
             contToDisc(contCoord.z));
}

//----------------------------------------------------------------------------//

//! Goes from discrete coords to continuous for a 3-vector
inline V3d discToCont(const V3i &discCoord)
{
  return V3d(discToCont(discCoord.x), discToCont(discCoord.y),
             discToCont(discCoord.z));  
}

//----------------------------------------------------------------------------//

inline Box3d continuousBounds(const Box3i &bbox)
{
  Box3d result;
  result.min.x = static_cast<float>(bbox.min.x);
  result.min.y = static_cast<float>(bbox.min.y);
  result.min.z = static_cast<float>(bbox.min.z);
  result.max.x = static_cast<float>(bbox.max.x + 1);
  result.max.y = static_cast<float>(bbox.max.y + 1);
  result.max.z = static_cast<float>(bbox.max.z + 1);
  return result;
}

//----------------------------------------------------------------------------//

//! Converts a floating point bounding box to an integer bounding box.
//! \note If the float-to-int conversion overflows, the result is
//! set to be std::numeric_limits<int>::max()
inline Box3i discreteBounds(const Box3d &bbox)
{
  using std::floor;
  using std::ceil;

  Box3i result;
  result.min.x = static_cast<int>(floor(clampForType<double, int>(bbox.min.x)));
  result.min.y = static_cast<int>(floor(clampForType<double, int>(bbox.min.y)));
  result.min.z = static_cast<int>(floor(clampForType<double, int>(bbox.min.z)));
  result.max.x = static_cast<int>(ceil(clampForType<double, int>(bbox.max.x)));
  result.max.y = static_cast<int>(ceil(clampForType<double, int>(bbox.max.y)));
  result.max.z = static_cast<int>(ceil(clampForType<double, int>(bbox.max.z)));
  return result;
}

//----------------------------------------------------------------------------//

inline Box3i clipBounds(const Box3i &bbox, const Box3i &bounds)
{
  Box3i result;
  result.min.x = std::max(bbox.min.x, bounds.min.x);
  result.min.y = std::max(bbox.min.y, bounds.min.y);
  result.min.z = std::max(bbox.min.z, bounds.min.z);
  result.max.x = std::min(bbox.max.x, bounds.max.x);
  result.max.y = std::min(bbox.max.y, bounds.max.y);
  result.max.z = std::min(bbox.max.z, bounds.max.z);
  return result;
}

//----------------------------------------------------------------------------//

//! \ingroup template_util
template <class Iter_T>
void advance(Iter_T &iter, int num) 
{
  if (num <= 0) {
    return;
  }
  for (int i=0; i<num; ++i, ++iter) {
    // Empty
  }
}

//----------------------------------------------------------------------------//

//! \ingroup template_util
template <class Iter_T>
void advance(Iter_T &iter, int num, const Iter_T &end) 
{
  if (num <= 0) {
    return;
  }
  for (int i=0; i<num && iter != end; ++i, ++iter) {
    // Empty
  }
}

//----------------------------------------------------------------------------//

inline V3i indexToCoord(const size_t idx, const V3i &res)
{
  const int i = idx % res.x;
  const int j = (idx / res.x) % res.y;
  const int k = idx / (res.x * res.y);
  return V3i(i, j, k);
}

//----------------------------------------------------------------------------//

FIELD3D_NAMESPACE_HEADER_CLOSE

//----------------------------------------------------------------------------//

#endif // Include guard