File: gwy3dview.c

package info (click to toggle)
gwyddion 2.57-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 48,860 kB
  • sloc: ansic: 405,916; python: 7,867; sh: 5,241; makefile: 4,507; xml: 3,786; cpp: 2,572; pascal: 418; perl: 154; ruby: 130
file content (3578 lines) | stat: -rw-r--r-- 114,377 bytes parent folder | download
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
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
/*
 *  $Id: gwy3dview.c 22477 2019-09-13 07:26:50Z yeti-dn $
 *  Copyright (C) 2003-2019 David Necas (Yeti), Petr Klapetek.
 *  E-mail: yeti@gwyddion.net, klapetek@gwyddion.net.
 *  Copyright (C) 2004 Martin Siler.
 *  E-mail: silerm@physics.muni.cz.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include <string.h>
#include <stdlib.h>

#include <gdk/gdkkeysyms.h>
#include <gdk/gdkevents.h>
#include <gtk/gtkmain.h>
#include <gtk/gtksignal.h>
#include <pango/pangocairo.h>

#ifdef HAVE_GTKGLEXT
#include <gtk/gtkgl.h>
#endif

#ifdef G_OS_WIN32
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#endif

#ifdef HAVE_GTKGLEXT
#ifdef GDK_WINDOWING_QUARTZ
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#ifdef HAVE_GL_GLEXT_H
#include <GL/glext.h>
#endif
#endif

#ifndef GL_BGRA
#ifdef GL_BGRA_EXT
#define GL_BGRA GL_BGRA_EXT
#else
#error FIXME: GL_BGRA is not available, should work around it.
#endif
#endif
#endif

#include <libgwyddion/gwymacros.h>
#include <libgwyddion/gwymath.h>
#include <libgwyddion/gwydebugobjects.h>
#include <libprocess/stats.h>
#include <libgwydgets/gwydgets.h>
#include <libdraw/gwypixfield.h>
#include <glib/gprintf.h>

#define GWY_3D_VIEW_GET_PRIVATE(o) ((Gwy3DViewPrivate*) o->priv)

#define DEG_2_RAD (G_PI/180.0)
#define RAD_2_DEG (180.0/G_PI)

#define BITS_PER_SAMPLE 8

#define  GWY_3D_ORTHO_CORRECTION  2.0
#define  GWY_3D_Z_DEFORMATION     0.01
#define  GWY_3D_Z_TRANSFORMATION  0.5
#define  GWY_3D_Z_DISPLACEMENT   -0.2
#define  GWY_3D_TICK_LENGTH 10

#define connect_swapped_after(obj, signal, cb, data) \
    g_signal_connect_object(obj, signal, G_CALLBACK(cb), data, \
                            G_CONNECT_SWAPPED | G_CONNECT_AFTER)

#ifdef HAVE_GTKGLEXT
enum {
    GWY_3D_VIEW_DEFAULT_SIZE_X = 260,
    GWY_3D_VIEW_DEFAULT_SIZE_Y = 260
};

enum {
    GWY_3D_SHAPE = 0,
    GWY_3D_N_LISTS
};

/* Changed components */
enum {
    GWY_3D_GRADIENT   = 1 << 0,
    GWY_3D_MATERIAL   = 1 << 1,
    GWY_3D_DATA_FIELD = 1 << 2,
    GWY_3D_MASK       = 0x07
};

enum {
    GWY_3D_JUST_LEFT_EDGE = 0,
    GWY_3D_JUST_TOP_EDGE = 0,
    GWY_3D_JUST_CENTER = 1,
    GWY_3D_JUST_RIGHT_EDGE = 2,
    GWY_3D_JUST_BOTTOM_EDGE = 2,
};

enum {
    PROP_0,
    PROP_MOVEMENT,
    PROP_REDUCED_SIZE,
    PROP_DATA_KEY,
    PROP_SETUP_PREFIX,
    PROP_GRADIENT_KEY,
    PROP_MATERIAL_KEY,
    PROP_MASK_KEY,
    PROP_LAST
};

typedef struct {
    GLfloat x, y, z;
} Gwy3DVector;

/**
 * Gwy3DListPool:
 * @base: The first list id in the pool.
 * @size: List id range length.
 * @pool: Bits correspond to GL lists, 0 means free, 1 assigned.
 *
 * GL list pool.
 **/
typedef struct {
    guint base;
    guint size;
    guint64 pool;
} Gwy3DListPool;

typedef struct {
    GwyDataField *mask_field;
    GQuark mask_key;
    gulong mask_id;
    gulong mask_item_id;
    gboolean need_update_list;
    gboolean button;
    gboolean has_moved;
} Gwy3DViewPrivate;

static void     gwy_3d_view_destroy              (GtkObject *object);
static void     gwy_3d_view_finalize             (GObject *object);
static void     gwy_3d_view_set_property         (GObject *object,
                                                  guint prop_id,
                                                  const GValue *value,
                                                  GParamSpec *pspec);
static void     gwy_3d_view_get_property         (GObject*object,
                                                  guint prop_id,
                                                  GValue *value,
                                                  GParamSpec *pspec);
static void     gwy_3d_view_realize              (GtkWidget *widget);
static void     gwy_3d_view_unrealize            (GtkWidget *widget);
static void     gwy_3d_view_container_connect    (Gwy3DView *gwy3dview,
                                                  const gchar *data_key_string,
                                                  gulong *id,
                                                  GCallback callback);
static void     gwy_3d_view_data_item_changed    (Gwy3DView *gwy3dview);
static void     gwy_3d_view_data_field_connect   (Gwy3DView *gwy3dview);
static void     gwy_3d_view_data_field_disconnect(Gwy3DView *gwy3dview);
static void     gwy_3d_view_data_field_changed   (Gwy3DView *gwy3dview);
static void     gwy_3d_view_setup_item_changed   (Gwy3DView *gwy3dview);
static void     gwy_3d_view_ensure_setup         (Gwy3DView *gwy3dview);
static void     gwy_3d_view_setup_connect        (Gwy3DView *gwy3dview);
static void     gwy_3d_view_setup_disconnect     (Gwy3DView *gwy3dview);
static void     gwy_3d_view_setup_changed        (Gwy3DView *gwy3dview,
                                                  GParamSpec *pspec);
static void     gwy_3d_view_gradient_item_changed(Gwy3DView *gwy3dview);
static void     gwy_3d_view_gradient_connect     (Gwy3DView *gwy3dview);
static void     gwy_3d_view_gradient_disconnect  (Gwy3DView *gwy3dview);
static void     gwy_3d_view_gradient_changed     (Gwy3DView *gwy3dview);
static void     gwy_3d_view_material_item_changed(Gwy3DView *gwy3dview);
static void     gwy_3d_view_material_connect     (Gwy3DView *gwy3dview);
static void     gwy_3d_view_material_disconnect  (Gwy3DView *gwy3dview);
static void     gwy_3d_view_material_changed     (Gwy3DView *gwy3dview);
static void     gwy_3d_view_update_lists         (Gwy3DView *gwy3dview);
static void     gwy_3d_view_realize_gl           (Gwy3DView *gwy3dview);
static void     gwy_3d_view_size_request         (GtkWidget *widget,
                                                  GtkRequisition *requisition);
static void     gwy_3d_view_size_allocate        (GtkWidget *widget,
                                                  GtkAllocation *allocation);
static gboolean gwy_3d_view_expose               (GtkWidget *widget,
                                                  GdkEventExpose *event);
static gboolean gwy_3d_view_configure            (GtkWidget *widget,
                                                  GdkEventConfigure *event);
static void     gwy_3d_view_send_configure       (Gwy3DView *gwy3dview);
static gboolean gwy_3d_view_button_press         (GtkWidget *widget,
                                                  GdkEventButton *event);
static gboolean gwy_3d_view_button_release       (GtkWidget *widget,
                                                  GdkEventButton *event);
static gboolean gwy_3d_view_scroll               (GtkWidget *widget,
                                                  GdkEventScroll *event);
static void     gwy_3d_calculate_pixel_sizes     (GwyDataField *dfield,
                                                  GLfloat *dx,
                                                  GLfloat *dy);
static Gwy3DVector* gwy_3d_make_normals          (GwyDataField *dfield,
                                                  Gwy3DVector *normals);
static gboolean gwy_3d_view_motion_notify        (GtkWidget *widget,
                                                  GdkEventMotion *event);
static void     gwy_3d_make_list                 (Gwy3DView *gwy3D,
                                                  GwyDataField *dfield,
                                                  GwyDataField *mask,
                                                  GwyPixmapLayer **ovlays);
static void     gwy_3d_draw_axes                 (Gwy3DView *gwy3dview,
                                                  gint width,
                                                  gint height);
static void     gwy_3d_draw_light_position       (Gwy3DView *gwy3dview);
static void     gwy_3d_set_projection            (Gwy3DView *gwy3dview,
                                                  GLfloat aspect);
static void     gwy_3d_view_update_labels        (Gwy3DView *gwy3dview);
static void     gwy_3d_view_label_changed        (Gwy3DView *gwy3dview);
static void     gwy_3d_view_queue_draw           (Gwy3DView *gwy3dview);
static void     gwy_3d_texture_text              (Gwy3DView     *gwy3dview,
                                                  Gwy3DViewLabel id,
                                                  GLfloat        raster_x,
                                                  GLfloat        raster_y,
                                                  GLfloat        raster_z,
                                                  GLfloat        rot,
                                                  guint          size,
                                                  gint           hjustify,
                                                  gint           vjustify);
static gint     gwy_3d_draw_fmscaletex           (Gwy3DView *view);
static void     gwy_3d_view_class_make_list_pool (Gwy3DListPool *pool);
static void     gwy_3d_view_assign_lists         (Gwy3DView *gwy3dview);
static void     gwy_3d_view_release_lists        (Gwy3DView *gwy3dview);
static void     gwy_3d_view_mask_item_changed    (Gwy3DView *gwy3dview);
static void     gwy_3d_view_mask_field_connect   (Gwy3DView *gwy3dview);
static void     gwy_3d_view_mask_field_disconnect(Gwy3DView *gwy3dview);
static void     gwy_3d_view_mask_field_changed   (Gwy3DView *gwy3dview);

/* Must match Gwy3DViewLabel */
static const struct {
    const gchar *key;
    const gchar *default_text;
}
labels[GWY_3D_VIEW_NLABELS] = {
    { "x",   "x: $x", },
    { "y",   "y: $y", },
    { "min", "$min",  },
    { "max", "$max",  },
};
#endif /* HAVE_GTKGLEXT */

static gboolean ugly_hack_globally_disable_axis_drawing = FALSE;

G_DEFINE_TYPE(Gwy3DView, gwy_3d_view, GTK_TYPE_WIDGET)

#ifdef HAVE_GTKGLEXT
static void
gwy_3d_view_class_init(Gwy3DViewClass *klass)
{
    GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
    GtkObjectClass *object_class;
    GtkWidgetClass *widget_class;

    gwy_debug(" ");
    g_type_class_add_private(klass, sizeof(Gwy3DViewPrivate));
    object_class = (GtkObjectClass*)klass;
    widget_class = (GtkWidgetClass*)klass;

    gobject_class->finalize = gwy_3d_view_finalize;
    gobject_class->set_property = gwy_3d_view_set_property;
    gobject_class->get_property = gwy_3d_view_get_property;

    object_class->destroy = gwy_3d_view_destroy;

    widget_class->realize = gwy_3d_view_realize;
    widget_class->unrealize = gwy_3d_view_unrealize;
    widget_class->expose_event = gwy_3d_view_expose;
    widget_class->configure_event = gwy_3d_view_configure;
    widget_class->size_request = gwy_3d_view_size_request;
    widget_class->size_allocate = gwy_3d_view_size_allocate;
    widget_class->button_press_event = gwy_3d_view_button_press;
    widget_class->button_release_event = gwy_3d_view_button_release;
    widget_class->scroll_event = gwy_3d_view_scroll;
    widget_class->motion_notify_event = gwy_3d_view_motion_notify;

    klass->list_pool = g_new0(Gwy3DListPool, 1);

    /**
     * Gwy3DView:movement-type:
     *
     * The :movement-type property represents type of action on user pointer
     * drag.
     **/
    g_object_class_install_property
        (gobject_class,
         PROP_MOVEMENT,
         g_param_spec_enum("movement-type",
                           "Movement type",
                           "What quantity is changed when uses moves pointer",
                           GWY_TYPE_3D_MOVEMENT, GWY_3D_MOVEMENT_NONE,
                           G_PARAM_READWRITE));

    /**
     * Gwy3DView:reduced-size:
     *
     * The :reduced-size is the size of downsampled data in quick preview.
     *
     * Note since 2.44 the reduced size has no influence because the 3D view
     * does not downsample anything.
     **/
    g_object_class_install_property
        (gobject_class,
         PROP_REDUCED_SIZE,
         g_param_spec_uint("reduced-size",
                           "Reduced size",
                           "The size of downsampled data in quick view",
                           2, G_MAXINT, 96,
                           G_PARAM_READWRITE));

    g_object_class_install_property
        (gobject_class,
         PROP_DATA_KEY,
         g_param_spec_string("data-key",
                             "Data key",
                             "Key identifying data field in container",
                             NULL, G_PARAM_READWRITE));

    g_object_class_install_property
        (gobject_class,
         PROP_SETUP_PREFIX,
         g_param_spec_string("setup-prefix",
                             "Setup prefix",
                             "Key prefix identifying view settings and labels "
                             "in container",
                             NULL, G_PARAM_READWRITE));

    g_object_class_install_property
        (gobject_class,
         PROP_GRADIENT_KEY,
         g_param_spec_string("gradient-key",
                             "Gradient key",
                             "Key identifying color gradient in container",
                             NULL, G_PARAM_READWRITE));

    g_object_class_install_property
        (gobject_class,
         PROP_MATERIAL_KEY,
         g_param_spec_string("material-key",
                             "Material key",
                             "Key identifying GL material in container",
                             NULL, G_PARAM_READWRITE));

    g_object_class_install_property
        (gobject_class,
         PROP_MASK_KEY,
         g_param_spec_string("mask-key",
                             "Mask key",
                             "Key identifying mask field in container",
                             NULL, G_PARAM_READWRITE));
}

static void
gwy_3d_view_init(Gwy3DView *gwy3dview)
{
    gwy3dview->view_scale_max = 8.0;
    gwy3dview->view_scale_min = 0.5;
    gwy3dview->movement       = GWY_3D_MOVEMENT_NONE;
    gwy3dview->reduced_size   = 96;
    gwy3dview->ovlays         = NULL;
    gwy3dview->priv = G_TYPE_INSTANCE_GET_PRIVATE(gwy3dview,
                                                   GWY_TYPE_3D_VIEW,
                                                   Gwy3DViewPrivate);

    gwy3dview->variables = g_hash_table_new_full(g_str_hash, g_str_equal,
                                                 NULL, g_free);

    gwy3dview->labels = g_new0(Gwy3DLabel*, GWY_3D_VIEW_NLABELS);
    gwy3dview->label_ids = g_new0(gulong, GWY_3D_VIEW_NLABELS);
}

