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
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
|
/*
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
*/
package javax.media.j3d;
import java.awt.AWTEvent;
import java.awt.Canvas;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.IllegalComponentStateException;
import java.awt.Point;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import javax.vecmath.Color3f;
import javax.vecmath.Point2d;
import javax.vecmath.Point3d;
import javax.vecmath.Vector4d;
/**
* The Canvas3D class provides a drawing canvas for 3D rendering. It
* is used either for on-screen rendering or off-screen rendering.
* Canvas3D is an extension of the AWT Canvas class that users may
* further subclass to implement additional functionality.
* <p>
* The Canvas3D object extends the Canvas object to include
* 3D-related information such as the size of the canvas in pixels,
* the Canvas3D's location, also in pixels, within a Screen3D object,
* and whether or not the canvas has stereo enabled.
* <p>
* Because all Canvas3D objects contain a
* reference to a Screen3D object and because Screen3D objects define
* the size of a pixel in physical units, Java 3D can convert a Canvas3D
* size in pixels to a physical world size in meters. It can also
* determine the Canvas3D's position and orientation in the
* physical world.
* <p>
* <b>On-screen Rendering vs. Off-screen Rendering</b>
* <p>
* The Canvas3D class is used either for on-screen rendering or
* off-screen rendering.
* On-screen Canvas3Ds are added to AWT or Swing Container objects
* like any other canvas. Java 3D automatically and continuously
* renders to all on-screen canvases that are attached to an active
* View object. On-screen Canvas3Ds can be either single or double
* buffered and they can be either stereo or monoscopic.
* <p>
* Off-screen Canvas3Ds must not be added to any Container. Java 3D
* renders to off-screen canvases in response to the
* <code>renderOffScreenBuffer</code> method. Off-screen Canvas3Ds
* are single buffered. However, on many systems, the actual
* rendering is done to an off-screen hardware buffer or to a 3D
* library-specific buffer and only copied to the off-screen buffer of
* the Canvas when the rendering is complete, at "buffer swap" time.
* Off-screen Canvas3Ds are monoscopic.
* <p>
* The setOffScreenBuffer method sets the off-screen buffer for this
* Canvas3D. The specified image is written into by the Java 3D renderer.
* The size of the specified ImageComponent determines the size, in
* pixels, of this Canvas3D - the size inherited from Component is
* ignored. Note that the size, physical width, and physical height of the
* associated Screen3D must be set
* explicitly prior to rendering. Failure to do so will result in an
* exception.
* <p>
* The getOffScreenBuffer method retrieves the off-screen
* buffer for this Canvas3D.
* <p>
* The renderOffScreenBuffer method schedules the rendering of a frame
* into this Canvas3D's off-screen buffer. The rendering is done from
* the point of view of the View object to which this Canvas3D has been
* added. No rendering is performed if this Canvas3D object has not been
* added to an active View. This method does not wait for the rendering
* to actually happen. An application that wishes to know when the
* rendering is complete must either subclass Canvas3D and
* override the postSwap method, or call waitForOffScreenRendering.
* <p>
* The setOfScreenLocation methods set the location of this off-screen
* Canvas3D. The location is the upper-left corner of the Canvas3D
* relative to the upper-left corner of the corresponding off-screen
* Screen3D. The function of these methods is similar to that of
* Component.setLocation for on-screen Canvas3D objects. The default
* location is (0,0).
* <p>
* <b>Accessing and Modifying an Eye's Image Plate Position</b>
* <p>
* A Canvas3D object provides sophisticated applications with access
* to the eye's position information in head-tracked, room-mounted
* runtime environments. It also allows applications to manipulate
* the position of an eye relative to an image plate in non-head-tracked
* runtime environments.
* <p>
* The setLeftManualEyeInImagePlate and setRightManualEyeInImagePlate
* methods set the position of the manual left and right eyes in image
* plate coordinates. These values determine eye placement when a head
* tracker is not in use and the application is directly controlling the
* eye position in image plate coordinates. In head-tracked mode or
* when the windowEyepointPolicy is RELATIVE_TO_FIELD_OF_VIEW or
* RELATIVE_TO_COEXISTENCE, this
* value is ignored. When the windowEyepointPolicy is RELATIVE_TO_WINDOW,
* only the Z value is used.
* <p>
* The getLeftEyeInImagePlate, getRightEyeInImagePlate, and
* getCenterEyeInImagePlate methods retrieve the actual position of the
* left eye, right eye, and center eye in image plate coordinates and
* copy that value into the object provided. The center eye is the
* fictional eye half-way between the left and right eye. These three
* values are a function of the windowEyepointPolicy, the tracking
* enable flag, and the manual left, right, and center eye positions.
* <p>
* <b>Monoscopic View Policy</b>
* <p>
* The setMonoscopicViewPolicy and getMonoscopicViewPolicy methods
* set and retrieve the policy regarding how Java 3D generates monoscopic
* view. If the policy is set to View.LEFT_EYE_VIEW, the view generated
* corresponds to the view as seen from the left eye. If set to
* View.RIGHT_EYE_VIEW, the view generated corresponds to the view as
* seen from the right eye. If set to View.CYCLOPEAN_EYE_VIEW, the view
* generated corresponds to the view as seen from the "center eye," the
* fictional eye half-way between the left and right eye. The default
* monoscopic view policy is View.CYCLOPEAN_EYE_VIEW.
* <p>
* <b>Immediate Mode Rendering</b>
* <p>
* Pure immediate-mode rendering provides for those applications and
* applets that do not want Java 3D to do any automatic rendering of
* the scene graph. Such applications may not even wish to build a
* scene graph to represent their graphical data. However, they use
* Java 3D's attribute objects to set graphics state and Java 3D's
* geometric objects to render geometry.
* <p>
* A pure immediate mode application must create a minimal set of
* Java 3D objects before rendering. In addition to a Canvas3D object,
* the application must create a View object, with its associated
* PhysicalBody and PhysicalEnvironment objects, and the following
* scene graph elements: a VirtualUniverse object, a high-resolution
* Locale object, a BranchGroup node object, a TransformGroup node
* object with associated transform, and a ViewPlatform
* leaf node object that defines the position and orientation within
* the virtual universe that generates the view.
* <p>
* In immediate mode, all rendering is done completely under user
* control. It is necessary for the user to clear the 3D canvas,
* render all geometry, and swap the buffers. Additionally,
* rendering the right and left eye for stereo viewing becomes the
* sole responsibility of the application. In pure immediate mode,
* the user must stop the Java 3D renderer, via the
* Canvas3D object <code>stopRenderer</code> method, prior to adding the
* Canvas3D object to an active View object (that is, one that is
* attached to a live ViewPlatform object).
* <p>
* Other Canvas3D methods related to immediate mode rendering are:
* <p>
* <ul>
* <code>getGraphicsContext3D</code> retrieves the immediate-mode
* 3D graphics context associated with this Canvas3D. It creates a
* new graphics context if one does not already exist.
* <p>
* <code>getGraphics2D</code> retrieves the
* 2D graphics object associated with this Canvas3D. It creates a
* new 2D graphics object if one does not already exist.
* <p>
* <code>swap</code> synchronizes and swaps buffers on a
* double-buffered canvas for this Canvas3D object. This method
* should only be called if the Java 3D renderer has been stopped.
* In the normal case, the renderer automatically swaps
* the buffer.
* </ul>
*
* <p>
* <b>Mixed Mode Rendering</b>
* <p>
* Mixing immediate mode and retained or compiled-retained mode
* requires more structure than pure immediate mode. In mixed mode,
* the Java 3D renderer is running continuously, rendering the scene
* graph into the canvas.
*
* <p>
* Canvas3D methods related to mixed mode rendering are:
*
* <p>
* <ul>
* <code>preRender</code> called by the Java 3D rendering loop after
* clearing the canvas and before any rendering has been done for
* this frame.
* <p>
* <code>postRender</code> called by the Java 3D rendering loop after
* completing all rendering to the canvas for this frame and before
* the buffer swap.
* <p>
* <code>postSwap</code> called by the Java 3D rendering loop after
* completing all rendering to the canvas, and all other canvases
* associated with this view, for this frame following the
* buffer swap.
* <p>
* <code>renderField</code> called by the Java 3D rendering loop
* during the execution of the rendering loop. It is called once
* for each field (i.e., once per frame on a mono system or once
* each for the right eye and left eye on a two-pass stereo system.
* </ul>
* <p>
* The above callback methods are called by the Java 3D rendering system
* and should <i>not</i> be called by an application directly.
*
* <p>
* The basic Java 3D <i>stereo</i> rendering loop,
* executed for each Canvas3D, is as follows:
* <ul><pre>
* clear canvas (both eyes)
* call preRender() // user-supplied method
* set left eye view
* render opaque scene graph objects
* call renderField(FIELD_LEFT) // user-supplied method
* render transparent scene graph objects
* set right eye view
* render opaque scene graph objects again
* call renderField(FIELD_RIGHT) // user-supplied method
* render transparent scene graph objects again
* call postRender() // user-supplied method
* synchronize and swap buffers
* call postSwap() // user-supplied method
* </pre></ul>
* <p>
* The basic Java 3D <i>monoscopic</i> rendering loop is as follows:
* <ul><pre>
* clear canvas
* call preRender() // user-supplied method
* set view
* render opaque scene graph objects
* call renderField(FIELD_ALL) // user-supplied method
* render transparent scene graph objects
* call postRender() // user-supplied method
* synchronize and swap buffers
* call postSwap() // user-supplied method
* </pre></ul>
* <p>
* In both cases, the entire loop, beginning with clearing the canvas
* and ending with swapping the buffers, defines a frame. The application
* is given the opportunity to render immediate-mode geometry at any of
* the clearly identified spots in the rendering loop. A user specifies
* his or her own rendering methods by extending the Canvas3D class and
* overriding the preRender, postRender, postSwap, and/or renderField
* methods.
* Updates to live Geometry, Texture, and ImageComponent objects
* in the scene graph are not allowed from any of these callback
* methods.
*
* <p>
* <b>Serialization</b>
* <p>
* Canvas3D does <i>not</i> support serialization. An attempt to
* serialize a Canvas3D object will result in an
* UnsupportedOperationException being thrown.
*
* <p>
* <b>Additional Information</b>
* <p>
* For more information, see the
* <a href="doc-files/intro.html">Introduction to the Java 3D API</a> and
* <a href="doc-files/ViewModel.html">View Model</a>
* documents.
*
* @see Screen3D
* @see View
* @see GraphicsContext3D
*/
public class Canvas3D extends Canvas {
/**
* Specifies the left field of a field-sequential stereo rendering loop.
* A left field always precedes a right field.
*/
public static final int FIELD_LEFT = 0;
/**
* Specifies the right field of a field-sequential stereo rendering loop.
* A right field always follows a left field.
*/
public static final int FIELD_RIGHT = 1;
/**
* Specifies a single-field rendering loop.
*/
public static final int FIELD_ALL = 2;
//
// The following constants are bit masks to specify which of the node
// components are dirty and need updates.
//
// Values for the geometryType field.
static final int POLYGONATTRS_DIRTY = 0x01;
static final int LINEATTRS_DIRTY = 0x02;
static final int POINTATTRS_DIRTY = 0x04;
static final int MATERIAL_DIRTY = 0x08;
static final int TRANSPARENCYATTRS_DIRTY = 0x10;
static final int COLORINGATTRS_DIRTY = 0x20;
// Values for lightbin, env set, texture, texture setting etc.
static final int LIGHTBIN_DIRTY = 0x40;
static final int LIGHTENABLES_DIRTY = 0x80;
static final int AMBIENTLIGHT_DIRTY = 0x100;
static final int ATTRIBUTEBIN_DIRTY = 0x200;
static final int TEXTUREBIN_DIRTY = 0x400;
static final int TEXTUREATTRIBUTES_DIRTY = 0x800;
static final int RENDERMOLECULE_DIRTY = 0x1000;
static final int FOG_DIRTY = 0x2000;
static final int MODELCLIP_DIRTY = 0x4000;
static final int VIEW_MATRIX_DIRTY = 0x8000;
// static final int SHADER_DIRTY = 0x10000; Not ready for this yet -- JADA
//
// Flag that indicates whether this Canvas3D is an off-screen Canvas3D
//
boolean offScreen = false;
//
// Issue 131: Flag that indicates whether this Canvas3D is a manually
// rendered Canvas3D (versus an automatically rendered Canvas3D).
//
// NOTE: manualRendering only applies to off-screen Canvas3Ds at this time.
// We have no plans to ever change this, but if we do, it might be necessary
// to determine which, if any, of the uses of "manualRendering" should be
// changed to "manualRendering&&offScreen"
//
boolean manualRendering = false;
// user specified offScreen Canvas location
Point offScreenCanvasLoc;
// user specified offScreen Canvas dimension
Dimension offScreenCanvasSize;
//
// Flag that indicates whether off-screen rendering is in progress or not
//
volatile boolean offScreenRendering = false;
//
// Flag that indicates we are waiting for an off-screen buffer to be
// created or destroyed by the Renderer.
//
volatile boolean offScreenBufferPending = false;
//
// ImageComponent used for off-screen rendering
//
ImageComponent2D offScreenBuffer = null;
// flag that indicates whether this canvas will use shared context
boolean useSharedCtx = true;
//
// Read-only flag that indicates whether stereo is supported for this
// canvas. This is always false for off-screen canvases.
//
boolean stereoAvailable;
//
// Flag to enable stereo rendering, if allowed by the
// stereoAvailable flag.
//
boolean stereoEnable = true;
//
// This flag is set when stereo mode is both enabled and
// available. Code that looks at stereo mode should use this
// flag.
//
boolean useStereo;
// Indicate whether it is left or right stereo pass currently
boolean rightStereoPass = false;
//
// Specifies how Java 3D generates monoscopic view
// (LEFT_EYE_VIEW, RIGHT_EYE_VIEW, or CYCLOPEAN_EYE_VIEW).
//
int monoscopicViewPolicy = View.CYCLOPEAN_EYE_VIEW;
// User requested stencil size
int requestedStencilSize;
// Actual stencil size return for this canvas
int actualStencilSize;
// True if stencil buffer is available for user
boolean userStencilAvailable;
// True if stencil buffer is available for system ( decal )
boolean systemStencilAvailable;
//
// Read-only flag that indicates whether double buffering is supported
// for this canvas. This is always false for off-screen canvases.
//
boolean doubleBufferAvailable;
//
// Flag to enable double buffered rendering, if allowed by the
// doubleBufferAvailable flag.
//
boolean doubleBufferEnable = true;
//
// This flag is set when doubleBuffering is both enabled and
// available Code that enables or disables double buffering should
// use this flag.
//
boolean useDoubleBuffer;
//
// Read-only flag that indicates whether scene antialiasing
// is supported for this canvas.
//
boolean sceneAntialiasingAvailable;
boolean sceneAntialiasingMultiSamplesAvailable;
// Use to see whether antialiasing is already set
private boolean antialiasingSet = false;
//
// Read-only flag that indicates the size of the texture color
// table for this canvas. A value of 0 indicates that the texture
// color table is not supported.
//
int textureColorTableSize;
// number of active/enabled texture unit
int numActiveTexUnit = 0;
// index iof last enabled texture unit
int lastActiveTexUnit = -1;
// True if shadingLanguage is supported, otherwise false.
boolean shadingLanguageGLSL = false;
// Query properties
J3dQueryProps queryProps;
// Flag indicating a fatal rendering error of some sort
private boolean fatalError = false;
//
// The positions of the manual left and right eyes in image-plate
// coordinates.
// By default, we will use the center of the screen for X and Y values
// (X values are adjusted for default eye separation), and
// 0.4572 meters (18 inches) for the Z value.
// These match defaults elsewhere in the system.
//
Point3d leftManualEyeInImagePlate = new Point3d(0.142, 0.135, 0.4572);
Point3d rightManualEyeInImagePlate = new Point3d(0.208, 0.135, 0.4572);
//
// View that is attached to this Canvas3D.
//
View view = null;
// View waiting to be set
View pendingView;
//
// View cache for this canvas and its associated view.
//
CanvasViewCache canvasViewCache = null;
// Issue 109: View cache for this canvas, for computing view frustum planes
CanvasViewCache canvasViewCacheFrustum = null;
// Since multiple renderAtomListInfo, share the same vecBounds
// we want to do the intersection test only once per renderAtom
// this flag is set to true after the first intersect and set to
// false during checkForCompaction in renderBin
boolean raIsVisible = false;
RenderAtom ra = null;
// Stereo related field has changed.
static final int STEREO_DIRTY = 0x01;
// MonoscopicViewPolicy field has changed.
static final int MONOSCOPIC_VIEW_POLICY_DIRTY = 0x02;
// Left/right eye in image plate field has changed.
static final int EYE_IN_IMAGE_PLATE_DIRTY = 0x04;
// Canvas has moved/resized.
static final int MOVED_OR_RESIZED_DIRTY = 0x08;
// Canvas Background changed (this may affect doInfinite flag)
static final int BACKGROUND_DIRTY = 0x10;
// Canvas Background Image changed
static final int BACKGROUND_IMAGE_DIRTY = 0x20;
// Mask that indicates this Canvas view dependence info. has changed,
// and CanvasViewCache may need to recompute the final view matries.
static final int VIEW_INFO_DIRTY = (STEREO_DIRTY |
MONOSCOPIC_VIEW_POLICY_DIRTY |
EYE_IN_IMAGE_PLATE_DIRTY |
MOVED_OR_RESIZED_DIRTY |
BACKGROUND_DIRTY |
BACKGROUND_IMAGE_DIRTY);
// Issue 163: Array of dirty bits is used because the Renderer and
// RenderBin run asynchronously. Now that they each have a separate
// instance of CanvasViewCache (due to the fix for Issue 109), they
// need separate dirty bits. Array element 0 is used for the Renderer and
// element 1 is used for the RenderBin.
static final int RENDERER_DIRTY_IDX = 0;
static final int RENDER_BIN_DIRTY_IDX = 1;
int[] cvDirtyMask = new int[2];
// This boolean informs the J3DGraphics2DImpl that the window is resized
boolean resizeGraphics2D = true;
//
// This boolean allows an application to start and stop the render
// loop on this canvas.
//
volatile boolean isRunning = true;
// This is used by MasterControl only. MC relay on this in a
// single loop to set renderer thread. During this time,
// the isRunningStatus can't change by user thread.
volatile boolean isRunningStatus = true;
// This is true when the canvas is ready to be rendered into
boolean active = false;
// This is true when the canvas is visible
boolean visible = false;
// This is true if context need to recreate
boolean ctxReset = true;
// The Screen3D that corresponds to this Canvas3D
Screen3D screen = null;
// Flag to indicate that image is render completely
// so swap is valid.
boolean imageReady = false;
// The 3D Graphics context used for immediate mode rendering
// into this canvas.
GraphicsContext3D graphicsContext3D = null;
boolean waiting = false;
boolean swapDone = false;
GraphicsConfiguration graphicsConfiguration;
// The Java 3D Graphics2D object used for Java2D/AWT rendering
// into this Canvas3D
J3DGraphics2DImpl graphics2D = null;
// Lock used to synchronize the creation of the 2D and 3D
// graphics context objects
Object gfxCreationLock = new Object();
// The source of the currently loaded localToVWorld for this Canvas3D
// (used to only update the model matrix when it changes)
// Transform3D localToVWorldSrc = null;
// The current vworldToEc Transform
Transform3D vworldToEc = new Transform3D();
// The view transform (VPC to EC) for the current eye.
// NOTE that this is *read-only*
Transform3D vpcToEc;
// Opaque object representing the underlying drawable (window). This
// is defined by the Pipeline.
Drawable drawable = null;
// graphicsConfigTable is a static hashtable which allows getBestConfiguration()
// in NativeConfigTemplate3D to map a GraphicsConfiguration to the pointer
// to the actual GLXFBConfig that glXChooseFBConfig() returns. The Canvas3D
// doesn't exist at the time getBestConfiguration() is called, and
// X11GraphicsConfig neither maintains this pointer nor provides a public
// constructor to allow Java 3D to extend it.
static Hashtable<GraphicsConfiguration,GraphicsConfigInfo> graphicsConfigTable =
new Hashtable<GraphicsConfiguration,GraphicsConfigInfo>();
// The native graphics version, vendor, and renderer information
String nativeGraphicsVersion = "<UNKNOWN>";
String nativeGraphicsVendor = "<UNKNOWN>";
String nativeGraphicsRenderer = "<UNKNOWN>";
boolean firstPaintCalled = false;
// This reflects whether or not this canvas has seen an addNotify. It is
// forced to true for off-screen canvases
boolean added = false;
// Flag indicating whether addNotify has been called (so we don't process it twice).
private boolean addNotifyCalled = false;
// This is the id for the underlying graphics context structure.
Context ctx = null;
// since the ctx id can be the same as the previous one,
// we need to keep a time stamp to differentiate the contexts with the
// same id
volatile long ctxTimeStamp = 0;
// The current context setting for local eye lighting
boolean ctxEyeLightingEnable = false;
// This AppearanceRetained Object refelects the current state of this
// canvas. It is used to optimize setting of attributes at render time.
AppearanceRetained currentAppear = new AppearanceRetained();
// This MaterialRetained Object refelects the current state of this canvas.
// It is used to optimize setting of attributes at render time.
MaterialRetained currentMaterial = new MaterialRetained();
/**
* The object used for View Frustum Culling
*/
CachedFrustum viewFrustum = new CachedFrustum();
/**
* The RenderBin bundle references used to decide what the underlying
* context contains.
*/
LightBin lightBin = null;
EnvironmentSet environmentSet = null;
AttributeBin attributeBin = null;
ShaderBin shaderBin = null;
RenderMolecule renderMolecule = null;
PolygonAttributesRetained polygonAttributes = null;
LineAttributesRetained lineAttributes = null;
PointAttributesRetained pointAttributes = null;
MaterialRetained material = null;
boolean enableLighting = false;
TransparencyAttributesRetained transparency = null;
ColoringAttributesRetained coloringAttributes = null;
Transform3D modelMatrix = null;
Transform3D projTrans = null;
TextureBin textureBin = null;
/**
* cached RenderBin states for lazy native states update
*/
LightRetained lights[] = null;
int frameCount[] = null;
long enableMask = -1;
FogRetained fog = null;
ModelClipRetained modelClip = null;
Color3f sceneAmbient = new Color3f();
TextureUnitStateRetained[] texUnitState = null;
/**
* These cached values are only used in Pure Immediate and Mixed Mode rendering
*/
TextureRetained texture = null;
TextureAttributesRetained texAttrs = null;
TexCoordGenerationRetained texCoordGeneration = null;
RenderingAttributesRetained renderingAttrs = null;
AppearanceRetained appearance = null;
ShaderProgramRetained shaderProgram = null;
// only used in Mixed Mode rendering
Object appHandle = null;
/**
* Dirty bit to determine if the NodeComponent needs to be re-sent
* down to the underlying API
*/
int canvasDirty = 0xffff;
// True when either one of dirtyRenderMoleculeList,
// dirtyDlistPerRinfoList, dirtyRenderAtomList size > 0
boolean dirtyDisplayList = false;
ArrayList<RenderMolecule> dirtyRenderMoleculeList = new ArrayList<RenderMolecule>();
ArrayList<RenderAtomListInfo> dirtyRenderAtomList = new ArrayList<RenderAtomListInfo>();
// List of (Rm, rInfo) pair of individual dlists that need to be rebuilt
ArrayList<Object[]> dirtyDlistPerRinfoList = new ArrayList<Object[]>();
ArrayList<Integer> displayListResourceFreeList = new ArrayList<Integer>();
ArrayList<Integer> textureIdResourceFreeList = new ArrayList<Integer>();
// an unique bit to identify this canvas
int canvasBit = 0;
// an unique number to identify this canvas : ( canvasBit = 1 << canvasId)
int canvasId = 0;
// Indicates whether the canvasId has been allocated
private boolean canvasIdAlloc = false;
// Avoid using this as lock, it cause deadlock
Object cvLock = new Object();
Object evaluateLock = new Object();
Object dirtyMaskLock = new Object();
// For D3D, instead of using the same variable in Renderer,
// each canvas has to build its own displayList.
boolean needToRebuildDisplayList = false;
// Read-only flag that indicates whether the following texture features
// are supported for this canvas.
static final int TEXTURE_3D = 0x0001;
static final int TEXTURE_COLOR_TABLE = 0x0002;
static final int TEXTURE_MULTI_TEXTURE = 0x0004;
static final int TEXTURE_COMBINE = 0x0008;
static final int TEXTURE_COMBINE_DOT3 = 0x0010;
static final int TEXTURE_COMBINE_SUBTRACT = 0x0020;
static final int TEXTURE_REGISTER_COMBINERS = 0x0040;
static final int TEXTURE_CUBE_MAP = 0x0080;
static final int TEXTURE_SHARPEN = 0x0100;
static final int TEXTURE_DETAIL = 0x0200;
static final int TEXTURE_FILTER4 = 0x0400;
static final int TEXTURE_ANISOTROPIC_FILTER = 0x0800;
static final int TEXTURE_LOD_RANGE = 0x1000;
static final int TEXTURE_LOD_OFFSET = 0x2000;
// Use by D3D to indicate using one pass Blend mode
// if Texture interpolation mode is support.
static final int TEXTURE_LERP = 0x4000;
static final int TEXTURE_NON_POWER_OF_TWO = 0x8000;
static final int TEXTURE_AUTO_MIPMAP_GENERATION = 0x10000;
int textureExtendedFeatures = 0;
// Extensions supported by the underlying canvas
//
// NOTE: we should remove EXT_BGR and EXT_ABGR when the imaging code is
// rewritten
// killed global alpha
//static final int SUN_GLOBAL_ALPHA = 0x1;
static final int EXT_ABGR = 0x2;
static final int EXT_BGR = 0x4;
static final int MULTISAMPLE = 0x8;
// The following 10 variables are set by the native
// createNewContext()/createQueryContext() methods
// Supported Extensions
int extensionsSupported = 0;
// Anisotropic Filter degree
float anisotropicDegreeMax = 1.0f;
// Texture Boundary Width Max
int textureBoundaryWidthMax = 0;
boolean multiTexAccelerated = false;
// Max number of texture coordinate sets
int maxTexCoordSets = 1;
// Max number of fixed-function texture units
int maxTextureUnits = 1;
// Max number of fragment shader texture units
int maxTextureImageUnits = 0;
// Max number of vertex shader texture units
int maxVertexTextureImageUnits = 0;
// Max number of combined shader texture units
int maxCombinedTextureImageUnits = 0;
// Max number of vertex attrs (not counting coord, etc.)
int maxVertexAttrs = 0;
// End of variables set by createNewContext()/createQueryContext()
// The total available number of texture units used by either the
// fixed-function or programmable shader pipeline.
// This is computed as: max(maxTextureUnits, maxTextureImageUnits)
int maxAvailableTextureUnits;
// Texture Width, Height Max
int textureWidthMax = 0;
int textureHeightMax = 0;
// Texture3D Width, Heigh, Depth Max
int texture3DWidthMax = -1;
int texture3DHeightMax = -1;
int texture3DDepthMax = -1;
// Cached position & size for CanvasViewCache.
// We don't want to call canvas.getxx method in Renderer
// since it will cause deadlock as removeNotify() need to get
// component lock of Canvas also and need to wait Renderer to
// finish before continue. So we invoke the method now in
// CanvasViewEventCatcher.
Point newPosition = new Point();
Dimension newSize = new Dimension();
// Remember OGL context resources to free
// before context is destroy.
// It is used when sharedCtx = false;
ArrayList<TextureRetained> textureIDResourceTable = new ArrayList<TextureRetained>(5);
// The following variables are used by the lazy download of
// states code to keep track of the set of current to be update bins
static final int LIGHTBIN_BIT = 0x0;
static final int ENVIRONMENTSET_BIT = 0x1;
static final int ATTRIBUTEBIN_BIT = 0x2;
static final int TEXTUREBIN_BIT = 0x3;
static final int RENDERMOLECULE_BIT = 0x4;
static final int TRANSPARENCY_BIT = 0x5;
static final int SHADERBIN_BIT = 0x6;
// bitmask to specify if the corresponding "bin" needs to be updated
int stateUpdateMask = 0;
// the set of current "bins" that is to be updated, the stateUpdateMask
// specifies if each bin in this set is updated or not.
Object curStateToUpdate[] = new Object[7];
/**
* The list of lights that are currently being represented in the native
* graphics context.
*/
LightRetained[] currentLights = null;
/**
* Flag to override RenderAttributes.depthBufferWriteEnable
*/
boolean depthBufferWriteEnableOverride = false;
/**
* Flag to override RenderAttributes.depthBufferEnable
*/
boolean depthBufferEnableOverride = false;
// current state of depthBufferWriteEnable
boolean depthBufferWriteEnable = true;
boolean vfPlanesValid = false;
// The event catcher for this canvas.
EventCatcher eventCatcher;
// The view event catcher for this canvas.
private CanvasViewEventCatcher canvasViewEventCatcher;
// The top-level parent window for this canvas.
private Window windowParent;
// Issue 458 - list of all parent containers for this canvas
// (includes top-level parent window)
private LinkedList<Container> containerParentList = new LinkedList<Container>();
// flag that indicates if light has changed
boolean lightChanged = false;
// resource control object
DrawingSurfaceObject drawingSurfaceObject;
// true if context is valid for rendering
boolean validCtx = false;
// true if canvas is valid for rendering
boolean validCanvas = false;
// true if ctx changed between render and swap. In this case
// cv.canvasDirty flag will not reset in Renderer.
// This case happen when GraphicsContext3D invoked doClear()
// and canvas removeNotify() called while Renderer is running
boolean ctxChanged = false;
// Default graphics configuration
private static GraphicsConfiguration defaultGcfg = null;
// Returns default graphics configuration if user passes null
// into the Canvas3D constructor
private static synchronized GraphicsConfiguration defaultGraphicsConfiguration() {
if (defaultGcfg == null) {
GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D();
defaultGcfg = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getBestConfiguration(template);
}
return defaultGcfg;
}
// Returns true if this is a valid graphics configuration, obtained
// via a GraphicsConfigTemplate3D.
private static boolean isValidConfig(GraphicsConfiguration gconfig) {
// If this is a valid GraphicsConfiguration object, then it will
// be in the graphicsConfigTable
return graphicsConfigTable.containsKey(gconfig);
}
// Checks the given graphics configuration, and throws an exception if
// the config is null or invalid.
private static synchronized GraphicsConfiguration
checkForValidGraphicsConfig(GraphicsConfiguration gconfig, boolean offScreen) {
// Issue 266 - for backwards compatibility with legacy applications,
// we will accept a null GraphicsConfiguration for an on-screen Canvas3D
// only if the "allowNullGraphicsConfig" system property is set to true.
if (!offScreen && VirtualUniverse.mc.allowNullGraphicsConfig) {
if (gconfig == null) {
// Print out warning if Canvas3D is called with a
// null GraphicsConfiguration
System.err.println(J3dI18N.getString("Canvas3D7"));
System.err.println(" " + J3dI18N.getString("Canvas3D18"));
// Use a default graphics config
gconfig = defaultGraphicsConfiguration();
}
}
// Validate input graphics config
if (gconfig == null) {
throw new NullPointerException(J3dI18N.getString("Canvas3D19"));
} else if (!isValidConfig(gconfig)) {
throw new IllegalArgumentException(J3dI18N.getString("Canvas3D17"));
}
return gconfig;
}
// Return the actual graphics config that will be used to construct
// the AWT Canvas. This is permitted to be non-unique or null.
private static GraphicsConfiguration getGraphicsConfig(GraphicsConfiguration gconfig) {
return Pipeline.getPipeline().getGraphicsConfig(gconfig);
}
/**
* Constructs and initializes a new Canvas3D object that Java 3D
* can render into. The following Canvas3D attributes are initialized
* to default values as shown:
* <ul>
* left manual eye in image plate : (0.142, 0.135, 0.4572)<br>
* right manual eye in image plate : (0.208, 0.135, 0.4572)<br>
* stereo enable : true<br>
* double buffer enable : true<br>
* monoscopic view policy : View.CYCLOPEAN_EYE_VIEW<br>
* off-screen mode : false<br>
* off-screen buffer : null<br>
* off-screen location : (0,0)<br>
* </ul>
*
* @param graphicsConfiguration a valid GraphicsConfiguration object that
* will be used to create the canvas. This object should not be null and
* should be created using a GraphicsConfigTemplate3D or the
* getPreferredConfiguration() method of the SimpleUniverse utility. For
* backward compatibility with earlier versions of Java 3D, a null or
* default GraphicsConfiguration will still work when used to create a
* Canvas3D on the default screen, but an error message will be printed.
* A NullPointerException or IllegalArgumentException will be thrown in a
* subsequent release.
*
* @exception IllegalArgumentException if the specified
* GraphicsConfiguration does not support 3D rendering
*/
public Canvas3D(GraphicsConfiguration graphicsConfiguration) {
this(null, checkForValidGraphicsConfig(graphicsConfiguration, false), false);
}
/**
* Constructs and initializes a new Canvas3D object that Java 3D
* can render into.
*
* @param graphicsConfiguration a valid GraphicsConfiguration object
* that will be used to create the canvas. This must be created either
* with a GraphicsConfigTemplate3D or by using the
* getPreferredConfiguration() method of the SimpleUniverse utility.
*
* @param offScreen a flag that indicates whether this canvas is
* an off-screen 3D rendering canvas. Note that if offScreen
* is set to true, this Canvas3D object cannot be used for normal
* rendering; it should not be added to any Container object.
*
* @exception NullPointerException if the GraphicsConfiguration
* is null.
*
* @exception IllegalArgumentException if the specified
* GraphicsConfiguration does not support 3D rendering
*
* @since Java 3D 1.2
*/
public Canvas3D(GraphicsConfiguration graphicsConfiguration, boolean offScreen) {
this(null, checkForValidGraphicsConfig(graphicsConfiguration, offScreen), offScreen);
}
// Private constructor only called by the two public constructors after
// they have validated the graphics config (and possibly constructed a new
// default config).
// The graphics config must be valid, unique, and non-null.
private Canvas3D(Object dummyObj1,
GraphicsConfiguration graphicsConfiguration,
boolean offScreen) {
this(dummyObj1,
graphicsConfiguration,
getGraphicsConfig(graphicsConfiguration),
offScreen);
}
// Private constructor only called by the previous private constructor.
// The graphicsConfiguration parameter is used by Canvas3D to lookup the
// graphics device and graphics template. The graphicsConfiguration2
// parameter is generated by the Pipeline from graphicsConfiguration and
// is only used to initialize the java.awt.Canvas.
private Canvas3D(Object dummyObj1,
GraphicsConfiguration graphicsConfiguration,
GraphicsConfiguration graphicsConfiguration2,
boolean offScreen) {
super(graphicsConfiguration2);
this.offScreen = offScreen;
this.graphicsConfiguration = graphicsConfiguration;
// Issue 131: Set the autoOffScreen variable based on whether this
// canvas3d implements the AutoOffScreenCanvas3D tagging interface.
// Eventually, we may replace this with an actual API.
boolean autoOffScreenCanvas3D = false;
if (this instanceof AutoOffScreenCanvas3D) {
autoOffScreenCanvas3D = true;
}
// Throw an illegal argument exception if an on-screen canvas is tagged
// as an auto-off-screen canvas
if (autoOffScreenCanvas3D && !offScreen) {
throw new IllegalArgumentException(J3dI18N.getString("Canvas3D25"));
}
// Issue 163 : Set dirty bits for both Renderer and RenderBin
cvDirtyMask[0] = VIEW_INFO_DIRTY;
cvDirtyMask[1] = VIEW_INFO_DIRTY;
GraphicsConfigInfo gcInfo = graphicsConfigTable.get(graphicsConfiguration);
requestedStencilSize = gcInfo.getGraphicsConfigTemplate3D().getStencilSize();
if (offScreen) {
// Issue 131: set manual rendering flag based on whether this is
// an auto-off-screen Canvas3D.
manualRendering = !autoOffScreenCanvas3D;
screen = new Screen3D(graphicsConfiguration, offScreen);
// QUESTION: keep a list of off-screen Screen3D objects?
// Does this list need to be grouped by GraphicsDevice?
synchronized(dirtyMaskLock) {
cvDirtyMask[0] |= MOVED_OR_RESIZED_DIRTY;
cvDirtyMask[1] |= MOVED_OR_RESIZED_DIRTY;
}
// this canvas will not receive the paint callback,
// so we need to set the necessary flags here
firstPaintCalled = true;
if (manualRendering) {
// since this canvas will not receive the addNotify
// callback from AWT, set the added flag here for
// evaluateActive to work correctly
added = true;
}
evaluateActive();
// create the rendererStructure object
//rendererStructure = new RendererStructure();
offScreenCanvasLoc = new Point(0, 0);
offScreenCanvasSize = new Dimension(0, 0);
this.setLocation(offScreenCanvasLoc);
this.setSize(offScreenCanvasSize);
newSize = offScreenCanvasSize;
newPosition = offScreenCanvasLoc;
// Issue 131: create event catchers for auto-offScreen
if (!manualRendering) {
eventCatcher = new EventCatcher(this);
canvasViewEventCatcher = new CanvasViewEventCatcher(this);
}
} else {
GraphicsDevice graphicsDevice;
graphicsDevice = graphicsConfiguration.getDevice();
eventCatcher = new EventCatcher(this);
canvasViewEventCatcher = new CanvasViewEventCatcher(this);
synchronized(VirtualUniverse.mc.deviceScreenMap) {
screen = VirtualUniverse.mc.deviceScreenMap.get(graphicsDevice);
if (screen == null) {
screen = new Screen3D(graphicsConfiguration, offScreen);
VirtualUniverse.mc.deviceScreenMap.put(graphicsDevice, screen);
}
}
}
lights = new LightRetained[VirtualUniverse.mc.maxLights];
frameCount = new int[VirtualUniverse.mc.maxLights];
for (int i=0; i<frameCount.length;i++) {
frameCount[i] = -1;
}
// Construct the drawing surface object for this Canvas3D
drawingSurfaceObject =
Pipeline.getPipeline().createDrawingSurfaceObject(this);
// Get double buffer, stereo available, scene antialiasing
// flags from graphics config
GraphicsConfigTemplate3D.getGraphicsConfigFeatures(this);
useDoubleBuffer = doubleBufferEnable && doubleBufferAvailable;
useStereo = stereoEnable && stereoAvailable;
useSharedCtx = VirtualUniverse.mc.isSharedCtx;
// Issue 131: assert that only an off-screen canvas can be demand-driven
assert (!offScreen && manualRendering) == false;
// Assert that offScreen is *not* stereo
assert (offScreen && useStereo) == false;
}
/**
* This method overrides AWT's handleEvent class...
*/
void sendEventToBehaviorScheduler(AWTEvent evt) {
ViewPlatform vp;
if ((view != null) && ((vp = view.getViewPlatform()) != null)) {
VirtualUniverse univ =
((ViewPlatformRetained)(vp.retained)).universe;
if (univ != null) {
univ.behaviorStructure.handleAWTEvent(evt);
}
}
}
/**
* Method to return whether or not the Canvas3D is recursively visible;
* that is, whether the Canas3D is currently visible on the screen. Note
* that we don't directly use isShowing() because that won't work for an
* auto-offScreen Canvas3D.
*/
private boolean isRecursivelyVisible() {
Container parent = getParent();
return isVisible() && parent != null && parent.isShowing();
}
/**
* Method to return whether the top-level Window parent is iconified
*/
private boolean isIconified() {
if (windowParent instanceof Frame) {
return (((Frame)windowParent).getExtendedState() & Frame.ICONIFIED) != 0;
}
return false;
}
// Issue 458 - evaluate this Canvas3D's visibility whenever we get a
// Window or Component Event that could change it.
void evaluateVisiblilty() {
boolean nowVisible = isRecursivelyVisible() && !isIconified();
// Only need to reevaluate and repaint if visibility has changed
if (this.visible != nowVisible) {
this.visible = nowVisible;
evaluateActive();
if (nowVisible) {
if (view != null) {
view.repaint();
}
}
}
}
/**
* This version looks for the view and notifies it.
*/
void redraw() {
if ((view != null) && active && isRunning) {
view.repaint();
}
}
/**
* Canvas3D uses the paint callback to track when it is possible to
* render into the canvas. Subclasses of Canvas3D that override this
* method need to call super.paint() in their paint method for Java 3D
* to function properly.
* @param g the graphics context
*/
@Override
public void paint(Graphics g) {
if (!firstPaintCalled && added && validCanvas &&
validGraphicsMode()) {
try {
newSize = getSize();
newPosition = getLocationOnScreen();
} catch (IllegalComponentStateException e) {
return;
}
synchronized (drawingSurfaceObject) {
drawingSurfaceObject.getDrawingSurfaceObjectInfo();
}
firstPaintCalled = true;
visible = true;
evaluateActive();
}
redraw();
}
// When this canvas is added to a frame, this notification gets called. We
// can get drawing surface information at this time. Note: we cannot get
// the X11 window id yet, unless it is a reset condition.
/**
* Canvas3D uses the addNotify callback to track when it is added
* to a container. Subclasses of Canvas3D that override this
* method need to call super.addNotify() in their addNotify() method for Java 3D
* to function properly.
*/
@Override
public void addNotify() {
// Return immediately if addNotify called twice with no removeNotify
if (addNotifyCalled) {
return;
}
addNotifyCalled = true;
// Issue 131: This method is now being called by JCanvas3D for its
// off-screen Canvas3D, so we need to handle off-screen properly here.
// Do nothing for manually-rendered off-screen canvases
if (manualRendering) {
return;
}
Renderer rdr = null;
if (isRunning && (screen != null)) {
// If there is other Canvas3D in the same screen
// rendering, stop it before JDK create new Canvas
rdr = screen.renderer;
if (rdr != null) {
VirtualUniverse.mc.postRequest(MasterControl.STOP_RENDERER, rdr);
while (!rdr.userStop) {
MasterControl.threadYield();
}
}
}
// Issue 131: Don't call super for off-screen Canvas3D
if (!offScreen) {
super.addNotify();
}
screen.addUser(this);
// Issue 458 - Add the eventCatcher as a component listener for each
// parent container in the window hierarchy
assert containerParentList.isEmpty();
windowParent = null;
Container container = this.getParent();
while (container != null) {
if (container instanceof Window) {
windowParent = (Window)container;
}
container.addComponentListener(eventCatcher);
container.addComponentListener(canvasViewEventCatcher);
containerParentList.add(container);
container = container.getParent();
}
this.addComponentListener(eventCatcher);
this.addComponentListener(canvasViewEventCatcher);
if (windowParent != null) {
windowParent.addWindowListener(eventCatcher);
}
synchronized(dirtyMaskLock) {
cvDirtyMask[0] |= MOVED_OR_RESIZED_DIRTY;
cvDirtyMask[1] |= MOVED_OR_RESIZED_DIRTY;
}
allocateCanvasId();
validCanvas = true;
added = true;
// Since we won't get a paint call for off-screen canvases, we need
// to set the first paint and visible flags here. We also need to
// call evaluateActive for the same reason.
if (offScreen) {
firstPaintCalled = true;
visible = true;
evaluateActive();
}
// In case the same canvas is removed and add back,
// we have to change isRunningStatus back to true;
if (isRunning && !fatalError) {
isRunningStatus = true;
}
ctxTimeStamp = 0;
if ((view != null) && (view.universe != null)) {
view.universe.checkForEnableEvents();
}
if (rdr != null) {
// Issue 84: Send a message to MC to restart renderer
// Note that this also obviates the need for the earlier fix to
// issue 131 which called redraw() for auto-off-screen Canvas3Ds
// (and this is a more robust fix)
VirtualUniverse.mc.postRequest(MasterControl.START_RENDERER, rdr);
while (rdr.userStop) {
MasterControl.threadYield();
}
}
}
// When this canvas is removed a frame, this notification gets called. We
// need to release the native context at this time. The underlying window
// is about to go away.
/**
* Canvas3D uses the removeNotify callback to track when it is removed
* from a container. Subclasses of Canvas3D that override this
* method need to call super.removeNotify() in their removeNotify()
* method for Java 3D to function properly.
*/
@Override
public void removeNotify() {
// Return immediately if addNotify not called first
if (!addNotifyCalled) {
return;
}
addNotifyCalled = false;
// Do nothing for manually-rendered off-screen canvases
if (manualRendering) {
return;
}
Renderer rdr = null;
if (isRunning && (screen != null)) {
// If there is other Canvas3D in the same screen
// rendering, stop it before JDK create new Canvas
rdr = screen.renderer;
if (rdr != null) {
VirtualUniverse.mc.postRequest(MasterControl.STOP_RENDERER, rdr);
while (!rdr.userStop) {
MasterControl.threadYield();
}
}
}
// Note that although renderer userStop is true,
// MasterControl can still schedule renderer to run through
// runMonotor(RUN_RENDERER_CLEANUP) which skip userStop
// thread checking.
// For non-offscreen rendering the following call will
// block waiting until all resources is free before
// continue
synchronized (drawingSurfaceObject) {
validCtx = false;
validCanvas = false;
}
removeCtx();
Pipeline.getPipeline().freeDrawingSurface(this, drawingSurfaceObject);
// Clear first paint and visible flags
firstPaintCalled = false;
visible = false;
screen.removeUser(this);
evaluateActive();
freeCanvasId();
ra = null;
graphicsContext3D = null;
ctx = null;
// must be after removeCtx() because
// it will free graphics2D textureID
graphics2D = null;
super.removeNotify();
// Release and clear.
for (Container container : containerParentList) {
container.removeComponentListener(eventCatcher);
container.removeComponentListener(canvasViewEventCatcher);
}
containerParentList.clear();
this.removeComponentListener(eventCatcher);
this.removeComponentListener(canvasViewEventCatcher);
if (eventCatcher != null) {
this.removeFocusListener(eventCatcher);
this.removeKeyListener(eventCatcher);
this.removeMouseListener(eventCatcher);
this.removeMouseMotionListener(eventCatcher);
this.removeMouseWheelListener(eventCatcher);
eventCatcher.reset();
}
if (windowParent != null) {
windowParent.removeWindowListener(eventCatcher);
windowParent.requestFocus();
}
added = false;
if (rdr != null) {
// Issue 84: Send a message to MC to restart renderer
VirtualUniverse.mc.postRequest(MasterControl.START_RENDERER, rdr);
while (rdr.userStop) {
MasterControl.threadYield();
}
}
// Fix for issue 102 removing strong reference and avoiding memory leak
// due retention of parent container
this.windowParent = null;
}
void allocateCanvasId() {
if (!canvasIdAlloc) {
canvasId = VirtualUniverse.mc.getCanvasId();
canvasBit = 1 << canvasId;
canvasIdAlloc = true;
}
}
void freeCanvasId() {
if (canvasIdAlloc) {
VirtualUniverse.mc.freeCanvasId(canvasId);
canvasBit = 0;
canvasId = 0;
canvasIdAlloc = false;
}
}
// This decides if the canvas is active
void evaluateActive() {
// Note that no need to check for isRunning, we want
// view register in order to create scheduler in pure immedite mode
// Also we can't use this as lock, otherwise there is a
// deadlock where updateViewCache get a lock of this and
// get a lock of this component. But Container
// remove will get a lock of this component follows by evaluateActive.
synchronized (evaluateLock) {
if ((visible || manualRendering) && firstPaintCalled) {
if (!active) {
active = true;
if (pendingView != null) {
pendingView.evaluateActive();
}
} else {
if ((pendingView != null) &&
!pendingView.activeStatus) {
pendingView.evaluateActive();
}
}
} else {
if (active) {
active = false;
if (view != null) {
view.evaluateActive();
}
}
}
}
if ((view != null) && (!active)) {
VirtualUniverse u = view.universe;
if ((u != null) && !u.isSceneGraphLock) {
u.waitForMC();
}
}
}
void setFrustumPlanes(Vector4d[] planes) {
if(VirtualUniverse.mc.viewFrustumCulling) {
/* System.err.println("Canvas3D.setFrustumPlanes()"); */
viewFrustum.set(planes);
}
}
/**
* Retrieve the Screen3D object that this Canvas3D is attached to.
* If this Canvas3D is an off-screen buffer, a new Screen3D object
* is created corresponding to the off-screen buffer.
* @return the 3D screen object that this Canvas3D is attached to
*/
public Screen3D getScreen3D() {
return screen;
}
/**
* Get the immediate mode 3D graphics context associated with
* this Canvas3D. A new graphics context object is created if one does
* not already exist.
* @return a GraphicsContext3D object that can be used for immediate
* mode rendering to this Canvas3D.
*/
public GraphicsContext3D getGraphicsContext3D() {
synchronized(gfxCreationLock) {
if (graphicsContext3D == null)
graphicsContext3D = new GraphicsContext3D(this);
}
return graphicsContext3D;
}
/**
* Get the 2D graphics object associated with
* this Canvas3D. A new 2D graphics object is created if one does
* not already exist.
*
* @return a Graphics2D object that can be used for Java 2D
* rendering into this Canvas3D.
*
* @since Java 3D 1.2
*/
public J3DGraphics2D getGraphics2D() {
synchronized(gfxCreationLock) {
if (graphics2D == null)
graphics2D = new J3DGraphics2DImpl(this);
}
return graphics2D;
}
/**
* This routine is called by the Java 3D rendering loop after clearing
* the canvas and before any rendering has been done for this frame.
* Applications that wish to perform operations in the rendering loop,
* prior to any actual rendering may override this function.
*
* <p>
* Updates to live Geometry, Texture, and ImageComponent objects
* in the scene graph are not allowed from this method.
*
* <p>
* NOTE: Applications should <i>not</i> call this method.
*/
public void preRender() {
// Do nothing; the user overrides this to cause some action
}
/**
* This routine is called by the Java 3D rendering loop after completing
* all rendering to the canvas for this frame and before the buffer swap.
* Applications that wish to perform operations in the rendering loop,
* following any actual rendering may override this function.
*
* <p>
* Updates to live Geometry, Texture, and ImageComponent objects
* in the scene graph are not allowed from this method.
*
* <p>
* NOTE: Applications should <i>not</i> call this method.
*/
public void postRender() {
// Do nothing; the user overrides this to cause some action
}
/**
* This routine is called by the Java 3D rendering loop after completing
* all rendering to the canvas, and all other canvases associated with
* this view, for this frame following the buffer swap.
* Applications that wish to perform operations at the very
* end of the rendering loop may override this function.
* In off-screen mode, all rendering is copied to the off-screen
* buffer before this method is called.
*
* <p>
* Updates to live Geometry, Texture, and ImageComponent objects
* in the scene graph are not allowed from this method.
*
* <p>
* NOTE: Applications should <i>not</i> call this method.
*/
public void postSwap() {
// Do nothing; the user overrides this to cause some action
}
/**
* This routine is called by the Java 3D rendering loop during the
* execution of the rendering loop. It is called once for each
* field (i.e., once per frame on
* a mono system or once each for the right eye and left eye on a
* two-pass stereo system. This is intended for use by applications that
* want to mix retained/compiled-retained mode rendering with some
* immediate mode rendering. Applications that wish to perform
* operations during the rendering loop, may override this
* function.
*
* <p>
* Updates to live Geometry, Texture, and ImageComponent objects
* in the scene graph are not allowed from this method.
*
* <p>
* NOTE: Applications should <i>not</i> call this method.
* <p>
*
* @param fieldDesc field description, one of: FIELD_LEFT, FIELD_RIGHT or
* FIELD_ALL. Applications that wish to work correctly in stereo mode
* should render the same image for both FIELD_LEFT and FIELD_RIGHT calls.
* If Java 3D calls the renderer with FIELD_ALL then the immediate mode
* rendering only needs to be done once.
*/
public void renderField(int fieldDesc) {
// Do nothing; the user overrides this to cause some action
}
/**
* Stop the Java 3D renderer on this Canvas3D object. If the
* Java 3D renderer is currently running, the rendering will be
* synchronized before being stopped. No further rendering will be done
* to this canvas by Java 3D until the renderer is started again.
* In pure immediate mode this method should be called prior to adding
* this canvas to an active View object.
*
* @exception IllegalStateException if this Canvas3D is in
* off-screen mode.
*/
public final void stopRenderer() {
// Issue 131: renderer can't be stopped only if it is an offscreen,
// manual canvas. Otherwise, it has to be seen as an onscreen canvas.
if (manualRendering)
throw new IllegalStateException(J3dI18N.getString("Canvas3D14"));
if (isRunning) {
VirtualUniverse.mc.postRequest(MasterControl.STOP_RENDERER, this);
isRunning = false;
}
}
/**
* Start the Java 3D renderer on this Canvas3D object. If the
* Java 3D renderer is not currently running, any rendering to other
* Canvas3D objects sharing the same View will be synchronized before this
* Canvas3D's renderer is (re)started. When a Canvas3D is created, it is
* initially marked as being started. This means that as soon as the
* Canvas3D is added to an active View object, the rendering loop will
* render the scene graph to the canvas.
*/
public final void startRenderer() {
// Issue 260 : ignore attempt to start renderer if fatal error
if (fatalError) {
return;
}
if (!isRunning) {
VirtualUniverse.mc.postRequest(MasterControl.START_RENDERER, this);
isRunning = true;
redraw();
}
}
/**
* Retrieves the state of the renderer for this Canvas3D object.
* @return the state of the renderer
*
* @since Java 3D 1.2
*/
public final boolean isRendererRunning() {
return isRunning;
}
// Returns the state of the fatal error flag
boolean isFatalError() {
return fatalError;
}
// Sets the fatal error flag to true; stop the renderer for this canvas
void setFatalError() {
fatalError = true;
if (isRunning) {
isRunning = false;
if (!manualRendering) {
VirtualUniverse.mc.postRequest(MasterControl.STOP_RENDERER, this);
}
}
}
/**
* Retrieves a flag indicating whether this Canvas3D is an
* off-screen canvas.
*
* @return <code>true</code> if this Canvas3D is an off-screen canvas;
* <code>false</code> if this is an on-screen canvas.
*
* @since Java 3D 1.2
*/
public boolean isOffScreen() {
return offScreen;
}
/**
* Sets the off-screen buffer for this Canvas3D. The specified
* image is written into by the Java 3D renderer. The size of the
* specified ImageComponent determines the size, in pixels, of
* this Canvas3D--the size inherited from Component is ignored.
* <p>
* NOTE: the size, physical width, and physical height of the associated
* Screen3D must be set explicitly prior to rendering.
* Failure to do so will result in an exception.
* <p>
*
* @param buffer the image component that will be rendered into by
* subsequent calls to renderOffScreenBuffer. The image component must not
* be part of a live scene graph, nor may it subsequently be made part of a
* live scene graph while being used as an off-screen buffer; an
* IllegalSharingException is thrown in such cases. The buffer may be null,
* indicating that the previous off-screen buffer is released without a new
* buffer being set.
*
* @exception IllegalStateException if this Canvas3D is not in
* off-screen mode.
*
* @exception RestrictedAccessException if an off-screen rendering
* is in process for this Canvas3D.
*
* @exception IllegalSharingException if the specified ImageComponent2D
* is part of a live scene graph
*
* @exception IllegalSharingException if the specified ImageComponent2D is
* being used by an immediate mode context, or by another Canvas3D as
* an off-screen buffer.
*
* @exception IllegalArgumentException if the image class of the specified
* ImageComponent2D is <i>not</i> ImageClass.BUFFERED_IMAGE.
*
* @exception IllegalArgumentException if the specified
* ImageComponent2D is in by-reference mode and its
* RenderedImage is null.
*
* @exception IllegalArgumentException if the ImageComponent2D format
* is <i>not</i> a 3-component format (e.g., FORMAT_RGB)
* or a 4-component format (e.g., FORMAT_RGBA).
*
* @see #renderOffScreenBuffer
* @see Screen3D#setSize(int, int)
* @see Screen3D#setSize(Dimension)
* @see Screen3D#setPhysicalScreenWidth
* @see Screen3D#setPhysicalScreenHeight
*
* @since Java 3D 1.2
*/
public void setOffScreenBuffer(ImageComponent2D buffer) {
int width, height;
boolean freeCanvasId = false;
if (!offScreen)
throw new IllegalStateException(J3dI18N.getString("Canvas3D1"));
if (offScreenRendering)
throw new RestrictedAccessException(J3dI18N.getString("Canvas3D2"));
// Check that offScreenBufferPending is not already set
J3dDebug.doAssert(!offScreenBufferPending, "!offScreenBufferPending");
if (offScreenBuffer != null && offScreenBuffer != buffer) {
ImageComponent2DRetained i2dRetained =
(ImageComponent2DRetained)offScreenBuffer.retained;
i2dRetained.setUsedByOffScreen(false);
}
if (buffer != null) {
ImageComponent2DRetained bufferRetained =
(ImageComponent2DRetained)buffer.retained;
if (bufferRetained.byReference &&
!(bufferRetained.getRefImage(0) instanceof BufferedImage)) {
throw new IllegalArgumentException(J3dI18N.getString("Canvas3D15"));
}
if (bufferRetained.getNumberOfComponents() < 3 ) {
throw new IllegalArgumentException(J3dI18N.getString("Canvas3D16"));
}
if (buffer.isLive()) {
throw new IllegalSharingException(J3dI18N.getString("Canvas3D26"));
}
if (bufferRetained.getInImmCtx()) {
throw new IllegalSharingException(J3dI18N.getString("Canvas3D27"));
}
if (buffer != offScreenBuffer && bufferRetained.getUsedByOffScreen()) {
throw new IllegalSharingException(J3dI18N.getString("Canvas3D28"));
}
bufferRetained.setUsedByOffScreen(true);
width = bufferRetained.width;
height = bufferRetained.height;
// Issues 347, 348 - assign a canvasId for off-screen Canvas3D
if (manualRendering) {
sendAllocateCanvasId();
}
}
else {
width = height = 0;
// Issues 347, 348 - release canvasId for off-screen Canvas3D
if (manualRendering) {
freeCanvasId = true;
}
}
if ((offScreenCanvasSize.width != width) ||
(offScreenCanvasSize.height != height)) {
if (drawable != null) {
// Fix for Issue 18 and Issue 175
// Will do destroyOffScreenBuffer in the Renderer thread.
sendDestroyCtxAndOffScreenBuffer();
drawable = null;
}
// Issue 396. Since context is invalid here, we should set it to null.
ctx = null;
// set the canvas dimension according to the buffer dimension
offScreenCanvasSize.setSize(width, height);
this.setSize(offScreenCanvasSize);
if (width > 0 && height > 0) {
sendCreateOffScreenBuffer();
}
}
else if (ctx != null) {
removeCtx();
}
if (freeCanvasId) {
sendFreeCanvasId();
}
offScreenBuffer = buffer;
synchronized(dirtyMaskLock) {
cvDirtyMask[0] |= MOVED_OR_RESIZED_DIRTY;
cvDirtyMask[1] |= MOVED_OR_RESIZED_DIRTY;
}
}
/**
* Retrieves the off-screen buffer for this Canvas3D.
*
* @return the current off-screen buffer for this Canvas3D.
*
* @exception IllegalStateException if this Canvas3D is not in
* off-screen mode.
*
* @since Java 3D 1.2
*/
public ImageComponent2D getOffScreenBuffer() {
if (!offScreen)
throw new IllegalStateException(J3dI18N.getString("Canvas3D1"));
return (offScreenBuffer);
}
/**
* Schedules the rendering of a frame into this Canvas3D's
* off-screen buffer. The rendering is done from the point of
* view of the View object to which this Canvas3D has been added.
* No rendering is performed if this Canvas3D object has not been
* added to an active View. This method does not wait for the rendering
* to actually happen. An application that wishes to know when
* the rendering is complete must either subclass Canvas3D and
* override the <code>postSwap</code> method, or call
* <code>waitForOffScreenRendering</code>.
*
* @exception NullPointerException if the off-screen buffer is null.
* @exception IllegalStateException if this Canvas3D is not in
* off-screen mode, or if either the width or the height of
* the associated Screen3D's size is <= 0, or if the associated
* Screen3D's physical width or height is <= 0.
* @exception RestrictedAccessException if an off-screen rendering
* is already in process for this Canvas3D or if the Java 3D renderer
* is stopped.
*
* @see #setOffScreenBuffer
* @see Screen3D#setSize(int, int)
* @see Screen3D#setSize(Dimension)
* @see Screen3D#setPhysicalScreenWidth
* @see Screen3D#setPhysicalScreenHeight
* @see #waitForOffScreenRendering
* @see #postSwap
*
* @since Java 3D 1.2
*/
public void renderOffScreenBuffer() {
if (!offScreen)
throw new IllegalStateException(J3dI18N.getString("Canvas3D1"));
// Issue 131: Cannot manually render to an automatic canvas.
if (!manualRendering)
throw new IllegalStateException(J3dI18N.getString("Canvas3D24"));
// Issue 260 : Cannot render if we already have a fatal error
if (fatalError) {
throw new IllegalRenderingStateException(J3dI18N.getString("Canvas3D30"));
}
if (offScreenBuffer == null)
throw new NullPointerException(J3dI18N.getString("Canvas3D10"));
Dimension screenSize = screen.getSize();
if (screenSize.width <= 0)
throw new IllegalStateException(J3dI18N.getString("Canvas3D8"));
if (screenSize.height <= 0)
throw new IllegalStateException(J3dI18N.getString("Canvas3D9"));
if (screen.getPhysicalScreenWidth() <= 0.0)
throw new IllegalStateException(J3dI18N.getString("Canvas3D12"));
if (screen.getPhysicalScreenHeight() <= 0.0)
throw new IllegalStateException(J3dI18N.getString("Canvas3D13"));
if (offScreenRendering)
throw new RestrictedAccessException(J3dI18N.getString("Canvas3D2"));
if (!isRunning)
throw new RestrictedAccessException(J3dI18N.getString("Canvas3D11"));
// Fix to issue 66
if ((!active) || (pendingView == null)) {
/* No rendering is performed if this Canvas3D object has not been
added to an active View. */
return;
}
// Issue 131: moved code that determines off-screen boundary to separate
// method that is called from the renderer
offScreenRendering = true;
// Fix to issue 66.
/* This is an attempt to do the following check in one atomic operation :
((view != null) && (view.inCanvasCallback)) */
boolean inCanvasCallback = false;
try {
inCanvasCallback = view.inCanvasCallback;
} catch (NullPointerException npe) {
/* Do nothing here */
}
if (inCanvasCallback) {
// Here we assume that view is stable if inCanvasCallback
// is true. This assumption is valid among all j3d threads as
// all access to view is synchronized by MasterControl.
// Issue : user threads access to view isn't synchronize hence
// is model will break.
if (screen.renderer == null) {
// It is possible that screen.renderer = null when this View
// is shared by another onScreen Canvas and this callback
// is from that Canvas. In this case it need one more
// round before the renderer.
screen.renderer = Screen3D.deviceRendererMap.get(screen.graphicsDevice);
// screen.renderer may equal to null when multiple
// screen is used and this Canvas3D is in different
// screen sharing the same View not yet initialize.
}
// if called from render call back, send a message directly to
// the renderer message queue, and call renderer doWork
// to do the offscreen rendering now
if (Thread.currentThread() == screen.renderer) {
J3dMessage createMessage = new J3dMessage();
createMessage.threads = J3dThread.RENDER_THREAD;
createMessage.type = J3dMessage.RENDER_OFFSCREEN;
createMessage.universe = this.view.universe;
createMessage.view = this.view;
createMessage.args[0] = this;
screen.renderer.rendererStructure.addMessage(createMessage);
// modify the args to reflect offScreen rendering
screen.renderer.args = new Object[4];
screen.renderer.args[0] = new Integer(Renderer.REQUESTRENDER);
screen.renderer.args[1] = this;
screen.renderer.args[2] = view;
// This extra argument 3 is needed in MasterControl to
// test whether offscreen Rendering is used or not
screen.renderer.args[3] = null;
// call renderer doWork directly since we are already in
// the renderer thread
screen.renderer.doWork(0);
} else {
// XXXX:
// Now we are in trouble, this will cause deadlock if
// waitForOffScreenRendering() is invoked
J3dMessage createMessage = new J3dMessage();
createMessage.threads = J3dThread.RENDER_THREAD;
createMessage.type = J3dMessage.RENDER_OFFSCREEN;
createMessage.universe = this.view.universe;
createMessage.view = this.view;
createMessage.args[0] = this;
screen.renderer.rendererStructure.addMessage(createMessage);
VirtualUniverse.mc.setWorkForRequestRenderer();
}
} else if (Thread.currentThread() instanceof BehaviorScheduler) {
// If called from behavior scheduler, send a message directly to
// the renderer message queue.
// Note that we didn't use
// currentThread() == view.universe.behaviorScheduler
// since the caller may be another universe Behavior
// scheduler.
J3dMessage createMessage = new J3dMessage();
createMessage.threads = J3dThread.RENDER_THREAD;
createMessage.type = J3dMessage.RENDER_OFFSCREEN;
createMessage.universe = this.view.universe;
createMessage.view = this.view;
createMessage.args[0] = this;
screen.renderer.rendererStructure.addMessage(createMessage);
VirtualUniverse.mc.setWorkForRequestRenderer();
} else {
// send a message to renderBin
// Fix for issue 66 : Since view might not been set yet,
// we have to use pendingView instead.
J3dMessage createMessage = new J3dMessage();
createMessage.threads = J3dThread.UPDATE_RENDER;
createMessage.type = J3dMessage.RENDER_OFFSCREEN;
createMessage.universe = this.pendingView.universe;
createMessage.view = this.pendingView;
createMessage.args[0] = this;
createMessage.args[1] = offScreenBuffer;
VirtualUniverse.mc.processMessage(createMessage);
}
}
/**
* Waits for this Canvas3D's off-screen rendering to be done.
* This method will wait until the <code>postSwap</code> method of this
* off-screen Canvas3D has completed. If this Canvas3D has not
* been added to an active view or if the renderer is stopped for this
* Canvas3D, then this method will return
* immediately. This method must not be called from a render
* callback method of an off-screen Canvas3D.
*
* @exception IllegalStateException if this Canvas3D is not in
* off-screen mode, or if this method is called from a render
* callback method of an off-screen Canvas3D.
*
* @see #renderOffScreenBuffer
* @see #postSwap
*
* @since Java 3D 1.2
*/
public void waitForOffScreenRendering() {
if (!offScreen) {
throw new IllegalStateException(J3dI18N.getString("Canvas3D1"));
}
if (Thread.currentThread() instanceof Renderer) {
throw new IllegalStateException(J3dI18N.getString("Canvas3D31"));
}
while (offScreenRendering) {
MasterControl.threadYield();
}
}
/**
* Sets the location of this off-screen Canvas3D. The location is
* the upper-left corner of the Canvas3D relative to the
* upper-left corner of the corresponding off-screen Screen3D.
* The function of this method is similar to that of
* <code>Component.setLocation</code> for on-screen Canvas3D
* objects. The default location is (0,0).
*
* @param x the <i>x</i> coordinate of the upper-left corner of
* the new location.
* @param y the <i>y</i> coordinate of the upper-left corner of
* the new location.
*
* @exception IllegalStateException if this Canvas3D is not in
* off-screen mode.
*
* @since Java 3D 1.2
*/
public void setOffScreenLocation(int x, int y) {
if (!offScreen)
throw new IllegalStateException(J3dI18N.getString("Canvas3D1"));
synchronized(cvLock) {
offScreenCanvasLoc.setLocation(x, y);
}
}
/**
* Sets the location of this off-screen Canvas3D. The location is
* the upper-left corner of the Canvas3D relative to the
* upper-left corner of the corresponding off-screen Screen3D.
* The function of this method is similar to that of
* <code>Component.setLocation</code> for on-screen Canvas3D
* objects. The default location is (0,0).
*
* @param p the point defining the upper-left corner of the new
* location.
*
* @exception IllegalStateException if this Canvas3D is not in
* off-screen mode.
*
* @since Java 3D 1.2
*/
public void setOffScreenLocation(Point p) {
if (!offScreen)
throw new IllegalStateException(J3dI18N.getString("Canvas3D1"));
synchronized(cvLock) {
offScreenCanvasLoc.setLocation(p);
}
}
/**
* Retrieves the location of this off-screen Canvas3D. The
* location is the upper-left corner of the Canvas3D relative to
* the upper-left corner of the corresponding off-screen Screen3D.
* The function of this method is similar to that of
* <code>Component.getLocation</code> for on-screen Canvas3D
* objects.
*
* @return a new point representing the upper-left corner of the
* location of this off-screen Canvas3D.
*
* @exception IllegalStateException if this Canvas3D is not in
* off-screen mode.
*
* @since Java 3D 1.2
*/
public Point getOffScreenLocation() {
if (!offScreen)
throw new IllegalStateException(J3dI18N.getString("Canvas3D1"));
return (new Point(offScreenCanvasLoc));
}
/**
* Retrieves the location of this off-screen Canvas3D and stores
* it in the specified Point object. The location is the
* upper-left corner of the Canvas3D relative to the upper-left
* corner of the corresponding off-screen Screen3D. The function
* of this method is similar to that of
* <code>Component.getLocation</code> for on-screen Canvas3D
* objects. This version of <code>getOffScreenLocation</code> is
* useful if the caller wants to avoid allocating a new Point
* object on the heap.
*
* @param rv Point object into which the upper-left corner of the
* location of this off-screen Canvas3D is copied.
* If <code>rv</code> is null, a new Point is allocated.
*
* @return <code>rv</code>
*
* @exception IllegalStateException if this Canvas3D is not in
* off-screen mode.
*
* @since Java 3D 1.2
*/
public Point getOffScreenLocation(Point rv) {
if (!offScreen)
throw new IllegalStateException(J3dI18N.getString("Canvas3D1"));
if (rv == null)
return (new Point(offScreenCanvasLoc));
else {
rv.setLocation(offScreenCanvasLoc);
return rv;
}
}
void endOffScreenRendering() {
ImageComponent2DRetained icRetained = (ImageComponent2DRetained)offScreenBuffer.retained;
boolean isByRef = icRetained.isByReference();
ImageComponentRetained.ImageData imageData = icRetained.getImageData(false);
if(!isByRef) {
// If icRetained has a null image ( BufferedImage)
if (imageData == null) {
assert (!isByRef);
icRetained.createBlankImageData();
imageData = icRetained.getImageData(false);
}
// Check for possible format conversion in imageData
else {
// Format convert imageData if format is unsupported.
icRetained.evaluateExtensions(this);
}
// read the image from the offscreen buffer
readOffScreenBuffer(ctx, icRetained.getImageFormatTypeIntValue(false),
icRetained.getImageDataTypeIntValue(), imageData.get(),
offScreenCanvasSize.width, offScreenCanvasSize.height);
} else {
icRetained.geomLock.getLock();
// Create a copy of format converted image in imageData if format is unsupported.
icRetained.evaluateExtensions(this);
// read the image from the offscreen buffer
readOffScreenBuffer(ctx, icRetained.getImageFormatTypeIntValue(false),
icRetained.getImageDataTypeIntValue(), imageData.get(),
offScreenCanvasSize.width, offScreenCanvasSize.height);
// For byRef, we might have to copy buffer back into
// the user's referenced ImageComponent2D
if(!imageData.isDataByRef()) {
if(icRetained.isImageTypeSupported()) {
icRetained.copyToRefImage(0);
} else {
// This method only handle RGBA conversion.
icRetained.copyToRefImageWithFormatConversion(0);
}
}
icRetained.geomLock.unLock();
}
}
/**
* Synchronize and swap buffers on a double buffered canvas for
* this Canvas3D object. This method should only be called if the
* Java 3D renderer has been stopped. In the normal case, the renderer
* automatically swaps the buffer.
* This method calls the <code>flush(true)</code> methods of the
* associated 2D and 3D graphics contexts, if they have been allocated.
*
* @exception RestrictedAccessException if the Java 3D renderer is
* running.
* @exception IllegalStateException if this Canvas3D is in
* off-screen mode.
*
* @see #stopRenderer
* @see GraphicsContext3D#flush
* @see J3DGraphics2D#flush
*/
public void swap() {
if (offScreen)
throw new IllegalStateException(J3dI18N.getString("Canvas3D14"));
if (isRunning)
throw new RestrictedAccessException(J3dI18N.getString("Canvas3D0"));
if (!firstPaintCalled) {
return;
}
if (view != null && graphicsContext3D != null) {
if ((view.universe != null) &&
(Thread.currentThread() == view.universe.behaviorScheduler)) {
graphicsContext3D.sendRenderMessage(false, GraphicsContext3D.SWAP, null, null);
} else {
graphicsContext3D.sendRenderMessage(true, GraphicsContext3D.SWAP, null, null);
}
graphicsContext3D.runMonitor(J3dThread.WAIT);
}
}
void doSwap() {
if (firstPaintCalled && useDoubleBuffer) {
try {
if (validCtx && (ctx != null) && (view != null)) {
synchronized (drawingSurfaceObject) {
if (validCtx) {
if (!drawingSurfaceObject.renderLock()) {
graphicsContext3D.runMonitor(J3dThread.NOTIFY);
return;
}
this.syncRender(ctx, true);
swapBuffers(ctx, drawable);
drawingSurfaceObject.unLock();
}
}
}
} catch (NullPointerException ne) {
drawingSurfaceObject.unLock();
}
}
// Increment the elapsedFrame for the behavior structure
// to trigger any interpolators
view.universe.behaviorStructure.incElapsedFrames();
graphicsContext3D.runMonitor(J3dThread.NOTIFY);
}
/**
* Wrapper for native createNewContext method.
*/
Context createNewContext(Context shareCtx, boolean isSharedCtx) {
Context retVal = createNewContext(
this.drawable,
shareCtx, isSharedCtx,
this.offScreen);
// compute the max available texture units
maxAvailableTextureUnits = Math.max(maxTextureUnits, maxTextureImageUnits);
// reset 'antialiasingSet' if new context is created for an already existing Canvas3D,
// e.g. resizing offscreen Canvas3D
antialiasingSet = false;
return retVal;
}
/**
* Make the context associated with the specified canvas current.
*/
final void makeCtxCurrent() {
makeCtxCurrent(ctx, drawable);
}
/**
* Make the specified context current.
*/
final void makeCtxCurrent(Context ctx) {
makeCtxCurrent(ctx, drawable);
}
final void makeCtxCurrent(Context ctx, Drawable drawable) {
if (ctx != screen.renderer.currentCtx || drawable != screen.renderer.currentDrawable) {
if (!drawingSurfaceObject.isLocked()) {
drawingSurfaceObject.renderLock();
useCtx(ctx, drawable);
drawingSurfaceObject.unLock();
} else {
useCtx(ctx, drawable);
}
screen.renderer.currentCtx = ctx;
screen.renderer.currentDrawable = drawable;
}
}
// Give the pipeline a chance to release the context; the Pipeline may
// or may not ignore this call.
void releaseCtx() {
if (screen.renderer.currentCtx != null) {
boolean needLock = !drawingSurfaceObject.isLocked();
if (needLock) {
drawingSurfaceObject.renderLock();
}
if (releaseCtx(screen.renderer.currentCtx)) {
screen.renderer.currentCtx = null;
screen.renderer.currentDrawable = null;
}
if (needLock) {
drawingSurfaceObject.unLock();
}
}
}
/**
* Sets the position of the manual left eye in image-plate
* coordinates. This value determines eye placement when a head
* tracker is not in use and the application is directly controlling
* the eye position in image-plate coordinates.
* In head-tracked mode or when the windowEyePointPolicy is
* RELATIVE_TO_FIELD_OF_VIEW or RELATIVE_TO_COEXISTENCE, this value
* is ignored. When the
* windowEyepointPolicy is RELATIVE_TO_WINDOW only the Z value is
* used.
* @param position the new manual left eye position
*/
public void setLeftManualEyeInImagePlate(Point3d position) {
this.leftManualEyeInImagePlate.set(position);
synchronized(dirtyMaskLock) {
cvDirtyMask[0] |= EYE_IN_IMAGE_PLATE_DIRTY;
cvDirtyMask[1] |= EYE_IN_IMAGE_PLATE_DIRTY;
}
redraw();
}
/**
* Sets the position of the manual right eye in image-plate
* coordinates. This value determines eye placement when a head
* tracker is not in use and the application is directly controlling
* the eye position in image-plate coordinates.
* In head-tracked mode or when the windowEyePointPolicy is
* RELATIVE_TO_FIELD_OF_VIEW or RELATIVE_TO_COEXISTENCE, this value
* is ignored. When the
* windowEyepointPolicy is RELATIVE_TO_WINDOW only the Z value is
* used.
* @param position the new manual right eye position
*/
public void setRightManualEyeInImagePlate(Point3d position) {
this.rightManualEyeInImagePlate.set(position);
synchronized(dirtyMaskLock) {
cvDirtyMask[0] |= EYE_IN_IMAGE_PLATE_DIRTY;
cvDirtyMask[1] |= EYE_IN_IMAGE_PLATE_DIRTY;
}
redraw();
}
/**
* Retrieves the position of the user-specified, manual left eye
* in image-plate
* coordinates and copies that value into the object provided.
* @param position the object that will receive the position
*/
public void getLeftManualEyeInImagePlate(Point3d position) {
position.set(this.leftManualEyeInImagePlate);
}
/**
* Retrieves the position of the user-specified, manual right eye
* in image-plate
* coordinates and copies that value into the object provided.
* @param position the object that will receive the position
*/
public void getRightManualEyeInImagePlate(Point3d position) {
position.set(this.rightManualEyeInImagePlate);
}
/**
* Retrieves the actual position of the left eye
* in image-plate
* coordinates and copies that value into the object provided.
* This value is a function of the windowEyepointPolicy, the tracking
* enable flag, and the manual left eye position.
* @param position the object that will receive the position
*/
public void getLeftEyeInImagePlate(Point3d position) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
position.set(canvasViewCache.getLeftEyeInImagePlate());
}
}
else {
position.set(leftManualEyeInImagePlate);
}
}
/**
* Retrieves the actual position of the right eye
* in image-plate
* coordinates and copies that value into the object provided.
* This value is a function of the windowEyepointPolicy, the tracking
* enable flag, and the manual right eye position.
* @param position the object that will receive the position
*/
public void getRightEyeInImagePlate(Point3d position) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
position.set(canvasViewCache.getRightEyeInImagePlate());
}
}
else {
position.set(rightManualEyeInImagePlate);
}
}
/**
* Retrieves the actual position of the center eye
* in image-plate
* coordinates and copies that value into the object provided.
* The center eye is the fictional eye half-way between the left and
* right eye.
* This value is a function of the windowEyepointPolicy, the tracking
* enable flag, and the manual right and left eye positions.
* @param position the object that will receive the position
* @see #setMonoscopicViewPolicy
*/
// XXXX: This might not make sense for field-sequential HMD.
public void getCenterEyeInImagePlate(Point3d position) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
position.set(canvasViewCache.getCenterEyeInImagePlate());
}
}
else {
Point3d cenEye = new Point3d();
cenEye.add(leftManualEyeInImagePlate, rightManualEyeInImagePlate);
cenEye.scale(0.5);
position.set(cenEye);
}
}
/**
* Retrieves the current ImagePlate coordinates to Virtual World
* coordinates transform and places it into the specified object.
* @param t the Transform3D object that will receive the
* transform
*/
// TODO: Document -- This will return the transform of left plate.
public void getImagePlateToVworld(Transform3D t) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
t.set(canvasViewCache.getImagePlateToVworld());
}
}
else {
t.setIdentity();
}
}
/**
* Computes the position of the specified AWT pixel value
* in image-plate
* coordinates and copies that value into the object provided.
* @param x the X coordinate of the pixel relative to the upper-left
* hand corner of the window.
* @param y the Y coordinate of the pixel relative to the upper-left
* hand corner of the window.
* @param imagePlatePoint the object that will receive the position in
* physical image plate coordinates (relative to the lower-left
* corner of the screen).
*/
// TODO: Document -- This transform the pixel location to the left image plate.
public void getPixelLocationInImagePlate(int x, int y,
Point3d imagePlatePoint) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
imagePlatePoint.x =
canvasViewCache.getWindowXInImagePlate((double)x);
imagePlatePoint.y =
canvasViewCache.getWindowYInImagePlate((double)y);
imagePlatePoint.z = 0.0;
}
} else {
imagePlatePoint.set(0.0, 0.0, 0.0);
}
}
void getPixelLocationInImagePlate(double x, double y, double z,
Point3d imagePlatePoint) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
canvasViewCache.getPixelLocationInImagePlate(
x, y, z, imagePlatePoint);
}
} else {
imagePlatePoint.set(0.0, 0.0, 0.0);
}
}
/**
* Computes the position of the specified AWT pixel value
* in image-plate
* coordinates and copies that value into the object provided.
* @param pixelLocation the coordinates of the pixel relative to
* the upper-left hand corner of the window.
* @param imagePlatePoint the object that will receive the position in
* physical image plate coordinates (relative to the lower-left
* corner of the screen).
*
* @since Java 3D 1.2
*/
// TODO: Document -- This transform the pixel location to the left image plate.
public void getPixelLocationInImagePlate(Point2d pixelLocation,
Point3d imagePlatePoint) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
imagePlatePoint.x =
canvasViewCache.getWindowXInImagePlate(pixelLocation.x);
imagePlatePoint.y =
canvasViewCache.getWindowYInImagePlate(pixelLocation.y);
imagePlatePoint.z = 0.0;
}
}
else {
imagePlatePoint.set(0.0, 0.0, 0.0);
}
}
/**
* Projects the specified point from image plate coordinates
* into AWT pixel coordinates. The AWT pixel coordinates are
* copied into the object provided.
* @param imagePlatePoint the position in
* physical image plate coordinates (relative to the lower-left
* corner of the screen).
* @param pixelLocation the object that will receive the coordinates
* of the pixel relative to the upper-left hand corner of the window.
*
* @since Java 3D 1.2
*/
// TODO: Document -- This transform the pixel location from the left image plate.
public void getPixelLocationFromImagePlate(Point3d imagePlatePoint,
Point2d pixelLocation) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
canvasViewCache.getPixelLocationFromImagePlate(
imagePlatePoint, pixelLocation);
}
}
else {
pixelLocation.set(0.0, 0.0);
}
}
/**
* Copies the current Vworld projection transform for each eye
* into the specified Transform3D objects. This transform takes
* points in virtual world coordinates and projects them into
* clipping coordinates, which are in the range [-1,1] in
* <i>X</i>, <i>Y</i>, and <i>Z</i> after clipping and perspective
* division.
* In monoscopic mode, the same projection transform will be
* copied into both the right and left eye Transform3D objects.
*
* @param leftProjection the Transform3D object that will receive
* a copy of the current projection transform for the left eye.
*
* @param rightProjection the Transform3D object that will receive
* a copy of the current projection transform for the right eye.
*
* @since Java 3D 1.3
*/
public void getVworldProjection(Transform3D leftProjection,
Transform3D rightProjection) {
if (canvasViewCache != null) {
ViewPlatformRetained viewPlatformRetained =
(ViewPlatformRetained)view.getViewPlatform().retained;
synchronized(canvasViewCache) {
leftProjection.mul(canvasViewCache.getLeftProjection(),
canvasViewCache.getLeftVpcToEc());
leftProjection.mul(viewPlatformRetained.getVworldToVpc());
// caluclate right eye if in stereo, otherwise
// this is the same as the left eye.
if (useStereo) {
rightProjection.mul(canvasViewCache.getRightProjection(),
canvasViewCache.getRightVpcToEc());
rightProjection.mul(viewPlatformRetained.getVworldToVpc());
}
else {
rightProjection.set(leftProjection);
}
}
}
else {
leftProjection.setIdentity();
rightProjection.setIdentity();
}
}
/**
* Copies the inverse of the current Vworld projection transform
* for each eye into the specified Transform3D objects. This
* transform takes points in clipping coordinates, which are in
* the range [-1,1] in <i>X</i>, <i>Y</i>, and <i>Z</i> after
* clipping and perspective division, and transforms them into
* virtual world coordinates.
* In monoscopic mode, the same inverse projection transform will
* be copied into both the right and left eye Transform3D objects.
*
* @param leftInverseProjection the Transform3D object that will
* receive a copy of the current inverse projection transform for
* the left eye.
* @param rightInverseProjection the Transform3D object that will
* receive a copy of the current inverse projection transform for
* the right eye.
*
* @since Java 3D 1.3
*/
public void getInverseVworldProjection(Transform3D leftInverseProjection,
Transform3D rightInverseProjection) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
leftInverseProjection.set(
canvasViewCache.getLeftCcToVworld());
// caluclate right eye if in stereo, otherwise
// this is the same as the left eye.
if (useStereo) {
rightInverseProjection.set(
canvasViewCache.getRightCcToVworld());
}
else {
rightInverseProjection.set(leftInverseProjection);
}
}
}
else {
leftInverseProjection.setIdentity();
rightInverseProjection.setIdentity();
}
}
/**
* Retrieves the physical width of this canvas window in meters.
* @return the physical window width in meters.
*/
public double getPhysicalWidth() {
double width = 0.0;
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
width = canvasViewCache.getPhysicalWindowWidth();
}
}
return width;
}
/**
* Retrieves the physical height of this canvas window in meters.
* @return the physical window height in meters.
*/
public double getPhysicalHeight() {
double height = 0.0;
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
height = canvasViewCache.getPhysicalWindowHeight();
}
}
return height;
}
/**
* Retrieves the current Virtual World coordinates to ImagePlate
* coordinates transform and places it into the specified object.
* @param t the Transform3D object that will receive the
* transform
*/
// TODO: Document -- This will return the transform of left plate.
public void getVworldToImagePlate(Transform3D t) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
t.set(canvasViewCache.getVworldToImagePlate());
}
}
else {
t.setIdentity();
}
}
void getLastVworldToImagePlate(Transform3D t) {
if (canvasViewCache != null) {
synchronized(canvasViewCache) {
t.set(canvasViewCache.getLastVworldToImagePlate());
}
}
else {
t.setIdentity();
}
}
/**
* Sets view that points to this Canvas3D.
* @param view view object that points to this Canvas3D
*/
void setView(View view) {
pendingView = view;
// We can't set View directly here in user thread since
// other threads may using canvas.view
// e.g. In Renderer, we use canvas3d.view.inCallBack
// before and after postSwap(), if view change in between
// than view.inCallBack may never reset to false.
VirtualUniverse.mc.postRequest(MasterControl.SET_VIEW, this);
evaluateActive();
}
void computeViewCache() {
synchronized(cvLock) {
if (view == null) {
canvasViewCache = null;
canvasViewCacheFrustum = null;
} else {
canvasViewCache = new CanvasViewCache(this,
screen.screenViewCache,
view.viewCache);
// Issue 109 : construct a separate canvasViewCache for
// computing view frustum
canvasViewCacheFrustum = new CanvasViewCache(this,
screen.screenViewCache,
view.viewCache);
synchronized (dirtyMaskLock) {
cvDirtyMask[0] = VIEW_INFO_DIRTY;
cvDirtyMask[1] = VIEW_INFO_DIRTY;
}
}
}
}
/**
* Gets view that points to this Canvas3D.
* @return view object that points to this Canvas3D
*/
public View getView() {
return pendingView;
}
/**
* Returns a status flag indicating whether or not stereo
* is available.
* This is equivalent to:
* <ul>
* <code>
* ((Boolean)queryProperties().
* get("stereoAvailable")).
* booleanValue()
* </code>
* </ul>
*
* @return a flag indicating whether stereo is available
*/
public boolean getStereoAvailable() {
return ((Boolean)queryProperties().get("stereoAvailable")).
booleanValue();
}
/**
* Turns stereo on or off. Note that this attribute is used
* only when stereo is available. Enabling stereo on a Canvas3D
* that does not support stereo has no effect.
* @param flag enables or disables the display of stereo
*
* @see #queryProperties
*/
public void setStereoEnable(boolean flag) {
stereoEnable = flag;
useStereo = stereoEnable && stereoAvailable;
synchronized(dirtyMaskLock) {
cvDirtyMask[0] |= STEREO_DIRTY;
cvDirtyMask[1] |= STEREO_DIRTY;
}
redraw();
}
/**
* Returns a status flag indicating whether or not stereo
* is enabled.
* @return a flag indicating whether stereo is enabled
*/
public boolean getStereoEnable() {
return this.stereoEnable;
}
/**
* Specifies how Java 3D generates monoscopic view. If set to
* View.LEFT_EYE_VIEW, the view generated corresponds to the view as
* seen from the left eye. If set to View.RIGHT_EYE_VIEW, the view
* generated corresponds to the view as seen from the right
* eye. If set to View.CYCLOPEAN_EYE_VIEW, the view generated
* corresponds to the view as seen from the 'center eye', the
* fictional eye half-way between the left and right eye. The
* default monoscopic view policy is View.CYCLOPEAN_EYE_VIEW.
* <p>
* NOTE: for backward compatibility with Java 3D 1.1, if this
* attribute is set to its default value of
* View.CYCLOPEAN_EYE_VIEW, the monoscopic view policy in the
* View object will be used. An application should not use both
* the deprecated View method and this Canvas3D method at the same
* time.
* @param policy one of View.LEFT_EYE_VIEW, View.RIGHT_EYE_VIEW, or
* View.CYCLOPEAN_EYE_VIEW.
*
* @exception IllegalStateException if the specified
* policy is CYCLOPEAN_EYE_VIEW, the canvas is a stereo canvas,
* and the viewPolicy for the associated view is HMD_VIEW
*
* @since Java 3D 1.2
*/
public void setMonoscopicViewPolicy(int policy) {
if((view !=null) && (view.viewPolicy == View.HMD_VIEW) &&
(monoscopicViewPolicy == View.CYCLOPEAN_EYE_VIEW) &&
(!useStereo)) {
throw new
IllegalStateException(J3dI18N.getString("View31"));
}
monoscopicViewPolicy = policy;
synchronized(dirtyMaskLock) {
cvDirtyMask[0] |= MONOSCOPIC_VIEW_POLICY_DIRTY;
cvDirtyMask[1] |= MONOSCOPIC_VIEW_POLICY_DIRTY;
}
redraw();
}
/**
* Returns policy on how Java 3D generates monoscopic view.
* @return policy one of View.LEFT_EYE_VIEW, View.RIGHT_EYE_VIEW or
* View.CYCLOPEAN_EYE_VIEW.
*
* @since Java 3D 1.2
*/
public int getMonoscopicViewPolicy() {
return this.monoscopicViewPolicy;
}
/**
* Returns a status flag indicating whether or not double
* buffering is available.
* This is equivalent to:
* <ul>
* <code>
* ((Boolean)queryProperties().
* get("doubleBufferAvailable")).
* booleanValue()
* </code>
* </ul>
*
* @return a flag indicating whether double buffering is available.
*/
public boolean getDoubleBufferAvailable() {
return ((Boolean)queryProperties().get("doubleBufferAvailable")).
booleanValue();
}
/**
* Turns double buffering on or off. If double buffering
* is off, all drawing is to the front buffer and no buffer swap
* is done between frames. It should be stressed that running
* Java 3D with double buffering disabled is not recommended.
* Enabling double buffering on a Canvas3D
* that does not support double buffering has no effect.
*
* @param flag enables or disables double buffering.
*
* @see #queryProperties
*/
public void setDoubleBufferEnable(boolean flag) {
doubleBufferEnable = flag;
useDoubleBuffer = doubleBufferEnable && doubleBufferAvailable;
if (Thread.currentThread() == screen.renderer) {
setRenderMode(ctx, FIELD_ALL, useDoubleBuffer);
}
redraw();
}
/**
* Returns a status flag indicating whether or not double
* buffering is enabled.
* @return a flag indicating if double buffering is enabled.
*/
public boolean getDoubleBufferEnable() {
return doubleBufferEnable;
}
/**
* Returns a status flag indicating whether or not scene
* antialiasing is available.
* This is equivalent to:
* <ul>
* <code>
* ((Boolean)queryProperties().
* get("sceneAntialiasingAvailable")).
* booleanValue()
* </code>
* </ul>
*
* @return a flag indicating whether scene antialiasing is available.
*/
public boolean getSceneAntialiasingAvailable() {
return ((Boolean)queryProperties().get("sceneAntialiasingAvailable")).
booleanValue();
}
/**
* Returns a flag indicating whether or not the specified shading
* language is supported. A ShaderError will be generated if an
* unsupported shading language is used.
*
* @param shadingLanguage the shading language being queried, one of:
* <code>Shader.SHADING_LANGUAGE_GLSL</code> or
* <code>Shader.SHADING_LANGUAGE_CG</code>.
*
* @return true if the specified shading language is supported,
* false otherwise.
*
* @since Java 3D 1.4
*/
public boolean isShadingLanguageSupported(int shadingLanguage) {
// Call queryProperties to ensure that the shading language flags are valid
queryProperties();
if (shadingLanguage == Shader.SHADING_LANGUAGE_GLSL)
return shadingLanguageGLSL;
return false;
}
/**
* Returns a read-only Map object containing key-value pairs that define
* various properties for this Canvas3D. All of the keys are
* String objects. The values are key-specific, but most will be
* Boolean, Integer, Float, Double, or String objects.
*
* <p>
* The currently defined keys are:
*
* <p>
* <ul>
* <table BORDER=1 CELLSPACING=1 CELLPADDING=1>
* <tr>
* <td><b>Key (String)</b></td>
* <td><b>Value Type</b></td>
* </tr>
* <tr>
* <td><code>shadingLanguageCg</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>shadingLanguageGLSL</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>doubleBufferAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>stereoAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>sceneAntialiasingAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>sceneAntialiasingNumPasses</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>stencilSize</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>texture3DAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureColorTableSize</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureLodRangeAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureLodOffsetAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureWidthMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureHeightMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureBoundaryWidthMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureEnvCombineAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureCombineDot3Available</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureCombineSubtractAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureCoordSetsMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureUnitStateMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureImageUnitsMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureImageUnitsVertexMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureImageUnitsCombinedMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>textureCubeMapAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureDetailAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureSharpenAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureFilter4Available</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>textureAnisotropicFilterDegreeMax</code></td>
* <td>Float</td>
* </tr>
* <tr>
* <td><code>textureNonPowerOfTwoAvailable</code></td>
* <td>Boolean</td>
* </tr>
* <tr>
* <td><code>vertexAttrsMax</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>compressedGeometry.majorVersionNumber</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>compressedGeometry.minorVersionNumber</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>compressedGeometry.minorMinorVersionNumber</code></td>
* <td>Integer</td>
* </tr>
* <tr>
* <td><code>native.version</code></td>
* <td>String</td>
* </tr>
* </table>
* </ul>
*
* <p>
* The descriptions of the values returned for each key are as follows:
*
* <p>
* <ul>
* <li>
* <code>shadingLanguageCg</code>
* <ul>
* A Boolean indicating whether or not Cg shading Language
* is available for this Canvas3D.
* </ul>
* </li>
*
* <li>
* <code>shadingLanguageGLSL</code>
* <ul>
* A Boolean indicating whether or not GLSL shading Language
* is available for this Canvas3D.
* </ul>
* </li>
*
* <li>
* <code>doubleBufferAvailable</code>
* <ul>
* A Boolean indicating whether or not double buffering
* is available for this Canvas3D. This is equivalent to
* the getDoubleBufferAvailable method. If this flag is false,
* the Canvas3D will be rendered in single buffer mode; requests
* to enable double buffering will be ignored.
* </ul>
* </li>
*
* <li>
* <code>stereoAvailable</code>
* <ul>
* A Boolean indicating whether or not stereo
* is available for this Canvas3D. This is equivalent to
* the getStereoAvailable method. If this flag is false,
* the Canvas3D will be rendered in monoscopic mode; requests
* to enable stereo will be ignored.
* </ul>
* </li>
*
* <li>
* <code>sceneAntialiasingAvailable</code>
* <ul>
* A Boolean indicating whether or not scene antialiasing
* is available for this Canvas3D. This is equivalent to
* the getSceneAntialiasingAvailable method. If this flag is false,
* requests to enable scene antialiasing will be ignored.
* </ul>
* </li>
*
* <li>
* <code>sceneAntialiasingNumPasses</code>
* <ul>
* An Integer indicating the number of passes scene antialiasing
* requires to render a single frame for this Canvas3D.
* If this value is zero, scene antialiasing is not supported.
* If this value is one, multisampling antialiasing is used.
* Otherwise, the number indicates the number of rendering passes
* needed.
* </ul>
* </li>
*
* <li>
* <code>stencilSize</code>
* <ul>
* An Integer indicating the number of stencil bits that are available
* for this Canvas3D.
* </ul>
* </li>
*
* <li>
* <code>texture3DAvailable</code>
* <ul>
* A Boolean indicating whether or not 3D Texture mapping
* is available for this Canvas3D. If this flag is false,
* 3D texture mapping is either not supported by the underlying
* rendering layer or is otherwise unavailable for this
* particular Canvas3D. All use of 3D texture mapping will be
* ignored in this case.
* </ul>
* </li>
*
* <li>
* <code>textureColorTableSize</code>
* <ul>
* An Integer indicating the maximum size of the texture color
* table for this Canvas3D. If the size is 0, the texture
* color table is either not supported by the underlying rendering
* layer or is otherwise unavailable for this particular
* Canvas3D. An attempt to use a texture color table larger than
* textureColorTableSize will be ignored; no color lookup will be
* performed.
* </ul>
* </li>
*
* <li>
* <code>textureLodRangeAvailable</code>
* <ul>
* A Boolean indicating whether or not setting only a subset of mipmap
* levels and setting a range of texture LOD are available for this
* Canvas3D.
* If it indicates false, setting a subset of mipmap levels and
* setting a texture LOD range are not supported by the underlying
* rendering layer, and an attempt to set base level, or maximum level,
* or minimum LOD, or maximum LOD will be ignored. In this case,
* images for all mipmap levels must be defined for the texture to be
* valid.
* </ul>
* </li>
*
* <li>
* <code>textureLodOffsetAvailable</code>
* <ul>
* A Boolean indicating whether or not setting texture LOD offset is
* available for this Canvas3D. If it indicates false, setting
* texture LOD offset is not supported by the underlying rendering
* layer, and an attempt to set the texture LOD offset will be ignored.
* </ul>
* </li>
*
* <li>
* <code>textureWidthMax</code>
* <ul>
* An Integer indicating the maximum texture width supported by
* this Canvas3D. If the width of a texture exceeds the maximum texture
* width for a Canvas3D, then the texture will be effectively disabled
* for that Canvas3D.
* </ul>
* </li>
*
* <li>
* <code>textureHeightMax</code>
* <ul>
* An Integer indicating the maximum texture height supported by
* this Canvas3D. If the height of a texture exceeds the maximum texture
* height for a Canvas3D, then the texture will be effectively disabled
* for that Canvas3D.
* </ul>
* </li>
*
* <li>
* <code>textureBoundaryWidthMax</code>
* <ul>
* An Integer indicating the maximum texture boundary width
* supported by the underlying rendering layer for this Canvas3D. If
* the maximum supported texture boundary width is 0, then texture
* boundary is not supported by the underlying rendering layer.
* An attempt to specify a texture boundary width > the
* textureBoundaryWidthMax will effectively disable the texture.
* </ul>
* </li>
*
* <li>
* <code>textureEnvCombineAvailable</code>
* <ul>
* A Boolean indicating whether or not texture environment combine
* operation is supported for this Canvas3D. If it indicates false,
* then texture environment combine is not supported by the
* underlying rendering layer, and an attempt to specify COMBINE
* as the texture mode will be ignored. The texture mode in effect
* will be REPLACE.
* </ul>
* </li>
*
* <li>
* <code>textureCombineDot3Available</code>
* <ul>
* A Boolean indicating whether or not texture combine mode
* COMBINE_DOT3 is
* supported for this Canvas3D. If it indicates false, then
* texture combine mode COMBINE_DOT3 is not supported by
* the underlying rendering layer, and an attempt to specify
* COMBINE_DOT3 as the texture combine mode will be ignored.
* The texture combine mode in effect will be COMBINE_REPLACE.
* </ul>
* </li>
*
* <li>
* <code>textureCombineSubtractAvailable</code>
* <ul>
* A Boolean indicating whether or not texture combine mode
* COMBINE_SUBTRACT is
* supported for this Canvas3D. If it indicates false, then
* texture combine mode COMBINE_SUBTRACT is not supported by
* the underlying rendering layer, and an attempt to specify
* COMBINE_SUBTRACT as the texture combine mode will be ignored.
* The texture combine mode in effect will be COMBINE_REPLACE.
* </ul>
* </li>
*
* <li>
* <code>textureCoordSetsMax</code>
* <ul>
* An Integer indicating the maximum number of texture coordinate sets
* supported by the underlying rendering layer.
* </ul>
* </li>
*
* <li>
* <code>textureUnitStateMax</code>
* <ul>
* An Integer indicating the maximum number of fixed-function texture units
* supported by the underlying rendering layer. If the number of
* application-sepcified texture unit states exceeds the maximum number
* for a Canvas3D, and the fixed-function rendering pipeline is used, then
* the texture will be effectively disabled for that Canvas3D.
* </ul>
* </li>
*
* <li>
* <code>textureImageUnitsMax</code>
* <ul>
* An Integer indicating the maximum number of texture image units
* that can be accessed by the fragment shader when programmable shaders
* are used.
* </ul>
* </li>
*
* <li>
* <code>textureImageUnitsVertexMax</code>
* <ul>
* An Integer indicating the maximum number of texture image units
* that can be accessed by the vertex shader when programmable shaders
* are used.
* </ul>
* </li>
*
* <li>
* <code>textureImageUnitsCombinedMax</code>
* <ul>
* An Integer indicating the combined maximum number of texture image units
* that can be accessed by the vertex shader and the fragment shader when
* programmable shaders are used.
* </ul>
* </li>
*
* <li>
* <code>textureCubeMapAvailable</code>
* <ul>
* A Boolean indicating whether or not texture cube map is supported
* for this Canvas3D. If it indicates false, then texture cube map
* is not supported by the underlying rendering layer, and an attempt
* to specify NORMAL_MAP or REFLECTION_MAP as the texture generation
* mode will be ignored. The texture generation mode in effect will
* be SPHERE_MAP.
* </ul>
* </li>
*
* <li>
* <code>textureDetailAvailable</code>
* <ul>
* A Boolean indicating whether or not detail texture is supported
* for this Canvas3D. If it indicates false, then detail texture is
* not supported by the underlying rendering layer, and an attempt
* to specify LINEAR_DETAIL, LINEAR_DETAIL_ALPHA or
* LINEAR_DETAIL_RGB as the texture magnification filter mode will
* be ignored. The texture magnification filter mode in effect will
* be BASE_LEVEL_LINEAR.
* As of Java 3D 1.5, this property is always false.
* </ul>
* </li>
*
* <li>
* <code>textureSharpenAvailable</code>
* <ul>
* A Boolean indicating whether or not sharpen texture is supported
* for this Canvas3D. If it indicates false, then sharpen texture
* is not supported by the underlying rendering layer, and an attempt
* to specify LINEAR_SHARPEN, LINEAR_SHARPEN_ALPHA or
* LINEAR_SHARPEN_RGB as the texture magnification filter mode
* will be ignored. The texture magnification filter mode in effect
* will be BASE_LEVEL_LINEAR.
* </ul>
* </li>
*
* <li>
* <code>textureFilter4Available</code>
* <ul>
* A Boolean indicating whether or not filter4 is supported for this
* Canvas3D. If it indicates flase, then filter4 is not supported
* by the underlying rendering layer, and an attempt to specify
* FILTER_4 as the texture minification filter mode or texture
* magnification filter mode will be ignored. The texture filter mode
* in effect will be BASE_LEVEL_LINEAR.
* </ul>
* </li>
*
* <li>
* <code>textureAnisotropicFilterDegreeMax</code>
* <ul>
* A Float indicating the maximum degree of anisotropic filter
* available for this Canvas3D. If it indicates 1.0, setting
* anisotropic filter is not supported by the underlying rendering
* layer, and an attempt to set anisotropic filter degree will be ignored.
* </ul>
* </li>
* <li>
* <code>textureNonPowerOfTwoAvailable</code>
* <ul>
* A Boolean indicating whether or not texture dimensions that are
* not powers of two are supported for
* for this Canvas3D. If it indicates false, then textures with
* non power of two sizes will be ignored. Set the property
* j3d.textureEnforcePowerOfTwo to revert to the pre-1.5 behavior
* of throwing exceptions for non power of two textures.
* </ul>
* </li>
*
* <li>
* <code>vertexAttrsMax</code>
* <ul>
* An Integer indicating the maximum number of vertex attributes
* supported by the underlying rendering layer. This is in addition to
* the vertex coordinate (position), color, normal, and so forth.
* </ul>
* </li>
*
* <li>
* <code>compressedGeometry.majorVersionNumber</code><br>
* <code>compressedGeometry.minorVersionNumber</code><br>
* <code>compressedGeometry.minorMinorVersionNumber</code>
* <ul>
* Integers indicating the major, minor, and minor-minor
* version numbers, respectively, of the version of compressed
* geometry supported by this version of Java 3D.
* </ul>
* </li>
*
* <li>
* <code>native.version</code>
* <ul>
* A String indicating the version number of the native graphics
* library. The format of this string is defined by the native
* library.
* </ul>
* </li>
* </ul>
*
* @return the properties of this Canavs3D
*
* @since Java 3D 1.2
*/
public final Map queryProperties() {
if (queryProps == null) {
boolean createDummyCtx = false;
synchronized (VirtualUniverse.mc.contextCreationLock) {
if (ctx == null) {
createDummyCtx = true;
}
}
if (createDummyCtx) {
GraphicsConfigTemplate3D.setQueryProps(this);
}
//create query Properties
createQueryProps();
}
if (fatalError) {
throw new IllegalStateException(J3dI18N.getString("Canvas3D29"));
}
return queryProps;
}
void createQueryContext() {
// create a dummy context to query for support of certain
// extensions, the context will destroy immediately
// inside the native code after setting the various
// fields in this object
createQueryContext(drawable, offScreen, 1, 1);
// compute the max available texture units
maxAvailableTextureUnits = Math.max(maxTextureUnits, maxTextureImageUnits);
}
/**
* Creates the query properties for this Canvas.
*/
private void createQueryProps() {
// Create lists of keys and values
ArrayList<String> keys = new ArrayList<String>();
ArrayList<Object> values = new ArrayList<Object>();
int pass = 0;
// properties not associated with graphics context
keys.add("doubleBufferAvailable");
values.add(new Boolean(doubleBufferAvailable));
keys.add("stereoAvailable");
values.add(new Boolean(stereoAvailable));
keys.add("sceneAntialiasingAvailable");
values.add(new Boolean(sceneAntialiasingAvailable));
keys.add("sceneAntialiasingNumPasses");
if (sceneAntialiasingAvailable) {
pass = (sceneAntialiasingMultiSamplesAvailable ?
1: Renderer.NUM_ACCUMULATION_SAMPLES);
}
values.add(new Integer(pass));
keys.add("stencilSize");
// Return the actual stencil size if the user owns it, otherwise
// return 0
if (userStencilAvailable) {
values.add(new Integer(actualStencilSize));
} else {
values.add(new Integer(0));
}
keys.add("compressedGeometry.majorVersionNumber");
values.add(new Integer(GeometryDecompressor.majorVersionNumber));
keys.add("compressedGeometry.minorVersionNumber");
values.add(new Integer(GeometryDecompressor.minorVersionNumber));
keys.add("compressedGeometry.minorMinorVersionNumber");
values.add(new Integer(GeometryDecompressor.minorMinorVersionNumber));
// Properties associated with graphics context
keys.add("texture3DAvailable");
values.add(new Boolean((textureExtendedFeatures & TEXTURE_3D) != 0));
keys.add("textureColorTableSize");
values.add(new Integer(textureColorTableSize));
keys.add("textureEnvCombineAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_COMBINE) != 0));
keys.add("textureCombineDot3Available");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_COMBINE_DOT3) != 0));
keys.add("textureCombineSubtractAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_COMBINE_SUBTRACT) != 0));
keys.add("textureCubeMapAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_CUBE_MAP) != 0));
keys.add("textureSharpenAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_SHARPEN) != 0));
keys.add("textureDetailAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_DETAIL) != 0));
keys.add("textureFilter4Available");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_FILTER4) != 0));
keys.add("textureAnisotropicFilterDegreeMax");
values.add(new Float(anisotropicDegreeMax));
keys.add("textureWidthMax");
values.add(new Integer(textureWidthMax));
keys.add("textureHeightMax");
values.add(new Integer(textureHeightMax));
keys.add("texture3DWidthMax");
values.add(new Integer(texture3DWidthMax));
keys.add("texture3DHeightMax");
values.add(new Integer(texture3DHeightMax));
keys.add("texture3DDepthMax");
values.add(new Integer(texture3DDepthMax));
keys.add("textureBoundaryWidthMax");
values.add(new Integer(textureBoundaryWidthMax));
keys.add("textureLodRangeAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_LOD_RANGE) != 0));
keys.add("textureLodOffsetAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_LOD_OFFSET) != 0));
keys.add("textureNonPowerOfTwoAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_NON_POWER_OF_TWO) != 0));
keys.add("textureAutoMipMapGenerationAvailable");
values.add(new Boolean(
(textureExtendedFeatures & TEXTURE_AUTO_MIPMAP_GENERATION) != 0));
keys.add("textureCoordSetsMax");
values.add(new Integer(maxTexCoordSets));
keys.add("textureUnitStateMax");
values.add(new Integer(maxTextureUnits));
keys.add("textureImageUnitsMax");
values.add(new Integer(maxTextureImageUnits));
keys.add("textureImageUnitsVertexMax");
values.add(new Integer(maxVertexTextureImageUnits));
keys.add("textureImageUnitsCombinedMax");
values.add(new Integer(maxCombinedTextureImageUnits));
keys.add("vertexAttrsMax");
values.add(new Integer(maxVertexAttrs));
keys.add("shadingLanguageGLSL");
values.add(new Boolean(shadingLanguageGLSL));
keys.add("native.version");
values.add(nativeGraphicsVersion);
keys.add("native.vendor");
values.add(nativeGraphicsVendor);
keys.add("native.renderer");
values.add(nativeGraphicsRenderer);
// Now Create read-only properties object
queryProps = new J3dQueryProps(keys, values);
}
/**
* Update the view cache associated with this canvas.
*/
void updateViewCache(boolean flag, CanvasViewCache cvc,
BoundingBox frustumBBox, boolean doInfinite) {
assert cvc == null;
synchronized(cvLock) {
if (firstPaintCalled && (canvasViewCache != null)) {
assert canvasViewCacheFrustum != null;
// Issue 109 : choose the appropriate cvCache
if (frustumBBox != null) {
canvasViewCacheFrustum.snapshot(true);
canvasViewCacheFrustum.computeDerivedData(flag, null,
frustumBBox, doInfinite);
} else {
canvasViewCache.snapshot(false);
canvasViewCache.computeDerivedData(flag, null,
null, doInfinite);
}
}
}
}
/**
* Set depthBufferWriteEnableOverride flag
*/
void setDepthBufferWriteEnableOverride(boolean flag) {
depthBufferWriteEnableOverride = flag;
}
/**
* Set depthBufferEnableOverride flag
*/
void setDepthBufferEnableOverride(boolean flag) {
depthBufferEnableOverride = flag;
}
// Static initializer for Canvas3D class
static {
VirtualUniverse.loadLibraries();
}
void resetTexture(Context ctx, int texUnitIndex) {
// D3D also need to reset texture attributes
this.resetTextureNative(ctx, texUnitIndex);
if (texUnitIndex < 0) {
texUnitIndex = 0;
}
texUnitState[texUnitIndex].mirror = null;
texUnitState[texUnitIndex].texture = null;
}
// reset all attributes so that everything e.g. display list,
// texture will recreate again in the next frame
void resetRendering() {
reset();
synchronized (dirtyMaskLock) {
cvDirtyMask[0] |= VIEW_INFO_DIRTY;
cvDirtyMask[1] |= VIEW_INFO_DIRTY;
}
}
void reset() {
int i;
currentAppear = new AppearanceRetained();
currentMaterial = new MaterialRetained();
viewFrustum = new CachedFrustum();
canvasDirty = 0xffff;
lightBin = null;
environmentSet = null;
attributeBin = null;
shaderBin = null;
textureBin = null;
renderMolecule = null;
polygonAttributes = null;
lineAttributes = null;
pointAttributes = null;
material = null;
enableLighting = false;
transparency = null;
coloringAttributes = null;
shaderProgram = null;
texture = null;
texAttrs = null;
if (texUnitState != null) {
TextureUnitStateRetained tus;
for (i=0; i < texUnitState.length; i++) {
tus = texUnitState[i];
if (tus != null) {
tus.texAttrs = null;
tus.texGen = null;
}
}
}
texCoordGeneration = null;
renderingAttrs = null;
appearance = null;
appHandle = null;
dirtyRenderMoleculeList.clear();
displayListResourceFreeList.clear();
dirtyDlistPerRinfoList.clear();
textureIdResourceFreeList.clear();
lightChanged = true;
modelMatrix = null;
modelClip = null;
fog = null;
sceneAmbient = new Color3f();
for (i=0; i< frameCount.length;i++) {
frameCount[i] = -1;
}
for (i=0; i < lights.length; i++) {
lights[i] = null;
}
if (currentLights != null) {
for (i=0; i < currentLights.length; i++) {
currentLights[i] = null;
}
}
enableMask = -1;
stateUpdateMask = 0;
depthBufferWriteEnableOverride = false;
depthBufferEnableOverride = false;
depthBufferWriteEnable = true;
vfPlanesValid = false;
lightChanged = false;
for (i=0; i < curStateToUpdate.length; i++) {
curStateToUpdate[i] = null;
}
// Issue 362 - need to reset display lists and ctxTimeStamp in this
// method, so that display lists will be recreated when canvas is
// removed from a view and then added back into a view with another
// canvas
needToRebuildDisplayList = true;
ctxTimeStamp = VirtualUniverse.mc.getContextTimeStamp();
}
void resetImmediateRendering() {
canvasDirty = 0xffff;
ra = null;
setSceneAmbient(ctx, 0.0f, 0.0f, 0.0f);
disableFog(ctx);
resetRenderingAttributes(ctx, false, false);
resetTexture(ctx, -1);
resetTexCoordGeneration(ctx);
resetTextureAttributes(ctx);
texUnitState[0].texAttrs = null;
texUnitState[0].texGen = null;
resetPolygonAttributes(ctx);
resetLineAttributes(ctx);
resetPointAttributes(ctx);
resetTransparency(ctx,
RenderMolecule.SURFACE,
PolygonAttributes.POLYGON_FILL,
false, false);
resetColoringAttributes(ctx,
1.0f, 1.0f,
1.0f, 1.0f, false);
updateMaterial(ctx, 1.0f, 1.0f, 1.0f, 1.0f);
resetRendering();
makeCtxCurrent();
synchronized (dirtyMaskLock) {
cvDirtyMask[0] |= VIEW_INFO_DIRTY;
cvDirtyMask[1] |= VIEW_INFO_DIRTY;
}
needToRebuildDisplayList = true;
ctxTimeStamp = VirtualUniverse.mc.getContextTimeStamp();
}
@Override
public Point getLocationOnScreen() {
try {
return super.getLocationOnScreen();
}
catch (IllegalComponentStateException e) {}
return new Point();
}
void setProjectionMatrix(Context ctx, Transform3D projTrans) {
this.projTrans = projTrans;
setProjectionMatrix(ctx, projTrans.mat);
}
void setModelViewMatrix(Context ctx, double[] viewMatrix, Transform3D mTrans) {
setModelViewMatrix(ctx, viewMatrix, mTrans.mat);
if (!useStereo) {
this.modelMatrix = mTrans;
} else {
// TODO : This seems wrong to do only for the right eye.
// A possible approach is to invalidate the cache at begin of
// each eye.
if (rightStereoPass) {
// Only set cache in right stereo pass, otherwise
// if the left stereo pass set the cache value,
// setModelViewMatrix() in right stereo pass will not
// perform in RenderMolecules.
this.modelMatrix = mTrans;
}
}
}
void setDepthBufferWriteEnable(boolean mode) {
depthBufferWriteEnable = mode;
setDepthBufferWriteEnable(ctx, mode);
}
void setNumActiveTexUnit(int n) {
numActiveTexUnit = n;
}
int getNumActiveTexUnit() {
return numActiveTexUnit;
}
void setLastActiveTexUnit(int n) {
lastActiveTexUnit = n;
}
int getLastActiveTexUnit() {
return lastActiveTexUnit;
}
// Create the texture state array
void createTexUnitState() {
texUnitState = new TextureUnitStateRetained[maxAvailableTextureUnits];
for (int t = 0; t < maxAvailableTextureUnits; t++) {
texUnitState[t] = new TextureUnitStateRetained();
texUnitState[t].texture = null;
texUnitState[t].mirror = null;
}
}
/**
* Enable separate specular color if it is not overriden by the
* property j3d.disableSeparateSpecular.
*/
void enableSeparateSpecularColor() {
boolean enable = !VirtualUniverse.mc.disableSeparateSpecularColor;
updateSeparateSpecularColorEnable(ctx, enable);
}
// Send a createOffScreenBuffer message to Renderer (via
// MasterControl) and wait for it to be done
private void sendCreateOffScreenBuffer() {
// Wait for the buffer to be created unless called from
// a Behavior or from a Rendering thread
if (!(Thread.currentThread() instanceof BehaviorScheduler) &&
!(Thread.currentThread() instanceof Renderer)) {
offScreenBufferPending = true;
}
// Send message to Renderer thread to perform createOffScreenBuffer.
VirtualUniverse.mc.sendCreateOffScreenBuffer(this);
// Wait for off-screen buffer to be created
while (offScreenBufferPending) {
// Issue 364: create master control thread if needed
VirtualUniverse.mc.createMasterControlThread();
MasterControl.threadYield();
}
}
// Send a destroyOffScreenBuffer message to Renderer (via
// MasterControl) and wait for it to be done
private void sendDestroyCtxAndOffScreenBuffer() {
// Wait for the buffer to be destroyed unless called from
// a Behavior or from a Rendering thread
Thread currentThread = Thread.currentThread();
if (!(currentThread instanceof BehaviorScheduler) &&
!(currentThread instanceof Renderer)) {
offScreenBufferPending = true;
}
// Fix for Issue 18 and Issue 175
// Send message to Renderer thread to perform remove Ctx and destroyOffScreenBuffer.
VirtualUniverse.mc.sendDestroyCtxAndOffScreenBuffer(this);
// Wait for ctx and off-screen buffer to be destroyed
while (offScreenBufferPending) {
// Issue 364: create master control thread if needed
VirtualUniverse.mc.createMasterControlThread();
MasterControl.threadYield();
}
}
// Send a allocateCanvasId message to Renderer (via MasterControl) without
// waiting for it to be done
private void sendAllocateCanvasId() {
// Send message to Renderer thread to allocate a canvasId
VirtualUniverse.mc.sendAllocateCanvasId(this);
}
// Send a freeCanvasId message to Renderer (via MasterControl) without
// waiting for it to be done
private void sendFreeCanvasId() {
// Send message to Renderer thread to free the canvasId
VirtualUniverse.mc.sendFreeCanvasId(this);
}
private void removeCtx() {
if ((screen != null) &&
(screen.renderer != null) &&
(ctx != null)) {
VirtualUniverse.mc.postRequest(MasterControl.FREE_CONTEXT,
new Object[]{this,
Long.valueOf(0L),
drawable,
ctx});
// Fix for Issue 19
// Wait for the context to be freed unless called from
// a Behavior or from a Rendering thread
Thread currentThread = Thread.currentThread();
if (!(currentThread instanceof BehaviorScheduler) &&
!(currentThread instanceof Renderer)) {
while (ctxTimeStamp != 0) {
MasterControl.threadYield();
}
}
ctx = null;
}
}
/**
* Serialization of Canvas3D objects is not supported.
*
* @exception UnsupportedOperationException this method is not supported
*
* @since Java 3D 1.3
*/
private void writeObject(java.io.ObjectOutputStream out)
throws java.io.IOException {
throw new UnsupportedOperationException(J3dI18N.getString("Canvas3D20"));
}
/**
* Serialization of Canvas3D objects is not supported.
*
* @exception UnsupportedOperationException this method is not supported
*
* @since Java 3D 1.3
*/
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
throw new UnsupportedOperationException(J3dI18N.getString("Canvas3D20"));
}
// mark that the current bin specified by the bit is already updated
void setStateIsUpdated(int bit) {
stateUpdateMask &= ~(1 << bit);
}
// mark that the bin specified by the bit needs to be updated
void setStateToUpdate(int bit, Object bin) {
stateUpdateMask |= 1 << bit;
curStateToUpdate[bit] = bin;
}
// update LightBin, EnvironmentSet, AttributeBin & ShaderBin if neccessary
// according to the stateUpdateMask
static int ENV_STATE_MASK = (1 << LIGHTBIN_BIT) |
(1 << ENVIRONMENTSET_BIT) |
(1 << ATTRIBUTEBIN_BIT) |
(1 << SHADERBIN_BIT);
void updateEnvState() {
if ((stateUpdateMask & ENV_STATE_MASK) == 0)
return;
if ((stateUpdateMask & (1 << LIGHTBIN_BIT)) != 0) {
((LightBin)curStateToUpdate[LIGHTBIN_BIT]).updateAttributes(this);
}
if ((stateUpdateMask & (1 << ENVIRONMENTSET_BIT)) != 0) {
((EnvironmentSet)
curStateToUpdate[ENVIRONMENTSET_BIT]).updateAttributes(this);
}
if ((stateUpdateMask & (1 << ATTRIBUTEBIN_BIT)) != 0) {
((AttributeBin)
curStateToUpdate[ATTRIBUTEBIN_BIT]).updateAttributes(this);
}
if ((stateUpdateMask & (1 << SHADERBIN_BIT)) != 0) {
((ShaderBin)
curStateToUpdate[SHADERBIN_BIT]).updateAttributes(this);
}
// reset the state update mask for those environment state bits
stateUpdateMask &= ~ENV_STATE_MASK;
}
/**
* update state if neccessary according to the stateUpdatedMask
*/
void updateState( int dirtyBits) {
if (stateUpdateMask == 0)
return;
updateEnvState();
if ((stateUpdateMask & (1 << TEXTUREBIN_BIT)) != 0) {
((TextureBin)
curStateToUpdate[TEXTUREBIN_BIT]).updateAttributes(this);
}
if ((stateUpdateMask & (1 << RENDERMOLECULE_BIT)) != 0) {
((RenderMolecule)
curStateToUpdate[RENDERMOLECULE_BIT]).updateAttributes(this,
dirtyBits);
}
if ((stateUpdateMask & (1 << TRANSPARENCY_BIT)) != 0) {
((RenderMolecule)curStateToUpdate[RENDERMOLECULE_BIT]).updateTransparencyAttributes(this);
stateUpdateMask &= ~(1 << TRANSPARENCY_BIT);
}
// reset state update mask
stateUpdateMask = 0;
}
// This method updates this Texture2D for raster.
// Note : No multi-texture is not used.
void updateTextureForRaster(Texture2DRetained texture) {
// Setup texture and texture attributes for texture unit 0.
Pipeline.getPipeline().updateTextureUnitState(ctx, 0, true);
setLastActiveTexUnit(0);
setNumActiveTexUnit(1);
texture.updateNative(this);
resetTexCoordGeneration(ctx);
resetTextureAttributes(ctx);
for(int i=1; i < maxTextureUnits; i++) {
resetTexture(ctx, i);
}
// set the active texture unit back to 0
activeTextureUnit(ctx, 0);
// Force the next textureBin to reload.
canvasDirty |= Canvas3D.TEXTUREBIN_DIRTY | Canvas3D.TEXTUREATTRIBUTES_DIRTY;
}
void restoreTextureBin() {
// Need to check TextureBin's shaderBin for null
// TextureBin can get clear() if there isn't any RM under it.
if((textureBin != null) && (textureBin.shaderBin != null)) {
textureBin.updateAttributes(this);
}
}
void textureFill(RasterRetained raster, Point2d winCoord,
float mapZ, float alpha) {
int winWidth = canvasViewCache.getCanvasWidth();
int winHeight = canvasViewCache.getCanvasHeight();
int rasterImageWidth = raster.image.width;
int rasterImageHeight = raster.image.height;
float texMinU = 0, texMinV = 0, texMaxU = 0, texMaxV = 0;
float mapMinX = 0, mapMinY = 0, mapMaxX = 0, mapMaxY = 0;
Point rasterSrcOffset = new Point();
raster.getSrcOffset(rasterSrcOffset);
Dimension rasterSize = new Dimension();
raster.getSize(rasterSize);
// System.err.println("rasterImageWidth " + rasterImageWidth + " rasterImageHeight " + rasterImageHeight);
// System.err.println("rasterSrcOffset " + rasterSrcOffset + " rasterSize " + rasterSize);
int rasterMinX = rasterSrcOffset.x;
int rasterMaxX = rasterSrcOffset.x + rasterSize.width;
int rasterMinY = rasterSrcOffset.y;
int rasterMaxY = rasterSrcOffset.y + rasterSize.height;
if ((rasterMinX >= rasterImageWidth) || (rasterMinY >= rasterImageHeight) ||
(rasterMaxX <= 0) || (rasterMaxY <= 0)) {
return;
}
if (rasterMinX < 0) {
rasterMinX = 0;
}
if (rasterMinY < 0) {
rasterMinY = 0;
}
if (rasterMaxX > rasterImageWidth) {
rasterMaxX = rasterImageWidth;
}
if (rasterMaxY > rasterImageHeight) {
rasterMaxY = rasterImageHeight;
}
texMinU = (float) rasterMinX / (float) rasterImageWidth;
texMaxU = (float) rasterMaxX / (float) rasterImageWidth;
mapMinX = (float) winCoord.x / (float) winWidth;
mapMaxX = (float) (winCoord.x + (rasterMaxX - rasterMinX)) / (float) winWidth;
if (raster.image.isYUp()) {
texMinV = (float) rasterMinY / (float) rasterImageHeight;
texMaxV = (float) rasterMaxY / (float) rasterImageHeight;
} else {
// System.err.println("In yUp is false case");
texMinV = 1.0f - (float) rasterMaxY / (float) rasterImageHeight;
texMaxV = 1.0f - (float) rasterMinY / (float) rasterImageHeight;
}
mapMinY = 1.0f - ((float) (winCoord.y + (rasterMaxY - rasterMinY)) / (float) winHeight);
mapMaxY = 1.0f - ((float) winCoord.y / (float) winHeight);
textureFillRaster(ctx, texMinU, texMaxU, texMinV, texMaxV,
mapMinX, mapMaxX, mapMinY, mapMaxY, mapZ, alpha, raster.image.useBilinearFilter());
}
void textureFill(BackgroundRetained bg, int winWidth, int winHeight) {
final int maxX = bg.image.width;
final int maxY = bg.image.height;
// System.err.println("maxX " + maxX + " maxY " + maxY);
float xzoom = (float)winWidth / maxX;
float yzoom = (float)winHeight / maxY;
float zoom = 0;
float texMinU = 0, texMinV = 0, texMaxU = 0, texMaxV = 0, adjustV = 0;
float mapMinX = 0, mapMinY = 0, mapMaxX = 0, mapMaxY = 0;
float halfWidth = 0, halfHeight = 0;
switch (bg.imageScaleMode) {
case Background.SCALE_NONE:
texMinU = 0.0f;
texMinV = 0.0f;
texMaxU = 1.0f;
texMaxV = 1.0f;
halfWidth = (float)winWidth/2.0f;
halfHeight = (float)winHeight/2.0f;
mapMinX = (float) ((0 - halfWidth)/halfWidth);
mapMinY = (float) ((0 - halfHeight)/halfHeight);
mapMaxX = (float) ((maxX - halfWidth)/halfWidth);
mapMaxY = (float) ((maxY - halfHeight)/halfHeight);
adjustV = ((float)winHeight - (float)maxY)/halfHeight;
mapMinY += adjustV;
mapMaxY += adjustV;
break;
case Background.SCALE_FIT_MIN:
zoom = Math.min(xzoom, yzoom);
texMinU = 0.0f;
texMinV = 0.0f;
texMaxU = 1.0f;
texMaxV = 1.0f;
mapMinX = -1.0f;
mapMaxY = 1.0f;
if (xzoom < yzoom) {
mapMaxX = 1.0f;
mapMinY = -1.0f + 2.0f * ( 1.0f - zoom * (float)maxY/(float) winHeight );
} else {
mapMaxX = -1.0f + zoom * (float)maxX/winWidth * 2;
mapMinY = -1.0f;
}
break;
case Background.SCALE_FIT_MAX:
zoom = Math.max(xzoom, yzoom);
mapMinX = -1.0f;
mapMinY = -1.0f;
mapMaxX = 1.0f;
mapMaxY = 1.0f;
if (xzoom < yzoom) {
texMinU = 0.0f;
texMinV = 0.0f;
texMaxU = (float)winWidth/maxX/zoom;
texMaxV = 1.0f;
} else {
texMinU = 0.0f;
texMinV = 1.0f - (float)winHeight/maxY/zoom;
texMaxU = 1.0f;
texMaxV = 1.0f;
}
break;
case Background.SCALE_FIT_ALL:
texMinU = 0.0f;
texMinV = 0.0f;
texMaxU = 1.0f;
texMaxV = 1.0f;
mapMinX = -1.0f;
mapMinY = -1.0f;
mapMaxX = 1.0f;
mapMaxY = 1.0f;
break;
case Background.SCALE_REPEAT:
texMinU = 0.0f;
texMinV = - yzoom;
texMaxU = xzoom;
texMaxV = 0.0f;
mapMinX = -1.0f;
mapMinY = -1.0f;
mapMaxX = 1.0f;
mapMaxY = 1.0f;
break;
case Background.SCALE_NONE_CENTER:
// TODO : Why is there a zoom ?
if(xzoom >= 1.0f){
texMinU = 0.0f;
texMaxU = 1.0f;
mapMinX = -(float)maxX/winWidth;
mapMaxX = (float)maxX/winWidth;
} else {
texMinU = 0.5f - (float)winWidth/maxX/2;
texMaxU = 0.5f + (float)winWidth/maxX/2;
mapMinX = -1.0f;
mapMaxX = 1.0f;
}
if (yzoom >= 1.0f) {
texMinV = 0.0f;
texMaxV = 1.0f;
mapMinY = -(float)maxY/winHeight;
mapMaxY = (float)maxY/winHeight;
} else {
texMinV = 0.5f - (float)winHeight/maxY/2;
texMaxV = 0.5f + (float)winHeight/maxY/2;
mapMinY = -1.0f;
mapMaxY = 1.0f;
}
break;
}
// System.err.println("Java 3D : mapMinX " + mapMinX + " mapMinY " + mapMinY +
// " mapMaxX " + mapMaxX + " mapMaxY " + mapMaxY);
textureFillBackground(ctx, texMinU, texMaxU, texMinV, texMaxV,
mapMinX, mapMaxX, mapMinY, mapMaxY, bg.image.useBilinearFilter());
}
void clear(BackgroundRetained bg, int winWidth, int winHeight) {
// Issue 239 - clear stencil if requested and available
// Note that this is a partial solution, since we eventually want an API
// to control this.
boolean clearStencil = VirtualUniverse.mc.stencilClear &&
userStencilAvailable;
clear(ctx, bg.color.x, bg.color.y, bg.color.z, clearStencil);
// TODO : This is a bug on not mirror bg. Will fix this as a bug after 1.5 beta.
// For now, as a workaround, we will check bg.image and bg.image.imageData not null.
if((bg.image != null) && (bg.image.imageData != null)) {
// setup Texture pipe.
updateTextureForRaster(bg.texture);
textureFill(bg, winWidth, winHeight);
// Restore texture pipe.
restoreTextureBin();
}
}
/**
* obj is either TextureRetained or DetailTextureImage
* if obj is DetailTextureImage then we just clear
* the resourceCreationMask of all the formats
* no matter it is create or not since we don't
* remember the format information for simplicity.
* We don't need to check duplicate value of id in the
* table since this procedure is invoke only when id
* of texture is -1 one time only.
* This is always call from Renderer thread.
*/
void addTextureResource(int id, TextureRetained obj) {
if (id <= 0) {
return;
}
if (useSharedCtx) {
screen.renderer.addTextureResource(id, obj);
} else {
// This will replace the previous key if exists
if (textureIDResourceTable.size() <= id) {
for (int i=textureIDResourceTable.size();
i < id; i++) {
textureIDResourceTable.add(null);
}
textureIDResourceTable.add(obj);
} else {
textureIDResourceTable.set(id, obj);
}
}
}
// handle free resource in the FreeList
void freeResourcesInFreeList(Context ctx) {
Iterator<Integer> it;
int val;
// free resource for those canvases that
// don't use shared ctx
if (displayListResourceFreeList.size() > 0) {
for (it = displayListResourceFreeList.iterator(); it.hasNext();) {
val = it.next().intValue();
if (val <= 0) {
continue;
}
Canvas3D.freeDisplayList(ctx, val);
}
displayListResourceFreeList.clear();
}
if (textureIdResourceFreeList.size() > 0) {
for (it = textureIdResourceFreeList.iterator(); it.hasNext();) {
val = it.next().intValue();
if (val <= 0) {
continue;
}
if (val >= textureIDResourceTable.size()) {
System.err.println("Error in freeResourcesInFreeList : ResourceIDTableSize = " +
textureIDResourceTable.size() +
" val = " + val);
} else {
TextureRetained tex = textureIDResourceTable.get(val);
if (tex != null) {
synchronized (tex.resourceLock) {
tex.resourceCreationMask &= ~canvasBit;
if (tex.resourceCreationMask == 0) {
tex.freeTextureId(val);
}
}
}
textureIDResourceTable.set(val, null);
}
Canvas3D.freeTexture(ctx, val);
}
textureIdResourceFreeList.clear();
}
}
void freeContextResources(Renderer rdr, boolean freeBackground,
Context ctx) {
TextureRetained tex;
// Just return if we don't have a valid renderer or context
if (rdr == null || ctx == null) {
return;
}
if (freeBackground) {
// Dispose of Graphics2D Texture
if (graphics2D != null) {
graphics2D.dispose();
}
}
for (int id = textureIDResourceTable.size()-1; id >= 0; id--) {
tex = textureIDResourceTable.get(id);
if (tex == null) {
continue;
}
// Issue 403 : this assertion doesn't hold in some cases
// TODO KCR : determine why this is the case
// assert id == ((TextureRetained)obj).objectId;
Canvas3D.freeTexture(ctx, id);
synchronized (tex.resourceLock) {
tex.resourceCreationMask &= ~canvasBit;
if (tex.resourceCreationMask == 0) {
tex.freeTextureId(id);
}
}
}
textureIDResourceTable.clear();
freeAllDisplayListResources(ctx);
}
void freeAllDisplayListResources(Context ctx) {
if ((view != null) && (view.renderBin != null)) {
view.renderBin.freeAllDisplayListResources(this, ctx);
if (useSharedCtx) {
// We need to rebuild all other Canvas3D resource
// shared by this Canvas3D. Since we didn't
// remember resource in Renderer but RenderBin only.
if ((screen != null) && (screen.renderer != null)) {
screen.renderer.needToRebuildDisplayList = true;
}
}
}
}
// *****************************************************************
// Wrappers for native methods go below here
// *****************************************************************
// This is the native method for creating the underlying graphics context.
private Context createNewContext(Drawable drawable,
Context shareCtx, boolean isSharedCtx,
boolean offScreen) {
return Pipeline.getPipeline().createNewContext(this, drawable,
shareCtx, isSharedCtx,
offScreen);
}
private void createQueryContext(Drawable drawable,
boolean offScreen, int width, int height) {
Pipeline.getPipeline().createQueryContext(this, drawable,
offScreen, width, height);
}
// This is the native for creating offscreen buffer
Drawable createOffScreenBuffer(Context ctx, int width, int height) {
return Pipeline.getPipeline().createOffScreenBuffer(this,
ctx, width, height);
}
void destroyOffScreenBuffer(Context ctx, Drawable drawable) {
assert drawable != null;
Pipeline.getPipeline().destroyOffScreenBuffer(this, ctx, drawable);
}
// This is the native for reading the image from the offscreen buffer
private void readOffScreenBuffer(Context ctx, int format, int type, Object data, int width, int height) {
Pipeline.getPipeline().readOffScreenBuffer(this, ctx, format, type, data, width, height);
}
// The native method for swapBuffers
void swapBuffers(Context ctx, Drawable drawable) {
Pipeline.getPipeline().swapBuffers(this, ctx, drawable);
}
// -----------------------------------------------------------------------------
// native method for setting Material when no material is present
void updateMaterial(Context ctx, float r, float g, float b, float a) {
Pipeline.getPipeline().updateMaterialColor(ctx, r, g, b, a);
}
static void destroyContext(Drawable drawable, Context ctx) {
Pipeline.getPipeline().destroyContext(drawable, ctx);
}
// This is the native method for doing accumulation.
void accum(Context ctx, float value) {
Pipeline.getPipeline().accum(ctx, value);
}
// This is the native method for doing accumulation return.
void accumReturn(Context ctx) {
Pipeline.getPipeline().accumReturn(ctx);
}
// This is the native method for clearing the accumulation buffer.
void clearAccum(Context ctx) {
Pipeline.getPipeline().clearAccum(ctx);
}
// This is the native method for getting the number of lights the underlying
// native library can support.
int getNumCtxLights(Context ctx) {
return Pipeline.getPipeline().getNumCtxLights(ctx);
}
// Native method for decal 1st child setup
boolean decal1stChildSetup(Context ctx) {
return Pipeline.getPipeline().decal1stChildSetup(ctx);
}
// Native method for decal nth child setup
void decalNthChildSetup(Context ctx) {
Pipeline.getPipeline().decalNthChildSetup(ctx);
}
// Native method for decal reset
void decalReset(Context ctx, boolean depthBufferEnable) {
Pipeline.getPipeline().decalReset(ctx, depthBufferEnable);
}
// Native method for decal reset
void ctxUpdateEyeLightingEnable(Context ctx, boolean localEyeLightingEnable) {
Pipeline.getPipeline().ctxUpdateEyeLightingEnable(ctx, localEyeLightingEnable);
}
// The following three methods are used in multi-pass case
// native method for setting blend color
void setBlendColor(Context ctx, float red, float green,
float blue, float alpha) {
Pipeline.getPipeline().setBlendColor(ctx, red, green,
blue, alpha);
}
// native method for setting blend func
void setBlendFunc(Context ctx, int src, int dst) {
Pipeline.getPipeline().setBlendFunc(ctx, src, dst);
}
// native method for setting fog enable flag
void setFogEnableFlag(Context ctx, boolean enableFlag) {
Pipeline.getPipeline().setFogEnableFlag(ctx, enableFlag);
}
boolean isAntialiasingSet() {
return antialiasingSet;
}
// Setup the full scene antialising in D3D and ogl when GL_ARB_multisamle supported
void setFullSceneAntialiasing(Context ctx, boolean enable) {
Pipeline.getPipeline().setFullSceneAntialiasing(ctx, enable);
antialiasingSet = enable;
}
// Native method to update separate specular color control
void updateSeparateSpecularColorEnable(Context ctx, boolean control) {
Pipeline.getPipeline().updateSeparateSpecularColorEnable(ctx, control);
}
// True under Solaris,
// False under windows when display mode <= 8 bit
private boolean validGraphicsMode() {
return Pipeline.getPipeline().validGraphicsMode();
}
// native method for setting light enables
void setLightEnables(Context ctx, long enableMask, int maxLights) {
Pipeline.getPipeline().setLightEnables(ctx, enableMask, maxLights);
}
// native method for setting scene ambient
void setSceneAmbient(Context ctx, float red, float green, float blue) {
Pipeline.getPipeline().setSceneAmbient(ctx, red, green, blue);
}
// native method for disabling fog
void disableFog(Context ctx) {
Pipeline.getPipeline().disableFog(ctx);
}
// native method for disabling modelClip
void disableModelClip(Context ctx) {
Pipeline.getPipeline().disableModelClip(ctx);
}
// native method for setting default RenderingAttributes
void resetRenderingAttributes(Context ctx,
boolean depthBufferWriteEnableOverride,
boolean depthBufferEnableOverride) {
Pipeline.getPipeline().resetRenderingAttributes(ctx,
depthBufferWriteEnableOverride,
depthBufferEnableOverride);
}
// native method for setting default texture
void resetTextureNative(Context ctx, int texUnitIndex) {
Pipeline.getPipeline().resetTextureNative(ctx, texUnitIndex);
}
// native method for activating a particular texture unit
void activeTextureUnit(Context ctx, int texUnitIndex) {
Pipeline.getPipeline().activeTextureUnit(ctx, texUnitIndex);
}
// native method for setting default TexCoordGeneration
void resetTexCoordGeneration(Context ctx) {
Pipeline.getPipeline().resetTexCoordGeneration(ctx);
}
// native method for setting default TextureAttributes
void resetTextureAttributes(Context ctx) {
Pipeline.getPipeline().resetTextureAttributes(ctx);
}
// native method for setting default PolygonAttributes
void resetPolygonAttributes(Context ctx) {
Pipeline.getPipeline().resetPolygonAttributes(ctx);
}
// native method for setting default LineAttributes
void resetLineAttributes(Context ctx) {
Pipeline.getPipeline().resetLineAttributes(ctx);
}
// native method for setting default PointAttributes
void resetPointAttributes(Context ctx) {
Pipeline.getPipeline().resetPointAttributes(ctx);
}
// native method for setting default TransparencyAttributes
void resetTransparency(Context ctx, int geometryType,
int polygonMode, boolean lineAA,
boolean pointAA) {
Pipeline.getPipeline().resetTransparency(ctx, geometryType,
polygonMode, lineAA,
pointAA);
}
// native method for setting default ColoringAttributes
void resetColoringAttributes(Context ctx,
float r, float g,
float b, float a,
boolean enableLight) {
Pipeline.getPipeline().resetColoringAttributes(ctx,
r, g,
b, a,
enableLight);
}
/**
* This native method makes sure that the rendering for this canvas
* gets done now.
*/
void syncRender(Context ctx, boolean wait) {
Pipeline.getPipeline().syncRender(ctx, wait);
}
// The native method that sets this ctx to be the current one
static boolean useCtx(Context ctx, Drawable drawable) {
return Pipeline.getPipeline().useCtx(ctx, drawable);
}
// Give the Pipeline a chance to release the context. The return
// value indicates whether the context was released.
private boolean releaseCtx(Context ctx) {
return Pipeline.getPipeline().releaseCtx(ctx);
}
void clear(Context ctx, float r, float g, float b, boolean clearStencil) {
Pipeline.getPipeline().clear(ctx, r, g, b, clearStencil);
}
void textureFillBackground(Context ctx, float texMinU, float texMaxU, float texMinV, float texMaxV,
float mapMinX, float mapMaxX, float mapMinY, float mapMaxY, boolean useBiliearFilter) {
Pipeline.getPipeline().textureFillBackground(ctx, texMinU, texMaxU, texMinV, texMaxV,
mapMinX, mapMaxX, mapMinY, mapMaxY, useBiliearFilter);
}
void textureFillRaster(Context ctx, float texMinU, float texMaxU, float texMinV, float texMaxV,
float mapMinX, float mapMaxX, float mapMinY, float mapMaxY, float mapZ, float alpha, boolean useBiliearFilter) {
Pipeline.getPipeline().textureFillRaster(ctx, texMinU, texMaxU, texMinV, texMaxV,
mapMinX, mapMaxX, mapMinY, mapMaxY, mapZ, alpha, useBiliearFilter);
}
void executeRasterDepth(Context ctx, float posX, float posY, float posZ,
int srcOffsetX, int srcOffsetY, int rasterWidth, int rasterHeight,
int depthWidth, int depthHeight, int depthType, Object depthData) {
Pipeline.getPipeline().executeRasterDepth(ctx, posX, posY, posZ,
srcOffsetX, srcOffsetY, rasterWidth, rasterHeight, depthWidth, depthHeight, depthType, depthData);
}
// The native method for setting the ModelView matrix.
void setModelViewMatrix(Context ctx, double[] viewMatrix, double[] modelMatrix) {
Pipeline.getPipeline().setModelViewMatrix(ctx, viewMatrix, modelMatrix);
}
// The native method for setting the Projection matrix.
void setProjectionMatrix(Context ctx, double[] projMatrix) {
Pipeline.getPipeline().setProjectionMatrix(ctx, projMatrix);
}
// The native method for setting the Viewport.
void setViewport(Context ctx, int x, int y, int width, int height) {
Pipeline.getPipeline().resizeOffscreenLayer(this, width, height);
Pipeline.getPipeline().setViewport(ctx, x, y, width, height);
}
// used for display Lists
void newDisplayList(Context ctx, int displayListId) {
Pipeline.getPipeline().newDisplayList(ctx, displayListId);
}
void endDisplayList(Context ctx) {
Pipeline.getPipeline().endDisplayList(ctx);
}
void callDisplayList(Context ctx, int id, boolean isNonUniformScale) {
Pipeline.getPipeline().callDisplayList(ctx, id, isNonUniformScale);
}
static void freeDisplayList(Context ctx, int id) {
Pipeline.getPipeline().freeDisplayList(ctx, id);
}
static void freeTexture(Context ctx, int id) {
Pipeline.getPipeline().freeTexture(ctx, id);
}
static int generateTexID(Context ctx) {
return Pipeline.getPipeline().generateTexID(ctx);
}
void texturemapping(Context ctx,
int px, int py,
int xmin, int ymin, int xmax, int ymax,
int texWidth, int texHeight,
int rasWidth,
int format, int objectId,
byte[] image,
int winWidth, int winHeight) {
Pipeline.getPipeline().texturemapping(ctx,
px, py,
xmin, ymin, xmax, ymax,
texWidth, texHeight,
rasWidth,
format, objectId,
image,
winWidth, winHeight);
}
boolean initTexturemapping(Context ctx, int texWidth,
int texHeight, int objectId) {
return Pipeline.getPipeline().initTexturemapping(ctx, texWidth,
texHeight, objectId);
}
// Set internal render mode to one of FIELD_ALL, FIELD_LEFT or
// FIELD_RIGHT. Note that it is up to the caller to ensure that
// stereo is available before setting the mode to FIELD_LEFT or
// FIELD_RIGHT. The boolean isTRUE for double buffered mode, FALSE
// foe single buffering.
void setRenderMode(Context ctx, int mode, boolean doubleBuffer) {
Pipeline.getPipeline().setRenderMode(ctx, mode, doubleBuffer);
}
// Set glDepthMask.
void setDepthBufferWriteEnable(Context ctx, boolean mode) {
Pipeline.getPipeline().setDepthBufferWriteEnable(ctx, mode);
}
// Methods to get actual capabilities from Canvas3D
boolean hasDoubleBuffer() {
return Pipeline.getPipeline().hasDoubleBuffer(this);
}
boolean hasStereo() {
return Pipeline.getPipeline().hasStereo(this);
}
int getStencilSize() {
return Pipeline.getPipeline().getStencilSize(this);
}
boolean hasSceneAntialiasingMultisample() {
return Pipeline.getPipeline().hasSceneAntialiasingMultisample(this);
}
boolean hasSceneAntialiasingAccum() {
return Pipeline.getPipeline().hasSceneAntialiasingAccum(this);
}
}
|