File: vtkStructuredImplicitConnectivity.cxx

package info (click to toggle)
vtk7 7.1.1%2Bdfsg2-8
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 127,396 kB
  • sloc: cpp: 1,539,584; ansic: 124,382; python: 78,038; tcl: 47,013; xml: 8,142; yacc: 5,040; java: 4,439; perl: 3,132; lex: 1,926; sh: 1,500; makefile: 126; objc: 83
file content (1580 lines) | stat: -rw-r--r-- 48,840 bytes parent folder | download | duplicates (2)
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
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkStructuredImplicitConnectivity.h

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkStructuredImplicitConnectivity.h"

// VTK includes
#include "vtkDataArray.h"
#include "vtkFieldDataSerializer.h"
#include "vtkImageData.h"
#include "vtkMPIController.h"
#include "vtkMultiProcessController.h"
#include "vtkMultiProcessStream.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkRectilinearGrid.h"
#include "vtkStructuredData.h"
#include "vtkStructuredExtent.h"
#include "vtkStructuredGrid.h"

// C/C++ includes
#include <algorithm>
#include <cassert>
#include <map>
#include <sstream>
#include <vector>

//==============================================================================
// INTERNAL DATASTRUCTURES & DEFINITIONS
//==============================================================================

// Some usefull extent macros
#define IMIN(ext) ext[0]
#define IMAX(ext) ext[1]
#define JMIN(ext) ext[2]
#define JMAX(ext) ext[3]
#define KMIN(ext) ext[4]
#define KMAX(ext) ext[5]

#define I(ijk) ijk[0]
#define J(ijk) ijk[1]
#define K(ijk) ijk[2]

namespace vtk
{
namespace detail
{

// Given two intervals A=[a1,a2] and B[b1,b2] the IntervalsConnect struct
// enumerates the cases where interval A connects to Interval B.
struct IntervalsConnect
{
  // NOTE: This enum is arranged s.t., negating a value in [-4,4] will yield
  // the mirror inverse
  enum connectivity_t
  {
    IMPLICIT_LO = -4, // Interval A implicitly connects with B on A's low end
    SUBSET      = -3, // Interval A is completely inside interval B
    OVERLAP_LO  = -2, // Interval A intersects with B on A's low end
    LO          = -1, // A's low end touches B's high end A.Low() == B.High()
    ONE_TO_ONE  =  0, // Intervals A,B are exactly the same.
    HI          =  1, // A's high end touches B's low end A.High() == B.Low()
    OVERLAP_HI  =  2, // Interval A intersects with B on A's high end
    SUPERSET    =  3, // Interval A *contains* all of interval B
    IMPLICIT_HI =  4, // Interval A implicitly connects with B on its high end.

    DISJOINT    =  5, // Intervals A,B are completely disjoint.
    UNDEFINED   =  6  // Undefined
  };

  static
  std::string OrientationToString( int orient[3] )
  {
    std::ostringstream oss;
    oss << "(";
    for(int i=0; i < 3; ++i)
    {
      if(i==1 || i==2)
      {
        oss << ", ";
      }
      switch( orient[i] )
      {
        case IMPLICIT_LO:
          oss << "IMPLICIT_LO";
          break;
        case SUBSET:
          oss << "SUBSET";
          break;
        case OVERLAP_LO:
          oss << "OVERLAP_LO";
          break;
        case LO:
          oss << "LO";
          break;
        case ONE_TO_ONE:
          oss << "ONE_TO_ONE";
          break;
        case HI:
          oss << "HI";
          break;
        case OVERLAP_HI:
          oss << "OVERLAP_HI";
          break;
        case SUPERSET:
          oss << "SUPERSET";
          break;
        case IMPLICIT_HI:
          oss << "IMPLICIT_HI";
          break;
        case DISJOINT:
          oss << "DISJOINT";
          break;
        case UNDEFINED:
          oss << "UNDEFINED";
          break;
        default:
          oss << "*UNKNOWN*";
      } // END switch
    } // END for
    oss << ")";
    return( oss.str() );
  }

}; // END struct IntervalsConnect

//------------------------------------------------------------------------------
//  Interval class Definition
//------------------------------------------------------------------------------
class Interval
{
public:
  Interval() : lo(0), hi(-1) {};
  Interval(const int l, const int h) : lo(l), hi(h) {};
  ~Interval() {};

  int Low() const { return this->lo; };
  int High() const { return this->hi; };
  int Cardinality() const { return(this->hi-this->lo+1); };
  bool Valid() const { return(this->lo <= this->hi); };
  void Set(const int l, const int h) { this->lo=l; this->hi=h; };
  void Invalidate() {this->Set(0,-1);}
  bool Within(const Interval& B) const
    { return( (this->lo >= B.Low()) && (this->hi <= B.High()) ); };

  bool ImplicitNeighbor(const Interval& B, int& type);
  static bool ImplicitNeighbors(
      const Interval& A, const Interval& B, int& type);