static void
gwy_3d_view_destroy(GtkObject *object)
{
    Gwy3DView *gwy3dview;
    Gwy3DViewPrivate *priv;
    guint i;

    gwy3dview = GWY_3D_VIEW(object);
    priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data, gwy3dview->data_item_id);
    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data,
                                  priv->mask_item_id);
    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data, gwy3dview->gradient_item_id);
    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data, gwy3dview->material_item_id);

    gwy_3d_view_setup_disconnect(gwy3dview);
    gwy_3d_view_data_field_disconnect(gwy3dview);
    gwy_3d_view_mask_field_disconnect(gwy3dview);
    gwy_3d_view_gradient_disconnect(gwy3dview);
    gwy_3d_view_material_disconnect(gwy3dview);

    if (gwy3dview->shape_list_base > 0)
        gwy_3d_view_release_lists(gwy3dview);

    GWY_OBJECT_UNREF(gwy3dview->data_field);
    GWY_OBJECT_UNREF(priv->mask_field);
    GWY_OBJECT_UNREF(gwy3dview->data);

    /* free overlays and disconnect them */
    if (gwy3dview->ovlays) {
        for (i = 0; i < gwy3dview->novlays; i++) {
            GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->ovlays[i],
                                          gwy3dview->ovlay_updated_id[i]);
            gwy_data_view_layer_unplugged(GWY_DATA_VIEW_LAYER(gwy3dview->ovlays[i]));
            GWY_OBJECT_UNREF(gwy3dview->ovlays[i]);
        }
        g_free(gwy3dview->ovlays);
        gwy3dview->ovlays = NULL;
    }

    GTK_OBJECT_CLASS(gwy_3d_view_parent_class)->destroy(object);
}

static void
gwy_3d_view_finalize(GObject *object)
{
    Gwy3DView *gwy3dview;

    gwy3dview = GWY_3D_VIEW(object);

    g_free(gwy3dview->labels);
    g_free(gwy3dview->label_ids);

    g_hash_table_destroy(gwy3dview->variables);

    G_OBJECT_CLASS(gwy_3d_view_parent_class)->finalize(object);
}

static void
gwy_3d_view_set_property(GObject *object,
                         guint prop_id,
                         const GValue *value,
                         GParamSpec *pspec)
{
    Gwy3DView *view = GWY_3D_VIEW(object);

    switch (prop_id) {
        case PROP_MOVEMENT:
        gwy_3d_view_set_movement_type(view, g_value_get_enum(value));
        break;

        case PROP_REDUCED_SIZE:
        gwy_3d_view_set_reduced_size(view, g_value_get_uint(value));
        break;

        case PROP_DATA_KEY:
        gwy_3d_view_set_data_key(view, g_value_get_string(value));
        break;

        case PROP_SETUP_PREFIX:
        gwy_3d_view_set_setup_prefix(view, g_value_get_string(value));
        break;

        case PROP_GRADIENT_KEY:
        gwy_3d_view_set_gradient_key(view, g_value_get_string(value));
        break;

        case PROP_MATERIAL_KEY:
        gwy_3d_view_set_material_key(view, g_value_get_string(value));
        break;

        case PROP_MASK_KEY:
        gwy_3d_view_set_mask_key(view, g_value_get_string(value));
        break;

        default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}

static void
gwy_3d_view_get_property(GObject*object,
                         guint prop_id,
                         GValue *value,
                         GParamSpec *pspec)
{
    Gwy3DView *view = GWY_3D_VIEW(object);

    switch (prop_id) {
        case PROP_MOVEMENT:
        g_value_set_enum(value, view->movement);
        break;

        case PROP_REDUCED_SIZE:
        g_value_set_uint(value, view->reduced_size);
        break;

        case PROP_DATA_KEY:
        g_value_set_static_string(value, g_quark_to_string(view->data_key));
        break;

        case PROP_SETUP_PREFIX:
        g_value_set_static_string(value, g_quark_to_string(view->setup_key));
        break;

        case PROP_GRADIENT_KEY:
        g_value_set_static_string(value, g_quark_to_string(view->gradient_key));
        break;

        case PROP_MATERIAL_KEY:
        g_value_set_static_string(value, g_quark_to_string(view->material_key));
        break;

        case PROP_MASK_KEY:
          g_value_set_static_string(value,
                   g_quark_to_string(GWY_3D_VIEW_GET_PRIVATE(view)->mask_key));
        break;

        default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}

static void
gwy_3d_view_unrealize(GtkWidget *widget)
{
    Gwy3DView *gwy3dview;

    gwy3dview = GWY_3D_VIEW(widget);

    gwy_3d_view_release_lists(gwy3dview);

    if (GTK_WIDGET_CLASS(gwy_3d_view_parent_class)->unrealize)
        GTK_WIDGET_CLASS(gwy_3d_view_parent_class)->unrealize(widget);
}

/**
 * gwy_3d_view_new:
 * @data: A #GwyContainer containing the data to display.
 *
 * Creates a new threedimensional OpenGL display of @data.
 *
 * The widget is initialized from container @data.
 *
 * Returns: The new OpenGL 3D widget as a #GtkWidget.
 **/
GtkWidget*
gwy_3d_view_new(GwyContainer *data)
{
    GdkGLConfig *glconfig;
    GtkWidget *widget;
    Gwy3DView *gwy3dview;

    g_return_val_if_fail(GWY_IS_CONTAINER(data), NULL);
    glconfig = gwy_widgets_get_gl_config();
    g_return_val_if_fail(glconfig, NULL);

    g_object_ref(data);

    gwy3dview = (Gwy3DView*)g_object_new(GWY_TYPE_3D_VIEW, NULL);
    widget = GTK_WIDGET(gwy3dview);

    gwy3dview->data = data;

    if (!gtk_widget_set_gl_capability(GTK_WIDGET(gwy3dview),
                                      glconfig,
                                      NULL,
                                      TRUE,
                                      GDK_GL_RGBA_TYPE))
        g_critical("Cannot set GL capability on widget");

    return widget;
}

static GwySIValueFormat*
gwy_3d_view_update_label(Gwy3DView *gwy3dview,
                         const gchar *key,
                         gdouble value,
                         gdouble maximum,
                         gdouble step,
                         gboolean is_z,
                         GwySIValueFormat *vf)
{
    GwySIUnit *unit;
    gchar buffer[80], *s;

    if (is_z)
        unit = gwy_data_field_get_si_unit_z(gwy3dview->data_field);
    else
        unit = gwy_data_field_get_si_unit_xy(gwy3dview->data_field);

    vf = gwy_si_unit_get_format_with_resolution(unit,
                                                GWY_SI_UNIT_FORMAT_VFMARKUP,
                                                maximum, step, vf);
    g_snprintf(buffer, sizeof(buffer), "%.*f %s",
               vf->precision, value/vf->magnitude, vf->units);
    s = g_hash_table_lookup(gwy3dview->variables, key);
    if (!s || !gwy_strequal(s, buffer))
        g_hash_table_insert(gwy3dview->variables, (gpointer)key,
                            g_strdup(buffer));

    return vf;
}

static void
gwy_3d_view_update_labels(Gwy3DView *gwy3dview)
{
    GwySIValueFormat *format;
    gdouble xreal, yreal, data_min, data_max, range, maximum;

    if (!gwy3dview->data_field)
        return;

    xreal = gwy_data_field_get_xreal(gwy3dview->data_field);
    yreal = gwy_data_field_get_yreal(gwy3dview->data_field);
    gwy_data_field_get_min_max(gwy3dview->data_field, &data_min, &data_max);
    range = fabs(data_max - data_min);
    maximum = MAX(fabs(data_min), fabs(data_max));

    format = NULL;
    format = gwy_3d_view_update_label(gwy3dview, "x",
                                      xreal, xreal, xreal/12.0,
                                      FALSE, format);
    format = gwy_3d_view_update_label(gwy3dview, "y",
                                      yreal, yreal, yreal/12.0,
                                      FALSE, format);
    format = gwy_3d_view_update_label(gwy3dview, "max",
                                      data_max, maximum, range/12.0,
                                      TRUE, format);
    format = gwy_3d_view_update_label(gwy3dview, "min",
                                      data_min, maximum, range/12.0,
                                      TRUE, format);
    gwy_si_unit_value_format_free(format);
}

static void
gwy_3d_view_container_connect(Gwy3DView *gwy3dview,
                              const gchar *data_key_string,
                              gulong *id,
                              GCallback callback)
{
    gchar *detailed_signal;

    if (!data_key_string || !gwy3dview->data) {
        gwy_debug("%p zeroing id for <%s>", gwy3dview, data_key_string);
        *id = 0;
        return;
    }
    gwy_debug("%p connecting to <%s>", gwy3dview, data_key_string);
    detailed_signal = g_newa(gchar, sizeof("item-changed::")
                                    + strlen(data_key_string));
    g_stpcpy(g_stpcpy(detailed_signal, "item-changed::"), data_key_string);
    *id = connect_swapped_after(gwy3dview->data, detailed_signal,
                                callback, gwy3dview);
}

/**
 * gwy_3d_view_set_data_key:
 * @gwy3dview: A 3D data view widget.
 * @key: Container string key identifying the data field to visualize.
 *
 * Sets the container key identifying the data field to visualize in a 3D view.
 **/
void
gwy_3d_view_set_data_key(Gwy3DView *gwy3dview,
                         const gchar *key)
{
    GQuark quark;

    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    gwy_debug("%p <%s>", gwy3dview, key);

    quark = key ? g_quark_from_string(key) : 0;
    if (gwy3dview->data_key == quark)
        return;

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data, gwy3dview->data_item_id);
    gwy_3d_view_data_field_disconnect(gwy3dview);
    gwy3dview->data_key = quark;
    gwy_3d_view_data_field_connect(gwy3dview);
    gwy_3d_view_container_connect(gwy3dview, g_quark_to_string(quark),
                                  &gwy3dview->data_item_id,
                                  G_CALLBACK(gwy_3d_view_data_item_changed));
    g_object_notify(G_OBJECT(gwy3dview), "data-key");
    gwy_3d_view_data_field_changed(gwy3dview);
}

/**
 * gwy_3d_view_get_data_key:
 * @gwy3dview: A 3D data view widget.
 *
 * Gets the container key identifying the data field to visualize in a 3D view.
 *
 * Returns: The string key, or %NULL if it isn't set.
 **/
const gchar*
gwy_3d_view_get_data_key(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    return g_quark_to_string(gwy3dview->data_key);
}

static void
gwy_3d_view_data_item_changed(Gwy3DView *gwy3dview)
{
    gwy_3d_view_data_field_disconnect(gwy3dview);
    gwy_3d_view_data_field_connect(gwy3dview);
    gwy_3d_view_data_field_changed(gwy3dview);
}

static void
gwy_3d_view_data_field_connect(Gwy3DView *gwy3dview)
{
    g_return_if_fail(!gwy3dview->data_field);
    if (!gwy3dview->data_key)
        return;

    if (!gwy_container_gis_object(gwy3dview->data, gwy3dview->data_key,
                                  &gwy3dview->data_field))
        return;

    g_object_ref(gwy3dview->data_field);
    gwy3dview->data_id
        = g_signal_connect_swapped(gwy3dview->data_field,
                                   "data-changed",
                                   G_CALLBACK(gwy_3d_view_data_field_changed),
                                   gwy3dview);
}

static void
gwy_3d_view_data_field_disconnect(Gwy3DView *gwy3dview)
{
    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data_field, gwy3dview->data_id);
    GWY_OBJECT_UNREF(gwy3dview->data_field);
}

static void
gwy_3d_view_data_field_changed(Gwy3DView *gwy3dview)
{
    gwy_debug("");
    gwy3dview->changed |= GWY_3D_DATA_FIELD;
    gwy_3d_view_update_labels(gwy3dview);
    gwy_3d_view_update_lists(gwy3dview);
}

/**
 * gwy_3d_view_set_ovlay:
 * @gwy3dview: A 3D data view widget.
 * @ovlays: List of @novlays pixmap layers usable as overlays.
 * @novlays: Number of items in @ovlays.
 *
 * Sets overlays for a 3D view.
 *
 * Since: 2.26
 **/
void
gwy_3d_view_set_ovlay(Gwy3DView *gwy3dview,
                      GwyPixmapLayer** ovlays,
                      guint novlays)
{
    gint i = 0;

    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    gwy_debug("");

    if (gwy3dview->ovlays) {
        for (i = 0; i < gwy3dview->novlays; i++) {
            gwy_data_view_layer_unplugged(GWY_DATA_VIEW_LAYER(gwy3dview->ovlays[i]));
            GWY_OBJECT_UNREF(gwy3dview->ovlays[i]);
        }
        g_free(gwy3dview->ovlays);
    }

    gwy3dview->ovlays = g_new(GwyPixmapLayer*, novlays);
    gwy3dview->ovlay_updated_id = g_new(guint, novlays);
    gwy3dview->novlays = novlays;
    for (i = 0; i < novlays; i++) {
        gwy3dview->ovlays[i] = ovlays[i];
        g_object_ref(gwy3dview->ovlays[i]);
        gtk_object_sink(GTK_OBJECT(gwy3dview->ovlays[i]));
        gwy3dview->ovlay_updated_id[i]
            = g_signal_connect_swapped(gwy3dview->ovlays[i],
                                       "updated",
                                       G_CALLBACK(gwy_3d_view_queue_draw),
                                       gwy3dview);
    }
    gwy_3d_view_update_lists(gwy3dview);
}

/**
 * gwy_3d_view_get_setup_prefix:
 * @gwy3dview: A 3D data view widget.
 *
 * Gets prefix identifying 3D view setup in the container.
 *
 * Returns: The setup key prefix.
 **/
const gchar*
gwy_3d_view_get_setup_prefix(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    return g_quark_to_string(gwy3dview->setup_key);
}

/**
 * gwy_3d_view_set_setup_prefix:
 * @gwy3dview: A 3D data view widget.
 * @key: Container string prefix for keys identifying the view setup
 *       parameters.  The #Gwy3DSetup is stored at key
 *       <literal>"/setup"</literal> under this prefix.  Label objects are
 *       also stored under this prefix.
 *
 * Sets the prefix of 3D view parameters in the container.
 **/
void
gwy_3d_view_set_setup_prefix(Gwy3DView *gwy3dview,
                             const gchar *key)
{
    GQuark quark;

    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    gwy_debug("%p <%s>", gwy3dview, key);

    quark = key ? g_quark_from_string(key) : 0;
    if (gwy3dview->setup_key == quark)
        return;

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data, gwy3dview->setup_item_id);
    gwy_3d_view_setup_disconnect(gwy3dview);
    gwy3dview->setup_key = quark;
    gwy_3d_view_ensure_setup(gwy3dview);
    gwy_3d_view_setup_connect(gwy3dview);
    gwy_3d_view_container_connect(gwy3dview, g_quark_to_string(quark),
                                  &gwy3dview->setup_item_id,
                                  G_CALLBACK(gwy_3d_view_setup_item_changed));

    g_object_notify(G_OBJECT(gwy3dview), "setup-prefix");
    /* TODO: must not call with NULL or handle it as `all' */
    gwy_3d_view_setup_changed(gwy3dview, NULL);
}

static void
gwy_3d_view_ensure_setup(Gwy3DView *gwy3dview)
{
    guint i, len;
    GString *key;
    Gwy3DSetup *setup;
    Gwy3DLabel *label;

    if (!gwy3dview->setup_key)
        return;

    key = g_string_new(g_quark_to_string(gwy3dview->setup_key));
    g_string_append_c(key, GWY_CONTAINER_PATHSEP);
    len = key->len;

    g_string_append(key, "setup");
    if (!gwy_container_gis_object_by_name(gwy3dview->data, key->str,
                                          &setup)) {
        setup = gwy_3d_setup_new();
        gwy_container_set_object_by_name(gwy3dview->data, key->str, setup);
        g_object_unref(setup);
    }

    for (i = 0; i < GWY_3D_VIEW_NLABELS; i++) {
        g_string_truncate(key, len);
        g_string_append(key, labels[i].key);
        if (gwy_container_gis_object_by_name(gwy3dview->data, key->str, &label))
            continue;

        label = gwy_3d_label_new(labels[i].default_text);
        gwy_container_set_object_by_name(gwy3dview->data, key->str, label);
        g_object_unref(label);
    }
    g_string_free(key, TRUE);
}

