File: UnitTest.cpp

package info (click to toggle)
field3d 1.7.3-6
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,684 kB
  • sloc: cpp: 25,324; ansic: 2,594; python: 222; sh: 72; makefile: 26
file content (2780 lines) | stat: -rw-r--r-- 90,354 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
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
//----------------------------------------------------------------------------//

/*
 * Copyright (c) 2009 Sony Pictures Imageworks
 *
 * 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.
 */

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

#include <iostream>
#include <stdlib.h>

#include <boost/test/included/unit_test.hpp>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

// The version can reliably be found in this header file from OpenEXR,
// for both 2.x and 3.x:
#include <OpenEXR/OpenEXRConfig.h>
#define COMBINED_OPENEXR_VERSION ((10000*OPENEXR_VERSION_MAJOR) + \
                                  (100*OPENEXR_VERSION_MINOR) + \
                                  OPENEXR_VERSION_PATCH)

// There's just no easy way to have an `#include` that works in both
// cases, so we use the version to switch which set of include files we
// use.
#if COMBINED_OPENEXR_VERSION >= 20599 /* 2.5.99: pre-3.0 */
#   include <Imath/ImathFrustum.h>
#else
    // OpenEXR 2.x, use the old locations
#   include <OpenEXR/ImathFrustum.h>
#endif

#include "Field3D/DenseField.h"
#include "Field3D/EmptyField.h"
#include "Field3D/Field3DFile.h"
#include "Field3D/FieldInterp.h"
#include "Field3D/InitIO.h"
#include "Field3D/MACField.h"
#include "Field3D/MIPField.h"
#include "Field3D/MIPUtil.h"
#include "Field3D/SparseField.h"
#include "Field3D/Types.h"
#include "Field3D/Log.h"

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

using namespace boost;
using namespace boost::unit_test;

using namespace std;

using namespace Field3D;
using namespace Field3D::Hdf5Util;

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

namespace {
  using namespace boost::posix_time;
  template <typename T>
  struct Add
  {
    Add() 
      : sum(static_cast<T>(0.0))
    { }
    T sum;
    void operator()(const T &val)
    { sum += val; }
  };
  template <typename T>
  struct WriteSequence
  {
    WriteSequence()
      : current(static_cast<T>(0))
    { }
    T current;
    void operator()(T &val)
    { 
      val = current; 
      current += static_cast<T>(1.0);
    }
  };
  struct Timer
  {
    Timer()
      : m_startTime(microsec_clock::local_time())
    { }
    size_t ms()
    { 
      return size_t((microsec_clock::local_time() - 
                     m_startTime).total_milliseconds()); 
    }
    size_t us()
    { 
      return size_t((microsec_clock::local_time() - 
                     m_startTime).total_microseconds()); 
    }
  private:
    ptime m_startTime;
  };  class ScopedPrintTimer
  {
  public:
    Timer timer;
    ScopedPrintTimer(int numThreads=1)
      : m_numThreads(numThreads)
      {}
    ~ScopedPrintTimer()
    {
      Msg::print("  Time elapsed: " + 
                 lexical_cast<string>(0.001 * timer.ms() / 
                                      float(m_numThreads)));
    }
    int m_numThreads;
  };
}

//----------------------------------------------------------------------------//
std::string
getTempFile(const std::string &file)
{
#ifdef WIN32
  std::string tempDir = ::getenv("TMP");
  if (*tempDir.rbegin() != '/' && *tempDir.rbegin() != '\\')
    tempDir += '/';
#else
  std::string tempDir = "/tmp/";
#endif
  
  // Make sure the path is valid.
  std::string valid_file(file);
  for (size_t i = 0; i < valid_file.size(); i++)
  {
    if (!isalnum(valid_file[i]) && valid_file[i] != '.')
      valid_file[i] = '_';
  }

  return tempDir + valid_file;
}

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

template <template <typename T> class Field_T, class Data_T>
void testBasicField()
{
  typedef Field_T<Data_T> SField;
  typedef Field_T<FIELD3D_VEC3_T<Data_T> > VField;
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;

  Msg::print("Basic Field tests for type " + 
             string(SField::staticClassType()));

  string currentTest;

  currentTest = "Checking empty field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    SField sField;
    VField vField;    
    BOOST_CHECK_EQUAL(sField.dataWindow().hasVolume(), false);
    BOOST_CHECK_EQUAL(vField.dataWindow().hasVolume(), false);   
  }

  currentTest = "Checking non-empty field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    SField sField;
    sField.setSize(V3i(10));
    VField vField;
    vField.setSize(V3i(10));
    BOOST_CHECK_EQUAL(sField.dataWindow().hasVolume(), true);
    BOOST_CHECK_EQUAL(vField.dataWindow().hasVolume(), true);   
  }
  
  currentTest = "Checking value in cleared field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Data_T sVal(1.1f);
    Vec3_T vVal(1.2f);
    V3i size(10);
    SField sField;
    sField.setSize(size);
    VField vField;
    vField.setSize(size);
    sField.clear(sVal);
    vField.clear(vVal);
    BOOST_CHECK_EQUAL(sField.value(5, 5, 5), sVal);
    BOOST_CHECK_EQUAL(vField.value(5, 5, 5), vVal);   
  }
  
  currentTest = "Checking reading and writing entire field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    V3i size(50);
    SField sField;
    VField vField;
    sField.setSize(size);
    vField.setSize(size);
    sField.clear(0.0f);
    vField.clear(Vec3_T(0.0f));
    for (int k = 0; k < size.z; k++) {
      for (int j = 0; j < size.y; j++) {
        for (int i = 0; i < size.x; i++) {
          Data_T sVal = static_cast<Data_T>(i + j + k);
          Vec3_T vVal = 
            Vec3_T(static_cast<Data_T>(i + 2 * j + 2 * k));
          sField.lvalue(i, j, k) = sVal;
          vField.lvalue(i, j, k) = vVal;
          BOOST_CHECK_EQUAL(sField.value(i, j, k), sVal);
          BOOST_CHECK_EQUAL(vField.value(i, j, k), vVal);
        }
      }
    }
  }

  currentTest = "Checking large extents, small data window";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Box3i extents(V3i(-5), V3i(50));
    Box3i data(V3i(20), V3i(30));
    SField sField;
    VField vField;
    sField.setSize(extents, data);
    vField.setSize(extents, data);
    sField.clear(0.0f);
    vField.clear(Vec3_T(0.0f));
    for (int k = data.min.z; k <= data.max.z; k++) {
      for (int j = data.min.y; j <= data.max.y; j++) {
        for (int i = data.min.x; i <= data.max.x; i++) {
          Data_T sVal = static_cast<Data_T>(i + j + k);
          Vec3_T vVal = 
            Vec3_T(static_cast<Data_T>(i + 2 * j + 2 * k));
          sField.lvalue(i, j, k) = sVal;
          vField.lvalue(i, j, k) = vVal;
          BOOST_CHECK_EQUAL(sField.value(i, j, k), sVal);
          BOOST_CHECK_EQUAL(vField.value(i, j, k), vVal);
        }
      }
    }
  }

#if 0

  currentTest = "Checking large extents, small data window, with safeValue()";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Box3i extents(V3i(-5), V3i(50));
    Box3i data(V3i(40), V3i(45));
    SField sField;
    VField vField;
    sField.setSize(extents, data);
    vField.setSize(extents, data);
    sField.clear(0.0f);
    vField.clear(Vec3_T(0.0f));
    Data_T safeSVal = 1.0f;
    Vec3_T safeVVal = Vec3_T(1.1f);
    for (int k = extents.min.z; k <= extents.max.z; k++) {
      for (int j = extents.min.y; j <= extents.max.y; j++) {
        for (int i = extents.min.x; i <= extents.max.x; i++) {
          Data_T sVal = static_cast<Data_T>(i + j + k);
          Vec3_T vVal = 
            Vec3_T(static_cast<Data_T>(i + 2 * j + 2 * k));
          if (data.intersects(V3i(i, j, k))) {
            sField.lvalue(i, j, k) = sVal;
            vField.lvalue(i, j, k) = vVal;
            BOOST_CHECK_EQUAL(sField.safeValue(i, j, k, safeSVal), sVal);
            BOOST_CHECK_EQUAL(vField.safeValue(i, j, k, safeVVal), vVal);
          } else {
            BOOST_CHECK_EQUAL(sField.safeValue(i, j, k, safeSVal), safeSVal);
            BOOST_CHECK_EQUAL(vField.safeValue(i, j, k, safeVVal), safeVVal);
          }
        }
      }
    }
  }