  bool Intersects(const Interval& B, Interval& Overlap, int& type);
  static bool Intersects(const Interval& A, const Interval& B,
                         Interval& Overlap, int& type);
private:
  int lo;
  int hi;
};

//------------------------------------------------------------------------------
bool Interval::ImplicitNeighbors(const Interval& A, const Interval& B, int& t)
{
  assert("pre: interval is not valid!" && A.Valid());
  assert("pre: B interval is not valid!" && B.Valid() );

  bool status = false;
  if( A.High()+1 == B.Low() )
  {
    status = true;
    t = IntervalsConnect::IMPLICIT_HI;
  }
  else if( B.High()+1 == A.Low() )
  {
    status = true;
    t = IntervalsConnect::IMPLICIT_LO;
  }
  return( status );
}

//------------------------------------------------------------------------------
bool Interval::ImplicitNeighbor(const Interval& B, int& type)
{
  return( Interval::ImplicitNeighbors(*this,B,type) );
}

//------------------------------------------------------------------------------
bool Interval::Intersects(const Interval& A, const Interval& B,
                          Interval& Overlap, int& type)
{
  assert("pre: interval is not valid!" && A.Valid());
  assert("pre: B interval is not valid!" && B.Valid() );

  bool status = false;

  // Disjoint cases
  if( A.High() < B.Low() )
  {
    type = IntervalsConnect::DISJOINT;
    Overlap.Invalidate();
    status = false;
  }
  else if( B.High() < A.Low() )
  {
    type = IntervalsConnect::DISJOINT;
    Overlap.Invalidate();
    status = false;
  }
  // ONE_TO_ONE case
  else if( A.Cardinality()==B.Cardinality() &&
           A.Low()==B.Low() &&
           A.High()==B.High() )
  {
    type = IntervalsConnect::ONE_TO_ONE;
    Overlap.Set(A.Low(),A.High());
    status = true;
  }
  // A is a SUBSET of B
  else if( A.Within(B) )
  {
    type = IntervalsConnect::SUBSET;
    Overlap.Set(A.Low(),A.High());
    status = true;
  }
  // A is a superset of B
  else if( B.Within(A) )
  {
    type = IntervalsConnect::SUPERSET;
    Overlap.Set(B.Low(),B.High());
    status = true;
  }
  // A touches B on the high end
  else if( A.High() == B.Low() )
  {
    type = IntervalsConnect::HI;
    Overlap.Set(A.High(),A.High());
    status = true;
  }
  // A touches B on the low end
  else if( A.Low() == B.High() )
  {
    type = IntervalsConnect::LO;
    Overlap.Set(A.Low(),A.Low());
    status = true;
  }
  // A intersects B on its low end
  else if( (A.Low() >= B.Low()) && (A.Low() <= B.High()) )
  {
    type = IntervalsConnect::OVERLAP_LO;
    Overlap.Set(A.Low(),B.High());
    status = true;
  }
  // A intersects B on its high end
  else if( (A.High() >= B.Low() ) && (A.High() <= B.High()) )
  {
    type = IntervalsConnect::OVERLAP_HI;
    Overlap.Set(B.Low(),A.High());
    status = true;
  }
  else
  {
    vtkGenericWarningMacro(
        << "Undefined interval intersection!"
        << "Code should not reach here!!!");
    type = IntervalsConnect::UNDEFINED;
    status = false;
    Overlap.Invalidate();
  }
  return( status );
}

//------------------------------------------------------------------------------
bool Interval::Intersects(const Interval& B, Interval& Overlap, int& type)
{
  return( Interval::Intersects(*this, B, Overlap, type) );
}

//------------------------------------------------------------------------------
struct ImplicitNeighbor
{
  int Rank;           // the rank of the neighbor
  int Extent[6];      // the extent of the neighbor
  int Orientation[3]; // the orientation w.r.t the local extent
  int Overlap[6];     // the overlap extent

  std::string ToString()
  {
    std::ostringstream oss;

    oss << "rank=" << this->Rank << " ";
    oss << "extent=[";
    oss << this->Extent[0] << ", ";
    oss << this->Extent[1] << ", ";
    oss << this->Extent[2] << ", ";
    oss << this->Extent[3] << ", ";
    oss << this->Extent[4] << ", ";
    oss << this->Extent[5] << "] ";
    oss << "overlap=[";
    oss << this->Overlap[0] << ", ";
    oss << this->Overlap[1] << ", ";
    oss << this->Overlap[2] << ", ";
    oss << this->Overlap[3] << ", ";
    oss << this->Overlap[4] << ", ";
    oss << this->Overlap[5] << "] ";
    oss << "orientation=";
    oss << IntervalsConnect::OrientationToString(this->Orientation);

    return( oss.str() );
  }
};

//------------------------------------------------------------------------------
struct DomainMetaData
{
  int WholeExtent[6];     // Extent of the entire domain

  int DataDescription;    // Data-description of the distributed dataset.
  int NDim;               // Number of dimensions according to DataDescription.
  int DimIndex[3];        // Stores the dimensions of the dataset in the
                          // the right order. This essentially allows to
                          // process 2-D (XY,XZ,YZ) and 3-D datasets in a
                          // transparent way.

  int GlobalImplicit[3];  // indicates for each dimension if there is globally
                          // implicit connectivity. Any value > 0 indicates
                          // implicit connectivity in the given direction.

  // Flat list of extents. Extents are organized as follows:
  // [id, imin, imax, jmin, jmax, kmin, kmax]
  std::vector< int > ExtentListInfo;

  /// \brief Checks if a grid with the given extent is within this domain
  /// \param ext the extent of the grid in query
  /// \return status true if the grid is insided, else false.
  bool HasGrid(int ext[6])
    { return( vtkStructuredExtent::Smaller(ext,this->WholeExtent) );  };

  /// \brief Initializes the domain metadata.
  void Initialize(int wholeExt[6])
  {
    memcpy(this->WholeExtent,wholeExt,6*sizeof(int));
    this->DataDescription =
        vtkStructuredData::GetDataDescriptionFromExtent(wholeExt);

    if (this->DataDescription == VTK_EMPTY)
    {
      return;
    }

    // Sanity checks!
    assert( "pre: data description is VTK_EMPTY!" &&
             (this->DataDescription != VTK_EMPTY) );
    assert( "pre: dataset must be 2-D or 3-D" &&
            (this->DataDescription >= VTK_XY_PLANE) );

    this->NDim = -1;
    std::fill(this->DimIndex,this->DimIndex+3,-1);
    std::fill(this->GlobalImplicit,this->GlobalImplicit+3,0);

    switch( this->DataDescription )
    {
      case VTK_XY_PLANE:
        this->NDim        = 2;
        this->DimIndex[0] = 0;
        this->DimIndex[1] = 1;
        break;
      case VTK_XZ_PLANE:
        this->NDim        = 2;
        this->DimIndex[0] = 0;
        this->DimIndex[1] = 2;
        break;
      case VTK_YZ_PLANE:
        this->NDim        = 2;
        this->DimIndex[0] = 1;
        this->DimIndex[1] = 2;
        break;
      case VTK_XYZ_GRID:
        this->NDim        = 3;
        this->DimIndex[0] = 0;
        this->DimIndex[1] = 1;
        this->DimIndex[2] = 2;
        break;
      default:
        vtkGenericWarningMacro(
            << "Cannot handle data description: "
            << this->DataDescription << "\n");
    } // END switch

    assert( "post: NDim==2 || NDim==3" && ( this->NDim==2 || this->NDim==3 ) );
  }

};

//------------------------------------------------------------------------------
struct StructuredGrid
{
  int ID;
  int Extent[6];
  int DataDescription;

  int Grow[3];     // indicates if the grid grows to the right along each dim.
  int Implicit[3]; // indicates implicit connectivity alone each dim.

  vtkPoints* Nodes;
  vtkPointData* PointData;

  // arrays used if the grid is a rectilinear grid
  vtkDataArray* X_Coords;
  vtkDataArray* Y_Coords;
  vtkDataArray* Z_Coords;