static void
gwy_3d_view_setup_item_changed(Gwy3DView *gwy3dview)
{
    gwy_3d_view_setup_disconnect(gwy3dview);
    gwy_3d_view_setup_connect(gwy3dview);
    gwy_3d_view_setup_changed(gwy3dview, NULL);
}

/* Here we assert setup and labels exist as they were instantiated by
 * gwy_3d_view_ensure_setup() (if not present). */
static void
gwy_3d_view_setup_connect(Gwy3DView *gwy3dview)
{
    guint i, len;
    GString *key;

    g_return_if_fail(!gwy3dview->setup);
    if (!gwy3dview->setup_key)
        return;

    key = g_string_new(g_quark_to_string(gwy3dview->setup_key));
    g_string_append_c(key, GWY_CONTAINER_PATHSEP);
    len = key->len;

    g_string_append(key, "setup");
    gwy_container_gis_object_by_name(gwy3dview->data, key->str,
                                     &gwy3dview->setup);
    g_assert(gwy3dview->setup);
    g_object_ref(gwy3dview->setup);
    gwy3dview->setup_id
        = g_signal_connect_swapped(gwy3dview->setup, "notify",
                                   G_CALLBACK(gwy_3d_view_setup_changed),
                                   gwy3dview);

    for (i = 0; i < GWY_3D_VIEW_NLABELS; i++) {
        if (gwy3dview->labels[i]) {
            g_critical("Label %u already set!", i);
            continue;
        }
        g_string_truncate(key, len);
        g_string_append(key, labels[i].key);
        gwy_container_gis_object_by_name(gwy3dview->data, key->str,
                                         &gwy3dview->labels[i]);
        g_assert(gwy3dview->labels[i]);
        g_object_ref(gwy3dview->labels[i]);
        gwy3dview->label_ids[i]
            = g_signal_connect_swapped(gwy3dview->labels[i], "notify",
                                       G_CALLBACK(gwy_3d_view_label_changed),
                                       gwy3dview);
    }
    g_string_free(key, TRUE);
}

static void
gwy_3d_view_setup_disconnect(Gwy3DView *gwy3dview)
{
    guint i;

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->setup, gwy3dview->setup_id);
    GWY_OBJECT_UNREF(gwy3dview->setup);

    for (i = 0; i < GWY_3D_VIEW_NLABELS; i++) {
        GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->labels[i],
                                      gwy3dview->label_ids[i]);
        GWY_OBJECT_UNREF(gwy3dview->labels[i]);
    }
}

static gboolean
gwy_3d_visualisation_has_light(Gwy3DVisualization visualization)
{
    return (visualization == GWY_3D_VISUALIZATION_LIGHTING
            || visualization == GWY_3D_VISUALIZATION_OVERLAY);
}

static gboolean
gwy_3d_visualisation_has_colormap(Gwy3DVisualization visualization)
{
    return (visualization == GWY_3D_VISUALIZATION_GRADIENT
            || visualization == GWY_3D_VISUALIZATION_OVERLAY
            || visualization == GWY_3D_VISUALIZATION_OVERLAY_NO_LIGHT);
}

static void
gwy_3d_view_setup_changed(Gwy3DView *gwy3dview,
                          GParamSpec *pspec)
{
    Gwy3DSetup *setup = gwy3dview->setup;

    gwy_debug("%p <%s>", gwy3dview, pspec ? pspec->name : "NULL");
    /* TODO: must decide what needs redraw, if anything */
    if (pspec) {
        if (!gwy_3d_visualisation_has_light(setup->visualization)
            && (gwy_strequal(pspec->name, "light-theta")
                || gwy_strequal(pspec->name, "light-phi")))
            return;
        if (!setup->axes_visible
            && gwy_strequal(pspec->name, "labels-visible"))
            return;
        if (gwy_strequal(pspec->name, "visualization")) {
            gwy_3d_view_update_lists(gwy3dview);
            return;
        }
        if (gwy_strequal(pspec->name, "hide-masked")) {
            gwy_3d_view_update_lists(gwy3dview);
            return;
        }
        if (!setup->axes_visible
            && gwy_strequal(pspec->name, "line-width"))
            return;
        if (!setup->fmscale_visible
            && (gwy_strequal(pspec->name, "fmscale-size")
                || gwy_strequal(pspec->name, "fmscale-y-align")
                || gwy_strequal(pspec->name, "fmscale-reserve-space")))
            return;
    }

    gwy_3d_view_queue_draw(gwy3dview);
}

/**
 * gwy_3d_view_get_gradient_key:
 * @gwy3dview: A 3D data view widget.
 *
 * Gets the container key identifying the colour gradient used to visualize
 * data in a 3D view.
 *
 * Returns: The string key, or %NULL if it isn't set.
 **/
const gchar*
gwy_3d_view_get_gradient_key(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    return g_quark_to_string(gwy3dview->gradient_key);
}

/**
 * gwy_3d_view_set_gradient_key:
 * @gwy3dview: A 3D data view widget.
 * @key: Container string key identifying the color gradient to use for
 *       gradient visualization mode.
 *
 * Sets the container key identifying the color gradient to use to visualize
 * data in a 3D view.
 **/
void
gwy_3d_view_set_gradient_key(Gwy3DView *gwy3dview,
                             const gchar *key)
{
    GQuark quark;

    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    gwy_debug("%p <%s>", gwy3dview, key);

    quark = key ? g_quark_from_string(key) : 0;
    if (gwy3dview->gradient_key == quark)
        return;

    if (gwy3dview->ovlays && gwy3dview->ovlays[0])
        gwy_layer_basic_set_gradient_key(GWY_LAYER_BASIC(gwy3dview->ovlays[0]),
                                         key);

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data, gwy3dview->gradient_item_id);
    gwy_3d_view_gradient_disconnect(gwy3dview);
    gwy3dview->gradient_key = quark;
    gwy_3d_view_gradient_connect(gwy3dview);
    gwy_3d_view_container_connect
                               (gwy3dview, g_quark_to_string(quark),
                                &gwy3dview->gradient_item_id,
                                G_CALLBACK(gwy_3d_view_gradient_item_changed));
    g_object_notify(G_OBJECT(gwy3dview), "gradient-key");
    gwy_3d_view_gradient_changed(gwy3dview);
}

static void
gwy_3d_view_gradient_item_changed(Gwy3DView *gwy3dview)
{
    gwy_3d_view_gradient_disconnect(gwy3dview);
    gwy_3d_view_gradient_connect(gwy3dview);
    gwy_3d_view_gradient_changed(gwy3dview);
}

static void
gwy_3d_view_gradient_connect(Gwy3DView *gwy3dview)
{
    const guchar *s = NULL;

    g_return_if_fail(!gwy3dview->gradient);
    if (gwy3dview->gradient_key)
        gwy_container_gis_string(gwy3dview->data, gwy3dview->gradient_key, &s);
    gwy3dview->gradient = gwy_gradients_get_gradient(s);
    gwy_resource_use(GWY_RESOURCE(gwy3dview->gradient));
    gwy3dview->gradient_id
        = g_signal_connect_swapped(gwy3dview->gradient, "data-changed",
                                   G_CALLBACK(gwy_3d_view_gradient_changed),
                                   gwy3dview);
}

static void
gwy_3d_view_gradient_disconnect(Gwy3DView *gwy3dview)
{
    if (!gwy3dview->gradient)
        return;

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->gradient, gwy3dview->gradient_id);
    gwy_resource_release(GWY_RESOURCE(gwy3dview->gradient));
    gwy3dview->gradient = NULL;
}

static void
gwy_3d_view_gradient_changed(Gwy3DView *gwy3dview)
{
    Gwy3DVisualization visualization = gwy3dview->setup->visualization;
    gwy_debug("");
    gwy3dview->changed |= GWY_3D_GRADIENT;
    if (gwy_3d_visualisation_has_colormap(visualization))
        gwy_3d_view_update_lists(gwy3dview);
}

/**
 * gwy_3d_view_get_material_key:
 * @gwy3dview: A 3D data view widget.
 *
 * Gets the key identifying the GL material used to visualize data in a 3D
 * view.
 *
 * Returns: The string key, or %NULL if it isn't set.
 **/
const gchar*
gwy_3d_view_get_material_key(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    return g_quark_to_string(gwy3dview->material_key);
}

/**
 * gwy_3d_view_set_material_key:
 * @gwy3dview: A 3D data view widget.
 * @key: Container string key identifying the color material to use for
 *       material visualization mode.
 *
 * Sets the container key of the GL material used to visualize data in a 3D
 * view.
 **/
void
gwy_3d_view_set_material_key(Gwy3DView *gwy3dview,
                            const gchar *key)
{
    GQuark quark;

    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    gwy_debug("%p <%s>", gwy3dview, key);

    quark = key ? g_quark_from_string(key) : 0;
    if (gwy3dview->material_key == quark)
        return;

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data, gwy3dview->material_item_id);
    gwy_3d_view_material_disconnect(gwy3dview);
    gwy3dview->material_key = quark;
    gwy_3d_view_material_connect(gwy3dview);
    gwy_3d_view_container_connect
                            (gwy3dview, g_quark_to_string(quark),
                             &gwy3dview->material_item_id,
                             G_CALLBACK(gwy_3d_view_material_item_changed));
    g_object_notify(G_OBJECT(gwy3dview), "material-key");
    gwy_3d_view_material_changed(gwy3dview);
}

static void
gwy_3d_view_material_item_changed(Gwy3DView *gwy3dview)
{
    gwy_3d_view_material_disconnect(gwy3dview);
    gwy_3d_view_material_connect(gwy3dview);
    gwy_3d_view_material_changed(gwy3dview);
}

static void
gwy_3d_view_material_connect(Gwy3DView *gwy3dview)
{
    const guchar *s = NULL;

    g_return_if_fail(!gwy3dview->material);
    if (gwy3dview->material_key)
        gwy_container_gis_string(gwy3dview->data, gwy3dview->material_key, &s);
    gwy3dview->material = gwy_gl_materials_get_gl_material(s);
    gwy_resource_use(GWY_RESOURCE(gwy3dview->material));
    gwy3dview->material_id
        = g_signal_connect_swapped(gwy3dview->material, "data-changed",
                                   G_CALLBACK(gwy_3d_view_material_changed),
                                   gwy3dview);
}

static void
gwy_3d_view_material_disconnect(Gwy3DView *gwy3dview)
{
    if (!gwy3dview->material)
        return;

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->material, gwy3dview->material_id);
    gwy_resource_release(GWY_RESOURCE(gwy3dview->material));
    gwy3dview->material = NULL;
}

static void
gwy_3d_view_material_changed(Gwy3DView *gwy3dview)
{
    gwy_debug("");
    gwy3dview->changed |= GWY_3D_MATERIAL;
    if (gwy3dview->setup->visualization == GWY_3D_VISUALIZATION_LIGHTING)
        gwy_3d_view_update_lists(gwy3dview);
}

static void
gwy_3d_view_update_lists(Gwy3DView *gwy3dview)
{
    Gwy3DViewPrivate *priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);

    if (!GTK_WIDGET_REALIZED(gwy3dview))
        return;

    gwy_debug("");
    priv->need_update_list = TRUE;
    gwy_3d_view_queue_draw(gwy3dview);
}

/**
 * gwy_3d_view_get_movement_type:
 * @gwy3dview: A 3D data view widget.
 *
 * Returns a movement type describing actual type of response on
 * the mouse motion event.
 *
 * Returns: Actual type of response on the mouse motion event
 **/
Gwy3DMovement
gwy_3d_view_get_movement_type(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), GWY_3D_MOVEMENT_NONE);
    return gwy3dview->movement;
}

/**
 * gwy_3d_view_set_movement_type:
 * @gwy3dview: A 3D data view widget.
 * @movement: A new type of response on the mouse motion event.
 *
 * Sets the type of widget response on the mouse motion event.
 **/
void
gwy_3d_view_set_movement_type(Gwy3DView *gwy3dview,
                              Gwy3DMovement movement)
{
    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    g_return_if_fail(movement <= GWY_3D_MOVEMENT_LIGHT);

    gwy3dview->movement = movement;
}

/**
 * gwy_3d_view_set_reduced_size:
 * @gwy3dview: A 3D data view widget.
 * @reduced_size: New reduced data size.
 *
 * Sets the reduced data size of a 3D view.
 *
 * Data larger than reduced size may be shown downsampled during transforms and
 * other changes to speed up the rendering.  Final, full-size rendering is then
 * performed after a timeout.
 *
 * In case of the original data are not square, the @reduced_size is the
 * greater size of the downsampled data, the other dimension is proportional
 * to the original size.
 *
 * Changes in reduced size do not cause immediate redraw when an operation
 * is pending and the view is shown in reduced size.  It only affects future
 * downsampling.
 *
 * Note since 2.44 the reduced size has no influence because the 3D view
 * does not downsample anything.
 **/
void
gwy_3d_view_set_reduced_size(Gwy3DView *gwy3dview,
                             guint reduced_size)
{
    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    g_return_if_fail(reduced_size >= 2);

    if (gwy3dview->reduced_size == reduced_size)
        return;

    gwy3dview->reduced_size = reduced_size;
    g_object_notify(G_OBJECT(gwy3dview), "reduced-size");
}

/**
 * gwy_3d_view_get_reduced_size:
 * @gwy3dview: A 3D data view widget.
 *
 * Returns the reduced data size of a 3D view.
 *
 * See gwy_3d_view_set_reduced_size() for details.
 *
 * Returns: The reduced data size.
 *
 * Note since 2.44 the reduced size has no influence because the 3D view does
 * not downsample anything.
 **/
guint
gwy_3d_view_get_reduced_size(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), 0);
    return gwy3dview->reduced_size;
}

/**
 * gwy_3d_view_get_label:
 * @gwy3dview: A 3D data view widget.
 * @label: Label type to obtain.
 *
 * Gets requested 3D label object of a 3D view.
 *
 * This is a convenience method that can be used instead of fetching the label
 * object from the data container.
 *
 * Returns: The 3D label object representing @label in @gwy3dview.
 **/
Gwy3DLabel*
gwy_3d_view_get_label(Gwy3DView *gwy3dview,
                      Gwy3DViewLabel label)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    g_return_val_if_fail(label < GWY_3D_VIEW_NLABELS, NULL);

    return gwy3dview->labels[label];
}

/**
 * gwy_3d_view_get_setup:
 * @gwy3dview: A 3D data view widget.
 *
 * Gets the 3D setup object of a 3D view.
 *
 * This is a convenience method that can be used instead of fetching the setup
 * object from the data container.
 *
 * Returns: The corresponding 3D setup.
 **/
Gwy3DSetup*
gwy_3d_view_get_setup(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);

    return gwy3dview->setup;
}

static void
swap_pixbuf_vertically_in_place(GdkPixbuf *pixbuf)
{
    gint rowstride, height, i, j;
    guchar *pixels, *a, *b;

    rowstride = gdk_pixbuf_get_rowstride(pixbuf);
    height = gdk_pixbuf_get_height(pixbuf);
    pixels = gdk_pixbuf_get_pixels(pixbuf);
    for (i = 0; i < height/2; i++) {
        a = pixels + i*rowstride;
        b = pixels + (height-1 - i)*rowstride;
        for (j = 0; j < rowstride; j++, a++, b++)
            GWY_SWAP(guchar, *a, *b);
    }
}