#endif

  currentTest = "Checking std::fill works with iterators";

  if (true) {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Data_T testVal = 1.5f;
    Box3i extents(V3i(-5), V3i(25));
    V3i res = extents.max - extents.min + V3i(1);
    SField sField;
    sField.setSize(extents);
    std::fill(sField.begin(), sField.end(), testVal);
    for (int k = extents.min.z; k <= extents.max.z; k++) {
      for (int j = extents.min.y; j <= extents.max.y; j++) {
        for (int i = extents.min.x; i <= extents.max.x; i++) {
          BOOST_CHECK_EQUAL(sField.value(i, j, k), testVal);
        }
      }
    }    
  }

  currentTest = "Checking read from const_iterator - full field";

  if (true) {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Data_T testVal = 1.5f;
    Box3i extents(V3i(-5), V3i(25));
    V3i res = extents.max - extents.min + V3i(1);
    int numCells = res.x * res.y * res.z;
    SField sField;
    sField.setSize(extents);
    std::fill(sField.begin(), sField.end(), testVal);    
    {
      typename SField::const_iterator i = sField.cbegin();
      typename SField::const_iterator end = sField.cend();
      int cellCountI = 0;
      for (; i != end; ++i) {
        BOOST_CHECK_EQUAL(*i, testVal);
        cellCountI++;
      }
      BOOST_CHECK_EQUAL(cellCountI, numCells);
    }
  }

  currentTest = "Checking read from const_iterator - empty field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Data_T testVal = 1.5f;
    Box3i extents(V3i(-5), V3i(25));
    V3i res = extents.max - extents.min + V3i(1);
    int numCells = res.x * res.y * res.z;
    SField sField;
    sField.setSize(extents);
    sField.clear(testVal);
    typename SField::const_iterator i = sField.cbegin();
    typename SField::const_iterator end = sField.cend();
    int cellCountI = 0;
    for (; i != end; ++i) {
      BOOST_CHECK_EQUAL(*i, testVal);
      cellCountI++;
    }
    BOOST_CHECK_EQUAL(cellCountI, numCells);
    // Write a single voxels and then run the test again
    sField.lvalue(10, 10, 10) = testVal;
    typename SField::const_iterator j = sField.cbegin();
    int cellCountJ = 0;
    for (; j != end; ++j) {
      BOOST_CHECK_EQUAL(*j, testVal);    
      cellCountJ++;
    }
    BOOST_CHECK_EQUAL(cellCountJ, numCells);    
  }

  currentTest = "Checking read of subset from const_iterator - empty field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Data_T testVal = 1.5f;
    Box3i extents(V3i(-5), V3i(25));
    SField sField;
    sField.setSize(extents);
    sField.clear(testVal);
    // Region to read
    Box3i toRead(V3i(10), V3i(18));
    typename SField::const_iterator i = sField.cbegin(toRead);
    typename SField::const_iterator end = sField.cend(toRead);
    int cellCountI = 0;
    for (; i != end; ++i) {
      BOOST_CHECK_EQUAL(*i, testVal);
      cellCountI++;
    }
    V3i res = toRead.max - toRead.min + V3i(1);
    int numCells = res.x * res.y * res.z;
    BOOST_CHECK_EQUAL(cellCountI, numCells);
    // Write a single voxels and then run the test again
    sField.lvalue(10, 10, 10) = testVal;
    typename SField::const_iterator j = sField.cbegin(toRead);
    int cellCountJ = 0;
    for (; j != end; ++j) {

      BOOST_CHECK_EQUAL(*j, testVal);    
      cellCountJ++;
    }
    BOOST_CHECK_EQUAL(cellCountJ, numCells);    
  }

  currentTest = "Checking read from iterator";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Data_T testVal = 1.5f;
    Box3i extents(V3i(-5), V3i(25));
    V3i res = extents.max - extents.min + V3i(1);
    int numCells = res.x * res.y * res.z;
    SField sField;
    sField.setSize(extents);
    sField.clear(testVal);
    typename SField::iterator i = sField.begin();
    typename SField::iterator end = sField.end();
    int cellCountI = 0;
    for (; i != end; ++i) {
      BOOST_CHECK_EQUAL(*i, testVal);
      cellCountI++;
    }
    BOOST_CHECK_EQUAL(cellCountI, numCells);
    // Write a single voxels and then run the test again
    sField.lvalue(10, 10, 10) = testVal;
    typename SField::iterator j = sField.begin();
    int cellCountJ = 0;
    for (; j != end; ++j) {
      BOOST_CHECK_EQUAL(*j, testVal);    
      cellCountJ++;
    }
    BOOST_CHECK_EQUAL(cellCountJ, numCells);    
  }


  currentTest = "Checking iterator correctness";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Box3i extents(V3i(-5), V3i(25));
    SField sField;
    VField vField;
    sField.setSize(extents);
    vField.setSize(extents);
    // Fill with data
    std::for_each(sField.begin(), sField.end(), 
                  WriteSequence<Data_T>());
    std::for_each(vField.begin(), vField.end(), 
                  WriteSequence<Vec3_T>());
    // Iterators to check
    typename SField::iterator iter = sField.begin();
    typename SField::const_iterator citer = sField.cbegin();
    // Check that iterators match explicit loop
    for (int k = extents.min.z; k <= extents.max.z; k++) {
      for (int j = extents.min.y; j <= extents.max.y; j++) {
        for (int i = extents.min.x; i <= extents.max.x; i++) {
          BOOST_CHECK_EQUAL(V3i(i, j, k), V3i(iter.x, iter.y, iter.z));
          BOOST_CHECK_EQUAL(V3i(i, j, k), V3i(citer.x, citer.y, citer.z));
          BOOST_CHECK_EQUAL(sField.value(i, j, k), *iter);
          BOOST_CHECK_EQUAL(sField.value(i, j, k), *citer);
          ++iter;
          ++citer;
        }
      }
    }
  }

  currentTest = "Checking random writes";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    int numWrites = 1000000;
    FIELD3D_RAND48 rng(134664222);
    int size = 200;
    V3i resolution(size);
    SField sField;
    VField vField; 
    sField.setSize(resolution);
    vField.setSize(resolution);
    for (int i = 0; i < numWrites; i++) {
      int x = static_cast<int>(rng.nextf(0, size));
      int y = static_cast<int>(rng.nextf(0, size-1));
      int z = static_cast<int>(rng.nextf(0, size-1));
      sField.lvalue(x, y, z) = rng.nextf();
      vField.lvalue(x, y, z) = Vec3_T(rng.nextf());
    } 
  }

  currentTest = "Checking that mapping picks up resizes";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    int start = 5;
    int end = 50;
    Box3i extents(V3i(start, start, start), V3i(end, end, end));
    Box3i extents2(V3i(start * 2), V3i(end * 2));
    SField sField;
    sField.setSize(extents);
    MatrixFieldMapping::Ptr mapping(new MatrixFieldMapping);
    sField.setMapping(mapping);
    V3d voxelSize(1.0/(end-start+1));
    V3d voxelSize2(1.0/(2*end-2*start+1));
    double size = (voxelSize - sField.mapping()->wsVoxelSize(0,0,0)).length();
    BOOST_CHECK_EQUAL(size < 1e-5, true);
    MatrixFieldMapping before;
    before = *mapping;
    sField.setSize(extents2);
    BOOST_CHECK_EQUAL(before.origin() == sField.mapping()->origin(), false);
    BOOST_CHECK_EQUAL(before.resolution() == sField.mapping()->resolution(), 
                      false);
    BOOST_CHECK_EQUAL((voxelSize2-sField.mapping()->
                         wsVoxelSize(0,0,0)).length()<1e-5, true);
  }

  currentTest = "Checking clone and copy constructors";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Box3i extents(V3i(-5), V3i(25));
    typename SField::Ptr sField(new SField);
    typename VField::Ptr 
      vField(new VField);
    (*sField).setSize(extents);
    (*vField).setSize(extents);
    // Fill with data
    std::for_each((*sField).begin(), (*sField).end(), 
                  WriteSequence<Data_T>());
    std::for_each((*vField).begin(), (*vField).end(), 
                  WriteSequence<Vec3_T>());
    sField->metadata().setIntMetadata("first",1);
    sField->metadata().setIntMetadata("second",2);

    typename SField::Ptr sfclone = 
      field_dynamic_cast<SField >((*sField).clone());
    BOOST_CHECK_EQUAL(isIdentical<Data_T>(sField, sfclone), true);

    typename VField::Ptr vfclone = 
      field_dynamic_cast<VField >((*vField).clone());
    BOOST_CHECK_EQUAL(isIdentical<Vec3_T>(vField, vfclone), true);

    BOOST_CHECK_EQUAL(sField->metadata().intMetadata("first",-1), 
                      sfclone->metadata().intMetadata("first", -1));
    BOOST_CHECK_EQUAL(sField->metadata().intMetadata("second", -1), 
                      sfclone->metadata().intMetadata("second",-1));
    
    typename SField::Ptr sfcopy = new SField(*sField);
    BOOST_CHECK_EQUAL(isIdentical<Data_T>(sField, sfcopy), true);

    typename VField::Ptr vfcopy = new VField(*vField);
    BOOST_CHECK_EQUAL(isIdentical<Vec3_T>(vField, vfcopy), true);

    BOOST_CHECK_EQUAL(sField->metadata().intMetadata("first",-1), 
                      sfcopy->metadata().intMetadata("first",-1));
    BOOST_CHECK_EQUAL(sField->metadata().intMetadata("second",-1), 
                      sfcopy->metadata().intMetadata("second",-1));

    typename SField::Ptr sfequal(new SField);
    *sfequal = *sField;
    BOOST_CHECK_EQUAL(isIdentical<Data_T>(sField, sfequal), true);

    typename VField::Ptr vfequal(new VField);
    *vfequal = *vField;
    BOOST_CHECK_EQUAL(isIdentical<Vec3_T>(vField, vfequal), true);

    BOOST_CHECK_EQUAL(sField->metadata().intMetadata("first",-1), 
                      sfequal->metadata().intMetadata("first",-1));
    BOOST_CHECK_EQUAL(sField->metadata().intMetadata("second",-1), 
                      sfequal->metadata().intMetadata("second",-1));
  }

}

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

template <class Data_T>
void testEmptyField()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;

  Msg::print("Basic Field tests for type " + 
             string(EmptyField<Data_T>::staticClassType())); 


  string currentTest;

  currentTest = "Checking empty field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    EmptyField<Data_T> sField;
    EmptyField<Vec3_T>   vField;    
    BOOST_CHECK_EQUAL(sField.dataWindow().hasVolume(), false);
    BOOST_CHECK_EQUAL(vField.dataWindow().hasVolume(), false);   
  }

  currentTest = "Checking non-empty field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    EmptyField<Data_T> sField;
    EmptyField<Vec3_T> vField;
    sField.setSize(V3i(10));
    vField.setSize(V3i(10));
    BOOST_CHECK_EQUAL(sField.dataWindow().hasVolume(), true);
    BOOST_CHECK_EQUAL(vField.dataWindow().hasVolume(), true);   
  }
  
  currentTest = "Checking value in cleared field";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    Data_T sVal(1.1f);
    Vec3_T vVal(1.2f);
    V3i size(10);
    EmptyField<Data_T> sField;
    EmptyField<Vec3_T> vField;
    sField.setSize(size);
    vField.setSize(size);
    sField.clear(sVal);
    vField.clear(vVal);
    BOOST_CHECK_EQUAL(sField.value(5, 5, 5), sVal);
    BOOST_CHECK_EQUAL(vField.value(5, 5, 5), vVal);   
  }
  
  currentTest = "Checking (bogus) reading and writing a nonexistent cell";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    V3i size(50);
    EmptyField<Data_T> sField;
    EmptyField<Vec3_T> vField;
    sField.setSize(size);
    vField.setSize(size);
    sField.clear(0.0f);
    vField.clear(Vec3_T(0.0f));
    Data_T sVal = static_cast<Data_T>(30.0f);
    Vec3_T vVal = Vec3_T(static_cast<Data_T>(50.0f));
    sField.lvalue(10, 10, 10) = sVal;
    vField.lvalue(10, 10, 10) = vVal;
    BOOST_CHECK_EQUAL(sField.value(10, 10, 10), 0.0f);
    BOOST_CHECK_EQUAL(vField.value(10, 10, 10), Vec3_T(0.0f));
  }

  currentTest = "Checking reading and writing the constant value";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    V3i size(50);
    EmptyField<Data_T> sField;
    EmptyField<Vec3_T> vField;
    sField.setSize(size);
    vField.setSize(size);
    sField.clear(0.0f);
    vField.clear(Vec3_T(0.0f));
    Data_T sVal = static_cast<Data_T>(30.0f);
    Vec3_T vVal = Vec3_T(static_cast<Data_T>(50.0f));
    sField.setConstantvalue(sVal);
    vField.setConstantvalue(vVal);
    BOOST_CHECK_EQUAL(sField.constantvalue(), sVal);
    BOOST_CHECK_EQUAL(vField.constantvalue(), vVal);
  }

  currentTest = "Checking that mapping picks up resizes";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    int start = 5;
    int end = 50;
    Box3i extents(V3i(start, start, start), V3i(end, end, end));
    Box3i extents2(V3i(start * 2), V3i(end * 2));
    EmptyField<Data_T> sField;
    sField.setSize(extents);
    MatrixFieldMapping::Ptr mapping(new MatrixFieldMapping);
    sField.setMapping(mapping);
    MatrixFieldMapping before;
    before = *mapping;
    sField.setSize(extents2);
    BOOST_CHECK_EQUAL(before.origin() == 
                      sField.mapping()->origin(), false);
    BOOST_CHECK_EQUAL(before.resolution() == 
                      sField.mapping()->resolution(), false);
  }

}

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

template <class Data_T>
void testFieldMapping()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;

  Msg::print("FieldMapping tests for type " + 
             string(DenseField<Data_T>::staticClassType()));

  string currentTest;

  currentTest = "Checking field mapping";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    V3i size(5);
    Box3i extents(V3i(-5), V3i(25));

    typename DenseField<Vec3_T>::Ptr vField(new DenseField<Vec3_T>);
    (*vField).setSize(extents);
    (*vField).clear(Vec3_T(1.0f, 0.0f, 0.0f));
    MatrixFieldMapping::Ptr mapping(new MatrixFieldMapping);
    (*vField).setMapping(mapping);
    MatrixFieldMapping::Ptr mapping1 =
      dynamic_pointer_cast<MatrixFieldMapping>(vField->mapping());

    typename DenseField<Vec3_T>::Ptr vField2 =
      field_dynamic_cast<DenseField<Vec3_T> >(vField->clone());

    M44d transform(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    MatrixFieldMapping::Ptr mapping2 =
      dynamic_pointer_cast<MatrixFieldMapping>(vField2->mapping());
    mapping2->setLocalToWorld(transform);
    // the matrices should be different, so compare matrices and make
    // sure they don't match
    BOOST_CHECK_EQUAL(mapping1->localToWorld() == 
                      mapping2->localToWorld(), false);

  }

  currentTest = "Checking time-varying MatrixFieldMapping";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    
    M44d sample1;
    sample1.setTranslation(V3f(2.0));
    M44d sample2;
    sample2.setTranslation(V3f(4.0));
    MatrixFieldMapping::Ptr mapping(new MatrixFieldMapping);
    mapping->setLocalToWorld(0.0, sample1);
    mapping->setLocalToWorld(1.0, sample2);

    BOOST_CHECK_EQUAL(mapping->localToWorldSamples().size(), 2);
    BOOST_CHECK_EQUAL(mapping->localToWorldSamples()[0].first, 0.0);
    BOOST_CHECK_EQUAL(mapping->localToWorldSamples()[1].first, 1.0);
  }

  currentTest = "Checking MatrixFieldMapping isIdentical()";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    
    M44d sample1, sample2;
    sample1.setTranslation(V3f(2.0));
    sample2.setTranslation(V3f(4.0));
    MatrixFieldMapping::Ptr mapping1(new MatrixFieldMapping),
      mapping2(new MatrixFieldMapping);
    BOOST_CHECK_EQUAL(mapping1->isIdentical(mapping2), true);
    mapping1->setLocalToWorld(0.0, sample1);
    mapping1->setLocalToWorld(1.0, sample2);
    mapping2->setLocalToWorld(0.0, sample1);
    BOOST_CHECK_EQUAL(mapping1->isIdentical(mapping2), false);
    mapping2->makeIdentity();
    mapping2->setLocalToWorld(0.1, sample1);
    mapping2->setLocalToWorld(1.0, sample2);
    BOOST_CHECK_EQUAL(mapping1->isIdentical(mapping2), false);
    mapping2->makeIdentity();
    mapping2->setLocalToWorld(0.0, sample1);
    mapping2->setLocalToWorld(1.0, sample1);
    BOOST_CHECK_EQUAL(mapping1->isIdentical(mapping2), false);
    mapping2->makeIdentity();
    mapping2->setLocalToWorld(0.0, sample1);
    mapping2->setLocalToWorld(1.0, sample2);
    BOOST_CHECK_EQUAL(mapping1->isIdentical(mapping2), true);
  }

}

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