  std::vector< ImplicitNeighbor > Neighbors;

//------------------------------------------------------------------------------
  bool IsRectilinearGrid()
  {
    if( (this->X_Coords != NULL) &&
        (this->Y_Coords != NULL) &&
        (this->Z_Coords != NULL) )
    {
      return true;
    }
    return false;
  }

//------------------------------------------------------------------------------
  void Clear()
  {
    if( this->Nodes != NULL )
    {
      this->Nodes->Delete();
      this->Nodes = NULL;
    }
    if( this->PointData != NULL )
    {
      this->PointData->Delete();
      this->PointData = NULL;
    }
    if( this->X_Coords != NULL )
    {
      this->X_Coords->Delete();
      this->X_Coords = NULL;
    }
    if( this->Y_Coords != NULL )
    {
      this->Y_Coords->Delete();
      this->Y_Coords = NULL;
    }
    if( this->Z_Coords != NULL )
    {
      this->Z_Coords->Delete();
      this->Z_Coords = NULL;
    }
    this->Neighbors.clear();
  }

//------------------------------------------------------------------------------
  void Initialize(StructuredGrid* grid)
  {
    assert("pre: input grid is NULL!" && (grid != NULL) );

    this->Initialize(grid->ID,grid->Extent,NULL,NULL);

    // Grow the extent in each dimension as needed
    for(int i=0; i < 3; ++i)
    {
      if( grid->Grow[i]==1 )
      {
        this->Extent[i*2+1] += 1;
      } // END if
    } // END for all dimensions

    // the number of nodes in the grown extent
    vtkIdType nnodes = vtkStructuredData::GetNumberOfPoints(
        this->Extent,grid->DataDescription);

   // Allocate coordinates, if needed
   if( grid->Nodes != NULL )
   {
     this->Nodes = vtkPoints::New();
     this->Nodes->SetDataType( grid->Nodes->GetDataType() );
     this->Nodes->SetNumberOfPoints( nnodes );
   } // END if has points
   else
   {
     this->Nodes = NULL;
   }

   // Allocate rectilinear grid coordinates, if needed
   if( (grid->X_Coords != NULL) &&
       (grid->Y_Coords != NULL) &&
       (grid->Z_Coords != NULL) )
   {
     int dims[3];
     vtkStructuredData::GetDimensionsFromExtent(
         this->Extent,dims,this->DataDescription);

     this->X_Coords = vtkDataArray::CreateDataArray(
         grid->X_Coords->GetDataType());
     this->X_Coords->SetNumberOfTuples( dims[0] );
     for(vtkIdType idx=0; idx < grid->X_Coords->GetNumberOfTuples(); ++idx)
     {
       this->X_Coords->SetTuple(idx,idx,grid->X_Coords);
     }

     this->Y_Coords = vtkDataArray::CreateDataArray(
         grid->Y_Coords->GetDataType());
     this->Y_Coords->SetNumberOfTuples( dims[1] );
     for(vtkIdType idx=0; idx < grid->Y_Coords->GetNumberOfTuples(); ++idx)
     {
        this->Y_Coords->SetTuple(idx,idx,grid->Y_Coords);
     }

     this->Z_Coords = vtkDataArray::CreateDataArray(
         grid->Z_Coords->GetDataType());
     this->Z_Coords->SetNumberOfTuples( dims[2] );
     for(vtkIdType idx=0; idx < grid->Z_Coords->GetNumberOfTuples(); ++idx)
     {
        this->Z_Coords->SetTuple(idx,idx,grid->Z_Coords);
     }
   } // END if rectilinear grid
   else
   {
     grid->X_Coords = NULL;
     grid->Y_Coords = NULL;
     grid->Z_Coords = NULL;
   }

   // Allocate fields, if needed
   if( grid->PointData != NULL )
   {
     this->PointData = vtkPointData::New();
     this->PointData->CopyAllocate(grid->PointData,nnodes);

     // NOTE: CopyAllocate, allocates the buffers internally, but, does not
     // set the number of tuples of each array to nnodes.
     for(int array=0; array < this->PointData->GetNumberOfArrays(); ++array)
     {
       vtkDataArray* a = this->PointData->GetArray( array );
       a->SetNumberOfTuples(nnodes);
     } // END for all arrays

   }
   else
   {
     this->PointData = NULL;
   }

   // copy everything from the given grid
   int desc   = grid->DataDescription;
   int ijk[3] = {0,0,0};

   for( I(ijk)=IMIN(grid->Extent); I(ijk) <= IMAX(grid->Extent); ++I(ijk) )
   {
     for( J(ijk)=JMIN(grid->Extent); J(ijk) <= JMAX(grid->Extent); ++J(ijk) )
     {
       for( K(ijk)=KMIN(grid->Extent); K(ijk) <= KMAX(grid->Extent); ++K(ijk) )
       {
         // Compute the source index
         vtkIdType srcIdx =
             vtkStructuredData::ComputePointIdForExtent(grid->Extent,ijk,desc);

         // Compute the target index
         vtkIdType targetIdx =
             vtkStructuredData::ComputePointIdForExtent(this->Extent,ijk,desc);

         // Copy nodes
         if( this->Nodes != NULL )
         {
           this->Nodes->SetPoint(targetIdx,grid->Nodes->GetPoint(srcIdx));
         }

         // Copy node-centered fields
         if( this->PointData != NULL )
         {
           this->PointData->CopyData(grid->PointData,srcIdx,targetIdx);
         }

       } // END for all k
     } // END for all j
   } // END for all i

  }

//------------------------------------------------------------------------------
  void Initialize(int id, int ext[6], vtkDataArray* x_coords,
      vtkDataArray* y_coords, vtkDataArray* z_coords, vtkPointData* fields)
  {
    assert("pre: NULL x_coords!" && (x_coords != NULL) );
    assert("pre: NULL y_coords!" && (y_coords != NULL) );
    assert("pre: NULL z_coords!" && (z_coords != NULL) );

    this->ID = id;
    memcpy(this->Extent,ext,6*sizeof(int));
    this->DataDescription = vtkStructuredData::GetDataDescriptionFromExtent(ext);
    std::fill(this->Grow,this->Grow+3,0);
    std::fill(this->Implicit,this->Implicit+3,0);

    this->Nodes = NULL;

    // Effectively, shallow copy the coordinate arrays and maintain ownership
    // of these arrays in the caller.
    this->X_Coords = vtkDataArray::CreateDataArray(x_coords->GetDataType());
    this->X_Coords->SetVoidArray(
        x_coords->GetVoidPointer(0),x_coords->GetNumberOfTuples(),1);

    this->Y_Coords = vtkDataArray::CreateDataArray(y_coords->GetDataType());
    this->Y_Coords->SetVoidArray(
        y_coords->GetVoidPointer(0),y_coords->GetNumberOfTuples(),1);

    this->Z_Coords = vtkDataArray::CreateDataArray(z_coords->GetDataType());
    this->Z_Coords->SetVoidArray(
        z_coords->GetVoidPointer(0),z_coords->GetNumberOfTuples(),1);

    if(fields != NULL)
    {
      this->PointData = vtkPointData::New();
      this->PointData->ShallowCopy(fields);
    }
    else
    {
      this->PointData = NULL;
    }
  }

//------------------------------------------------------------------------------
  void Initialize(int id, int ext[6], vtkPoints* nodes, vtkPointData* fields)
  {
  this->ID = id;
  memcpy(this->Extent,ext,6*sizeof(int));
  this->DataDescription = vtkStructuredData::GetDataDescriptionFromExtent(ext);
  std::fill(this->Grow,this->Grow+3,0);
  std::fill(this->Implicit,this->Implicit+3,0);

  this->X_Coords = NULL;
  this->Y_Coords = NULL;
  this->Z_Coords = NULL;

  if(nodes != NULL)
  {
    this->Nodes = vtkPoints::New();
    this->Nodes->ShallowCopy(nodes);
  }
  else
  {
    this->Nodes = NULL;
  }

  if(fields != NULL)
  {
    this->PointData = vtkPointData::New();
    this->PointData->ShallowCopy(fields);
  }
  else
  {
    this->PointData = NULL;
  }
  }

};

//------------------------------------------------------------------------------
//  CommManager class Definition
//------------------------------------------------------------------------------

class CommunicationManager
{
public:
  CommunicationManager() {};
  ~CommunicationManager() { this->Clear(); };