/**
 * gwy_3d_view_get_pixbuf:
 * @gwy3dview: A 3D data view widget.
 *
 * Copies the contents of the 3D view framebuffer to a GdkPixbuf.
 *
 * The size of the pixbuf is indentical to the size of the widget.
 *
 * Returns: A newly allocated GdkPixbuf a copy of the framebuffer.
 **/
GdkPixbuf*
gwy_3d_view_get_pixbuf(Gwy3DView *gwy3dview)
{
    gint width, height;
    guchar *pixels;
    GdkPixbuf *pixbuf;

    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    g_return_val_if_fail(GTK_WIDGET_REALIZED(gwy3dview), NULL);

    width = GTK_WIDGET(gwy3dview)->allocation.width;
    height = GTK_WIDGET(gwy3dview)->allocation.height;

    pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);
    pixels = gdk_pixbuf_get_pixels(pixbuf);
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
    swap_pixbuf_vertically_in_place(pixbuf);

    return pixbuf;
}

/**
 * gwy_3d_view_get_pixbuf_with_alpha:
 * @gwy3dview: A 3D data view widget.
 *
 * Creates a GdkPixbuf from the contents of the 3D view framebuffer, with
 * transparent background.
 *
 * The size of the pixbuf is indentical to the size of the widget.
 *
 * The rendered surface is cut perfectly.  However, if the scene contains also
 * antialiased labels, these are cut in a way which currently only works with
 * a white background.
 *
 * Returns: A newly allocated GdkPixbuf a copy of the framebuffer.
 *
 * Since: 2.54
 **/
GdkPixbuf*
gwy_3d_view_get_pixbuf_with_alpha(Gwy3DView *gwy3dview)
{
    gint width, height, rowstride, i, j;
    guchar *pixels, *p;
    GLfloat *depthdata, *d;
    GdkPixbuf *pixbuf;
    GwyDataField *mask;
    gdouble *m;

    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    g_return_val_if_fail(GTK_WIDGET_REALIZED(gwy3dview), NULL);

    width = GTK_WIDGET(gwy3dview)->allocation.width;
    height = GTK_WIDGET(gwy3dview)->allocation.height;

    pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, width, height);
    pixels = gdk_pixbuf_get_pixels(pixbuf);
    rowstride = gdk_pixbuf_get_rowstride(pixbuf);
    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

    /* This reads 1 (infinity) in background values and smaller values where
     * the shape or axes are visible.  But it does not distinguish labels
     * and colour bar because we draw them as pixmaps. */
    depthdata = g_new0(GLfloat, width*height);
    glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, depthdata);

    mask = gwy_data_field_new(width, height, width, height, TRUE);

    for (i = 0; i < height; i++) {
        p = pixels + i*rowstride;
        d = depthdata + i*width;
        m = mask->data + i*width;
        for (j = width; j; j--, m++, d++, p += 4) {
            /* The rendered 3D shape.  This we always keep. */
            if (*d < 1.0)
                continue;
            /* Outside.  This we may want to delete, but only if there is
             * nothing drawn. */
            if (p[0] != 0xff || p[1] != 0xff || p[2] != 0xff)
                *m = 1.0;
        }
    }

    /* XXX: We don't know where exactly OpenGL drew the text after
     * transformations. But all non-white pixels and all pixels enclosed by
     * non-white pixels should be preserved.  This retains insides of letters
     * with holes, but it's better than nothing... */
    gwy_data_field_fill_voids(mask, TRUE);

    for (i = 0; i < height; i++) {
        p = pixels + i*rowstride;
        d = depthdata + i*width;
        m = mask->data + i*width;
        for (j = width; j; j--, m++, d++, p += 4) {
            if (*d == 1.0 && *m == 0.0)
                p[3] = 0x00;
        }
    }
    g_object_unref(mask);
    g_free(depthdata);

    swap_pixbuf_vertically_in_place(pixbuf);

    return pixbuf;
}

/**
 * gwy_3d_view_get_data:
 * @gwy3dview: A 3D data view widget.
 *
 * Returns the data container this 3D view displays.
 *
 * Returns: The container as a #GwyContainer.
 **/
GwyContainer*
gwy_3d_view_get_data(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    return gwy3dview->data;
}

/**
 * gwy_3d_view_get_scale_range:
 * @gwy3dview: A 3D data view widget.
 * @min_scale: Location to put minimum scale, or %NULL.
 * @max_scale: Location to put maximum scale, or %NULL.
 *
 * Obtains the minimum and maximum zoom of a 3D data view
 **/
void
gwy_3d_view_get_scale_range(Gwy3DView *gwy3dview,
                            gdouble *min_scale,
                            gdouble *max_scale)
{
    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));

    if (min_scale)
        *min_scale = gwy3dview->view_scale_min;
    if (max_scale)
        *max_scale = gwy3dview->view_scale_max;
}

/**
 * gwy_3d_view_set_scale_range:
 * @gwy3dview: A 3D data view widget.
 * @min_scale: Minimum zoom of the 3D data view, pass 0.0 to keep the current
 *             value.
 * @max_scale: Maximum zoom of the 3D data view, pass 0.0 to keep the current
 *             value.
 *
 * Sets the minimum and maximum zoom of a 3D data view.
 *
 * Recommended zoom values are 0.5 - 5.0.
 **/
void
gwy_3d_view_set_scale_range(Gwy3DView *gwy3dview,
                            gdouble min_scale,
                            gdouble max_scale)
{
    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    g_return_if_fail(min_scale >= 0.0 && max_scale >= 0.0);

    if (!min_scale)
        min_scale = gwy3dview->view_scale_min;
    if (!max_scale)
        max_scale = gwy3dview->view_scale_max;

    g_return_if_fail(min_scale <= max_scale);

    gwy3dview->view_scale_min = min_scale;
    gwy3dview->view_scale_max = max_scale;
    if (gwy3dview->setup) {
        gdouble val;

        val = CLAMP(gwy3dview->setup->scale, min_scale, max_scale);
        if (val != gwy3dview->setup->scale)
            g_object_set(gwy3dview->setup, "scale", val, NULL);
    }
}

/******************************************************************************/
static void
gwy_3d_view_queue_draw(Gwy3DView *gwy3dview)
{
    gwy_debug("%p", gwy3dview);

    if (!GTK_WIDGET_DRAWABLE(gwy3dview))
        return;

    gtk_widget_queue_draw(GTK_WIDGET(gwy3dview));
}

static void
gwy_3d_view_label_changed(Gwy3DView *gwy3dview)
{
    gwy_3d_view_queue_draw(gwy3dview);
}

static void
gwy_3d_view_realize(GtkWidget *widget)
{
    Gwy3DView *gwy3dview;
    GdkWindowAttr attributes;
    gint attributes_mask;

    gwy_debug("realizing a Gwy3DView (%ux%u)",
              widget->allocation.width, widget->allocation.height);

    GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);
    gwy3dview = GWY_3D_VIEW(widget);

    attributes.window_type = GDK_WINDOW_CHILD;
    attributes.x = widget->allocation.x;
    attributes.y = widget->allocation.y;
    attributes.width = widget->allocation.width;
    attributes.height = widget->allocation.height;
    attributes.wclass = GDK_INPUT_OUTPUT;
    attributes.visual = gtk_widget_get_visual(widget);
    attributes.colormap = gtk_widget_get_colormap(widget);
    attributes.event_mask = gtk_widget_get_events(widget)
                           | GDK_EXPOSURE_MASK
                           | GDK_POINTER_MOTION_MASK
                           | GDK_POINTER_MOTION_HINT_MASK
                           | GDK_BUTTON1_MOTION_MASK
                           | GDK_BUTTON_PRESS_MASK
                           | GDK_BUTTON_RELEASE_MASK
                           | GDK_VISIBILITY_NOTIFY_MASK;

    attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;

    widget->window = gdk_window_new(gtk_widget_get_parent_window(widget),
                                    &attributes, attributes_mask);
    gdk_window_set_user_data(widget->window, widget);

    /* Force widget to listen to relevant events.  Works around oxygen
     * misdetection of ‘empty’ areas.  See KDE bug #317292. */
    gtk_widget_add_events(widget, attributes.event_mask);

    widget->style = gtk_style_attach(widget->style, widget->window);
    gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);

    gwy_3d_view_send_configure(gwy3dview);
    gwy_3d_view_realize_gl(gwy3dview);
}

static gboolean
gwy_3d_view_configure(GtkWidget *widget,
                      GdkEventConfigure *event)
{
    if (GTK_WIDGET_CLASS(gwy_3d_view_parent_class)->configure_event)
        GTK_WIDGET_CLASS(gwy_3d_view_parent_class)->configure_event(widget,
                                                                    event);

    GWY_3D_VIEW_GET_PRIVATE(GWY_3D_VIEW(widget))->need_update_list = TRUE;

    return FALSE;
}

static void
gwy_3d_view_send_configure(Gwy3DView *gwy3dview)
{
    GtkWidget *widget;
    GdkEvent *event;

    event = gdk_event_new(GDK_CONFIGURE);

    widget = GTK_WIDGET(gwy3dview);
    event->configure.window = g_object_ref(widget->window);
    event->configure.send_event = TRUE;
    event->configure.x = widget->allocation.x;
    event->configure.y = widget->allocation.y;
    event->configure.width = widget->allocation.width;
    event->configure.height = widget->allocation.height;

    gtk_widget_event(widget, event);
    gdk_event_free(event);
}

static void
gwy_3d_view_size_request(G_GNUC_UNUSED GtkWidget *widget,
                         GtkRequisition *requisition)
{
    requisition->width = GWY_3D_VIEW_DEFAULT_SIZE_X;
    requisition->height = GWY_3D_VIEW_DEFAULT_SIZE_Y;
}

static void
gwy_3d_view_size_allocate(GtkWidget *widget,
                          GtkAllocation *allocation)
{
    g_return_if_fail(allocation != NULL);

    widget->allocation = *allocation;

    if (GTK_WIDGET_REALIZED(widget)) {
        gdk_window_move_resize(widget->window,
                               allocation->x, allocation->y,
                               allocation->width, allocation->height);

        gwy_3d_view_send_configure(GWY_3D_VIEW(widget));
    }
}

/* Convert GwyRGBA to GLfloat[4] array */
static void
gwy_3d_view_rgba_dv(GLenum face,
                    GLenum pname,
                    const GwyRGBA *rgba)
{
    gfloat fparams[4];

    fparams[0] = rgba->r;
    fparams[1] = rgba->g;
    fparams[2] = rgba->b;
    fparams[3] = rgba->a;
    glMaterialfv(face, pname, fparams);
}

static gboolean
gwy_3d_view_expose(GtkWidget *widget,
                   G_GNUC_UNUSED GdkEventExpose *event)
{
    GwyGLMaterial *material;
    GdkGLContext  *glcontext;
    GdkGLDrawable *gldrawable;
    Gwy3DView *gwy3dview;
    Gwy3DViewPrivate *priv;

    GLfloat light_position[] = { 0.0, 0.0, 4.0, 1.0 };

    GLfloat w = widget->allocation.width;
    GLfloat h = widget->allocation.height;
    gint sw = 0;

    gwy_debug("width: %f, height: %f", w, h);

    g_return_val_if_fail(GWY_IS_3D_VIEW(widget), FALSE);
    gwy3dview = GWY_3D_VIEW(widget);
    priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);

    glcontext  = gtk_widget_get_gl_context(widget);
    gldrawable = gtk_widget_get_gl_drawable(widget);
    gwy_debug("GLContext: %p, GLDrawable: %p", glcontext, gldrawable);

    /*** OpenGL BEGIN ***/
    if (!gdk_gl_drawable_gl_begin(gldrawable, glcontext))
        return FALSE;

    if (priv->need_update_list) {
        gwy_3d_make_list(gwy3dview,
                         gwy3dview->data_field, priv->mask_field,
                         gwy3dview->ovlays);
        priv->need_update_list = FALSE;
    }

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glViewport(0, 0, w, h);
    if (gwy3dview->setup->fmscale_visible
        && gwy_3d_visualisation_has_colormap(gwy3dview->setup->visualization)) {
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, w, 0, h, -1, 1);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        glDisable(GL_DEPTH_TEST);
        glEnable(GL_TEXTURE_2D);
        glDisable(GL_LIGHTING);

        sw = gwy_3d_draw_fmscaletex(gwy3dview);
        gwy_debug("Scale width: %d", sw);
        if (!gwy3dview->setup->fmscale_reserve_space)
            sw = 0;

        glDisable(GL_TEXTURE_2D);
        glEnable(GL_DEPTH_TEST);

        glViewport(0, 0, w-sw, h);
    }
    glLoadIdentity();

    /* View transformation. */
    gwy_3d_set_projection(gwy3dview, (w-sw)/h);
    glTranslatef(0.0, 0.0, -10.0);
    glScalef(gwy3dview->setup->scale,
             gwy3dview->setup->scale,
             gwy3dview->setup->scale);

    glRotatef(gwy3dview->setup->rotation_y*RAD_2_DEG, 1.0, 0.0, 0.0);
    glRotatef(gwy3dview->setup->rotation_x*RAD_2_DEG, 0.0,  0.0, 1.0);
    glScalef(1.0f, 1.0f, gwy3dview->setup->z_scale);

    /* Render shape */
    if (gwy3dview->setup->visualization == GWY_3D_VISUALIZATION_LIGHTING) {
        material = gwy3dview->material;

        glDisable(GL_COLOR_MATERIAL);
        glEnable(GL_LIGHTING);
        gwy_3d_view_rgba_dv(GL_FRONT, GL_AMBIENT,
                            gwy_gl_material_get_ambient(material));
        gwy_3d_view_rgba_dv(GL_FRONT, GL_DIFFUSE,
                            gwy_gl_material_get_diffuse(material));
        gwy_3d_view_rgba_dv(GL_FRONT, GL_SPECULAR,
                            gwy_gl_material_get_specular(material));
        glMaterialf(GL_FRONT, GL_SHININESS,
                    (GLfloat)gwy_gl_material_get_shininess(material)*128.0f);
        glPushMatrix();
        /* Scale-out the light source so that it does not come close to the
         * surface for small z_scale. */
        glScalef(1.0f, 1.0f, 1.0/gwy3dview->setup->z_scale);
        glRotatef(gwy3dview->setup->light_theta * RAD_2_DEG, 0.0f, 0.0f, 1.0f);
        glRotatef(gwy3dview->setup->light_phi * RAD_2_DEG, 0.0f, 1.0f, 0.0f);
        glLightfv(GL_LIGHT0, GL_POSITION, light_position);
        glPopMatrix();
    }
    else if (gwy3dview->setup->visualization == GWY_3D_VISUALIZATION_OVERLAY) {
        glEnable(GL_COLOR_MATERIAL);
        glEnable(GL_LIGHTING);
        glPushMatrix();
        /* Scale-out the light source so that it does not come close to the
         * surface for small z_scale. */
        glScalef(1.0f, 1.0f, 1.0/gwy3dview->setup->z_scale);
        glRotatef(gwy3dview->setup->light_theta * RAD_2_DEG, 0.0f, 0.0f, 1.0f);
        glRotatef(gwy3dview->setup->light_phi * RAD_2_DEG, 0.0f, 1.0f, 0.0f);
        glLightfv(GL_LIGHT0, GL_POSITION, light_position);
        glPopMatrix();
    }
    else {
        glDisable(GL_LIGHTING);
    }

    glCallList(gwy3dview->shape_list_base + gwy3dview->shape_current);
    if (gwy3dview->setup->axes_visible)
        gwy_3d_draw_axes(gwy3dview, w-sw, h);

    if (gwy3dview->movement == GWY_3D_MOVEMENT_LIGHT && priv->button)
        gwy_3d_draw_light_position(gwy3dview);

    /* Swap buffers */
    if (gdk_gl_drawable_is_double_buffered(gldrawable))
        gdk_gl_drawable_swap_buffers(gldrawable);
    else
        glFlush();

    gdk_gl_drawable_gl_end(gldrawable);
    /*** OpenGL END ***/

    return FALSE;
}