void testFrustumMapping()
{
  Msg::print("FrustumMapping tests");
  ScopedPrintTimer timer;

  int intRes = 64;
  float floatRes = static_cast<float>(intRes);

  DenseField<float>::Ptr field(new DenseField<float>);
  field->setSize(V3i(intRes));

  FrustumFieldMapping::Ptr fm(new FrustumFieldMapping);
  field->setMapping(fm);
  fm = field_dynamic_cast<FrustumFieldMapping>(field->mapping());

  M44d identity;
  identity.makeIdentity();

  BOOST_CHECK_EQUAL(fm->cameraToWorld(), identity);
  BOOST_CHECK(fm->screenToWorldSamples().size() == 1);
  BOOST_CHECK(fm->cameraToWorldSamples().size() == 1);
  BOOST_CHECK(fm->nearPlaneSamples().size() == 1);
  BOOST_CHECK(fm->farPlaneSamples().size() == 1);
  
  V3d wsP(0.0, 0.0, -1.5);
  V3d vsP, lsP;
  
  fm->worldToVoxel(wsP, vsP);
  fm->worldToLocal(wsP, lsP);

  BOOST_CHECK_EQUAL(vsP.x, floatRes / 2.0);
  BOOST_CHECK_EQUAL(vsP.y, floatRes / 2.0);
  BOOST_CHECK(vsP.z > 0.0);
  BOOST_CHECK(vsP.z < floatRes);

  BOOST_CHECK_EQUAL(lsP.x, 0.5);
  BOOST_CHECK_EQUAL(lsP.y, 0.5);
  BOOST_CHECK(lsP.z > 0.0);
  BOOST_CHECK(lsP.z < 1.0);

  // Check uniform slice distribution

  fm->setZDistribution(FrustumFieldMapping::UniformDistribution);
  field->setMapping(fm);
  fm = field_dynamic_cast<FrustumFieldMapping>(field->mapping());

  wsP.setValue(0.0, 0.0, -1.5);
  fm->worldToLocal(wsP, lsP);
  BOOST_CHECK_EQUAL(lsP.z, 0.5);
}

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

template <template <typename T> class Field_T, class Data_T>
void testLinearInterp()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;
  typedef Field_T<Data_T> SField;
  typedef Field_T<Vec3_T> VField;

  Msg::print("Linear interpolation tests for type " +
             string(SField::staticClassType()));

  string currentTest = "Simple linear inter test";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    SField sField;
    sField.setSize(V3i(10), 2);
    LinearFieldInterp<Data_T> lin;
    Box3i bottomSlice(V3i(-2), V3i(0, 9, 9));
    sField.clear(0.0f);
    std::fill(sField.begin(bottomSlice), sField.end(bottomSlice), 1.0f);
    BOOST_CHECK_EQUAL(sField.value(1, 0, 0), 0.0f);
    BOOST_CHECK_EQUAL(sField.value(0, 0, 0), 1.0f);
    BOOST_CHECK_EQUAL(lin.sample(sField, V3d(1.0, 3.1, 2.1)), 0.5f);
    BOOST_CHECK_EQUAL(lin.sample(sField, V3d(1.5, 3.1, 2.1)), 0.0f);
    BOOST_CHECK_EQUAL(lin.sample(sField, V3d(0.5, 3.1, 2.1)), 1.0f);
  }
}

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

template <template <typename T> class Field_T, class Data_T>
void testFastLinearInterp()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;
  typedef Field_T<Data_T> SField;
  typedef Field_T<Vec3_T> VField;

  Msg::print("Linear fast interpolation tests for type " + 
             string(SField::staticClassType()));

  string currentTest = "Simple linear inter test";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    SField sField;
    sField.setSize(V3i(10), 2);
    typename Field_T<Data_T>::LinearInterp lin;
    Box3i bottomSlice(V3i(-2), V3i(0, 9, 9));
    sField.clear(0.0f);
    std::fill(sField.begin(bottomSlice), sField.end(bottomSlice), 1.0f);
    BOOST_CHECK_EQUAL(sField.value(1, 0, 0), 0.0f);
    BOOST_CHECK_EQUAL(sField.value(0, 0, 0), 1.0f);
    BOOST_CHECK_EQUAL(lin.sample(sField, V3d(1.0, 3.1, 2.1)), 0.5f);
    BOOST_CHECK_EQUAL(lin.sample(sField, V3d(1.5, 3.1, 2.1)), 0.0f);
    BOOST_CHECK_EQUAL(lin.sample(sField, V3d(0.5, 3.1, 2.1)), 1.0f);
  }
}

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

template <template <typename T> class Field_T, class Data_T>
void testCubicInterp()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;
  typedef Field_T<Data_T> SField;
  typedef Field_T<Vec3_T> VField;

  Msg::print("Cubic interpolation tests for type " + 
             string(SField::staticClassType()));

  string currentTest = "Simple Cubic inter test";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    typename SField::Ptr sField(new SField);

    sField->setSize(V3i(10), 2);
    CubicFieldInterp<Data_T> cube;
    Box3i bottomSlice(V3i(-2), V3i(0, 9, 9));
    sField->clear(0.0f);
    std::fill(sField->begin(bottomSlice), sField->end(bottomSlice), 1.0f);

    BOOST_CHECK_EQUAL(sField->value(1, 0, 0), 0.0f);
    BOOST_CHECK_EQUAL(sField->value(0, 0, 0), 1.0f);
    BOOST_CHECK_EQUAL(cube.sample(*sField, V3d(1.0, 3.1, 2.1)), 0.5f);
    BOOST_CHECK_EQUAL(cube.sample(*sField, V3d(1.5, 3.1, 2.1)), 0.0f);
    BOOST_CHECK_EQUAL(cube.sample(*sField, V3d(0.5, 3.1, 2.1)), 1.0f);
  }
}

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

template <template <typename T> class Field_T, class Data_T>
void testFastCubicInterp()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;
  typedef Field_T<Data_T> SField;
  typedef Field_T<Vec3_T> VField;

  Msg::print("Cubic fast interpolation tests for type " + 
             string(SField::staticClassType()));

  string currentTest = "Simple Cubic inter test";

  {
    Msg::print(currentTest);
    ScopedPrintTimer t;
    typename SField::Ptr sField(new SField);

    sField->setSize(V3i(10), 2);
    typename Field_T<Data_T>::CubicInterp cube;
    Box3i bottomSlice(V3i(-2), V3i(0, 9, 9));
    sField->clear(0.0f);
    std::fill(sField->begin(bottomSlice), sField->end(bottomSlice), 1.0f);

    BOOST_CHECK_EQUAL(sField->value(1, 0, 0), 0.0f);
    BOOST_CHECK_EQUAL(sField->value(0, 0, 0), 1.0f);
    BOOST_CHECK_EQUAL(cube.sample(*sField, V3d(1.0, 3.1, 2.1)), 0.5f);
    BOOST_CHECK_EQUAL(cube.sample(*sField, V3d(1.5, 3.1, 2.1)), 0.0f);
    BOOST_CHECK_EQUAL(cube.sample(*sField, V3d(0.5, 3.1, 2.1)), 1.0f);
  }
}

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

template <template <typename T> class Field_T, class Data_T, bool DoOgawa_T>
void testField3DFile()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;
  typedef Field_T<Data_T> SField;
  typedef Field_T<Vec3_T> VField;

  Msg::print("Field3DFile tests for type " + 
             string(SField::staticClassType()) + 
             (DoOgawa_T ? " ogawa" : " hdf5"));

  if (DoOgawa_T) {
    Field3DOutputFile::useOgawa(true);
    Field3D::setNumIOThreads(8);
  } else {
    Field3DOutputFile::useOgawa(false);
  }

  string currentTest;

  currentTest = "Checking create bad file fails";

  // This isn't good to test - hdf5 spits out tons of errors
  if (!true) {
    Msg::print(currentTest);
    ScopedPrintTimer t;    
    string filename("/mpp/misspelled.f3d");
    Field3DOutputFile out;
    bool createSuccess = out.create(filename);
    BOOST_CHECK_EQUAL(createSuccess, false);
  }

  currentTest = "Checking write file, then read";

  {
    Msg::print(currentTest);
    string basename = "test_" + string(SField::staticClassType());
    if (DoOgawa_T) {
      basename += "ogawa";
    } else {
      basename += "hdf5";
    }
    string filename(getTempFile(basename + ".f3d"));
    Box3i extents(V3i(0), V3i(160));
    Box3i dataWindow(V3i(20, 10, 0), V3i(100, 100, 100));

    string field1Name("field1");
    string field2Name("field2");
    string field3Name("field3");
    string densityName("density");
    string velName("v");
    string tempName("temperature");

    // Create the scalar field
    typename SField::Ptr sField(new SField);
    sField->setSize(extents, dataWindow);
    MatrixFieldMapping::Ptr mm(new MatrixFieldMapping);
    M44d mtx;
    mtx.setTranslation(Vec3_T(1.1, 2.2, 4.4));
    mm->setLocalToWorld(mtx);
    sField->setMapping(mm);
    sField->clear(1.2);
    sField->metadata().setFloatMetadata("testfloat", 1.0f);
    sField->metadata().setIntMetadata("testint", 2);
    sField->metadata().setStrMetadata("teststring", "3!");

    // Create the vector field
    typename VField::Ptr vField(new VField);
    vField->setSize(extents, dataWindow);
    MatrixFieldMapping::Ptr mapping(new MatrixFieldMapping);
    mapping->setLocalToWorld(mtx);
    vField->setMapping(mapping);
    vField->clear(Vec3_T(0.5));
    vField->metadata().setFloatMetadata("testfloat", 1.0f);
    vField->metadata().setIntMetadata("testint", 2);
    vField->metadata().setStrMetadata("teststring", "3!");

    // Fill scalar fields with all data 
    std::for_each(sField->begin(), sField->end(), WriteSequence<Data_T>());

    // Fill the vector field with a few random data, the rest remains the
    // cleared value
    Box3i toFill(dataWindow);
    toFill.min = V3i(30, 30, 30);
    toFill.max = V3i(49, 49, 40);
    std::for_each(vField->begin(), vField->end(), 
                  WriteSequence<Vec3_T>());

    // Create the output file
    Field3DOutputFile out, outS, outV;
    bool createSuccess = out.create(filename);
    outS.create(filename + ".s");
    outV.create(filename + ".v");
    BOOST_CHECK_EQUAL(createSuccess, true);

    // Write two layers
    bool writeSuccess;
    writeSuccess = out.writeScalarLayer<Data_T>(field1Name, densityName, 
                                                sField);
    outS.writeScalarLayer<Data_T>(field1Name, densityName, sField);
    BOOST_CHECK_EQUAL(writeSuccess, true);
    writeSuccess = out.writeVectorLayer<Data_T>(field2Name, velName, 
                                                vField);
    outV.writeVectorLayer<Data_T>(field2Name, velName, vField);
    BOOST_CHECK_EQUAL(writeSuccess, true);

    /// write out global metadata
    V3f metaVecFloat(1.0,2.0,3.0);
    float metaFloat(123.0);
    V3i metaVecInt(4,5,6);
    int metaInt (456);
    string metaStr("Great Job!!!");
    out.metadata().setVecFloatMetadata("testGlobalMetadataVecFloat", 
                                       metaVecFloat);
    out.metadata().setFloatMetadata("testGlobalMetadataFloat", metaFloat);
    out.metadata().setVecIntMetadata("testGlobalMetadataVecInt", metaVecInt);
    out.metadata().setIntMetadata("testGlobalMetadataInt" , metaInt);
    out.metadata().setStrMetadata("testGlobalMetadataStr", metaStr);

    out.writeGlobalMetadata();

    out.close();
    
    // Open file up again
    Field3DInputFile iFile;
    iFile.open(filename);

    // check the global meta data are correct
    V3f inMetaVecFloat = 
      iFile.metadata().vecFloatMetadata("testGlobalMetadataVecFloat", V3f(9.0));
    BOOST_CHECK_EQUAL(metaVecFloat,inMetaVecFloat);
    float inMetaFloat = 
      iFile.metadata().floatMetadata("testGlobalMetadataFloat", 9.0f);
    BOOST_CHECK_EQUAL(metaFloat,inMetaFloat);
    V3i inMetaVecInt = 
      iFile.metadata().vecIntMetadata("testGlobalMetadataVecInt", V3i(9));
    BOOST_CHECK_EQUAL(metaVecInt,inMetaVecInt);
    int inMetaInt = 
      iFile.metadata().intMetadata("testGlobalMetadataInt", 9); 
    BOOST_CHECK_EQUAL(metaInt,inMetaInt);
    string inMetaStr = 
      iFile.metadata().strMetadata("testGlobalMetadataStr", "Hello");
    BOOST_CHECK_EQUAL(metaStr,inMetaStr);


    // Check that names are correct
    vector<string> partitions, names;
    iFile.getPartitionNames(partitions);
    bool field1InFile = find(partitions.begin(), partitions.end(),
                             field1Name) != partitions.end();
    Msg::print("Checking that partition " + field1Name + " exists in file.");
    bool field2InFile = find(partitions.begin(), partitions.end(),
                             field2Name) != partitions.end();
    Msg::print("Checking that partition " + field2Name + " exists in file.");
    bool field3InFile = find(partitions.begin(), partitions.end(),
                             field3Name) != partitions.end();
    Msg::print("Checking that partition " + field3Name + " exists in file.");
    BOOST_CHECK_EQUAL(field1InFile, true);
    BOOST_CHECK_EQUAL(field2InFile, true);
    BOOST_CHECK_EQUAL(field3InFile, false);
    iFile.getScalarLayerNames(names, field1Name);
    bool densityInFile = find(names.begin(), names.end(),
                              densityName) != names.end();
    names.clear();
    iFile.getVectorLayerNames(names, field2Name);

    bool velInFile = find(names.begin(), names.end(),
                          velName) != names.end();
    bool tempInFile = find(names.begin(), names.end(),
                           tempName) != names.end();

    BOOST_CHECK_EQUAL(densityInFile, true);
    BOOST_CHECK_EQUAL(velInFile, true);    
    BOOST_CHECK_EQUAL(tempInFile, false);

    // Read layers
    typename Field<Data_T>::Vec dOnFile;
    typename Field<Data_T>::Ptr dInMem;
    typename Field<Vec3_T>::Vec vOnFile;
    typename Field<Vec3_T>::Ptr vInMem;
    dInMem = sField;
    vInMem = vField;
    dOnFile = iFile.readScalarLayers<Data_T>(field1Name, densityName);
    vOnFile = iFile.readVectorLayers<Data_T>(field2Name, velName);
    BOOST_CHECK_EQUAL(dOnFile.size(), static_cast<size_t>(1));
    BOOST_CHECK_EQUAL(vOnFile.size(), static_cast<size_t>(1));

    // This check makes the test fail here so we don't get seg faults below
    BOOST_REQUIRE_EQUAL(dOnFile.size() == 1 && vOnFile.size() == 1, true);

    // Check mappings
    BOOST_CHECK_EQUAL(sField->mapping()->isIdentical(dOnFile[0]->mapping()), 
                      true);

    // Grab field data
    typename Field<Data_T>::Ptr s1 = dOnFile[0];
    typename Field<Data_T>::Ptr s2 = dInMem;
    typename Field<Vec3_T>::Ptr v1 = vOnFile[0];
    typename Field<Vec3_T>::Ptr v2 = vInMem;

    // Check scalar layer data
    {
      Msg::print("Verifying scalar data is identical");
      ScopedPrintTimer t;
      BOOST_CHECK_EQUAL(isIdentical<Data_T>(s1, s2), true);
    }

#if 0
    Box3i dw = v1->dataWindow();
    Field<Vec3_T> *p1 = v1.get(), *p2 = v2.get();
    for (int k = dw.min.z; k <= dw.max.z; ++k) {
      for (int j = dw.min.y; j <= dw.max.y; ++j) {
        for (int i = dw.min.x; i <= dw.max.x; ++i) {
          if (p1->value(i, j, k) != p2->value(i, j, k)) {
            cout << "Mismatch voxel: " << V3i(i, j, k) << endl;
          }
        }
      }
    }
#endif

    // Check vector layer data
    {
      Msg::print("Verifying vector data is identical");
      ScopedPrintTimer t;
      BOOST_CHECK_EQUAL(isIdentical<Vec3_T>(v1, v2), true);
    }

    // Check scalar metadata
    {
      Msg::print("Verifying scalar field's metadata is identical");
      const float fMeta  = s2->metadata().floatMetadata("testfloat", 0.0f);
      const int iMeta    = s2->metadata().intMetadata("testint", 0);
      const string sMeta = s2->metadata().strMetadata("teststring", "");
      BOOST_CHECK_EQUAL(fMeta, 1.0f);
      BOOST_CHECK_EQUAL(iMeta, 2);
      BOOST_CHECK_EQUAL(sMeta, "3!");
    }
 
  }

}

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