  unsigned char* GetRcvBuffer(const int fromRank);
  unsigned int GetRcvBufferSize(const int fromRank);

  void EnqueueRcv(const int fromRank);
  void EnqueueSend(const int toRank, unsigned char* data, unsigned int nbytes);
  void Exchange(vtkMPIController* comm);
  int NumMsgs();
  void Clear();

private:
  // map send/rcv buffers based on rank.
  std::map< int, unsigned char* > Send;
  std::map< int, int> SendByteSize;
  std::map< int, unsigned char* > Rcv;
  std::map< int, int> RcvByteSize;
  std::vector< vtkMPICommunicator::Request > Requests;

  // exchanges buffer-sizes
  void AllocateRcvBuffers(vtkMPIController* comm);
};

//------------------------------------------------------------------------------
void CommunicationManager::Clear()
{
  this->Requests.clear();
  this->SendByteSize.clear();
  this->RcvByteSize.clear();

  std::map<int,unsigned char*>::iterator it;
  for(it=this->Send.begin(); it != this->Send.end(); ++it)
  {
    delete [] it->second;
  }
  this->Send.clear();

  for(it=this->Rcv.begin(); it != this->Rcv.end(); ++it)
  {
    delete [] it->second;
  }
  this->Rcv.clear();
}

//------------------------------------------------------------------------------
unsigned char* CommunicationManager::GetRcvBuffer(const int fromRank)
{
  assert( "pre: cannot find buffer for requested rank!" &&
          (this->Rcv.find( fromRank ) != this->Rcv.end()) );
  return( this->Rcv[ fromRank ] );
}

//------------------------------------------------------------------------------
unsigned int CommunicationManager::GetRcvBufferSize(const int fromRank)
{
  assert( "pre: cannot find bytesize size of requested rank!" &&
          (this->RcvByteSize.find( fromRank ) != this->RcvByteSize.end()) );
  return( this->RcvByteSize[ fromRank ]  );
}

//------------------------------------------------------------------------------
int CommunicationManager::NumMsgs()
{
  return static_cast<int>( this->Send.size()+this->Rcv.size() );
}

//------------------------------------------------------------------------------
void CommunicationManager::EnqueueRcv(const int fromRank)
{
  assert("pre: rcv from rank has already been enqueued!" &&
          (this->Rcv.find(fromRank)==this->Rcv.end()) );

  this->Rcv[ fromRank ] = NULL;
  this->RcvByteSize[ fromRank ] = 0;
}

//------------------------------------------------------------------------------
void CommunicationManager::EnqueueSend(
      const int toRank, unsigned char* data, unsigned int nbytes)
{
  assert("pre: send to rank has already been enqueued!" &&
          (this->Send.find(toRank)==this->Send.end()));

  this->Send[ toRank ] = data;
  this->SendByteSize[ toRank ] = nbytes;
}

//------------------------------------------------------------------------------
void CommunicationManager::AllocateRcvBuffers(vtkMPIController* comm)
{
  std::map<int,int>::iterator it;

  // STEP 0: Allocate vector to store request objects for non-blocking comm.
  int rqstIdx = 0;
  this->Requests.resize(this->NumMsgs());

  // STEP 1: Post receives
  for(it=this->RcvByteSize.begin(); it != this->RcvByteSize.end(); ++it)
  {
    int fromRank = it->first;
    int* dataPtr = &(it->second);
    comm->NoBlockReceive(dataPtr,1,fromRank,0,this->Requests[rqstIdx]);
    ++rqstIdx;
  }

  // STEP 2: Post Sends
  for(it=this->SendByteSize.begin(); it != this->SendByteSize.end(); ++it)
  {
    int toRank   = it->first;
    int* dataPtr = &(it->second);
    comm->NoBlockSend(dataPtr,1,toRank,0,this->Requests[rqstIdx]);
    ++rqstIdx;
  }

  // STEP 3: WaitAll
  if (!this->Requests.empty())
  {
    comm->WaitAll(this->NumMsgs(),&this->Requests[0]);
  }
  this->Requests.clear();

  // STEP 4: Allocate rcv buffers
  std::map<int,unsigned char*>::iterator bufferIter = this->Rcv.begin();
  for( ;bufferIter != this->Rcv.end(); ++bufferIter)
  {
    int fromRank = bufferIter->first;
    assert("pre: rcv buffer should be NULL!" && (this->Rcv[fromRank]==NULL) );
    this->Rcv[ fromRank ] = new unsigned char[ this->RcvByteSize[fromRank] ];
  }
}

//------------------------------------------------------------------------------
void CommunicationManager::Exchange(vtkMPIController* comm)
{
  std::map<int,unsigned char*>::iterator it;

  // STEP 0: exchange & allocate buffer sizes
  this->AllocateRcvBuffers(comm);

  // STEP 1: Allocate vector to store request objects for non-blocking comm.
  int rqstIdx = 0;
  this->Requests.resize(this->NumMsgs());

  // STEP 2: Post Rcvs
  for(it=this->Rcv.begin(); it != this->Rcv.end(); ++it)
  {
    int fromRank          = it->first;
    unsigned char* buffer = it->second;
    assert("pre: rcv buffer size not found!" &&
            this->RcvByteSize.find(fromRank) != this->RcvByteSize.end() );
    unsigned int bytesize = this->RcvByteSize[ fromRank ];

    comm->NoBlockReceive(buffer,bytesize,fromRank,0,this->Requests[rqstIdx]);
    ++rqstIdx;
  }

  // STEP 3: Post Sends
  for(it=this->Send.begin(); it != this->Send.end(); ++it)
  {
    int toRank            = it->first;
    unsigned char* buffer = it->second;
    assert("pre: rcv buffer size not found!" &&
            this->SendByteSize.find(toRank) != this->SendByteSize.end() );
    unsigned int bytesize = this->SendByteSize[ toRank ];

    comm->NoBlockSend(buffer,bytesize,toRank,0,this->Requests[rqstIdx]);
    ++rqstIdx;
  }

  // STEP 4: WaitAll
  if (!this->Requests.empty())
  {
    comm->WaitAll(this->NumMsgs(),&this->Requests[0]);
  }
  this->Requests.clear();
}

} // END namespace detail
} // END namespace vtk
//==============================================================================
// END INTERNAL DATASTRUCTURE DEFINITIONS
//==============================================================================