static gboolean
gwy_3d_view_button_press(GtkWidget *widget,
                         GdkEventButton *event)
{
    Gwy3DView *gwy3dview = GWY_3D_VIEW(widget);
    Gwy3DViewPrivate *priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);

    gwy3dview->mouse_begin_x = event->x;
    gwy3dview->mouse_begin_y = event->y;
    priv->button = TRUE;
    priv->has_moved = FALSE;

    return FALSE;
}

static gboolean
gwy_3d_view_button_release(GtkWidget *widget,
                           G_GNUC_UNUSED GdkEventButton *event)
{
    Gwy3DView *gwy3dview = GWY_3D_VIEW(widget);
    Gwy3DViewPrivate *priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);

    gwy_debug("%d %d", priv->button, priv->has_moved);
    priv->button = FALSE;
    if (priv->has_moved && gwy3dview->movement == GWY_3D_MOVEMENT_LIGHT)
        gwy_3d_view_queue_draw(gwy3dview);

    return FALSE;
}

static gboolean
gwy_3d_view_scroll(GtkWidget *widget, GdkEventScroll *event)
{
    Gwy3DView *gwy3dview = GWY_3D_VIEW(widget);
    GdkScrollDirection dir = event->direction;
    gboolean enlarge;
    gdouble val, q;

    enlarge = (dir == GDK_SCROLL_UP || dir == GDK_SCROLL_RIGHT);

    q = exp(2.5*(enlarge ? GWY_3D_Z_DEFORMATION : -GWY_3D_Z_DEFORMATION));
    if (event->state & GDK_SHIFT_MASK) {
        val = gwy3dview->setup->z_scale*q;
        g_object_set(gwy3dview->setup, "z-scale", val, NULL);
    }
    else {
        val = gwy3dview->setup->scale*q;
        val = CLAMP(val, gwy3dview->view_scale_min, gwy3dview->view_scale_max);
        g_object_set(gwy3dview->setup, "scale", val, NULL);
    }

    return TRUE;
}

static gboolean
gwy_3d_view_motion_notify(GtkWidget *widget,
                          G_GNUC_UNUSED GdkEventMotion *event)
{
    Gwy3DView *gwy3dview = GWY_3D_VIEW(widget);
    Gwy3DViewPrivate *priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);
    GdkModifierType mods;
    gdouble h, dx, dy, val;
    gint ex, ey;

    gdk_window_get_pointer(widget->window, &ex, &ey, &mods);
    h = widget->allocation.height;
    dx = ex - gwy3dview->mouse_begin_x;
    dy = ey - gwy3dview->mouse_begin_y;
    gwy3dview->mouse_begin_x = ex;
    gwy3dview->mouse_begin_y = ey;
    priv->has_moved = TRUE;

    gwy_debug("motion event: (%d, %d), shape=%d",
              ex, ey, gwy3dview->shape_current);

    if (mods & GDK_BUTTON1_MASK) {
        gwy_debug("with movement %d", gwy3dview->movement);
        switch (gwy3dview->movement) {
            case GWY_3D_MOVEMENT_NONE:
            break;

            case GWY_3D_MOVEMENT_ROTATION:
            g_object_set(gwy3dview->setup,
                         "rotation-x",
                         gwy3dview->setup->rotation_x + dx*DEG_2_RAD,
                         "rotation-y",
                         gwy3dview->setup->rotation_y + dy*DEG_2_RAD,
                         NULL);
            break;

            case GWY_3D_MOVEMENT_SCALE:
            val = gwy3dview->setup->scale*(1.0 + dy/h);
            val = CLAMP(val,
                        gwy3dview->view_scale_min, gwy3dview->view_scale_max);
            g_object_set(gwy3dview->setup, "scale", val, NULL);
            break;

            case GWY_3D_MOVEMENT_DEFORMATION:
            val = gwy3dview->setup->z_scale;
            val *= exp(-GWY_3D_Z_DEFORMATION*dy);
            g_object_set(gwy3dview->setup, "z-scale", val, NULL);
            break;

            case GWY_3D_MOVEMENT_LIGHT:
            g_object_set(gwy3dview->setup,
                         "light-theta",
                         gwy3dview->setup->light_theta + dy*DEG_2_RAD,
                         "light-phi",
                         gwy3dview->setup->light_phi + dx*DEG_2_RAD,
                         NULL);
            break;
        }
    }

    return FALSE;
}

/**
 * gwy_3d_calculate_pixel_sizes:
 * @dfield: A data field.
 * @pdx: Location to store x-direction step, or NULL.
 * @pdy: Location to store y-direction step, or NULL.
 *
 * Calculates pixel sizes used for visualization.
 *
 * The smaller step of @pdx and @pdy is always 1.0, which mean the GL dimension
 * will be equal to the resolution.  The larger is calculated to keep the
 * physical aspect ratio.
 **/
static void
gwy_3d_calculate_pixel_sizes(GwyDataField *dfield,
                             GLfloat *dx,
                             GLfloat *dy)
{
   gint xres, yres;
   gdouble xreal, yreal;

   xres = gwy_data_field_get_xres(dfield);
   yres = gwy_data_field_get_yres(dfield);
   xreal = gwy_data_field_get_xreal(dfield);
   yreal = gwy_data_field_get_yreal(dfield);
   /* The smaller triangle side is 1.0, the larger is, well, at least that.
    * To get pixel-wise behaviour, just set dx=dy=1. */
   if (xres/xreal <= yres/yreal) {
       *dx = (yres/yreal)/(xres/xreal);
       *dy = 1.0;
   }
   else {
       *dx = 1.0;
       *dy = (xres/xreal)/(yres/yreal);
   }
}

/**
 * gwy_3d_make_normals:
 * @dfield: A data field.
 * @normals: Array of normals to fill.  It must have the same number of
 *           elements as @dfield.
 *
 * Calculates surface normals used for visualization.
 *
 * Returns: @normals again, %NULL if when memory could not be allocated.
 **/
static Gwy3DVector*
gwy_3d_make_normals(GwyDataField *dfield,
                    Gwy3DVector *normals)
{
   typedef struct { Gwy3DVector A, B; } RectangleNorm;
   const gdouble *data;
   gint i, j, xres, yres;
   GLfloat dx, dy, dx2, dy2;
   RectangleNorm * norms;

   g_return_val_if_fail(normals, NULL);

   xres = gwy_data_field_get_xres(dfield);
   yres = gwy_data_field_get_yres(dfield);
   data = gwy_data_field_get_data_const(dfield);
   gwy_3d_calculate_pixel_sizes(dfield, &dx, &dy);
   dx2 = dx*dx;
   dy2 = dy*dy;

   /* memory for normals of triangles
    * total count of rectangels is (xres-1)*(yres-1), each one has 2n triangles
    * 3 componernts per vector
    */
   norms = g_new(RectangleNorm, (xres - 1) * (yres - 1));
   if (norms == NULL)
       return NULL;

   /* Calculation of normals of triangles */
   for (j = 0; j < yres-1; j++) {
      for (i = 0; i < xres-1; i++) {
         GLfloat a, b, c, ab, ac, bc, n;

         a = data[(yres-1 - j)*xres + i];
         b = data[(yres-2 - j)*xres + i];
         c = data[(yres-1 - j)*xres + i+1];
         ab = a - b;
         ac = a - c;
         n = 1.0/sqrt(dy2*ac*ac + dx2*ab*ab + dx2*dy2);
         norms[j*(xres-1) + i].A.x = dy*ac*n;
         norms[j*(xres-1) + i].A.y = -dx*ab*n;
         norms[j*(xres-1)+ i].A.z = dx*dy*n;

         a = b;
         b = c;
         c = data[(yres-2 - j)*xres + i+1];
         ac = a - c;
         bc = b - c;
         n = 1.0/sqrt(dy2*ac*ac + dx2*bc*bc + dx2*dy2);
         norms[j*(xres-1) + i].B.x = dy*ac*n;
         norms[j*(xres-1) + i].B.y = -bc*dx*n;
         norms[j*(xres-1) + i].B.z = dx*dy*n;
      }
   }

   /* two of corner vertices have only one triangle adjacent
    * (first and last vertex) */
   normals[0] = norms[0].A;
   normals[xres * yres - 1] = norms[(xres-1) * (yres-1) - 1].B;
   /*the other two corner vertecies have two triangles adjacent*/
   normals[xres - 1].x = (norms[xres - 2].A.x + norms[xres - 2].B.x)/2.0f;
   normals[xres - 1].y = (norms[xres - 2].A.y + norms[xres - 2].B.y)/2.0f;
   normals[xres - 1].z = (norms[xres - 2].A.z + norms[xres - 2].B.z)/2.0f;
   normals[xres * (yres -1)].x = (norms[(xres - 1)*(yres -2)].A.x
                                  + norms[(xres - 1)*(yres -2)].B.x)/2.0f;
   normals[xres * (yres -1)].y = (norms[xres - 2].A.y
                                  + norms[(xres - 1)*(yres -2)].B.y)/2.0f;
   normals[xres * (yres -1)].z = (norms[xres - 2].A.z
                                  + norms[(xres - 1)*(yres -2)].B.z)/2.0f;
   /*the vertices on the edge of the matrix have three adjacent triangles*/
   for (i = 1; i < xres - 1; i ++) {
       const Gwy3DVector *a = &(norms[i-1].A);
       const Gwy3DVector *b = &(norms[i-1].B);
       const Gwy3DVector *c = &(norms[i].A);

       normals[i].x = (a->x + b->x + c->x)/3.0;
       normals[i].y = (a->y + b->y + c->y)/3.0;
       normals[i].z = (a->z + b->z + c->z)/3.0;
   }

   for (i = 1; i < xres - 1; i ++) {
       const Gwy3DVector *a = &(norms[(xres - 1)*(yres - 2) + i-1].B);
       const Gwy3DVector *b = &(norms[(xres - 1)*(yres - 2) + i-1].A);
       const Gwy3DVector *c = &(norms[(xres - 1)*(yres - 2) + i].B);

       normals[xres * (yres - 1) + i].x = (a->x + b->x + c->x)/3.0;
       normals[xres * (yres - 1) + i].y = (a->y + b->y + c->y)/3.0;
       normals[xres * (yres - 1) + i].z = (a->z + b->z + c->z)/3.0;
   }

   for (i = 1; i < yres - 1; i ++) {
       const Gwy3DVector *a = &(norms[(i-1) * (xres-1)].A);
       const Gwy3DVector *b = &(norms[(i-1) * (xres-1)].B);
       const Gwy3DVector *c = &(norms[i *     (xres-1)].A);

       normals[i * xres].x = (a->x + b->x + c->x)/3.0;
       normals[i * xres].y = (a->y + b->y + c->y)/3.0;
       normals[i * xres].z = (a->z + b->z + c->z)/3.0;
   }

   for (i = 1; i < yres - 1; i ++) {
       const Gwy3DVector *a = &(norms[i     * (xres-1) - 1].B);
       const Gwy3DVector *b = &(norms[(i+1) * (xres-1) - 1].A);
       const Gwy3DVector *c = &(norms[(i+1) * (xres-1) - 1].B);

       normals[i * xres - 1].x = (a->x + b->x + c->x)/3.0;
       normals[i * xres - 1].y = (a->y + b->y + c->y)/3.0;
       normals[i * xres - 1].z = (a->z + b->z + c->z)/3.0;
   }

   /* The vertices inside of matrix have six adjacent triangles*/
   for (j = 1; j < yres - 1; j++) {
       for (i = 1; i < xres - 1; i++) {
           Gwy3DVector *adj_tri[6];
           int k;

           adj_tri[0] = &(norms[(j-1)*(xres-1) + i - 1].B);
           adj_tri[1] = &(norms[(j-1)*(xres-1) + i    ].A);
           adj_tri[2] = &(norms[(j-1)*(xres-1) + i    ].B);
           adj_tri[3] = &(norms[j    *(xres-1) + i    ].A);
           adj_tri[4] = &(norms[j    *(xres-1) + i - 1].A);
           adj_tri[5] = &(norms[j    *(xres-1) + i - 1].B);
           normals[j*xres + i].x = 0.0f;
           normals[j*xres + i].y = 0.0f;
           normals[j*xres + i].z = 0.0f;
           for (k = 0; k < 6; k++) {
               normals[j*xres + i].x += adj_tri[k]->x;
               normals[j*xres + i].y += adj_tri[k]->y;
               normals[j*xres + i].z += adj_tri[k]->z;
           }
           normals[j*xres + i].x /= 6.0f;
           normals[j*xres + i].y /= 6.0f;
           normals[j*xres + i].z /= 6.0f;
       }
   }

   g_free(norms);

   return normals;
}

#define GWY_3D_VERTEX(i,j) \
  do { \
  z = data[(yres-1 - (j))*xres + (i)];               \
  color = colors + (yres-1 - (j))*rowstride + (i)*3; \
  glNormal3d(normals[(j)*xres+(i)].x,                \
             normals[(j)*xres+(i)].y,                \
             normals[(j)*xres+(i)].z);               \
  glColor3d((GLfloat) *(color)/255.0,                \
            (GLfloat) *(color+1)/255.0,              \
            (GLfloat) *(color+2)/255.0);             \
  glVertex3d((i)*dx, (j)*dy, z);                     \
  } while (0)