template <class Data_T>
void testEmptySparseFieldToDisk()
{
  string TName(DataTypeTraits<Data_T>::name());
  Msg::print(string("Testing empty sparse field to disk for ") + 
            "<" + TName + ">");

  ScopedPrintTimer t;    

  string filename(getTempFile("test_empty_sparse.f3d"));
  Box3i extents(V3i(0), V3i(160));
  Box3i dataWindow(V3i(20, 10, 0), V3i(200, 200, 200));
  
  string field1Name("field1");
  string densityName("density");
  
  // Create the scalar field
  typename SparseField<Data_T>::Ptr msf(new SparseField<Data_T>);
  BOOST_REQUIRE(msf != NULL);
  msf->setSize(extents, dataWindow);
  msf->clear(1.2);
  
  // Create the output file
  Field3DOutputFile out;
  bool createSuccess = out.create(filename);
  BOOST_CHECK_EQUAL(createSuccess, true);
  
  // Write two layers
  bool writeSuccess;
  writeSuccess = out.writeScalarLayer<Data_T>(field1Name, densityName, msf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  out.close(); 
}

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

template <template <typename T> class Field_T, class Data_T>
void testLayerFetching()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;
  typedef Field_T<Data_T> SField;
  typedef Field_T<Vec3_T> VField;

  Msg::print("Testing layer fetching for " + 
             string(SField::staticClassType()));

  ScopedPrintTimer t;    

  string filename(getTempFile("testLayerFetching_" + 
                  string(SField::staticClassType()) + ".f3d"));
  Box3i extents(V3i(0), V3i(160));
  Box3i dataWindow(V3i(20, 10, 50), V3i(100, 100, 100));

  typename SField::Ptr sf(new SField);
  typename VField::Ptr vf(new VField);

  sf->setSize(extents, dataWindow);
  vf->setSize(extents, dataWindow);

  // Write the file

  Field3DOutputFile out;
  bool createSuccess = out.create(filename);
  BOOST_CHECK_EQUAL(createSuccess, true);
  
  bool writeSuccess = out.writeScalarLayer<Data_T>("field1", "density", sf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeScalarLayer<Data_T>("field2", "density", sf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeScalarLayer<Data_T>("field3", "density", sf);  
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeVectorLayer<Data_T>("field1", "v", vf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeVectorLayer<Data_T>("field2", "v", vf);
  BOOST_CHECK_EQUAL(writeSuccess, true);

  out.close();

  // Check the file ---

  Field3DInputFile in;
  in.open(filename);

  typename Field<Data_T>::Vec densityFields;
  densityFields = in.readScalarLayers<Data_T>("density");

  BOOST_CHECK_EQUAL(densityFields.size(), static_cast<size_t>(3));

  typename Field<Vec3_T>::Vec vFields;
  vFields = in.readVectorLayers<Data_T>("v");

  BOOST_CHECK_EQUAL(vFields.size(), static_cast<size_t>(2));

  // Try fetching proxy versions ---

  EmptyField<float>::Vec field1Density = 
    in.readProxyLayer<float>("field1", "density", false);
  EmptyField<float>::Vec field2Density = 
    in.readProxyLayer<float>("field2", "density", false);
  EmptyField<float>::Vec field3Density = 
    in.readProxyLayer<float>("field3", "density", false);
  EmptyField<float>::Vec field1Vel = 
    in.readProxyLayer<float>("field1", "v", true);
  EmptyField<float>::Vec field2Vel = 
    in.readProxyLayer<float>("field2", "v", true);

  BOOST_CHECK(field1Density.size() == static_cast<size_t>(1));
  BOOST_CHECK(field2Density.size() == static_cast<size_t>(1));
  BOOST_CHECK(field3Density.size() == static_cast<size_t>(1));
  BOOST_CHECK(field1Vel.size() == static_cast<size_t>(1));
  BOOST_CHECK(field2Vel.size() == static_cast<size_t>(1));
  
  BOOST_CHECK_EQUAL(field1Density[0]->extents().min, extents.min);
  BOOST_CHECK_EQUAL(field1Density[0]->extents().max, extents.max);
  BOOST_CHECK_EQUAL(field2Density[0]->extents().min, extents.min);
  BOOST_CHECK_EQUAL(field2Density[0]->extents().max, extents.max);
  BOOST_CHECK_EQUAL(field3Density[0]->extents().min, extents.min);
  BOOST_CHECK_EQUAL(field3Density[0]->extents().max, extents.max);
  BOOST_CHECK_EQUAL(field1Vel[0]->extents().min, extents.min);
  BOOST_CHECK_EQUAL(field1Vel[0]->extents().max, extents.max);
  BOOST_CHECK_EQUAL(field2Vel[0]->extents().min, extents.min);
  BOOST_CHECK_EQUAL(field2Vel[0]->extents().max, extents.max);

  BOOST_CHECK_EQUAL(field1Density[0]->dataWindow().min, dataWindow.min);
  BOOST_CHECK_EQUAL(field1Density[0]->dataWindow().max, dataWindow.max);
  BOOST_CHECK_EQUAL(field2Density[0]->dataWindow().min, dataWindow.min);
  BOOST_CHECK_EQUAL(field2Density[0]->dataWindow().max, dataWindow.max);
  BOOST_CHECK_EQUAL(field3Density[0]->dataWindow().min, dataWindow.min);
  BOOST_CHECK_EQUAL(field3Density[0]->dataWindow().max, dataWindow.max);
  BOOST_CHECK_EQUAL(field1Vel[0]->dataWindow().min, dataWindow.min);
  BOOST_CHECK_EQUAL(field1Vel[0]->dataWindow().max, dataWindow.max);
  BOOST_CHECK_EQUAL(field2Vel[0]->dataWindow().min, dataWindow.min);
  BOOST_CHECK_EQUAL(field2Vel[0]->dataWindow().max, dataWindow.max);
}

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

template <template <typename T> class Field_T, class Data_T>
void testReadAsDifferentType()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;
  typedef Field_T<Data_T> SField;
  typedef Field_T<Vec3_T> VField;

  Msg::print("Testing on-the-fly conversion for " +
             string(SField::staticClassType()));

  ScopedPrintTimer t;    

  string filename(getTempFile("testReadAsDifferentType_" + 
                  string(SField::staticClassType()) + ".f3d"));
  Box3i extents(V3i(0), V3i(160));
  Box3i dataWindow(V3i(20, 10, 50), V3i(100, 100, 100));

  MatrixFieldMapping::Ptr mm1(new MatrixFieldMapping);
  MatrixFieldMapping::Ptr mm2(new MatrixFieldMapping);
  M44d mat1;
  M44d mat2;
  mat1.setTranslation(V3d(5.0, 6.0, 7.0));
  mat2.setTranslation(V3d(51.0, 67.0, 7.0));
  mm1->setLocalToWorld(mat1);
  mm2->setLocalToWorld(mat2);
  
  typename SparseField<Data_T>::Ptr sparse(new SparseField<Data_T>);
  sparse->setMapping(mm1);
  sparse->setSize(extents, dataWindow);
  sparse->clear(1.0f);
  sparse->lvalue(dataWindow.min.x, dataWindow.min.y, dataWindow.min.z) = 
    Data_T(1.0);
  typename DenseField<Data_T>::Ptr dense(new DenseField<Data_T>);
  dense->setMapping(mm2);
  dense->setSize(extents, dataWindow);
  dense->clear(2.0f);

  // Write the file

  Field3DOutputFile out;
  bool createSuccess = out.create(filename);
  BOOST_CHECK_EQUAL(createSuccess, true);
  
  bool writeSuccess = 
    out.writeScalarLayer<Data_T>("field1", "density", sparse);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeScalarLayer<Data_T>("field2", "density", sparse);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeScalarLayer<Data_T>("field3", "density", dense);  
  BOOST_CHECK_EQUAL(writeSuccess, true);

  out.close();

#if 0

  // Read it back out as the templated type

  Field3DInputFile in;
  in.open(filename);

  typename SField::Vec mf1, mf2, mf3;

  mf1 = in.readScalarLayersAs<Field_T, Data_T>("field1", "density");
  mf2 = in.readScalarLayersAs<Field_T, Data_T>("field2", "density");
  mf3 = in.readScalarLayersAs<Field_T, Data_T>("field3", "density");

  BOOST_CHECK_EQUAL(mf1.size(), static_cast<size_t>(1));
  BOOST_CHECK_EQUAL(mf2.size(), static_cast<size_t>(1));
  BOOST_CHECK_EQUAL(mf3.size(), static_cast<size_t>(1));

  // Check that the data is identical
  BOOST_CHECK(isIdentical<Data_T>(mf1[0], sparse));
  BOOST_CHECK(isIdentical<Data_T>(mf2[0], sparse));
  BOOST_CHECK(isIdentical<Data_T>(mf3[0], dense));

  // Mess with the data, and make sure it fails this time
  mf1[0]->lvalue(30, 30, 60) = 9.9;
  BOOST_CHECK_EQUAL(isIdentical<Data_T>(mf1[0], sparse), false);

#endif

}

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

void testDiscreteToContinuous()
{
  Msg::print("Testing disc2cont and cont2disc");

  BOOST_CHECK_EQUAL(contToDisc(0.5), 0);
  BOOST_CHECK_EQUAL(contToDisc(0.1), 0);
  BOOST_CHECK_EQUAL(contToDisc(0.9), 0);
  BOOST_CHECK(contToDisc(0.5) != 1);
  BOOST_CHECK_EQUAL(contToDisc(1.0), 1);
  BOOST_CHECK_EQUAL(contToDisc(V2d(0.5, 1.5)), V2i(0, 1));
  BOOST_CHECK_EQUAL(contToDisc(V3d(6.1, 8.5, 9.9)), V3i(6, 8, 9));

  BOOST_CHECK_EQUAL(discToCont(0), 0.5);
  BOOST_CHECK_EQUAL(discToCont(10), 10.5);
  BOOST_CHECK_EQUAL(discToCont(V2i(9, 99)), V2d(9.5, 99.5));
  BOOST_CHECK_EQUAL(discToCont(V3i(1, 9, 99)), V3d(1.5, 9.5, 99.5));
}

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

//! \todo Rewrite this for new metadata types
void testFieldMetadata()
{
  Msg::print("Testing meta data container for FieldBase");

#if USE_ANY_METADATA
// not used anymore, leaving the test code in for legacy in case it's
// needed later

  DenseField<float>::Ptr f(new DenseField<float>);

  BOOST_CHECK_EQUAL(f->metaData.size(), static_cast<size_t>(0));
  BOOST_CHECK_EQUAL(f->metaData.empty(), true);

  string doubleAttr("attrib_double");
  string floatAttr("attrib_float");
  string boolAttr("attrib_bool");

  f->metaData[doubleAttr] = boost::any(5.0);
  f->metaData[floatAttr] = boost::any(5.0f);
  f->metaData[boolAttr] = boost::any(true);

  BOOST_CHECK_EQUAL(f->metaData.size(), static_cast<size_t>(3));
  
  try {
    double a = any_cast<double>(f->metaData[doubleAttr]);
    float b = any_cast<float>(f->metaData[floatAttr]);
    bool c = any_cast<bool>(f->metaData[boolAttr]);
  }
  catch (boost::bad_any_cast &e) {
    BOOST_FAIL("Failed on any_cast");
  }

  BOOST_CHECK_THROW(any_cast<double>(f->metaData[floatAttr]), 
                    boost::bad_any_cast);

#endif

}

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

void testUnnamedFieldError()
{
  Msg::print("Testing that unnamed fields error out when writing");
  {
    Field3DOutputFile out;
    DenseFieldf::Ptr dense(new DenseFieldf);
    dense->setSize(V3i(50, 50, 50));
    bool success;
    {
      success = out.writeScalarLayer<float>(dense);
    }
    BOOST_CHECK_EQUAL(success, false);
  }
}

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

void testBasicFileOpen()
{
  Msg::print("Testing basic Field3DFile open/close");
  {
    Field3DInputFile in;
    BOOST_CHECK_EQUAL(in.open(getTempFile("test_DenseField_float_hdf5.f3d")), 
                      true);
    in.close();
  }
  {
    Field3DInputFile in;
    BOOST_CHECK_EQUAL(in.open(getTempFile("test_DenseField_float_ogawa.f3d")), 
                      true);
    in.close();
  }
}

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

template <class Float_T>
void testMACField()
{
  typedef MACField<FIELD3D_VEC3_T<Float_T> > MACField_T;

  Msg::print("Testing MAC Field");
  {
    Float_T clearVal(0.0);
    Float_T uVal(10.0);
    Float_T vVal(20.0);
    Float_T wVal(40.0);

    V3i uCoord(2, 1, 1);
    V3i vCoord(1, 2, 1);
    V3i wCoord(1, 1, 2);

    Float_T uValHalf((uVal + clearVal) / 2.0);
    Float_T vValHalf((vVal + clearVal) / 2.0);
    Float_T wValHalf((wVal + clearVal) / 2.0);

    V3i res(20, 30, 40);

    MACField<FIELD3D_VEC3_T<Float_T> > field;
    field.setSize(res);
    field.clear(FIELD3D_VEC3_T<Float_T>(0.0));
    field.u(uCoord.x, uCoord.y, uCoord.z) = uVal;
    BOOST_CHECK_EQUAL(field.uCenter(1, 1, 1), uValHalf);
    BOOST_CHECK_EQUAL(field.value(1, 1, 1), FIELD3D_VEC3_T<Float_T>(uValHalf, 
                                                          clearVal,
                                                          clearVal));
    field.v(vCoord.x, vCoord.y, vCoord.z) = vVal;
    BOOST_CHECK_EQUAL(field.vCenter(1, 1, 1), vValHalf);
    BOOST_CHECK_EQUAL(field.value(1, 1, 1), FIELD3D_VEC3_T<Float_T>(uValHalf, 
                                                          vValHalf,
                                                          clearVal));
    field.w(wCoord.x, wCoord.y, wCoord.z) = wVal;
    BOOST_CHECK_EQUAL(field.wCenter(1, 1, 1), wValHalf);
    BOOST_CHECK_EQUAL(field.value(1, 1, 1), FIELD3D_VEC3_T<Float_T>(uValHalf, 
                                                          vValHalf,
                                                          wValHalf));

    // Counter used to check the correct # of visited locations
    int count = 0;

    // Check U loop ---

    typename MACField_T::const_mac_comp_iterator u = 
      field.cbegin_comp(MACCompU);
    typename MACField_T::const_mac_comp_iterator uEnd = 
      field.cend_comp(MACCompU);
    for (; u != uEnd; ++u) {
      BOOST_CHECK(*u == static_cast<Float_T>(uVal) || 
                  *u == static_cast<Float_T>(clearVal));
      if (u.x == uCoord.x && u.y == uCoord.y && u.z == uCoord.z) {
        BOOST_CHECK_EQUAL(*u, uVal);
      } else {
        BOOST_CHECK_EQUAL(*u, clearVal);
      }
      count++;
    }

    BOOST_CHECK_EQUAL(count, (res.x + 1) * res.y * res.z);

    // Check V loop ---

    count = 0;
    typename MACField_T::const_mac_comp_iterator v = 
      field.cbegin_comp(MACCompV);
    typename MACField_T::const_mac_comp_iterator vEnd = 
      field.cend_comp(MACCompV);
    for (; v != vEnd; ++v) {
      BOOST_CHECK(*v == static_cast<Float_T>(vVal) || 
                  *v == static_cast<Float_T>(clearVal));
      if (v.x == vCoord.x && v.y == vCoord.y && v.z == vCoord.z) {
        BOOST_CHECK_EQUAL(*v, vVal);
      } else {
        BOOST_CHECK_EQUAL(*v, clearVal);
      }
      count++;
    }

    BOOST_CHECK_EQUAL(count, res.x * (res.y + 1) * res.z);

    // Check W loop ---

    count = 0;
    typename MACField_T::const_mac_comp_iterator w = 
      field.cbegin_comp(MACCompW);
    typename MACField_T::const_mac_comp_iterator wEnd = 
      field.cend_comp(MACCompW);
    for (; w != wEnd; ++w) {
      BOOST_CHECK(*w == static_cast<Float_T>(wVal) || 
                  *w == static_cast<Float_T>(clearVal));
      if (w.x == wCoord.x && w.y == wCoord.y && w.z == wCoord.z) {
        BOOST_CHECK_EQUAL(*w, wVal);
      } else {
        BOOST_CHECK_EQUAL(*w, clearVal);
      }
      count++;
    }

    BOOST_CHECK_EQUAL(count, res.x * res.y * (res.z + 1));

  }


  Msg::print("Testing MAC Field subset iterator");
  {
    V3i res(5, 6, 7);
    MACField<FIELD3D_VEC3_T<Float_T> > field;
    field.setSize(res);

    // neg x face
    {
      field.clear(FIELD3D_VEC3_T<Float_T>(0.0));

      Box3i subset(V3i(0, 0, 0), V3i(0, res.y - 1, res.z - 1));

      typename MACField_T::mac_comp_iterator usub = 
        field.begin_comp(MACCompU, subset);
      typename MACField_T::mac_comp_iterator uEndsub = 
        field.end_comp(MACCompU, subset);
      for (; usub != uEndsub; ++usub) {
        *usub = 1.0;
      }
      typename MACField_T::const_mac_comp_iterator u = 
        field.cbegin_comp(MACCompU);
      typename MACField_T::const_mac_comp_iterator uEnd = 
        field.cend_comp(MACCompU);
      for (; u != uEnd; ++u) {
        if (u.x == 0 || u.x == 1) {
          BOOST_CHECK_EQUAL(*u, 1.0);
        } else {
          BOOST_CHECK_EQUAL(*u, 0.0);
        }
      }
    }

    // pos x face
    {
      field.clear(FIELD3D_VEC3_T<Float_T>(0.0));

      Box3i subset(V3i(res.x - 1, 0, 0), V3i(res.x - 1, res.y - 1, res.z - 1));

      typename MACField_T::mac_comp_iterator usub = 
        field.begin_comp(MACCompU, subset);
      typename MACField_T::mac_comp_iterator uEndsub = 
        field.end_comp(MACCompU, subset);
      for (; usub != uEndsub; ++usub) {
        *usub = 1.0;
      }
      typename MACField_T::const_mac_comp_iterator u = 
        field.cbegin_comp(MACCompU);
      typename MACField_T::const_mac_comp_iterator uEnd = 
        field.cend_comp(MACCompU);
      for (; u != uEnd; ++u) {
        if (u.x == res.x - 1 || u.x == res.x) {
          BOOST_CHECK_EQUAL(*u, 1.0);
        } else {
          BOOST_CHECK_EQUAL(*u, 0.0);
        }
      }
    }

    // neg y face
    {
      field.clear(FIELD3D_VEC3_T<Float_T>(0.0));

      Box3i subset(V3i(0, 0, 0), V3i(res.x - 1, 0, res.z - 1));

      typename MACField_T::mac_comp_iterator vsub = 
        field.begin_comp(MACCompV, subset);
      typename MACField_T::mac_comp_iterator vsubEnd = 
        field.end_comp(MACCompV, subset);
      for (; vsub != vsubEnd; ++vsub) {
        *vsub = 1.0;
      }
      typename MACField_T::const_mac_comp_iterator v = 
        field.cbegin_comp(MACCompV);
      typename MACField_T::const_mac_comp_iterator vEnd = 
        field.cend_comp(MACCompV);
      for (; v != vEnd; ++v) {
        if (v.y == 0 || v.y == 1) {
          BOOST_CHECK_EQUAL(*v, 1.0);
        } else {
          BOOST_CHECK_EQUAL(*v, 0.0);
        }
      }
    }

    // pos y face
    {
      field.clear(FIELD3D_VEC3_T<Float_T>(0.0));

      Box3i subset(V3i(0, res.y - 1, 0), V3i(res.x - 1, res.y - 1, res.z - 1));

      typename MACField_T::mac_comp_iterator vsub = 
        field.begin_comp(MACCompV, subset);
      typename MACField_T::mac_comp_iterator vsubEnd = 
        field.end_comp(MACCompV, subset);
      for (; vsub != vsubEnd; ++vsub) {
        *vsub = 1.0;
      }
      typename MACField_T::const_mac_comp_iterator v = 
        field.cbegin_comp(MACCompV);
      typename MACField_T::const_mac_comp_iterator vEnd = 
        field.cend_comp(MACCompV);
      for (; v != vEnd; ++v) {
        if (v.y == res.y - 1 || v.y == res.y) {
          BOOST_CHECK_EQUAL(*v, 1.0);
        } else {
          BOOST_CHECK_EQUAL(*v, 0.0);
        }
      }
    }

    // neg z face
    {
      field.clear(FIELD3D_VEC3_T<Float_T>(0.0));

      Box3i subset(V3i(0, 0, 0), V3i(res.x - 1, res.y - 1, 0));

      typename MACField_T::mac_comp_iterator wsub = 
        field.begin_comp(MACCompW, subset);
      typename MACField_T::mac_comp_iterator wsubEnd = 
        field.end_comp(MACCompW, subset);
      for (; wsub != wsubEnd; ++wsub) {
        *wsub = 1.0;
      }
      typename MACField_T::const_mac_comp_iterator w = 
        field.cbegin_comp(MACCompW);
      typename MACField_T::const_mac_comp_iterator wEnd = 
        field.cend_comp(MACCompW);
      for (; w != wEnd; ++w) {
        if (w.z == 0 || w.z == 1) {
          BOOST_CHECK_EQUAL(*w, 1.0);
        } else {
          BOOST_CHECK_EQUAL(*w, 0.0);
        }
      }
    }

    // pos z face
    {
      field.clear(FIELD3D_VEC3_T<Float_T>(0.0));

      Box3i subset(V3i(0, 0, res.z - 1), V3i(res.x - 1, res.y - 1, res.z - 1));

      typename MACField_T::mac_comp_iterator wsub = 
        field.begin_comp(MACCompW, subset);
      typename MACField_T::mac_comp_iterator wsubEnd = 
        field.end_comp(MACCompW, subset);
      for (; wsub != wsubEnd; ++wsub) {
        *wsub = 1.0;
      }
      typename MACField_T::const_mac_comp_iterator w = 
        field.cbegin_comp(MACCompW);
      typename MACField_T::const_mac_comp_iterator wEnd = 
        field.cend_comp(MACCompW);
      for (; w != wEnd; ++w) {
        if (w.z == res.z - 1 || w.z == res.z) {
          BOOST_CHECK_EQUAL(*w, 1.0);
        } else {
          BOOST_CHECK_EQUAL(*w, 0.0);
        }
      }
    }
  }

}


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

template <class Float_T>
void testEmptyMACFieldToDisk()
{
  typedef MACField<FIELD3D_VEC3_T<Float_T> > MACField_T;

  string TName(DataTypeTraits<Float_T>::name());
  Msg::print(string("Testing empty MAC field to disk for ") + 
            "<" + TName + ">");

  ScopedPrintTimer t;    

  string filename(getTempFile("test_empty_mac.f3d"));
  Box3i extents(V3i(0), V3i(160));
  Box3i dataWindow(V3i(20, 10, 0), V3i(200, 200, 200));
  
  string field1Name("field1");
  string velocityName("v_mac");
  
  // Create the scalar field
  typename MACField_T::Ptr msf(new MACField_T);
  BOOST_REQUIRE(msf != NULL);
  msf->setSize(extents, dataWindow);
  msf->clear(FIELD3D_VEC3_T<Float_T>(1.2));
  
  // Create the output file
  Field3DOutputFile out;
  bool createSuccess = out.create(filename);
  BOOST_CHECK_EQUAL(createSuccess, true);
  
  // Write mac velocity layer
  bool writeSuccess;
  writeSuccess = out.writeVectorLayer<Float_T>(field1Name, velocityName, msf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  out.close(); 

  // Read the file back in
  Field3DInputFile in;
  BOOST_CHECK_EQUAL(in.open(filename), true);
  typename Field<FIELD3D_VEC3_T<Float_T> >::Vec fields = 
    in.readVectorLayers<Float_T>();
  BOOST_CHECK_EQUAL(fields.size(), 1);
  BOOST_CHECK_EQUAL(fields[0] != NULL, true);
  BOOST_CHECK_EQUAL(field_dynamic_cast<MACField_T>(fields[0]) != NULL, true);
}

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

template <class Data_T>
void testSparseFieldBlockAccess()
{
  string TName(DataTypeTraits<Data_T>::name());
  Msg::print("Testing SparseField<" + TName + "> block iterator");
  {
    SparseField<Data_T> field;
    field.setSize(V3i(100, 100, 100));
    
    {
      typename SparseField<Data_T>::block_iterator i = field.blockBegin();
      typename SparseField<Data_T>::block_iterator end = field.blockEnd();
      
      for (; i != end; ++i) {
        bool allocated = field.blockIsAllocated(i.x, i.y, i.z);
        BOOST_CHECK_EQUAL(allocated, false);
      }
    }

    // Write one voxel
    V3i v(1, 1, 1);
    field.lvalue(v.x, v.y, v.z) = static_cast<Data_T>(1.0);
    BOOST_CHECK_EQUAL(field.blockIsAllocated(0, 0, 0), true);
    BOOST_CHECK_EQUAL(field.voxelIsInAllocatedBlock(v.x, v.y, v.z), true);
    BOOST_CHECK_EQUAL(field.blockIsAllocated(0, 0, 1), false);
    
    // Clear out that first block
    Data_T val = static_cast<Data_T>(1.0);
    field.setBlockEmptyValue(0, 0, 0, val);
    BOOST_CHECK_EQUAL(field.getBlockEmptyValue(0, 0, 0), val);
    BOOST_CHECK_EQUAL(field.blockIsAllocated(0, 0, 0), false);
    BOOST_CHECK_EQUAL(field.voxelIsInAllocatedBlock(v.x, v.y, v.z), false);

    // Check the empty value
    BOOST_CHECK_EQUAL(field.value(v.x, v.y, v.z), val);

    // Check the blockIndexIsValid call
    BOOST_CHECK_EQUAL(field.blockIndexIsValid(0, 0, 0), true);
    BOOST_CHECK_EQUAL(field.blockIndexIsValid(8, 0, 0), false);

  }
}

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

template <template <typename T> class Field_T, class Data_T>
void testDuplicatePartitions()
{
  typedef FIELD3D_VEC3_T<Data_T> Vec3_T;
  typedef Field_T<Data_T> SField;
  typedef Field_T<Vec3_T> VField;

  Msg::print("Testing duplicate partition names for " + 
             string(SField::staticClassType()));

  string filename(getTempFile("testDuplicatePartitions_" +
                  string(SField::staticClassType()) + ".f3d"));

  Box3i extents(V3i(0), V3i(160));
  Box3i dataWindow(V3i(20, 10, 50), V3i(100, 100, 100));

  typename SField::Ptr sf(new SField);
  typename VField::Ptr vf(new VField);

  sf->setSize(extents, dataWindow);
  vf->setSize(extents, dataWindow);

  MatrixFieldMapping::Ptr mm1(new MatrixFieldMapping);
  MatrixFieldMapping::Ptr mm2(new MatrixFieldMapping);
  MatrixFieldMapping::Ptr mm3(new MatrixFieldMapping);
  M44d mat1, mat2, mat3;
  mat1.setTranslation(V3d(5.0, 6.0, 7.0));
  mat2.setTranslation(V3d(51.0, 67.0, 7.0));
  mm1->setLocalToWorld(mat1);
  mm2->setLocalToWorld(mat2);
  
  sf->setMapping(mm1);
  vf->setMapping(mm1);  

  // Write the file

  Field3DOutputFile out;
  bool createSuccess = out.create(filename);
  BOOST_CHECK_EQUAL(createSuccess, true);
  
  bool writeSuccess = out.writeScalarLayer<Data_T>("default", "density", sf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  out.writeScalarLayer<Data_T>("", "density", sf);
  BOOST_CHECK_EQUAL(writeSuccess, true);

  // Alter the mapping and add the layer again ---

  sf->setMapping(mm2);  
  vf->setMapping(mm2);  
  writeSuccess = out.writeScalarLayer<Data_T>("default", 
                                              "density_different_mapping", sf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeVectorLayer<Data_T>("default", 
                                              "v_different_mapping", vf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeScalarLayer<Data_T>("", "density_different_mapping", 
                                              sf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeVectorLayer<Data_T>("", "v_different_mapping", vf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
    
  // Alter the mapping again and add the layer again ---

  vf->setMapping(mm3);  
  writeSuccess = out.writeVectorLayer<Data_T>("default", 
                                              "v_second_different_mapping", vf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
  writeSuccess = out.writeVectorLayer<Data_T>("", "v_second_different_mapping", 
                                              vf);
  BOOST_CHECK_EQUAL(writeSuccess, true);
    
  // Double check that partition and layer names are correct ---

  vector<string> partitionNames;
  out.getPartitionNames(partitionNames);

  BOOST_CHECK_EQUAL(partitionNames.size(), static_cast<size_t>(2));

  out.close();

  // Now read it all in again ---

  Field3DInputFile in;
  bool readSuccess = in.open(filename);

  BOOST_CHECK(readSuccess);

  typename Field<Data_T>::Vec scalars;
  typename Field<Vec3_T>::Vec vectors;
  
  scalars = in.readScalarLayers<Data_T>();
  BOOST_CHECK_EQUAL(scalars.size(), static_cast<size_t>(4));
  vectors = in.readVectorLayers<Data_T>();
  BOOST_CHECK_EQUAL(vectors.size(), static_cast<size_t>(4));

}

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

void testTimeVaryingMatrixFieldMapping()
{
  Msg::print("Testing time varying MatrixFieldMapping");

  // Create matrix mapping with multiple time samples ---

  MatrixFieldMapping::Ptr mm(new MatrixFieldMapping);

  M44d sample0, sample1, sample2, sample3;
  sample0.setTranslation(V3f(1.0));
  sample1.setTranslation(V3f(2.0));
  sample2.setTranslation(V3f(3.0));
  sample3.setTranslation(V3f(4.0));
  
  mm->setLocalToWorld(-0.5, sample0);
  mm->setLocalToWorld(-0.1, sample1);
  mm->setLocalToWorld(0.1, sample2);
  mm->setLocalToWorld(0.5, sample3);

  // Dummy field. All zeroes.
  DenseField<float>::Ptr field(new DenseField<float>);
  field->name = "test";
  field->attribute = "attr";
  field->setSize(V3i(64));
  field->setMapping(mm);
  mm = field_dynamic_cast<MatrixFieldMapping>(field->mapping());
  BOOST_CHECK(mm);

  // Write to disk
  Field3DOutputFile out;
  string filename(getTempFile("testTimeVaryingMatrixFieldMapping.f3d")); 
  out.create(filename);
  out.writeScalarLayer<float>(field);

  // Read from disk
  Field3DInputFile in;
  in.open(filename);
  Field<float>::Vec fields = in.readScalarLayers<float>();
  BOOST_CHECK_EQUAL(fields.size(), 1);
  
  // Grab mapping
  FieldMapping::Ptr fileMapping = fields[0]->mapping();
  MatrixFieldMapping::Ptr fileMM = field_dynamic_cast<MatrixFieldMapping>(fileMapping);
  BOOST_CHECK(fileMM);
  
  // Check that mappings are identical
  BOOST_CHECK_EQUAL(mm->isIdentical(fileMM, 1e-6), true);
}

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

void testTimeVaryingFrustumFieldMapping()
{
  Msg::print("Testing time varying FrustumFieldMapping");

  // Create frustum mapping with multiple time samples ---

  FrustumFieldMapping::Ptr fm(new FrustumFieldMapping);

  Imath::Frustum<double> frustum(0.1, 10.0, 45.0, 0.0, 1.0);
  M44d csToWs0, csToWs1, csToWs2, csToWs3;
  csToWs0.setTranslation(V3d(0.0, 1.0, 0.0));
  csToWs1.setTranslation(V3d(0.0, 2.0, 0.0));
  csToWs2.setTranslation(V3d(0.0, 1.0, 0.0));
  csToWs3.setTranslation(V3d(0.0, -1.0, 0.0));
  M44d ssToCs = frustum.projectionMatrix().inverse();
  M44d ssToWs0 = ssToCs * csToWs0;
  M44d ssToWs1 = ssToCs * csToWs1;
  M44d ssToWs2 = ssToCs * csToWs2;
  M44d ssToWs3 = ssToCs * csToWs3;

  fm->setTransforms(0.0, ssToWs0, csToWs0);
  fm->setTransforms(0.1, ssToWs1, csToWs1);
  fm->setTransforms(0.5, ssToWs2, csToWs2);
  fm->setTransforms(1.0, ssToWs3, csToWs3);

  // Dummy field. All zeroes.
  DenseField<float>::Ptr field(new DenseField<float>);
  field->name = "test";
  field->attribute = "attr";
  field->setSize(V3i(64));
  field->setMapping(fm);
  fm = field_dynamic_cast<FrustumFieldMapping>(field->mapping());
  BOOST_CHECK(fm);

  // Write to disk
  Field3DOutputFile out;
  string filename(getTempFile("testTimeVaryingFrustumFieldMapping.f3d")); 
  out.create(filename);
  out.writeScalarLayer<float>(field);

  // Read from disk
  Field3DInputFile in;
  in.open(filename);
  Field<float>::Vec fields = in.readScalarLayers<float>();
  BOOST_CHECK_EQUAL(fields.size(), 1);
  
  // Grab mapping
  FieldMapping::Ptr fileMapping = fields[0]->mapping();
  FrustumFieldMapping::Ptr fileFM = 
    field_dynamic_cast<FrustumFieldMapping>(fileMapping);
  BOOST_CHECK(fileFM);
  
  // Check that mappings are identical
  BOOST_CHECK_EQUAL(fm->isIdentical(fileFM, 1e-6), true);

  // Check that mappings differ from a default instance
  FrustumFieldMapping::Ptr defaultMapping(new FrustumFieldMapping);
  BOOST_CHECK_EQUAL(defaultMapping->isIdentical(fm, 1e-6), false);
  BOOST_CHECK_EQUAL(defaultMapping->isIdentical(fileFM, 1e-6), false);
}

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

// ---------------------------------------------------------------------------//
// Functions -----------------------------------------------------------------//
// ---------------------------------------------------------------------------//

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

template <typename Data_T > 
void createWorkBuffer( 
  typename DenseField<Data_T>::Ptr destPtr, std::vector<Imath::Box3i> &workBuf )
{
  V3i res = destPtr->mapping()->resolution();
  for( int i = 0; i < res.y; ++i ){
    for( int j = 0; j < res.z; ++j ) {
      workBuf.push_back( Imath::Box3i( Imath::V3i( 0,  i, j ), 
                                       Imath::V3i( res.x - 1, i , j ) ) );
      
    }
  }
}

template <typename Data_T> 
void createWorkBuffer( 
  typename SparseField<Data_T>::Ptr destPtr, std::vector<Imath::Box3i> &workBuf )
{
    // for sparse loop over each block to be thread safe.
  typename SparseField<Data_T>::block_iterator i = destPtr->blockBegin();
  typename SparseField<Data_T>::block_iterator end = destPtr->blockEnd();
  for (; i != end; ++i) 
  {
    workBuf.push_back(i.blockBoundingBox());
  }
}



//----------------------------------------------------------------------------//
// Conv class declaration
template <class Field_T>
class CopyThreaded
{
 public:
 
  // Forward declaration -----------------------------------------------------//
  
  //Class for doing all the work
  class Worker;

  // Constructors ------------------------------------------------------------//
   
  // Creates an empty CopyThreaded object
  CopyThreaded()
    :
    m_numWorkThreads(1)
    {}

  // Witch chosen parameters
  CopyThreaded(int inThreads = 8)
    :
    m_numWorkThreads(inThreads)
    {}
  
  // Destructor --------------------------------------------------------------//
  virtual ~CopyThreaded() 
    {}

  // Functions ---------------------------------------------------------------//

  // Performs the copyion of the volume
  bool simpleFunc( typename Field_T::Ptr srcPtr, typename Field_T::Ptr destPtr);

 protected:

  int m_numWorkThreads;        // Number of worker threads;

  boost::mutex m_bufMutex;     // Mutex for reading from buffer

  std::vector<Imath::Box3i> m_workBuf; // Buffer for holding the work data first conv

}; //CopyThreaded class declaration end

//----------------------------------------------------------------------------//
// CopyThreaded::Worker
//----------------------------------------------------------------------------//
 
template <class Field_T>
class CopyThreaded<Field_T>::Worker
{
 public:

  typedef typename Field_T::value_type Data_T;

  // Constructors ------------------------------------------------------------//
  Worker( 
    CopyThreaded<Field_T>* inBoss, 
    typename Field_T::Ptr inSrcPtr, 
    typename Field_T::Ptr inDestPtr)
    : 
      m_boss( inBoss ), 
      m_srcPtr( inSrcPtr ), 
      m_destPtr( inDestPtr )
  { }
  
  // Destructor --------------------------------------------------------------//
  virtual ~Worker() 
  { }

  // Main function -----------------------------------------------------------//
  void operator()()
  {

    //Start execution
    while( true ) { 
      
      // Declaration for the current work segment
      Imath::Box3i workSeg;
      
      // Lock work buffer while reading from it
      {
        boost::mutex::scoped_lock lock( m_boss->m_bufMutex );
	    
        // Get work from work buffer if it is not empty
        if ( !m_boss->m_workBuf.empty() ) {
          // Fetch work
          workSeg = m_boss->m_workBuf.back();
          // Delete work segment
          m_boss->m_workBuf.pop_back();
          
        }
        // Or buffers empty, exit
        else {
          return;
        } 
      } 
      //typename Field_T::CubicInterp interp;
      // Create iterators for volume field
      typename Field_T::const_iterator itSrc = m_srcPtr->cbegin( workSeg );
      // create iterators for the result field
      typename Field_T::iterator itDest = m_destPtr->begin( workSeg );
      typename Field_T::iterator itDestEnd = m_destPtr->end( workSeg );

      // Iterate through each volume element
      for( ; itDest != itDestEnd; ++itSrc, ++itDest) {        
        // Copy through field and get back voxel value
        *itDest = *itSrc;
        //Imath::V3i vsP(itSrc.x, itSrc.y, itSrc.z);
        //*itDest = interp.sample(*m_srcPtr, vsP);
      }
    }
  }


 private:
  
  CopyThreaded<Field_T>* m_boss;     // Pointer to parent boss instance
  typename Field_T::Ptr   m_srcPtr;  // Pointer to the incoming volume
  typename Field_T::Ptr   m_destPtr; // Pointer to the outgoing result/

};


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

// Performs the copyion of the volume
template <class Field_T>
bool CopyThreaded<Field_T>::simpleFunc( 
  typename Field_T::Ptr  srcPtr, 
  typename Field_T::Ptr  destPtr)
{
  using namespace Field3D;
  typedef typename Field_T::value_type Data_T;

  // Resulting densefield pointer pointing to the incoming volume will give undesired result
  if ( srcPtr.get() == destPtr.get() ) {
    Msg::print(
              "Error::CopyThreaded::copy()::"
              "resulting field same as incoming"); // Change these to exceptions?
    return false;
  }

  Imath::Box3i srcExtents = srcPtr->extents();
  Imath::Box3i srcDataWindow = srcPtr->dataWindow();

  // Make sure destPtr is the same size as srcPtr
  V3i srcRes = srcPtr->mapping()->resolution();
  V3i destRes = destPtr->mapping()->resolution();

  if ( srcRes.x != destRes.x ||
       srcRes.y != destRes.y ||
       srcRes.z != destRes.z   ) {

    destPtr->matchDefinition(srcPtr);
  }

  // Downcast to MatrixFieldMapping ptr type to extract tranformation matrices
  MatrixFieldMapping::Ptr srcMapping =
    FIELD_DYNAMIC_CAST<MatrixFieldMapping>( srcPtr->mapping());  


  if (srcMapping == 0){
    Msg::print(
              "Error::CopyThreaded::copy()::"
              "FieldMapping not of matrix type");
    return false;
  }
   

  //Create work buffer for the workers
  createWorkBuffer<Data_T>( destPtr, m_workBuf);
 
  // Thread group for the workers
  boost::thread_group group;
  //Create workers
  for( int i = 0; i < m_numWorkThreads; ++i ) {
    group.create_thread( Worker(this, srcPtr, destPtr) );
  }

  // Make sure every thread is finished before exiting
  group.join_all();

  return true;
}
//----------------------------------------------------------------------------//


template <template <typename T> class Field_T, class Data_T>
void testThreadField()
{

  typedef Field_T<Data_T> SField;
  Box3i extents(V3i(0), V3i(62,128,62));
  //Box3i extents(V3i(0), V3i(128,256,128));
  typename SField::Ptr src = new(SField);
  typename SField::Ptr dest = new(SField);

  float testVal = 1.5f;
  dest->setSize(extents);
  dest->clear(testVal);
  src->setSize(extents);
  src->clear(testVal);
  //intialized src with random value
  {
    V3i srcRes = src->mapping()->resolution();
    Imath::Rand32 rng(0);
    typename SField::iterator i = src->begin();
    typename SField::iterator end = src->end();
    for (; i != end; ++i) {
      float val = rng.nextf();
      *i = val;          
    }  
  }
  
  std::vector<int> numThreads;
  numThreads.push_back(1);
  numThreads.push_back(4);
  numThreads.push_back(8);

 

  for (std::vector<int>::const_iterator i=numThreads.begin(), end=numThreads.end();
       i != end; ++i) 
  {
    {
      Msg::print("Testing " + src->className()+ " with " 
                 + lexical_cast<string>(*i) + " # of threads.");
      ScopedPrintTimer t(*i);
      CopyThreaded<SField> vol( *i );
      vol.simpleFunc(src, dest);
    }
    // verify data
    {
      typename SField::const_iterator itSrc = src->cbegin();
      typename SField::const_iterator itDest = dest->cbegin();
      typename SField::const_iterator itDestEnd = dest->cend();
      // Iterate through each volume element
      for( ; itDest != itDestEnd; ++itSrc, ++itDest) {        
        BOOST_CHECK_EQUAL(*itDest, *itSrc);
      }
      dest->clear(testVal);
    }
  }
}

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

template <template <typename T> class MIP_T, 
          template <typename T> class Field_T, 
          class Data_T,
          bool DoOgawa_T>
void testMIPField()
{
  typedef MIP_T<Data_T> FieldType;

  string TName(DataTypeTraits<Data_T>::name());
  Msg::print(string("Testing ") + 
             MIP_T<Data_T>::staticClassType()+ 
             (DoOgawa_T ? " ogawa" : " hdf5"));

  if (DoOgawa_T) {
    Field3DOutputFile::useOgawa(true);
    Field3D::setNumIOThreads(8);
  } else {
    Field3DOutputFile::useOgawa(false);
  }

  typename Field_T<Data_T>::Ptr level0(new Field_T<Data_T>);
  typename Field_T<Data_T>::Ptr level1(new Field_T<Data_T>);
  typename Field_T<Data_T>::Ptr level2(new Field_T<Data_T>);

  level0->setSize(V3i(100));
  level1->setSize(V3i(50));
  level2->setSize(V3i(25));

  level0->clear(1.0);
  level1->clear(0.5);
  level2->clear(0.25);

  std::vector<typename Field_T<Data_T>::Ptr> levels;
  levels.push_back(level0);
  levels.push_back(level1);
  levels.push_back(level2);

  typename MIP_T<Data_T>::Ptr mipField(new MIP_T<Data_T>);
  mipField->setup(levels);
  mipField->name = "mip";
  mipField->attribute = "density";
  
  string basename = "test_" + string(MIP_T<Data_T>::staticClassType());
  if (DoOgawa_T) {
    basename += "ogawa";
  } else {
    basename += "hdf5";
  }
  string filename(getTempFile(basename + ".f3d"));
    
  Field3DOutputFile out;
  out.create(filename);
  out.writeScalarLayer<float>(mipField);
  out.close();

  Field3DInputFile in;
  in.open(filename);

  typename Field<Data_T>::Vec fields = in.readScalarLayers<Data_T>();
  BOOST_CHECK_EQUAL(fields.size(), 1);

  mipField = field_dynamic_cast<MIP_T<Data_T> >(fields[0]);

  BOOST_CHECK_EQUAL(mipField != NULL, true);
  BOOST_CHECK_EQUAL(mipField->numLevels(), 3);
  bool matchLevel0 = isIdentical<Data_T>(mipField->mipLevel(0), level0);
  BOOST_CHECK(matchLevel0);
  bool matchLevel1 = isIdentical<Data_T>(mipField->mipLevel(1), level1);
  BOOST_CHECK(matchLevel1);
  bool matchLevel2 = isIdentical<Data_T>(mipField->mipLevel(2), level2);
  BOOST_CHECK(matchLevel2);
}

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

template <template <typename T> class MIP_T, 
          template <typename T> class Field_T, 
          class Data_T>
void testMIPFieldColor()
{
  string TName(DataTypeTraits<Data_T>::name());
  Msg::print(string("Testing ") + MIP_T<Data_T>::staticClassType());

  // typename Field_T<Data_T>::Ptr level0(new Field_T<Data_T>);
  typename Field_T<Data_T>::Ptr level1(new Field_T<Data_T>);
  typename Field_T<Data_T>::Ptr level2(new Field_T<Data_T>);
  typename Field_T<Data_T>::Ptr level3(new Field_T<Data_T>);
  typename Field_T<Data_T>::Ptr level4(new Field_T<Data_T>);
  typename Field_T<Data_T>::Ptr level5(new Field_T<Data_T>);

  // level0->setSize(V3i(400));
  level1->setSize(V3i(200));
  level2->setSize(V3i(100));
  level3->setSize(V3i(50));
  level4->setSize(V3i(25));
  level5->setSize(V3i(13));

  // level0->clear(V3f(1.0, 0.1, 0.1));
  level1->clear(V3f(0.1, 1.0, 0.1));
  level2->clear(V3f(0.1, 0.1, 1.0));
  level3->clear(V3f(1.0, 1.0, 0.1));
  level4->clear(V3f(1.0, 0.1, 1.0));
  level5->clear(V3f(0.1, 1.0, 1.0));

  std::vector<typename Field_T<Data_T>::Ptr> levels;
  // levels.push_back(level0);
  levels.push_back(level1);
  levels.push_back(level2);
  levels.push_back(level3);
  levels.push_back(level4);
  levels.push_back(level5);

  typename MIP_T<Data_T>::Ptr mipField(new MIP_T<Data_T>);
  mipField->setup(levels);
  mipField->name = "mip";
  mipField->attribute = "emission";
  
  Field3DOutputFile out;
  string filename(getTempFile(string(MIP_T<Data_T>::staticClassType()) + ".f3d")); 

  out.create(filename);
  out.writeVectorLayer<float>(mipField);
}

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

template <template <typename T> class Field_T, 
          class Data_T>
void testMIPMake()
{
  typedef MIPField<Field_T<Data_T> > MIPType;

  string TName(DataTypeTraits<Data_T>::name());

  typename Field_T<Data_T>::Ptr level0(new Field_T<Data_T>);

  level0->setSize(V3i(200));
  
  int val = 0;
  for (typename Field_T<Data_T>::iterator i = level0->begin(), end = level0->end();
       i != end; ++i) {
    *i = val;
    val = (val + 1) % 128;
  }

  std::vector<int> numThreads;
  numThreads.push_back(1);
  numThreads.push_back(4);
  numThreads.push_back(8);

  for (std::vector<int>::const_iterator i = numThreads.begin(), 
         end = numThreads.end(); i != end; ++i) 
  {
    Msg::print("Testing makeMIP" + 
               string(MIPType::staticClassType()) + " with " 
               + lexical_cast<string>(*i) + " # of threads.");
    typename MIPType::Ptr mipField = makeMIP<MIPType, TriangleFilter>(*level0, 32, *i);
    mipField->name = "mip";
    mipField->attribute = "density";
  
    std::stringstream base;
    base << "testMIPMake_";
    base << string(MIPType::staticClassType()) << "_";
    base << *i << ".f3d";

    Field3DOutputFile out;
    string filename(getTempFile(base.str())); 

    out.create(filename);
    out.writeScalarLayer<Data_T>(mipField);
    out.close();

    Field3DInputFile in;
    in.open(filename);
    typename Field<Data_T>::Vec fields = in.readScalarLayers<Data_T>();
    mipField = field_dynamic_cast<MIPType>(fields[0]);

    BOOST_CHECK_EQUAL(fields.size(), 1);
    BOOST_CHECK_EQUAL(mipField != NULL, true);
    BOOST_CHECK_EQUAL(mipField->numLevels(), 4);
    bool matchLevel0 = isIdentical<Data_T>(mipField->mipLevel(0), level0);
    BOOST_CHECK(matchLevel0);

  }
}

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

#define DO_BASIC_TESTS         1
#define DO_INTERP_TESTS        1
#define DO_CUBIC_INTERP_TESTS  1
#define DO_BASIC_FILE_TESTS    1
#define DO_ADVANCED_FILE_TESTS 1
#define DO_SPARSE_BLOCK_TESTS  1
#define DO_MAC_TESTS           1
#define DO_THREAD_TESTS        1
#define DO_MIP_TESTS           1

test_suite*
init_unit_test_suite(int argc, char* argv[])
{
  typedef Field3D::half half;

  initIO();

  test_suite* test = BOOST_TEST_SUITE("Field3D Test Suite");
  
  test->add(BOOST_TEST_CASE(&testDiscreteToContinuous));
  test->add(BOOST_TEST_CASE(&testFieldMetadata));

#if DO_BASIC_TESTS

  test->add(BOOST_TEST_CASE((&testBasicField<DenseField, half>)));
  test->add(BOOST_TEST_CASE((&testBasicField<SparseField, half>)));
  test->add(BOOST_TEST_CASE((&testBasicField<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testBasicField<SparseField, float>)));
  test->add(BOOST_TEST_CASE((&testBasicField<DenseField, double>)));
  test->add(BOOST_TEST_CASE((&testBasicField<SparseField, double>)));

  // EmptyField needs to a different function because its lvalue() is
  // deliberately disabled and replaced with constantvalue() and
  // setConstantvalue()
  test->add(BOOST_TEST_CASE((&testEmptyField<half>)));
  test->add(BOOST_TEST_CASE((&testEmptyField<float>)));
  test->add(BOOST_TEST_CASE((&testEmptyField<double>)));

  // tests to make sure the field clone properly makes a clone of the
  // mapping, so the old mapping will be preserved
  test->add(BOOST_TEST_CASE((&testFieldMapping<float>)));
  test->add(BOOST_TEST_CASE((&testFieldMapping<double>)));

  test->add(BOOST_TEST_CASE((&testFrustumMapping)));

#endif

#if DO_INTERP_TESTS

  test->add(BOOST_TEST_CASE((&testLinearInterp<DenseField, half>)));
  test->add(BOOST_TEST_CASE((&testLinearInterp<SparseField, half>)));
  test->add(BOOST_TEST_CASE((&testLinearInterp<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testLinearInterp<SparseField, float>)));
  test->add(BOOST_TEST_CASE((&testLinearInterp<DenseField, double>)));
  test->add(BOOST_TEST_CASE((&testLinearInterp<SparseField, double>)));

  test->add(BOOST_TEST_CASE((&testFastLinearInterp<DenseField, half>)));
  test->add(BOOST_TEST_CASE((&testFastLinearInterp<SparseField, half>)));
  test->add(BOOST_TEST_CASE((&testFastLinearInterp<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testFastLinearInterp<SparseField, float>)));
  test->add(BOOST_TEST_CASE((&testFastLinearInterp<DenseField, double>)));
  test->add(BOOST_TEST_CASE((&testFastLinearInterp<SparseField, double>)));

#endif

#if DO_CUBIC_INTERP_TESTS

  test->add(BOOST_TEST_CASE((&testCubicInterp<DenseField, half>)));
  test->add(BOOST_TEST_CASE((&testCubicInterp<SparseField, half>)));
  test->add(BOOST_TEST_CASE((&testCubicInterp<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testCubicInterp<SparseField, float>)));
  test->add(BOOST_TEST_CASE((&testCubicInterp<DenseField, double>)));
  test->add(BOOST_TEST_CASE((&testCubicInterp<SparseField, double>)));

  test->add(BOOST_TEST_CASE((&testFastCubicInterp<DenseField, half>)));
  test->add(BOOST_TEST_CASE((&testFastCubicInterp<SparseField, half>)));
  test->add(BOOST_TEST_CASE((&testFastCubicInterp<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testFastCubicInterp<SparseField, float>)));
  test->add(BOOST_TEST_CASE((&testFastCubicInterp<DenseField, double>)));
  test->add(BOOST_TEST_CASE((&testFastCubicInterp<SparseField, double>)));

#endif

#if DO_BASIC_FILE_TESTS

  test->add(BOOST_TEST_CASE((&testField3DFile<DenseField, half, true>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<SparseField, half, true>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<DenseField, float, true>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<SparseField, float, true>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<DenseField, double, true>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<SparseField, double, true>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<DenseField, half, false>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<SparseField, half, false>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<DenseField, float, false>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<SparseField, float, false>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<DenseField, double, false>)));
  test->add(BOOST_TEST_CASE((&testField3DFile<SparseField, double, false>)));
  test->add(BOOST_TEST_CASE(&testUnnamedFieldError));
  test->add(BOOST_TEST_CASE(&testBasicFileOpen));

#endif

#if DO_ADVANCED_FILE_TESTS

  test->add(BOOST_TEST_CASE((&testEmptySparseFieldToDisk<half>)));
  test->add(BOOST_TEST_CASE((&testEmptySparseFieldToDisk<float>)));
  test->add(BOOST_TEST_CASE((&testEmptySparseFieldToDisk<double>)));

  test->add(BOOST_TEST_CASE((&testEmptyMACFieldToDisk<half>)));
  test->add(BOOST_TEST_CASE((&testEmptyMACFieldToDisk<float>)));
  test->add(BOOST_TEST_CASE((&testEmptyMACFieldToDisk<double>)));

  test->add(BOOST_TEST_CASE((&testLayerFetching<DenseField, half>)));
  test->add(BOOST_TEST_CASE((&testLayerFetching<SparseField, half>)));
  test->add(BOOST_TEST_CASE((&testLayerFetching<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testLayerFetching<SparseField, float>)));
  test->add(BOOST_TEST_CASE((&testLayerFetching<DenseField, double>)));
  test->add(BOOST_TEST_CASE((&testLayerFetching<SparseField, double>)));

  test->add(BOOST_TEST_CASE((&testReadAsDifferentType<DenseField, half>)));
  test->add(BOOST_TEST_CASE((&testReadAsDifferentType<SparseField, half>)));
  test->add(BOOST_TEST_CASE((&testReadAsDifferentType<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testReadAsDifferentType<SparseField, float>)));
  test->add(BOOST_TEST_CASE((&testReadAsDifferentType<DenseField, double>)));
  test->add(BOOST_TEST_CASE((&testReadAsDifferentType<SparseField, double>)));

  test->add(BOOST_TEST_CASE((&testDuplicatePartitions<DenseField, half>)));
  test->add(BOOST_TEST_CASE((&testDuplicatePartitions<SparseField, half>)));
  test->add(BOOST_TEST_CASE((&testDuplicatePartitions<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testDuplicatePartitions<SparseField, float>)));
  test->add(BOOST_TEST_CASE((&testDuplicatePartitions<DenseField, double>)));
  test->add(BOOST_TEST_CASE((&testDuplicatePartitions<SparseField, double>)));

  test->add(BOOST_TEST_CASE((&testTimeVaryingMatrixFieldMapping)));
  test->add(BOOST_TEST_CASE((&testTimeVaryingFrustumFieldMapping)));

#endif

#if DO_SPARSE_BLOCK_TESTS
  test->add(BOOST_TEST_CASE((&testSparseFieldBlockAccess<half>)));
  test->add(BOOST_TEST_CASE((&testSparseFieldBlockAccess<float>)));
  test->add(BOOST_TEST_CASE((&testSparseFieldBlockAccess<double>)));
#endif

#if DO_MAC_TESTS
  test->add(BOOST_TEST_CASE((&testMACField<float>)));
#endif


#if DO_THREAD_TESTS
  test->add(BOOST_TEST_CASE((&testThreadField<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testThreadField<SparseField, float>)));
#endif 

#if DO_MIP_TESTS
  test->add(BOOST_TEST_CASE((&testMIPField<MIPDenseField, DenseField, float, true>)));
  test->add(BOOST_TEST_CASE((&testMIPField<MIPDenseField, DenseField, float, false>)));
  test->add(BOOST_TEST_CASE((&testMIPFieldColor<MIPDenseField, DenseField, V3f>)));
  test->add(BOOST_TEST_CASE((&testMIPField<MIPSparseField, SparseField, float, true>)));
  test->add(BOOST_TEST_CASE((&testMIPField<MIPSparseField, SparseField, float, false>)));
  test->add(BOOST_TEST_CASE((&testMIPFieldColor<MIPSparseField, SparseField, V3f>)));
  test->add(BOOST_TEST_CASE((&testMIPMake<DenseField, float>)));
  test->add(BOOST_TEST_CASE((&testMIPMake<SparseField, float>)));
#endif

  return test;
}