vtkStandardNewMacro(vtkStructuredImplicitConnectivity);

//------------------------------------------------------------------------------
vtkStructuredImplicitConnectivity::vtkStructuredImplicitConnectivity()
{
  this->DomainInfo  = NULL;
  this->InputGrid   = NULL;
  this->OutputGrid  = NULL;
  this->CommManager = NULL;
  this->Controller  = vtkMPIController::SafeDownCast(
            vtkMultiProcessController::GetGlobalController());
}

//------------------------------------------------------------------------------
vtkStructuredImplicitConnectivity::~vtkStructuredImplicitConnectivity()
{
  delete this->DomainInfo;
  this->DomainInfo = NULL;

  if( this->InputGrid != NULL )
  {
    this->InputGrid->Clear();
    delete this->InputGrid;
    this->InputGrid = NULL;
  }

  if( this->OutputGrid != NULL )
  {
    this->OutputGrid->Clear();
    delete this->OutputGrid;
    this->OutputGrid = NULL;
  }

  if( this->CommManager != NULL )
  {
    this->CommManager->Clear();
    delete this->CommManager;
    this->CommManager = NULL;
  }

  this->Controller = NULL;
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::PrintSelf(ostream& os,vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << "Controller: "      << this->Controller << std::endl;
  if( this->Controller != NULL )
  {
    os << "Number of Ranks: " << this->Controller->GetNumberOfProcesses();
    os << std::endl;
  } // END if Controller != NULL

  os << "Input Grid: " << this->InputGrid  << std::endl;
  if( this->InputGrid != NULL )
  {
    os << "Extent: [" << this->InputGrid->Extent[0];
    os << ", " << this->InputGrid->Extent[1];
    os << ", " << this->InputGrid->Extent[2];
    os << ", " << this->InputGrid->Extent[3];
    os << ", " << this->InputGrid->Extent[4];
    os << ", " << this->InputGrid->Extent[5];
    os << "] " << std::endl;

    os << "Grow: [" << this->InputGrid->Grow[0];
    os << ", " << this->InputGrid->Grow[1];
    os << ", " << this->InputGrid->Grow[2];
    os << "] " << std::endl;

    os << "Number of Neighbors: " << this->InputGrid->Neighbors.size();
    os << std::endl;
    size_t N = this->InputGrid->Neighbors.size();
    for(size_t nei=0; nei < N; ++nei)
    {
      os << "\t" << this->InputGrid->Neighbors[ nei ].ToString();
      os << std::endl;
    } // END for all neighbors
  } // END if InputGrid != NULL
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::SetWholeExtent(int wholeExt[6])
{
  delete this->DomainInfo;

  this->DomainInfo = new vtk::detail::DomainMetaData();
  this->DomainInfo->Initialize(wholeExt);

  assert("post: Domain description does not match across ranks!" &&
          this->GlobalDataDescriptionMatch() );
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::RegisterGrid(
      const int gridID,
      int extent[6],
      vtkPoints* gridNodes,
      vtkPointData* pointData)
{
  // Sanity Checks!
  assert("pre: NULL Domain, whole extent is not set!" &&
          (this->DomainInfo != NULL) );
  assert("pre: input not NULL in this process!" &&
          (this->InputGrid == NULL) );
  assert("pre: input grid ID should be >= 0" && (gridID >= 0) );

  delete this->InputGrid;
  this->InputGrid = NULL;

  // Only add if the grid falls within the output extent. Processes that do
  // not contain the VOI will fail this test.
  if (this->DomainInfo->HasGrid(extent))
  {
    this->InputGrid = new vtk::detail::StructuredGrid();
    this->InputGrid->Initialize(gridID,extent,gridNodes,pointData);
  }
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::RegisterRectilinearGrid(
            const int gridID,
            int extent[6],
            vtkDataArray* xcoords,
            vtkDataArray* ycoords,
            vtkDataArray* zcoords,
            vtkPointData* pointData)
{
  // Sanity Checks!
  assert("pre: NULL Domain, whole extent is not set!" &&
          (this->DomainInfo != NULL) );
  assert("pre: input not NULL in this process!" &&
          (this->InputGrid == NULL) );
  assert("pre: input grid ID should be >= 0" && (gridID >= 0) );

  delete this->InputGrid;
  this->InputGrid = NULL;

  // Only add if the grid falls within the output extent. Processes that do
  // not contain the VOI will fail this test.
  if (this->DomainInfo->HasGrid(extent))
  {
    this->InputGrid = new vtk::detail::StructuredGrid();
    this->InputGrid->Initialize(gridID, extent, xcoords, ycoords, zcoords,
                                pointData);
  }
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::ExchangeExtents()
{
  // Sanity checks!
  assert("pre: null controller!" && (this->Controller != NULL) );
  assert("pre: null domain!" && (this->DomainInfo != NULL) );

  // STEP 0: Construct the extent buffer that will be sent from each process.
  // Each process sends 7 ints: [gridId imin imax jmin jmax kmin kmax]
  int extbuffer[7];
  if( this->InputGrid == NULL )
  {
    // pad the buffer with -1, indicating that this process has no grid
    std::fill(extbuffer,extbuffer+7,-1);
  }
  else
  {
    extbuffer[0] = this->InputGrid->ID;
    memcpy(&extbuffer[1],this->InputGrid->Extent,6*sizeof(int));
  }

  // STEP 1: Allocate receive buffer, we receive 7 ints for each rank
  int nranks = this->Controller->GetNumberOfProcesses();
  this->DomainInfo->ExtentListInfo.resize(7*nranks,0);

  // STEP 2: AllGather
  int* rcvbuffer = &(this->DomainInfo->ExtentListInfo)[0];
  this->Controller->AllGather(extbuffer,rcvbuffer,7);
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::ComputeNeighbors()
{
  if (!this->InputGrid)
  {
    return;
  }

  int type;
  vtk::detail::Interval A; // used to store the local interval at each dim
  vtk::detail::Interval B; // used to store the remote interval at each dim
  vtk::detail::Interval Overlap; // used to store the computed overlap
  vtk::detail::ImplicitNeighbor Neighbor; // used to store neighbor information

  int nranks = this->Controller->GetNumberOfProcesses();
  for(int rank=0; rank < nranks; ++rank)
  {
    int rmtID = this->DomainInfo->ExtentListInfo[rank*7];
    if( (rmtID == this->InputGrid->ID) || (rmtID == -1) )
    {
      // skip self or empty remote grid
      continue;
    }

    int* rmtExtent = &(this->DomainInfo->ExtentListInfo)[rank*7+1];

    // Initialize neighbor data-structure
    Neighbor.Rank = rank;
    memcpy(Neighbor.Extent,rmtExtent,6*sizeof(int));
    memcpy(Neighbor.Overlap,Neighbor.Extent,6*sizeof(int));
    std::fill(Neighbor.Orientation,Neighbor.Orientation+3,
        vtk::detail::IntervalsConnect::UNDEFINED);

    bool disregard = false;
    int nimplicit  = 0;

    for(int dim=0; dim < this->DomainInfo->NDim; ++dim)
    {
      int d = this->DomainInfo->DimIndex[dim];
      assert("pre: invalid dimension!" && (d >= 0) && (d <= 2) );

      A.Set( this->InputGrid->Extent[d*2], this->InputGrid->Extent[d*2+1] );
      B.Set( rmtExtent[d*2], rmtExtent[d*2+1] );

      if( A.ImplicitNeighbor(B,type) )
      {
        this->InputGrid->Implicit[ d ]= 1;
        Neighbor.Orientation[ d ] = type;

        // Compute overlap based on the fact that we are communicating
        // data to the left <=> grow to the right.
        if( type == vtk::detail::IntervalsConnect::IMPLICIT_HI )
        {
          ++nimplicit;
          Neighbor.Overlap[d*2]    =
          Neighbor.Overlap[d*2+1]  = Neighbor.Extent[d*2];
          this->InputGrid->Grow[d] = 1; /* increment by 1 in this dimension */
        } // END if IMPLICIT_HI
        else if( type == vtk::detail::IntervalsConnect::IMPLICIT_LO )
        {
          ++nimplicit;
          Neighbor.Overlap[d*2]   =
          Neighbor.Overlap[d*2+1] = this->InputGrid->Extent[d*2];
        } // END else if IMPLICIT_LO
        else
        {
          vtkGenericWarningMacro(
              << "Invalid implicit connectivity type! "
              << "Code should not reach here!\n"
              );
        } // END else
      } // END if implicit
      else if( A.Intersects(B,Overlap,type) )
      {
        Neighbor.Orientation[ d ] = type;
        Neighbor.Overlap[d*2]     = Overlap.Low();
        Neighbor.Overlap[d*2+1]   = Overlap.High();
      } // END if intersect
      else
      {
        disregard = true;
        Neighbor.Orientation[ d ] = type;
      } // END else
    } // END for all dimensions

    // Determine whether to include the neighbor to the list of neighbors in
    // this rank.

    if( !(nimplicit > 1 || disregard) )
    {
      this->InputGrid->Neighbors.push_back( Neighbor );
    }

  } // END for all ranks
}

//------------------------------------------------------------------------------
bool vtkStructuredImplicitConnectivity::GlobalDataDescriptionMatch()
{
  int sum = -1;
  this->Controller->AllReduce(
      &this->DomainInfo->DataDescription,&sum,1,vtkCommunicator::SUM_OP);
  if( (sum/this->Controller->GetNumberOfProcesses()) ==
      this->DomainInfo->DataDescription)
  {
    return true;
  }
  return false;
}

//------------------------------------------------------------------------------
bool vtkStructuredImplicitConnectivity::HasImplicitConnectivity()
{
  if( this->DomainInfo == NULL )
  {
    vtkGenericWarningMacro(<< "NULL domain, WholeExtent not set!");
    return false;
  }

  if( (this->DomainInfo->GlobalImplicit[0] > 0) ||
      (this->DomainInfo->GlobalImplicit[1] > 0) ||
      (this->DomainInfo->GlobalImplicit[2] > 0) )
  {
    return true;
  }
  return false;
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::GetGlobalImplicitConnectivityState()
{
  // Sanity checks!
  assert("pre: null controller!" && (this->Controller != NULL) );

  int sndbuffer[3];
  if( this->InputGrid == NULL)
  {
    std::fill(sndbuffer,sndbuffer+3,0);
  }
  else
  {
    memcpy(sndbuffer,this->InputGrid->Implicit,3*sizeof(int));
  }

  this->Controller->AllReduce(
      sndbuffer,this->DomainInfo->GlobalImplicit,3,vtkCommunicator::SUM_OP);
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::EstablishConnectivity()
{
  // Sanity checks!
  assert("pre: null controller!" && (this->Controller != NULL) );
  assert("pre: NULL domain, WholeExtent not set!" &&
          (this->DomainInfo != NULL) );

  // STEP 0: Exchange extents
  this->ExchangeExtents();

  // STEP 1: Compute Neighbors
  this->ComputeNeighbors();

  // STEP 2: Get Global Implicit connectivity state
  this->GetGlobalImplicitConnectivityState();

  // STEP 3: Barrier synchronization
  this->Controller->Barrier();
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::GetOutputStructuredGrid(
        const int gridID, vtkStructuredGrid* grid)
{
  assert("pre: NULL output grid!" && (grid != NULL) );
  assert("pre: output grid is NULL!" && (this->OutputGrid != NULL));
  assert("pre: mismatch gridID" && (this->OutputGrid->ID == gridID));
  assert("pre: output grid has no points!" &&
          (this->OutputGrid->Nodes != NULL) );

  // silence warnings, the intent for the gridID here is for extending the
  // implementation in the future to allow multiple grids per process.
  static_cast<void>(gridID);

  grid->Initialize();
  grid->SetExtent(this->OutputGrid->Extent);
  grid->SetPoints(this->OutputGrid->Nodes);
  grid->GetPointData()->ShallowCopy(this->OutputGrid->PointData);
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::GetOutputImageData(
        const int gridID, vtkImageData* grid)
{
  assert("pre: NULL output grid!" && (grid != NULL) );
  assert("pre: output grid is NULL!" && (this->OutputGrid != NULL));
  assert("pre: mismatch gridID" && (this->OutputGrid->ID == gridID));

  // silence warnings, the intent for the gridID here is for extending the
  // implementation in the future to allow multiple grids per process.
  static_cast<void>(gridID);

  grid->SetExtent(this->OutputGrid->Extent);
  grid->GetPointData()->ShallowCopy(this->OutputGrid->PointData);
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::GetOutputRectilinearGrid(
      const int gridID, vtkRectilinearGrid* grid)
{
  assert("pre: NULL output grid!" && (grid != NULL) );
  assert("pre: output grid is NULL!" && (this->OutputGrid != NULL));
  assert("pre: mismatch gridID" && (this->OutputGrid->ID == gridID));

  // silence warnings, the intent for the gridID here is for extending the
  // implementation in the future to allow multiple grids per process.
  static_cast<void>(gridID);

  grid->SetExtent(this->OutputGrid->Extent);
  grid->GetPointData()->ShallowCopy(this->OutputGrid->PointData);
  grid->SetXCoordinates(this->OutputGrid->X_Coords);
  grid->SetYCoordinates(this->OutputGrid->Y_Coords);
  grid->SetZCoordinates(this->OutputGrid->Z_Coords);
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::ConstructOutput()
{
  if( this->OutputGrid != NULL )
  {
    this->OutputGrid->Clear();
    delete this->OutputGrid;
    this->OutputGrid = NULL;
  }

   this->OutputGrid = new vtk::detail::StructuredGrid();
   this->OutputGrid->Initialize( this->InputGrid );
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::UpdateNeighborList(const int dim)
{
  assert("pre: dimension index out-of-bounds!" && (dim >= 0) && (dim <= 2) );
  assert("pre: input grid is NULL!" && this->InputGrid != NULL );
  assert("pre: domain info is NULL!" && this->DomainInfo != NULL);

  vtk::detail::ImplicitNeighbor* neiPtr = NULL;
  size_t nNeis = this->InputGrid->Neighbors.size();
  for( size_t nei=0; nei < nNeis; ++nei )
  {
    neiPtr     = &(this->InputGrid->Neighbors)[nei];
    int orient = neiPtr->Orientation[ dim ];

    if( orient==vtk::detail::IntervalsConnect::IMPLICIT_HI ||
        orient==vtk::detail::IntervalsConnect::IMPLICIT_LO ||
        orient==vtk::detail::IntervalsConnect::UNDEFINED)
    {
      continue;
    }// END if implicit connectivity

    // Update neighbor extent
    if( neiPtr->Extent[dim*2+1] < this->DomainInfo->WholeExtent[dim*2+1] )
    {
      neiPtr->Extent[dim*2+1]++;
    } // END if update neighbor extent

    // Update overlap extent
    if( neiPtr->Overlap[dim*2+1] < this->DomainInfo->WholeExtent[dim*2+1] &&
        neiPtr->Overlap[dim*2+1]+1 <= neiPtr->Extent[dim*2+1])
    {
      neiPtr->Overlap[dim*2+1]++;
    } // END if update overlap


    assert("post: overlap extent out-of-bounds of output grid extent!" &&
      vtkStructuredExtent::Smaller(neiPtr->Overlap,this->OutputGrid->Extent));
  } // END for all neighbors
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::PackData(
      int ext[6], vtkMultiProcessStream& bytestream)
{
  // Sanity checks
  assert("pre: input grid is NULL!" && (this->InputGrid != NULL) );
  assert("pre: output grid is NULL!" && (this->OutputGrid != NULL) );
  assert("pre: extent is out-of-bounds the output grid!" &&
          vtkStructuredExtent::Smaller(ext,this->OutputGrid->Extent));

  bytestream.Push( ext, 6);

  if( this->OutputGrid->Nodes != NULL )
  {
    bytestream << VTK_STRUCTURED_GRID;
    vtkIdType nnodes = vtkStructuredData::GetNumberOfPoints(ext);
    bytestream << nnodes;

    int ijk[3] = {0,0,0};
    for( I(ijk)=IMIN(ext); I(ijk) <= IMAX(ext); ++I(ijk) )
    {
      for( J(ijk)=JMIN(ext); J(ijk) <= JMAX(ext); ++J(ijk) )
      {
        for( K(ijk)=KMIN(ext); K(ijk) <= KMAX(ext); ++K(ijk) )
        {
          vtkIdType idx = vtkStructuredData::ComputePointIdForExtent(
              this->OutputGrid->Extent,ijk,this->OutputGrid->DataDescription);
          bytestream.Push(this->OutputGrid->Nodes->GetPoint(idx),3);
        } // END for all k
      } // END for all j
    } // END for all i
  } // END if structured grid
  else if( this->OutputGrid->IsRectilinearGrid() )
  {
    bytestream << VTK_RECTILINEAR_GRID;
    vtkDataArray* coords[3];
    coords[0] = this->OutputGrid->X_Coords;
    coords[1] = this->OutputGrid->Y_Coords;
    coords[2] = this->OutputGrid->Z_Coords;
    for(int dim=0; dim < 3; ++dim)
    {
      assert("pre: NULL coordinates" && coords[dim] != NULL);
      int flag = -1;
      if( ext[dim*2] == ext[dim*2+1] )
      {
        flag = 1;
        bytestream << flag;
        bytestream << coords[ dim ]->GetTuple1(0);
      }
      else
      {
        bytestream << flag;
      }
    } // END for all dimensions
  } // END if rectilinear grid
  else
  {
    bytestream << VTK_UNIFORM_GRID;
  }

  // serialize the node-centered fields
  if(this->OutputGrid->PointData != NULL)
  {
    vtkFieldDataSerializer::SerializeSubExtent(
        ext,this->OutputGrid->Extent,this->OutputGrid->PointData,bytestream);
  }
  else
  {
    bytestream << 0;
  }
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::UnPackData(
      unsigned char* buffer, unsigned int size)
{
  assert("pre: output grid is NULL!" && (this->OutputGrid != NULL) );

  if( size == 0 )
  {
    return;
  }

  assert("pre: NULL buffer encountered!" && (buffer != NULL) );

  vtkMultiProcessStream bytestream;
  bytestream.SetRawData(buffer,size);

  int* ext = NULL;
  unsigned int sz = 0;
  bytestream.Pop(ext,sz);
  assert("post: ext size should be 6" && (sz==6) );
  assert("post: ext is out-of-bounds the output grid!" &&
          vtkStructuredExtent::Smaller(ext,this->OutputGrid->Extent));

  int datatype = -1;
  bytestream >> datatype;


  if( datatype == VTK_STRUCTURED_GRID )
  {
    int nnodes   = 0;
    bytestream >> nnodes;
    assert("pre: nnodes must be greater than 0!" && (nnodes > 0) );
    assert("post: output grid must have nodes!" &&
           (this->OutputGrid->Nodes != NULL) );

    int ijk[3]         = {0,0,0};
    double* pnt        = new double[3];
    unsigned int pntsz = 3;

    for( I(ijk)=IMIN(ext); I(ijk) <= IMAX(ext); ++I(ijk) )
    {
      for( J(ijk)=JMIN(ext); J(ijk) <= JMAX(ext); ++J(ijk) )
      {
        for( K(ijk)=KMIN(ext); K(ijk) <= KMAX(ext); ++K(ijk) )
        {
          vtkIdType idx = vtkStructuredData::ComputePointIdForExtent(
              this->OutputGrid->Extent,ijk,this->OutputGrid->DataDescription);
          assert("post: idx is out-of-bounds!" && (idx >= 0) &&
                  (idx < this->OutputGrid->Nodes->GetNumberOfPoints()) );

          bytestream.Pop(pnt,pntsz);
          assert("post: pntsz!=3" && (pntsz==3) );

          this->OutputGrid->Nodes->SetPoint(idx,pnt);
        } // END for all k
      } // END for all j
    } // END for all i

    delete [] pnt;
  } // END if structured
  else if( datatype == VTK_RECTILINEAR_GRID )
  {
    vtkDataArray* coords[3];
    coords[0] = this->OutputGrid->X_Coords;
    coords[1] = this->OutputGrid->Y_Coords;
    coords[2] = this->OutputGrid->Z_Coords;
    for(int dim=0; dim < 3; ++dim)
    {
      assert("pre: NULL coordinates" && coords[dim] != NULL);
      int flag = 0;
      bytestream >> flag;
      if( flag == 1 )
      {
        double coordinate;
        vtkIdType lastIdx = coords[ dim ]->GetNumberOfTuples()-1;
        bytestream >> coordinate;
        coords[ dim ]->SetTuple1(lastIdx, coordinate);
      }
    } // END for all dimensions
  } // END if rectilinear

  // de-serialize the node-centered fields
  if( this->OutputGrid->PointData != NULL )
  {
    vtkFieldDataSerializer::DeSerializeToSubExtent(
      ext,this->OutputGrid->Extent,this->OutputGrid->PointData,bytestream);
  }

  delete [] ext;
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::AllocateBuffers(const int dim)
{
  assert("pre: dimension index out-of-bounds!" && (dim >= 0) && (dim <= 2) );

  // Allocate CommBuffer data-structure
  if(this->CommManager == NULL)
  {
    this->CommManager = new vtk::detail::CommunicationManager();
  }

  // Clear previously calculated buffers, since we call this iteratively as
  // we carry out the communication along each dimension independently.
  this->CommManager->Clear();

  size_t nNeis = this->InputGrid->Neighbors.size();
  for(size_t nei=0; nei < nNeis; ++nei)
  {
    vtk::detail::ImplicitNeighbor* neiPtr= &(this->InputGrid->Neighbors)[nei];
    int orient = neiPtr->Orientation[ dim ];

    if( orient == vtk::detail::IntervalsConnect::IMPLICIT_HI )
    {
      // enqueue rcv from the rank of this neighbor
      this->CommManager->EnqueueRcv(neiPtr->Rank);
    } // END if
    else if( orient == vtk::detail::IntervalsConnect::IMPLICIT_LO)
    {
      // enqueue send to the rank of this neighbor
      vtkMultiProcessStream bytestream;
      this->PackData(neiPtr->Overlap,bytestream);

      unsigned char* buffer = NULL;
      unsigned int bytesize = 0;
      bytestream.GetRawData(buffer,bytesize);

      this->CommManager->EnqueueSend(neiPtr->Rank,buffer,bytesize);
    } // END else if
  } // END for all neighbors
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::GrowGrid(const int dim)
{
  assert("pre: dimension index out-of-bounds!" && (dim >= 0) && (dim <= 2) );
  assert("pre: input grid is NULL!" && this->InputGrid != NULL );

  // STEP 0: Allocate buffers & associated data-structures
  this->AllocateBuffers( dim );
  assert("pre: CommManager is NULL!" && (this->CommManager != NULL) );

  // STEP 1: Exchange data
  this->CommManager->Exchange(this->Controller);

  // STEP 4: Unpack data to output grid
  size_t nNeis = this->InputGrid->Neighbors.size();
  for( size_t nei=0; nei < nNeis; ++nei)
  {
    vtk::detail::ImplicitNeighbor* neiPtr= &(this->InputGrid->Neighbors)[nei];
    int orient  = neiPtr->Orientation[ dim ];
    int neiRank = neiPtr->Rank;

    if( orient == vtk::detail::IntervalsConnect::IMPLICIT_HI)
    {
      unsigned char* buffer = this->CommManager->GetRcvBuffer(neiRank);
      unsigned int   size   = this->CommManager->GetRcvBufferSize(neiRank);
      this->UnPackData(buffer,size);
    } // END if rcv'ed data

  } // END for all neighbors
}

//------------------------------------------------------------------------------
void vtkStructuredImplicitConnectivity::ExchangeData()
{
  // Sanity checks!
  assert( "pre: null controller!" && (this->Controller != NULL) );

  if(this->InputGrid != NULL)
  {
    // STEP 0: construct output grid data-structure
    this->ConstructOutput();

    // STEP 1: Process each dimension
    for(int d=0; d < this->DomainInfo->NDim; ++d)
    {
      int dim = this->DomainInfo->DimIndex[ d ];
      this->GrowGrid( dim );

      // STEP 2: Update neighbor list, w/ the grown grid information
      this->UpdateNeighborList( dim );
    } // END for all dimensions
  } // END if
  else
  {
    this->OutputGrid = NULL;
  } // END else

  // Barrier synchronization
  this->Controller->Barrier();
}