static void
gwy_3d_make_list(Gwy3DView *gwy3dview,
                 GwyDataField *dfield,
                 GwyDataField *mask_field,
                 GwyPixmapLayer** ovlays)
{
    gint i, j, xres, yres, rowstride;
    gdouble data_min, data_max, res;
    GLfloat dx, dy;
    Gwy3DVector *normals;
    const gdouble *data;
    const gdouble *mask = NULL;
    GdkPixbuf *pixbuf;
    guchar *colors;
    gboolean glon;

    g_return_if_fail(GWY_IS_DATA_FIELD(dfield));

    xres = gwy_data_field_get_xres(dfield);
    yres = gwy_data_field_get_yres(dfield);
    gwy_data_field_get_min_max(dfield, &data_min, &data_max);

    data = gwy_data_field_get_data_const(dfield);
    if (GWY_IS_DATA_FIELD(mask_field))
        mask = gwy_data_field_get_data_const(mask_field);

    normals = g_new(Gwy3DVector, xres * yres);
    if (!gwy_3d_make_normals(dfield, normals)) {
        /*TODO solve not enough memory problem*/
        g_return_if_reached();
    }

    gwy_3d_calculate_pixel_sizes(dfield, &dx, &dy);
    res = MAX(xres*dx, yres*dy);
    if (gwy3dview->ovlays) {
        GdkPixbuf *lpb;
        gint l;

        pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, 0, 8, xres, yres);
        gdk_pixbuf_fill(pixbuf, 0x00000000);

        for (l = 0; l < gwy3dview->novlays; l++) {
            if (ovlays[l]) {
                lpb = gwy_pixmap_layer_paint(ovlays[l]);
                if (lpb)
                    gdk_pixbuf_composite(lpb, pixbuf,
                                         0, 0, xres, yres,
                                         0, 0,
                                         (gdouble)xres/gdk_pixbuf_get_width(lpb),
                                         (gdouble)yres/gdk_pixbuf_get_height(lpb),
                                         GDK_INTERP_TILES, 0xff);
            }
        }
    }
    else {
        GwyGradient *grad = gwy3dview->gradient;

        if (!grad)
            grad = gwy_gradients_get_gradient(NULL);

        gwy_resource_use(GWY_RESOURCE(grad));
        pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, 0, 8, xres, yres);
        gwy_pixbuf_draw_data_field(pixbuf, dfield, grad);
        gwy_resource_release(GWY_RESOURCE(grad));
    }

    colors = gdk_pixbuf_get_pixels(pixbuf);
    rowstride = gdk_pixbuf_get_rowstride(pixbuf);

    glNewList(gwy3dview->shape_list_base + GWY_3D_SHAPE, GL_COMPILE);
    glPushMatrix();
    glTranslatef(-xres*dx/res, -yres*dy/res, GWY_3D_Z_DISPLACEMENT);
    glScalef(2.0/res, 2.0/res, GWY_3D_Z_TRANSFORMATION/(data_max - data_min));
    glTranslatef(0.0, 0.0, -data_min);
    /* zdifr = 1.0/(data_max - data_min); */

    for (j = 0; j < yres-1; j++) {
        glBegin(GL_TRIANGLE_STRIP);
        glon = TRUE;
        for (i = 0; i < xres-1; i++) {
            gdouble z;
            guchar *color;
            if (gwy3dview->setup->hide_masked && mask != NULL) {
                if (mask[(yres-1 - j)*xres + i] == 0.0
                    && mask[(yres-2 - j)*xres + i] == 0.0
                    && !glon) {
                    glBegin(GL_TRIANGLE_STRIP);
                    glon = TRUE;
                    if (mask[(yres-1 - j)*xres + i - 1] > 0.0
                        && mask[(yres-2 - j)*xres + i - 1] > 0.0) {
                        GWY_3D_VERTEX(i, j);
                    }
                    else if (mask[(yres-1 - j)*xres + i - 1] > 0.0) {
                        GWY_3D_VERTEX(i-1, j+1);
                    }
                    else if (mask[(yres-2 - j)*xres + i - 1] > 0.0) {
                        GWY_3D_VERTEX(i-1, j);
                    }
                }
                if (mask[(yres-1 - j)*xres + i] == 0 && glon)
                    GWY_3D_VERTEX(i, j);
                if (mask[(yres-2 - j)*xres + i] == 0 && glon)
                    GWY_3D_VERTEX(i, j+1);
                if (mask[(yres-1 - j)*xres + i] > 0
                    || mask[(yres-2 - j)*xres + i] > 0) {
                    glEnd();
                    glon = FALSE;
                }
            }
            else {
                GWY_3D_VERTEX(i, j);
                GWY_3D_VERTEX(i, j+1);
            }
        }
        glEnd();
    }
    g_free(normals);
    glPopMatrix();
    glEndList();

    g_object_unref(pixbuf);
}

/*
 * gwy_3d_util_mult_matrix:
 * @a, @b: matrices to multiply
 * @mpMatrix: result
 *
 * multiplies the matrices
 *
*/
static void
gwy_3d_util_mult_matrix(const GLdouble *a, const GLdouble *b,
                        GLdouble *mpMatrix)
{
    int i, j;

    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            mpMatrix[i*4+j]
                = a[i*4+0]*b[0*4+j]
                + a[i*4+1]*b[1*4+j]
                + a[i*4+2]*b[2*4+j]
                + a[i*4+3]*b[3*4+j];
        }
    }
}

/* mpMatrix is the current model-projection-matrix */
static void
gwy_3d_util_get_mpmatrix(GLdouble *mpMatrix)
{
    GLdouble mM[16], pM[16];
    glGetDoublev(GL_MODELVIEW_MATRIX, mM);
    glGetDoublev(GL_PROJECTION_MATRIX, pM);

    gwy_3d_util_mult_matrix(mM, pM, mpMatrix);
}

/* wx,wy,wz denote the pont x,y,z will result
 * in under the model-projection-matrix mpM
 * and the viewport vpMatrix
*/
static int
gwy_3d_util_project(GLdouble x, GLdouble y, GLdouble z,
                    const GLdouble *mpM, const GLint *vpMatrix,
                    GLdouble *wx, GLdouble *wy, GLdouble *wz)
{
    GLdouble temp[4];
    /* Matrix-Vector-Product */
    temp[0] = mpM[0]*x + mpM[4]*y + mpM[8]*z + mpM[12];
    temp[1] = mpM[1]*x + mpM[5]*y + mpM[9]*z + mpM[13];
    temp[2] = mpM[2]*x + mpM[6]*y + mpM[10]*z + mpM[14];
    temp[3] = mpM[3]*x + mpM[7]*y + mpM[11]*z + mpM[15];

    if (temp[3] == 0.0)
        return GL_FALSE;

    temp[0] /= temp[3];
    temp[1] /= temp[3];
    temp[2] /= temp[3];

    *wx = (0.5*temp[0] + 0.5)*vpMatrix[2] + vpMatrix[0];
    *wy = (0.5*temp[1] + 0.5)*vpMatrix[3] + vpMatrix[1];
    *wz = 0.5*temp[2] + 0.5;

    return GL_TRUE;
}

static inline gint
uppow2(gint x)
{
    x--;
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    x++;

    return x;
}

static void
gwy_3d_draw_axes(Gwy3DView *widget, gint width, gint height)
{
    GLfloat dx, dy, rx, Ax, Ay, Bx, By, Cx, Cy, ticklen, xt, yt;
    gdouble data_min, data_max;
    gint xres, yres, res;
    gboolean yfirst;
    GwyGLMaterial *mat_none;

    gwy_debug(" ");

    xres = gwy_data_field_get_xres(widget->data_field);
    yres = gwy_data_field_get_yres(widget->data_field);
    gwy_data_field_get_min_max(widget->data_field, &data_min, &data_max);
    gwy_3d_calculate_pixel_sizes(widget->data_field, &dx, &dy);
    res = MAX(xres*dx, yres*dy);

    Ax = Ay = Bx = By = Cx = Cy = 0.0f;
    yfirst = TRUE;
    rx = fmod(widget->setup->rotation_x*RAD_2_DEG, 360.0);
    if (rx < 0.0)
        rx += 360.0;

    mat_none = gwy_gl_materials_get_gl_material(GWY_GL_MATERIAL_NONE);

    glPushMatrix();
    glTranslatef(-dx*xres/res, -dy*yres/res, GWY_3D_Z_DISPLACEMENT);
    glScalef(2.0/res, 2.0/res, GWY_3D_Z_TRANSFORMATION/(data_max - data_min));
    gwy_3d_view_rgba_dv(GL_FRONT, GL_AMBIENT,
                        gwy_gl_material_get_ambient(mat_none));
    gwy_3d_view_rgba_dv(GL_FRONT, GL_DIFFUSE,
                        gwy_gl_material_get_diffuse(mat_none));
    gwy_3d_view_rgba_dv(GL_FRONT, GL_SPECULAR,
                        gwy_gl_material_get_specular(mat_none));
    glMaterialf(GL_FRONT, GL_SHININESS,
                (GLfloat)gwy_gl_material_get_shininess(mat_none)*128.0f);

    /* This is optimistic.  Hope something reasonable happens when the selected
     * line width is not actually supported. */
    glLineWidth(widget->setup->line_width);

    if (rx >= 0.0 && rx <= 90.0) {
        Ay = dy*yres;
        Cx = dx*xres;
        yfirst = TRUE;
    }
    else if (rx > 90.0 && rx <= 180.0) {
        Ax = dx*xres;
        Ay = dy*yres;
        By = dy*yres;
        yfirst = FALSE;
    }
    else if (rx > 180.0 && rx <= 270.0) {
        Ax = dx*xres;
        Bx = dx*xres;
        By = dy*yres;
        Cy = dy*yres;
        yfirst = TRUE;
    }
    else if (rx >= 270.0 && rx <= 360.0) {
        Bx = dx*xres;
        Cx = dx*xres;
        Cy = dy*yres;
        yfirst = FALSE;
    }
    ticklen = 0.01f*(dx*xres + dy*yres);

    /* X, Y and Z axes */
    glBegin(GL_LINE_STRIP);
    glColor3f(0.0, 0.0, 0.0);
    glVertex2f(Ax, Ay);
    glVertex2f(Bx, By);
    glVertex2f(Cx, Cy);
    glVertex3f(Cx, Cy, data_max - data_min);
    glEnd();

    glBegin(GL_LINES);
    /* X-axis ticks */
    xt = ticklen*(Bx - Cx)/(ABS(Cx - Bx) + ABS(Cy - By));
    yt = ticklen*(By - Cy)/(ABS(Cx - Bx) + ABS(Cy - By));

    glVertex2f(Ax, Ay);
    glVertex2f(Ax + xt, Ay + yt);

    glVertex2f((Ax+Bx)/2, (Ay+By)/2);
    glVertex2f((Ax+Bx)/2 + xt, (Ay+By)/2 + yt);

    glVertex2f(Bx, By);
    glVertex2f(Bx + xt, By + yt);

    /* Y-axis ticks */
    xt = ticklen*(Bx - Ax)/(ABS(Bx - Ax) + ABS(By - Ay));
    yt = ticklen*(By - Ay)/(ABS(Bx - Ax) + ABS(By - Ay));

    glVertex2f(Bx, By);
    glVertex2f(Bx + xt, By + yt);

    glVertex2f((Cx+Bx)/2, (Cy+By)/2);
    glVertex2f((Cx+Bx)/2 + xt, (Cy+By)/2 + yt);

    glVertex2f(Cx, Cy);
    glVertex2f(Cx + xt, Cy + yt);

    /* Z-axis ticks */
    glVertex3f(Cx, Cy, data_max - data_min);
    glVertex3f(Cx + xt, Cy + yt, data_max - data_min);

    glVertex3f(Cx, Cy, (data_max - data_min)/2);
    glVertex3f(Cx + xt, Cy + yt, (data_max - data_min)/2);
    glEnd();

    /*
    TODO: create bitmaps with labels in the beginning (possibly in init_gl)
          into display lists and draw here
    */
    /* FIXME: I was able to fix the ticks drawing but this is still terribly
     * broken for non-square images.  (Yeti) */
    if (widget->setup->labels_visible
        && !ugly_hack_globally_disable_axis_drawing) {
        guint view_size;
        gint size;
        GLdouble mM[16], pM[16], mpM[16];
        GLdouble sx, sy, sz,
                 tx, ty, tz,
                 ux, uy, uz,
                 vx, vy, vz,
                 rotA, rotB;
        GLint vpM[4];

        sx = sy = sz = tx = ty = tz = ux = uy = uz = vx = vy = vz = 0;

        view_size = MIN(width, height);
        size = (gint)(sqrt(view_size)*0.8);

        gwy_3d_util_get_mpmatrix(mpM);
        glGetDoublev(GL_MODELVIEW_MATRIX, mM);
        glGetDoublev(GL_PROJECTION_MATRIX, pM);

        glGetIntegerv(GL_VIEWPORT, vpM);

        glColor3f(1.0, 1.0, 1.0);

        gwy_3d_util_project(Ax, Ay, -0.0f, mpM, vpM, &sx, &sy, &sz);
        gwy_3d_util_project(Bx, By, -0.0f, mpM, vpM, &tx, &ty, &tz);
        rotA = atan2(ty-sy, tx-sx);

        gwy_3d_util_project(Cx, Cy, -0.0f, mpM, vpM, &sx, &sy, &sz);
        rotB = G_PI/2.0 - atan2(sx-tx, sy-ty);

        gwy_3d_util_project((Ax+Bx)/2 - (Cx-Bx)*0.1,
                            (Ay+By)/2 - (Cy-By)*0.1,
                            -0.0f,
                            mpM, vpM, &sx, &sy, &sz);
        gwy_3d_util_project((Bx+Cx)/2 - (Ax-Bx)*0.1,
                            (By+Cy)/2 - (Ay-By)*0.1,
                            -0.0f,
                            mpM, vpM, &tx, &ty, &tz);
        gwy_3d_util_project(Cx - (Ax-Bx)*0.1,
                            Cy - (Ay-By)*0.1,
                            0.0f,
                            mpM, vpM, &ux, &uy, &uz);
        gwy_3d_util_project(Cx - (Ax-Bx)*0.1,
                            Cy - (Ay-By)*0.1,
                            data_max-data_min,
                            mpM, vpM, &vx, &vy, &vz);

        /* setup 2d */
        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();
        glOrtho(0, width, 0, height, -1, 1);

        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glLoadIdentity();

        glDisable(GL_DEPTH_TEST);
        glEnable(GL_TEXTURE_2D);
        glDisable(GL_LIGHTING);

        glEnable(GL_BLEND);
        glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

        gwy_3d_texture_text(widget, yfirst ? GWY_3D_VIEW_LABEL_Y
                                           : GWY_3D_VIEW_LABEL_X,
                            sx, sy, sz, rotA,
                            size, GWY_3D_JUST_CENTER, GWY_3D_JUST_CENTER);

        gwy_3d_texture_text(widget, yfirst ? GWY_3D_VIEW_LABEL_X
                                           : GWY_3D_VIEW_LABEL_Y,
                            tx, ty, tz, rotB,
                            size, GWY_3D_JUST_CENTER, GWY_3D_JUST_CENTER);

        gwy_3d_texture_text(widget, GWY_3D_VIEW_LABEL_MAX,
                            vx, vy, vz, 0,
                            size, GWY_3D_JUST_LEFT_EDGE, GWY_3D_JUST_CENTER);

        gwy_3d_texture_text(widget, GWY_3D_VIEW_LABEL_MIN,
                            ux, uy, uz, 0,
                            size, GWY_3D_JUST_LEFT_EDGE, GWY_3D_JUST_CENTER);

        /* unset 2d */
        glDisable(GL_BLEND);

        glDisable(GL_TEXTURE_2D);
        glEnable(GL_DEPTH_TEST);
        glEnable(GL_LIGHTING);

        glMatrixMode(GL_PROJECTION);
        glPopMatrix();

        glMatrixMode(GL_MODELVIEW);
        glPopMatrix();
    }

    glPopMatrix();
}

static void
gwy_3d_draw_light_position(Gwy3DView *widget)
{
    GwyGLMaterial *mat_none;
    GLfloat plane_z;
    gdouble data_min, data_max, data_mean;
    int i;

    gwy_debug(" ");

    gwy_data_field_get_min_max(widget->data_field, &data_min, &data_max);
    data_mean = gwy_data_field_get_avg(widget->data_field);

    mat_none = gwy_gl_materials_get_gl_material(GWY_GL_MATERIAL_NONE);
    gwy_3d_view_rgba_dv(GL_FRONT, GL_AMBIENT,
                        gwy_gl_material_get_ambient(mat_none));
    gwy_3d_view_rgba_dv(GL_FRONT, GL_DIFFUSE,
                        gwy_gl_material_get_diffuse(mat_none));
    gwy_3d_view_rgba_dv(GL_FRONT, GL_SPECULAR,
                        gwy_gl_material_get_specular(mat_none));
    glMaterialf(GL_FRONT, GL_SHININESS,
                (GLfloat)gwy_gl_material_get_shininess(mat_none)*128.0f);

    glPushMatrix();
    plane_z = GWY_3D_Z_TRANSFORMATION
              *(data_mean - data_min)/(data_max  - data_min)
              + GWY_3D_Z_DISPLACEMENT;

    glTranslatef(0.0f, 0.0f, plane_z);
    glRotatef(-widget->setup->light_theta * RAD_2_DEG, 0.0f, 0.0f, 1.0f);
    glRotatef(widget->setup->light_phi * RAD_2_DEG, 0.0f, 1.0f, 0.0f);
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    glBegin(GL_QUAD_STRIP);
    for (i = -180; i <= 180; i += 5) {
        GLfloat x = cos(i * DEG_2_RAD) * G_SQRT2;
        GLfloat z = sin(i * DEG_2_RAD) * G_SQRT2;
        glVertex3f(x,  0.05f, z);
        glVertex3f(x, -0.05f, z);
    }
    glEnd();

    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    glBegin(GL_LINE_STRIP);
        glVertex3f(0.0f,  0.0f,  0.0f);
        glVertex3f(0.0f,  0.05f, G_SQRT2);
        glVertex3f(0.0f, -0.05f, G_SQRT2);
        glVertex3f(0.0f,  0.0f,  0.0f);
    glEnd();

    glPopMatrix();
}

static void
gwy_3d_view_realize_gl(Gwy3DView *gwy3dview)
{
    GdkGLContext *glcontext;
    GdkGLDrawable *gldrawable;

    GLfloat ambient[] = { 0.1, 0.1, 0.1, 1.0 };
    GLfloat diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
    GLfloat position[] = { 0.0, 3.0, 3.0, 1.0 };

    GLfloat lmodel_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
    GLfloat local_view[] = { 0.0 } ;

    gwy_debug("GL capable %d", gtk_widget_is_gl_capable(GTK_WIDGET(gwy3dview)));

    glcontext = gtk_widget_get_gl_context(GTK_WIDGET(gwy3dview));
    gldrawable = gtk_widget_get_gl_drawable(GTK_WIDGET(gwy3dview));
    /*** OpenGL BEGIN ***/
    gwy_debug("drawable %p, context %p", gldrawable, glcontext);

    if (!gdk_gl_drawable_gl_begin(gldrawable, glcontext))
        return;

    glClearColor(1.0, 1.0, 1.0, 1.0);
    glClearDepth(1.0);

    glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
    glLightfv(GL_LIGHT0, GL_POSITION, position);
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
    glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view);

    glFrontFace(GL_CW);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_AUTO_NORMAL);
    glEnable(GL_NORMALIZE);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    /* Shape display lists */
    gwy_3d_view_assign_lists(gwy3dview);
    //gwy_3d_make_list(gwy3dview, gwy3dview->data_field, mask, gwy3dview->ovlays);
    GWY_3D_VIEW_GET_PRIVATE(gwy3dview)->need_update_list = TRUE;

    gdk_gl_drawable_gl_end(gldrawable);
    /*** OpenGL END ***/

    return;
}

static void
gwy_3d_set_projection(Gwy3DView *gwy3dview, GLfloat aspect)
{
    gwy_debug(" ");

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (aspect > 1) {
        switch (gwy3dview->setup->projection) {
            case GWY_3D_PROJECTION_ORTHOGRAPHIC:
            glOrtho(-aspect * GWY_3D_ORTHO_CORRECTION,
                     aspect * GWY_3D_ORTHO_CORRECTION,
                     -1.0   * GWY_3D_ORTHO_CORRECTION, /* * deformation_z*/
                      1.0   * GWY_3D_ORTHO_CORRECTION, /* * deformation_z*/
                      5.0,
                      60.0);
            break;

            case GWY_3D_PROJECTION_PERSPECTIVE:
            glFrustum(-aspect, aspect, -1.0, 1.0, 5.0, 60.0);
            break;
        }
    }
    else {
        aspect = 1.0/aspect;
        switch (gwy3dview->setup->projection) {
            case GWY_3D_PROJECTION_ORTHOGRAPHIC:
            glOrtho(-1.0   * GWY_3D_ORTHO_CORRECTION,
                     1.0   * GWY_3D_ORTHO_CORRECTION,
                    -aspect * GWY_3D_ORTHO_CORRECTION, /* * deformation_z*/
                     aspect * GWY_3D_ORTHO_CORRECTION, /* * deformation_z*/
                      5.0,
                      60.0);
            break;

            case GWY_3D_PROJECTION_PERSPECTIVE:
            glFrustum(-1.0, 1.0, -aspect, aspect, 5.0, 60.0);
            break;
        }
    }
    glMatrixMode(GL_MODELVIEW);
}

static PangoLayout*
gwy_3d_prepare_layout(cairo_t *cr, gdouble zoom)
{
    PangoFontDescription *fontdesc;
    PangoLayout *layout;

    layout = pango_cairo_create_layout(cr);
    fontdesc = pango_font_description_from_string("Arial 12");
    pango_font_description_set_size(fontdesc, GWY_ROUND(0.8*PANGO_SCALE*zoom));
    pango_layout_set_font_description(layout, fontdesc);
    pango_font_description_free(fontdesc);

    return layout;
}

static guchar*
gwy_3d_view_render_string(gdouble size,
                          const gchar *text,
                          gint *width,
                          gint *height,
                          gint *stride)
{
    PangoLayout *clayout;
    gint wstride;
    gint px, py;
    cairo_t *cr;
    cairo_surface_t *surface;
    guchar *alpha;

#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 6, 0)
    wstride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, 1);
#else
    wstride = sizeof(guint32);
#endif
    alpha = g_new(guchar, wstride);
    surface = cairo_image_surface_create_for_data(alpha, CAIRO_FORMAT_ARGB32,
                                                  1, 1, wstride);
    cr = cairo_create(surface);
    clayout = gwy_3d_prepare_layout(cr, size);

    cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
    pango_layout_set_markup(clayout, text, -1);
    pango_layout_get_pixel_size(clayout, &px, &py);
    *width = px;
    *height = py;
    px = uppow2(px);
    py = uppow2(py);

    g_free(alpha);
    cairo_destroy(cr);

#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 6, 0)
    wstride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, px);
#else
    wstride = ((4*px + sizeof(guint32)-1)/sizeof(guint32))*sizeof(guint32);
#endif
    alpha = g_new0(guchar, wstride*py);
    surface = cairo_image_surface_create_for_data(alpha, CAIRO_FORMAT_ARGB32,
                                                  px, py, wstride);
    cr = cairo_create(surface);
    cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
    pango_cairo_update_layout(cr, clayout);
    pango_layout_set_markup(clayout, text, -1);
    pango_cairo_show_layout(cr, clayout);

    gwy_debug("c-layout size: %d %d stride %d", *width, *height, wstride);
    *stride = wstride;

    g_object_unref(clayout);
    cairo_destroy(cr);
    cairo_surface_destroy(surface);

    return alpha;
}

/* image to opengl-texture */
static void
gwy_3d_cairo_to_tex(guchar *image,
                    gint width, gint height, gint stride)
{
    GLint w2 = uppow2(width), h2 = uppow2(height);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glPixelStorei(GL_UNPACK_ROW_LENGTH, stride/4);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w2, h2,
                 0, GL_BGRA, GL_UNSIGNED_BYTE, image);
}

/* puts textured rectangle t into view */
static void
gwy_3d_draw_ctex(GLuint t,
                 gint hjust, gint vjust,
                 gint width, gint height)
{
    GLfloat w2 = uppow2(width), h2 = uppow2(height);
    GLfloat wt = width/w2, ht = height/h2;
    GLfloat ho = -(hjust)*width/2;
    GLfloat vo = (int)(vjust-2)*height/2;

    glBindTexture(GL_TEXTURE_2D, t);

    glBegin(GL_QUADS);
    glTexCoord2f(0, ht);
    glVertex2f(ho, vo);

    glTexCoord2f(0, 0);
    glVertex2f(ho, vo+height);

    glTexCoord2f(wt, 0);
    glVertex2f(ho+width, vo+height);

    glTexCoord2f(wt, ht);
    glVertex2f(ho+width, vo);
    glEnd();

    glBindTexture(GL_TEXTURE_2D, 0);
}

/* draws text using a texture */
static void
gwy_3d_texture_text(Gwy3DView     *gwy3dview,
                    Gwy3DViewLabel id,
                    GLfloat        raster_x,
                    GLfloat        raster_y,
                    GLfloat        raster_z,
                    GLfloat        rot,
                    guint          size,
                    gint           hjustify,
                    gint           vjustify)
{
    GLuint tex = 0;
    Gwy3DLabel *label;
    gint width, height, stride, displacement_x, displacement_y;
    guchar *img;
    gchar *text;

    /* Render the label into an off-screen buffer */
    label = gwy3dview->labels[id];
    displacement_x = GWY_ROUND(label->delta_x);
    displacement_y = GWY_ROUND(label->delta_y);
    text = gwy_3d_label_expand_text(label, gwy3dview->variables);
    size = gwy_3d_label_user_size(label, size);

    img = gwy_3d_view_render_string(size, text, &width, &height, &stride);
    g_free(text);

    gwy_3d_cairo_to_tex(img, width, height, stride);
    glPushMatrix();
    glTranslatef(raster_x+displacement_x, raster_y+displacement_y, raster_z);
    glRotatef(rot*180.0/G_PI, 0, 0, 1);
    gwy_3d_draw_ctex(tex, hjustify, vjustify, width, height);
    glPopMatrix();

    g_free(img);
}

/* converts GwyGradient in gradient to cairo_pattern_t in pattern */
static void
gwy_gradient_to_cairo_pattern(cairo_pattern_t *pattern, GwyGradient *gradient)
{
    GwyGradientPoint gp;
    gint i = 0, npoints = gwy_gradient_get_npoints(gradient);
    for (i = 0; i < npoints; i++) {
        gp = gwy_gradient_get_point(gradient, i);
        cairo_pattern_add_color_stop_rgba(pattern, gp.x,
                                          gp.color.r, gp.color.g, gp.color.b,
                                          gp.color.a);
    }
}

/* puts string into PangoLayout, printf style */
static void
gwy_3d_format_layout(PangoLayout *layout,
                     GString *string,
                     const gchar *format,
                     ...)
{
    gchar *buffer;
    gint length;
    guint i;
    va_list args;

    g_string_truncate(string, 0);
    va_start(args, format);
    length = g_vasprintf(&buffer, format, args);
    va_end(args);
    g_string_append_len(string, buffer, length);
    g_free(buffer);

    /* Replace ASCII with proper minus */
    if (string->str[0] == '-') {
        /* Fix -0.0 */
        i = 1;
        while (string->str[i] == '0')
            i++;
        if (string->str[i] == '.' || string->str[i] == ',')
            i++;
        while (string->str[i] == '0')
            i++;

        if (i > 1 && (!string->str[i] || g_ascii_isspace(string->str[i]))) {
            g_string_erase(string, 0, 1);
        }
        else {
            g_string_erase(string, 0, 1);
            g_string_prepend_unichar(string, 0x2212);
        }
    }

    pango_layout_set_markup(layout, string->str, string->len);
}

/* auxilliary function to compute decimal points from tickdist */
static gint
gwy_3d_step_to_prec(gdouble d)
{
    gdouble resd = log10(7.5)-log10(d);
    if (resd != resd)
        return 1;
    if (resd > 1e20)
        return 1;
    if (resd < 1.0)
        resd = 1.0;
    return (gint) floor(resd);
}

/* prints layout onto cairo context, vertically centered */
static void
gwy_3d_pango_cairo_show_layout_vcentered(cairo_t *cr, PangoLayout *layout)
{
    int lw, lh;
    gdouble ch;
    pango_layout_get_size(layout, &lw, &lh);
    ch = (double)(lh)/PANGO_SCALE;
    cairo_rel_move_to(cr, 0, -ch/2.0);
    pango_cairo_show_layout(cr, layout);
}

/* init cario context */
static cairo_t*
gwy_cairo_create_cairo_context(gint width,
                               gint height,
                               cairo_surface_t **surf)
{
    cairo_t *cr;

    *surf = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
    cr = cairo_create(*surf);
    cairo_set_source_rgb(cr, 1, 1, 1);
    cairo_paint(cr);
    cairo_set_source_rgb(cr, 0, 0, 0);
    return cr;
}

/* renders false color bar into returned surface */
static cairo_surface_t*
gwy_3d_fmscaletex(gint height, gdouble bot, gdouble top,
                  gint fontsize, gdouble line_width,
                  GwySIUnit *siunit,
                  GwyGradient *gradient,
                  gboolean inverted,
                  gint *width,
                  gboolean noticks)
{
    PangoLayout *layout;
    cairo_t *cr;
    cairo_surface_t *surf;
    gdouble x_max;
    gdouble scale, x, m, tickdist, max;
    GwySIValueFormat *format;
    GString *s;
    gint tick, layw1, layw2, layh;
    gint units_width, label_height, mintickdist, prec = 1;
    G_GNUC_UNUSED gboolean do_draw = TRUE;
    gint size, fmw, l;
    cairo_pattern_t *pattern;
    gdouble zoom;

    s = g_string_new(NULL);
    cr = gwy_cairo_create_cairo_context(1, 1, &surf);
    layout = gwy_3d_prepare_layout(cr, fontsize);
    zoom = 0.8/12.0*(float)fontsize;

    x_max = MAX(fabs(bot), fabs(top));
    format = gwy_si_unit_get_format(siunit, GWY_SI_UNIT_FORMAT_VFMARKUP,
                                    x_max, NULL);
    gwy_3d_format_layout(layout, s, " %s", format->units);
    pango_layout_get_pixel_size(layout, &units_width, &label_height);
    size = height - label_height*2;
    mintickdist = label_height*1.5; /* mintickdist is in pixels; tickdist is in
                                     * meters or whichever basic unit */
    /* prec computation starts here */
    /* Don't attempt to draw anything if rounding errors are too large or
     * scale calculation can overflow */
    x = top - bot;
    max = MAX(fabs(bot),  fabs(top));
    if (x < 1e-15*max || x <= 1e4*G_MINDOUBLE || max >= 1e-4*G_MAXDOUBLE)
        do_draw = FALSE;
    scale = size/(top - bot);
    x = mintickdist/scale;
    m = pow10(floor(log10(x)));
    x /= m;
    if (x == 1.0)
        x = 1.0;
    else if (x <= 2.0)
        x = 2.0;
    else if (x <= 5.0)
        x = 5.0;
    else
        x = 10.0;
    tickdist = x*m;
    x = ceil(bot/tickdist)*tickdist;
    max = top - 0.999999*label_height/scale;
    prec = gwy_3d_step_to_prec(tickdist/format->magnitude);
    /* prec computation ends here */

    gwy_3d_format_layout(layout, s, "%.*f %s",
                         prec, top/format->magnitude, format->units);
    pango_layout_get_pixel_size(layout, &layw1, &layh);
    gwy_3d_format_layout(layout, s, "%.*f %s",
                         prec, bot/format->magnitude, format->units);
    pango_layout_get_pixel_size(layout, &layw2, &layh);

    l = MAX(layw1, layw2);
    tick = zoom*GWY_3D_TICK_LENGTH; /* physical tick length */
    fmw = 18*zoom;
    *width = fmw + 2*line_width + l + 2*zoom + tick + 2;

    cairo_surface_destroy(surf);
    cairo_destroy(cr);

    cr = gwy_cairo_create_cairo_context(uppow2(*width), uppow2(height), &surf);
    pango_cairo_update_layout(cr, layout);
    cairo_set_line_width(cr, line_width);

    gwy_3d_format_layout(layout, s, "%.*f", prec, bot/format->magnitude);

    cairo_translate(cr, fmw+2, height - label_height+0.5);
    cairo_move_to(cr, 0, 0);
    cairo_rel_line_to(cr, tick, 0);
    cairo_stroke(cr);
    cairo_move_to(cr, tick+2*zoom, 0);
    gwy_3d_pango_cairo_show_layout_vcentered(cr, layout);
    if (!noticks) {
        if ((x-bot)*scale < label_height) {
            x += tickdist;
            /* cairo_translate(cr, 0, -tickdist*scale); */
        }

        cairo_translate(cr, 0, -(x-bot)*scale);

        while (x <= max) {
            cairo_move_to(cr, 0, 0);
            cairo_rel_line_to(cr, tick, 0);
            cairo_stroke(cr);
            cairo_move_to(cr, tick+2*zoom, 0);
            gwy_3d_format_layout(layout, s, "%.*f",
                                 prec, x/format->magnitude);
            gwy_3d_pango_cairo_show_layout_vcentered(cr, layout);
            cairo_translate(cr, 0, -tickdist*scale);
            x += tickdist;
        }
    }

    cairo_identity_matrix(cr);
    cairo_translate(cr, fmw+2, label_height+0.5);
    cairo_move_to(cr, 0, 0);
    cairo_rel_line_to(cr, tick, 0);
    cairo_stroke(cr);
    cairo_move_to(cr, tick+2*zoom, 0);
    gwy_3d_format_layout(layout, s, "%.*f %s",
                  prec, top/format->magnitude, format->units);
    gwy_3d_pango_cairo_show_layout_vcentered(cr, layout);

    cairo_identity_matrix(cr);

    cairo_translate(cr, 1.5, label_height+0.5);
    if (inverted)
      pattern = cairo_pattern_create_linear(0, 0, 0, size);
    else
      pattern = cairo_pattern_create_linear(0, size, 0, 0);
    gwy_gradient_to_cairo_pattern(pattern, gradient);
    cairo_set_source(cr, pattern);
    cairo_rectangle(cr, 0, 0, fmw, size);
    cairo_fill(cr);
    cairo_pattern_destroy(pattern);

    cairo_set_source_rgb(cr, 0, 0, 0);
    cairo_rectangle(cr, 0, 0, fmw, size);
    cairo_stroke(cr);

    cairo_surface_flush(surf);

    gwy_si_unit_value_format_free(format);
    g_object_unref(layout);
    cairo_destroy(cr);
    g_string_free(s, TRUE);

    return surf;
}

/* draws a false color bar */
static gint
gwy_3d_draw_fmscaletex(Gwy3DView *view)
{
    gint height = GTK_WIDGET(view)->allocation.height;
    gint width = GTK_WIDGET(view)->allocation.width;
    gint fontsize = (gint)(sqrt(MIN(width, height))*0.8);
    gint reduced_height, actual_width, he;
    cairo_surface_t *surf;
    Gwy3DSetup *setup = view->setup;
    gdouble min, max;
    gboolean noticks;
    GwySIUnit *zunit;
    GwyLayerBasic *blayer;
    GwyDataField *dfield;

    /* XXX: This function requires view->ovlays[0] to be present.  Is is always
     * satisfied when we can get here?  */
    g_return_val_if_fail(view->ovlays[0], 0);

    reduced_height = GWY_ROUND(height * setup->fmscale_size);
    if (reduced_height < 12)
        return 0;

    glTranslatef(width, 0, 0);
    glColor3f(1.0, 1.0, 1.0);

    blayer = GWY_LAYER_BASIC(view->ovlays[0]);
    gwy_layer_basic_get_range(blayer, &min, &max);
    noticks = (gwy_layer_basic_get_range_type(blayer)
               == GWY_LAYER_BASIC_RANGE_ADAPT);

    dfield = GWY_DATA_FIELD(view->ovlays[0]->data_field);
    zunit = gwy_data_field_get_si_unit_z(dfield);
    surf = gwy_3d_fmscaletex(reduced_height, min, max,
                             fontsize, sqrt(setup->line_width),
                             zunit,
                             view->gradient,
                             FALSE,   /* FIXME: When it should be TRUE? */
                             &actual_width, noticks);

    gwy_3d_cairo_to_tex(cairo_image_surface_get_data(surf),
                        actual_width,
                        reduced_height,
                        cairo_image_surface_get_stride(surf));

    he = GWY_ROUND((1.0 - setup->fmscale_yalign) * (height - reduced_height));
    glTranslatef(0, he, 0);

    gwy_3d_draw_ctex(0, GWY_3D_JUST_RIGHT_EDGE, GWY_3D_JUST_BOTTOM_EDGE,
                     actual_width, reduced_height);
    cairo_surface_destroy(surf);

    return actual_width;
}

/**
 * gwy_3d_view_class_make_list_pool:
 * @klass: 3D view class.
 *
 * Allocates a pool of OpenGL lists to assign list numbers from.
 *
 * We are only able to get GLContext-unique list id's from glGenLists(),
 * but lists with the same id's seem to interfere across GLContexts.  See
 * bug #53 for more.
 *
 * We store the pool in bits of one 64bit integer.
 **/
static void
gwy_3d_view_class_make_list_pool(Gwy3DListPool *pool)
{
    guint try_size = 64;

    glGetError();
    while (try_size >= 1) {
        pool->base = glGenLists(GWY_3D_N_LISTS*try_size);
        if (!glGetError()) {
            gwy_debug("Allocated a pool with %u items (%u lists)",
                      try_size, GWY_3D_N_LISTS*try_size);
            pool->size = try_size;
            return;
        }
        try_size = (try_size*2)/3;
    }
    g_warning("Cannot get any OpenGL lists");
    pool->base = 0;
}

/**
 * gwy_3d_view_allocate_lists:
 * @gwy3dview: A 3D data view widget.
 *
 * Allocates a block of free OpenGL lists from pool for this 3D view to use.
 **/
static void
gwy_3d_view_assign_lists(Gwy3DView *gwy3dview)
{
    Gwy3DListPool *pool;
    guint64 b;
    guint i;

    pool = GWY_3D_VIEW_GET_CLASS(gwy3dview)->list_pool;
    if (!pool->size) {
        g_return_if_fail(GTK_WIDGET_REALIZED(gwy3dview));
        gwy_3d_view_class_make_list_pool(pool);
    }
    g_return_if_fail(pool->size > 0);

    b = 1;
    for (i = 0; i < pool->size && (pool->pool & b); i++)
        b <<= 1;
    if (i == pool->size) {
        g_critical("No more free OpenGL lists");
        return;
    }

    gwy_debug("Assigned list #%u", i);
    pool->pool |= b;
    gwy3dview->shape_list_base = pool->base + i*GWY_3D_N_LISTS;
}

/**
 * gwy_3d_view_release_lists:
 * @gwy3dview: A 3D data view widget.
 *
 * Release OpenGL lists in use by this 3D view back to the pool.
 **/
static void
gwy_3d_view_release_lists(Gwy3DView *gwy3dview)
{
    Gwy3DListPool *pool;
    guint i;
    guint64 b = 1;

    pool = GWY_3D_VIEW_GET_CLASS(gwy3dview)->list_pool;
    g_return_if_fail(gwy3dview->shape_list_base >= pool->base);

    i = (gwy3dview->shape_list_base - pool->base)/GWY_3D_N_LISTS;
    gwy_debug("Released list #%u", i);
    b <<= i;
    pool->pool &= ~b;
    gwy3dview->shape_list_base = 0;
}


/**
 * gwy_3d_view_set_mask_key:
 * @gwy3dview: A 3D data view widget.
 * @key: Container string key identifying the mask field for visualisation
 *
 * Sets the container key identifying the mask field for
 * visualisation in a 3D view.
 **/
void
gwy_3d_view_set_mask_key(Gwy3DView *gwy3dview,
                         const gchar *key)
{
    GQuark quark;
    Gwy3DViewPrivate *priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);

    g_return_if_fail(GWY_IS_3D_VIEW(gwy3dview));
    gwy_debug("%p <%s>", gwy3dview, key);

    quark = key ? g_quark_from_string(key) : 0;
    if (priv->mask_key == quark)
        return;

    GWY_SIGNAL_HANDLER_DISCONNECT(gwy3dview->data, priv->mask_item_id);
    gwy_3d_view_mask_field_disconnect(gwy3dview);
    priv->mask_key = quark;
    gwy_3d_view_mask_field_connect(gwy3dview);
    gwy_3d_view_container_connect(gwy3dview, g_quark_to_string(quark),
                                  &priv->mask_item_id,
                                  G_CALLBACK(gwy_3d_view_mask_item_changed));
    g_object_notify(G_OBJECT(gwy3dview), "mask-key");
    gwy_3d_view_mask_field_changed(gwy3dview);
}

/**
 * gwy_3d_view_get_mask_key:
 * @gwy3dview: A 3D data view widget.
 *
 * Gets the container key identifying the mask field for
 * visualisation in a 3D view.
 *
 * Returns: The string key, or %NULL if it isn't set.
 **/
const gchar*
gwy_3d_view_get_mask_key(Gwy3DView *gwy3dview)
{
    g_return_val_if_fail(GWY_IS_3D_VIEW(gwy3dview), NULL);
    return g_quark_to_string(GWY_3D_VIEW_GET_PRIVATE(gwy3dview)->mask_key);
}

static void
gwy_3d_view_mask_item_changed(Gwy3DView *gwy3dview)
{
    gwy_3d_view_mask_field_disconnect(gwy3dview);
    gwy_3d_view_mask_field_connect(gwy3dview);
    gwy_3d_view_mask_field_changed(gwy3dview);
}

static void
gwy_3d_view_mask_field_connect(Gwy3DView *gwy3dview)
{
    Gwy3DViewPrivate *priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);
    g_return_if_fail(!priv->mask_field);
    if (!priv->mask_key)
        return;

    if (!gwy_container_gis_object(gwy3dview->data, priv->mask_key,
                                  &priv->mask_field))
        return;

    g_object_ref(priv->mask_field);
    priv->mask_id
        = g_signal_connect_swapped(priv->mask_field,
                                   "data-changed",
                                   G_CALLBACK(gwy_3d_view_mask_field_changed),
                                   gwy3dview);
}

static void
gwy_3d_view_mask_field_disconnect(Gwy3DView *gwy3dview)
{
    Gwy3DViewPrivate *priv = GWY_3D_VIEW_GET_PRIVATE(gwy3dview);

    GWY_SIGNAL_HANDLER_DISCONNECT(priv->mask_field, priv->mask_id);
    GWY_OBJECT_UNREF(priv->mask_field);
}

static void
gwy_3d_view_mask_field_changed(Gwy3DView *gwy3dview)
{
    gwy_debug("");
    gwy3dview->changed |= GWY_3D_DATA_FIELD;
    gwy_3d_view_update_labels(gwy3dview);
    gwy_3d_view_update_lists(gwy3dview);
}

#else /* HAVE_GTKGLEXT */
/* Export the same set of symbols if we don't have OpenGL support.  But let
 * them all fail. */
static void
gwy_3d_view_init(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
}

static void
gwy_3d_view_class_init(G_GNUC_UNUSED Gwy3DViewClass *klass)
{
}

GtkWidget*
gwy_3d_view_new(G_GNUC_UNUSED GwyContainer *data)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

const gchar*
gwy_3d_view_get_setup_prefix(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

void
gwy_3d_view_set_setup_prefix(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                             G_GNUC_UNUSED const gchar *key)
{
    g_critical("OpenGL support was not compiled in.");
}

void
gwy_3d_view_set_ovlay(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                      G_GNUC_UNUSED GwyPixmapLayer** ovlays,
                      G_GNUC_UNUSED guint novlays)
{
    g_critical("OpenGL support was not compiled in.");
}

const gchar*
gwy_3d_view_get_data_key(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

void
gwy_3d_view_set_data_key(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                         G_GNUC_UNUSED const gchar *key)
{
    g_critical("OpenGL support was not compiled in.");
}

const gchar*
gwy_3d_view_get_mask_key(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

void
gwy_3d_view_set_mask_key(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                         G_GNUC_UNUSED const gchar *key)
{
    g_critical("OpenGL support was not compiled in.");
}

const gchar*
gwy_3d_view_get_gradient_key(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

void
gwy_3d_view_set_gradient_key(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                             G_GNUC_UNUSED const gchar *key)
{
    g_critical("OpenGL support was not compiled in.");
}

const gchar*
gwy_3d_view_get_material_key(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

void
gwy_3d_view_set_material_key(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                             G_GNUC_UNUSED const gchar *key)
{
    g_critical("OpenGL support was not compiled in.");
}

guint
gwy_3d_view_get_reduced_size(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return 0;
}

void
gwy_3d_view_set_reduced_size(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                             G_GNUC_UNUSED guint reduced_size)
{
    g_critical("OpenGL support was not compiled in.");
}

Gwy3DMovement
gwy_3d_view_get_movement_type(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return 0;
}

void
gwy_3d_view_set_movement_type(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                              G_GNUC_UNUSED Gwy3DMovement movement)
{
    g_critical("OpenGL support was not compiled in.");
}

GdkPixbuf*
gwy_3d_view_get_pixbuf(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

GdkPixbuf*
gwy_3d_view_get_pixbuf_with_alpha(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

Gwy3DLabel*
gwy_3d_view_get_label(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                      G_GNUC_UNUSED Gwy3DViewLabel label)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

Gwy3DSetup*
gwy_3d_view_get_setup(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

GwyContainer*
gwy_3d_view_get_data(G_GNUC_UNUSED Gwy3DView *gwy3dview)
{
    g_critical("OpenGL support was not compiled in.");
    return NULL;
}

void
gwy_3d_view_get_scale_range(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                            G_GNUC_UNUSED gdouble *min_scale,
                            G_GNUC_UNUSED gdouble *max_scale)
{
    g_critical("OpenGL support was not compiled in.");
}

void
gwy_3d_view_set_scale_range(G_GNUC_UNUSED Gwy3DView *gwy3dview,
                            G_GNUC_UNUSED gdouble min_scale,
                            G_GNUC_UNUSED gdouble max_scale)
{
    g_critical("OpenGL support was not compiled in.");
}
#endif /* HAVE_GTKGLEXT */

/**
 * gwy_3d_view_class_disable_axis_drawing:
 * @disable: %TRUE to disable 3D view axes globally, %FALSE to enable them.
 *
 * Globally disables drawing of 3D view axes.
 *
 * If axis drawing is disabled, axes are never drawn.  If it is not disabled,
 * their rendering depends on the 3D view setup.
 *
 * This function is a hack and exists to work around various GL implementations
 * that crash on pixmap drawing operations.
 *
 * Since: 2.14
 **/
void
gwy_3d_view_class_disable_axis_drawing(gboolean disable)
{
    ugly_hack_globally_disable_axis_drawing = disable;
}

/************************** Documentation ****************************/

/**
 * SECTION:gwy3dview
 * @title: Gwy3DView
 * @short_description: OpenGL 3D data display
 * @see_also: #Gwy3DWindow -- window combining 3D view with controls,
 *            #GwyGLMaterial -- OpenGL materials,
 *            #Gwy3DLabel -- Labels on 3D view,
 *            #Gwy3DSetup -- 3D scene setup
 *
 * #Gwy3DView displays a data field as a threedimensional heightfield using
 * OpenGL. You can create a new 3D view for a data container with
 * gwy_3d_view_new().  By default, it inherits properties like palette from
 * <link linkend="GwyDataView">data view</link> settings, but supports separate
 * settings -- see gwy_3d_view_set_gradient_key() et al.
 *
 * #Gwy3DView allows the user to interactively rotate, scale, z-scale the data
 * or move lights, depending on its <link linkend="Gwy3DMovement">movement
 * state</link>. There are no controls provided for mode change, you have to
 * provide some yourself and set the movement mode with
 * gwy_3d_view_set_movement_type().
 *
 * You have initialize GtkGLExt with gtk_gl_init_check() and then Gwyddion's
 * OpenGL with gwy_widgets_gl_init() before you can use #Gwy3DView.  These
 * functions may not always succeed, see their description for more.  If
 * OpenGL initialization fails (possibly because its support was not compiled
 * in) #Gwy3DView cannot be even instantiated.
 **/

/* vim: set cin et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */