hellovr_opengl_main.cpp 94.9 KB
Newer Older
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
//========= Copyright Valve Corporation ============//

/*#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
*/

#include <SDL.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
#include <gl/glu.h>
#include <stdio.h>
#include <string>
#include <cstdlib>

#include <openvr.h>

#include "shared/lodepng.h"
#include "shared/Matrices.h"
#include "shared/pathtools.h"

#include "rply.h"

static int vertex_cb(p_ply_argument argument);
static int face_cb(p_ply_argument argument);

static float *CubeVertices;
static int *CubeIndices;
static int CurrentVertex;
static int CurrentIndex;



static float BACKGROUND[3];
static const char * PATH;
static int ISOS;
static int TIMESTEPS;
static float **isocolours; // [ISOS][4];
const char **plyfiles;
static float **translations;
static float userpos[3];

//#define LOCALTEST

/*#ifdef LOCALTEST
#define PATH "Y:\\v2t\\datasets\\mpcdf_CO2_CaO\\cubes-bigger\\IsosurfacesFixed\\"
#else
#define PATH "data\\CO2-CaO-B\\"
//#define PATH "C:\\Users\\mobile\\Desktop\\openvrDemos\\win64\\data\\CO2-CaO-B\\"
#endif
*/
#define ZLAYERS 12

//number of components in our vertices data xyz+nxnynz+rgba
#define numComponents 10

#define MAXGPU 300
//use 32 or 16 bits for index (in case more than 64k vertices / mesh
#define INDICESGL32 

//isosurfaces (or meshes such as atoms etc)
//#define ISOS 5

//shown on https://www.vbw-bayern.de/vbw/Aktionsfelder/Innovation-F-T/Forschung-und-Technologie/Zukunft-digital-Big-Data.jsp

#define GRID 1
#define GRIDSTR "1"
#define NUMLODS 1

/*#ifndef LOCALTEST
#define TIMESTEPS 423
#else
#define TIMESTEPS 1
#endif*/

#define NUMPLY (TIMESTEPS * ISOS)


//http://stackoverflow.com/questions/3018313/algorithm-to-convert-rgb-to-hsv-and-hsv-to-rgb-in-range-0-255-for-both
void hsv2rgb(float *hsv, float *rgb) {
	float h = hsv[0], s = hsv[1], v = hsv[2], p, q, t, f, r, g, b;

	(h == 360.) ? (h = 0.) : (h /= 60.);
	f = h - floor(h);

	p = v*(1.f - s);
	q = v*(1.f - s*f);
	t = v*(1.f - s*(1.f - f));

	if (0. <= h && h < 1.){
		r = v; g = t; b = p;
	}	else if (1. <= h && h < 2.) {
		r = q; g = v; b = p;
	}	else if (2. <= h && h < 3.){
		r = p; g = v; b = t;
	}else if (3. <= h && h < 4.){
		r = p; g = q; b = v;
	}else if (4. <= h && h < 5.){
		r = t; g = p; b = v;
	}else if (5. <= h && h < 6.){
		r = v; g = p;b = q;
	}
	else{
		r = 0.; g = 0.; b = 0.;
	}
	rgb[0] = r; rgb[1] = g; rgb[2] = b;
}


class CGLRenderModel
{
public:
	CGLRenderModel( const std::string & sRenderModelName );
	~CGLRenderModel();

	bool BInit( const vr::RenderModel_t & vrModel, const vr::RenderModel_TextureMap_t & vrDiffuseTexture );
	void Cleanup();
	void Draw();
	const std::string & GetName() const { return m_sModelName; }

private:
	GLuint m_glVertBuffer;
	GLuint m_glIndexBuffer;
	GLuint m_glVertArray;
	GLuint m_glTexture;
	GLsizei m_unVertexCount;
	std::string m_sModelName;
};

static bool g_bPrintf = true;

//-----------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
class CMainApplication
{
public:
	CMainApplication(int argc, char *argv[]);
	virtual ~CMainApplication();

	bool BInit();
	bool BInitGL();
	bool BInitCompositor();

	void SetupRenderModels();

	void Shutdown();

	void RunMainLoop();
	bool HandleInput();
	void ProcessVREvent(const vr::VREvent_t & event);
	void RenderFrame();

	bool SetupTexturemaps();
	bool SetupDepthPeeling();

	void SetupScene();
	bool AddModelToScene(Matrix4 mat, std::vector<float> &vertdata, 
#ifndef INDICESGL32
		std::vector<short> & vertindices, 
#else
		std::vector<GLuint> & vertindices,
#endif
		const char *const data, bool water, bool colours, int set);

	void DrawControllers();

	bool SetupStereoRenderTargets();
	void SetupDistortion();
	void SetupCameras();

	void RenderStereoTargets();
	void RenderDistortion();
	void RenderScene(vr::Hmd_Eye nEye);

	Matrix4 GetHMDMatrixProjectionEye(vr::Hmd_Eye nEye);
	Matrix4 GetHMDMatrixPoseEye(vr::Hmd_Eye nEye);
	Matrix4 GetCurrentViewProjectionMatrix(vr::Hmd_Eye nEye);
	void UpdateHMDMatrixPose();

	Matrix4 ConvertSteamVRMatrixToMatrix4(const vr::HmdMatrix34_t &matPose);

	GLuint CompileGLShader(const char *pchShaderName, const char *pchVertexShader, const char *pchFragmentShader);
	bool CreateAllShaders();

	void SetupRenderModelForTrackedDevice(vr::TrackedDeviceIndex_t unTrackedDeviceIndex);
	CGLRenderModel *FindOrLoadRenderModel(const char *pchRenderModelName);
	void RenderAllTrackedRenderModels(vr::Hmd_Eye nEye);
private:
	bool m_bDebugOpenGL;
	bool m_bVerbose;
	bool m_bPerf;
	bool m_bVblank;
	bool m_bGlFinishHack;

	vr::IVRSystem *m_pHMD;
	vr::IVRRenderModels *m_pRenderModels;
	std::string m_strDriver;
	std::string m_strDisplay;
	vr::TrackedDevicePose_t m_rTrackedDevicePose[vr::k_unMaxTrackedDeviceCount];
	Matrix4 m_rmat4DevicePose[vr::k_unMaxTrackedDeviceCount];
	bool m_rbShowTrackedDevice[vr::k_unMaxTrackedDeviceCount];

	std::vector<float> **vertdataarray; //[LOD][PLY]
#ifndef INDICESGL32
	std::vector<short> **vertindicesarray;//[LOD][PLY]
#else
	std::vector<GLuint> **vertindicesarray;//[LOD][PLY]
#endif
private: // SDL bookkeeping
	SDL_Window *m_pWindow;
	uint32_t m_nWindowWidth;
	uint32_t m_nWindowHeight;

	SDL_GLContext m_pContext;

	void PaintGrid(const vr::Hmd_Eye &nEye, const int iso);

private: // OpenGL bookkeeping
	int m_iTrackedControllerCount;
	int m_iTrackedControllerCount_Last;
	int m_iValidPoseCount;
	int m_iValidPoseCount_Last;
	bool m_bShowCubes;
	bool buttonPressed[2][vr::k_unMaxTrackedDeviceCount]; //grip, application menu
	std::string m_strPoseClasses;                            // what classes we saw poses for this frame
	char m_rDevClassChar[vr::k_unMaxTrackedDeviceCount];   // for each device, a character representing its class

	int m_iSceneVolumeWidth;
	int m_iSceneVolumeHeight;
	int m_iSceneVolumeDepth;
	float m_fScaleSpacing;
	float m_fScale;

	int m_iSceneVolumeInit;                                  // if you want something other than the default 20x20x20

	float m_fNearClip;
	float m_fFarClip;

	GLuint *m_iTexture; //[3+ZLAYERS];
	GLuint peelingFramebuffer;
	unsigned int **m_uiVertcount;// [LODS][NUMPLY];

	GLuint **m_glSceneVertBuffer; // [LODS][NUMPLY];
	GLuint **m_unSceneVAO; //[LODS][NUMPLY];
	GLuint **m_unSceneVAOIndices; //[LODS][NUMPLY];
	int currentset;
	float elapsedtime;
	static const float videospeed;
	int currentiso;
	int firstdevice;
	GLuint m_unLensVAO;
	GLuint m_glIDVertBuffer;
	GLuint m_glIDIndexBuffer;
	unsigned int m_uiIndexSize;

	GLuint m_glControllerVertBuffer;
	GLuint m_unControllerVAO;
	unsigned int m_uiControllerVertcount;

	Matrix4 m_mat4HMDPose;
	Matrix4 m_mat4eyePosLeft;
	Matrix4 m_mat4eyePosRight;

	Matrix4 m_mat4ProjectionCenter;
	Matrix4 m_mat4ProjectionLeft;
	Matrix4 m_mat4ProjectionRight;

	Vector3 UserPosition;

	struct VertexDataScene
	{
		Vector3 position;
		Vector2 texCoord;
	};

	struct VertexDataLens
	{
		Vector2 position;
		Vector2 texCoordRed;
		Vector2 texCoordGreen;
		Vector2 texCoordBlue;
	};

	GLuint m_unSceneProgramID;
	GLuint m_unLensProgramID;
	GLuint m_unControllerTransformProgramID;
	GLuint m_unRenderModelProgramID;

	GLint m_nSceneMatrixLocation;
	GLint m_nBlendingIntLocation;
	GLint m_nControllerMatrixLocation;
	GLint m_nRenderModelMatrixLocation;

	struct FramebufferDesc
	{
		GLuint m_nDepthBufferId;
		GLuint m_nRenderTextureId;
		GLuint m_nRenderFramebufferId;
		GLuint m_nResolveTextureId;
		GLuint m_nResolveFramebufferId;
	};
	FramebufferDesc leftEyeDesc;
	FramebufferDesc rightEyeDesc;

	bool CreateFrameBuffer( int nWidth, int nHeight, FramebufferDesc &framebufferDesc );
	
	uint32_t m_nRenderWidth;
	uint32_t m_nRenderHeight;

	std::vector< CGLRenderModel * > m_vecRenderModels;
	CGLRenderModel *m_rTrackedDeviceToRenderModel[ vr::k_unMaxTrackedDeviceCount ];

	char * pixels; //for saving screenshots to disk
	int framecounter;
	bool savetodisk;
};

const float CMainApplication::videospeed = 0.01f;


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void dprintf( const char *fmt, ... )
{
	va_list args;
	char buffer[ 2048 ];

	va_start( args, fmt );
	vsprintf_s( buffer, fmt, args );
	va_end( args );

	if ( g_bPrintf )
		printf( "%s", buffer );

	OutputDebugStringA( buffer );

	//SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning", buffer, 0);
}

//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMainApplication::CMainApplication(int argc, char *argv[])
	: m_pWindow(NULL)
	, m_pContext(NULL)
	, m_nWindowWidth(1920)
	, m_nWindowHeight(1080)
	, m_unSceneProgramID(0)
	, m_unLensProgramID(0)
	, m_unControllerTransformProgramID(0)
	, m_unRenderModelProgramID(0)
	, m_pHMD(NULL)
	, m_pRenderModels(NULL)
	, m_bDebugOpenGL(false)
	, m_bVerbose(false)
	, m_bPerf(false)
	, m_bVblank(false)
	, m_bGlFinishHack(true)
	, m_glControllerVertBuffer(0)
	, m_unControllerVAO(0)
	, m_unLensVAO(0)
	, m_unSceneVAO(0)
	, m_nSceneMatrixLocation(-1)
	, m_nBlendingIntLocation(-1)
	, m_nControllerMatrixLocation(-1)
	, m_nRenderModelMatrixLocation(-1)
	, m_iTrackedControllerCount(0)
	, m_iTrackedControllerCount_Last(-1)
	, m_iValidPoseCount(0)
	, m_iValidPoseCount_Last(-1)
	, m_iSceneVolumeInit(20)
	, m_strPoseClasses("")
	, m_bShowCubes(true)
	, currentset(0)
	, elapsedtime(videospeed*float(SDL_GetTicks()))
	, currentiso(ISOS)
	, firstdevice(-1)
	, m_iTexture(0)
	, peelingFramebuffer(0)
	, m_uiVertcount(0)
	, m_glSceneVertBuffer(0)
	//, UserPosition(Vector3(-101.0f * 0.15f*0.5f*GRID + 12.5f, -15.0f, -101.0f * 0.15f*0.5f*GRID + 101.0f * 0.15f*0.25f))
	, UserPosition(Vector3(-userpos[0] * 0.04f, -userpos[1] * 0.04f, -userpos[2] * 0.04f))
	, vertdataarray(0)
	, vertindicesarray(0)
	, pixels(0)
	, framecounter(0)
	, savetodisk(false)
{
	for (int j=0;j<2;j++)
		for (int i = 0; i < vr::k_unMaxTrackedDeviceCount; i++) {
			buttonPressed[j][i] = false;
		}

	for( int i = 1; i < argc; i++ )
	{
		if( !stricmp( argv[i], "-gldebug" ) )
		{
			m_bDebugOpenGL = true;
		}
		else if( !stricmp( argv[i], "-verbose" ) )
		{
			m_bVerbose = true;
		}
		else if( !stricmp( argv[i], "-novblank" ) )
		{
			m_bVblank = false;
		}
		else if( !stricmp( argv[i], "-noglfinishhack" ) )
		{
			m_bGlFinishHack = false;
		}
		else if( !stricmp( argv[i], "-noprintf" ) )
		{
			g_bPrintf = false;
		}
		else if ( !stricmp( argv[i], "-cubevolume" ) && ( argc > i + 1 ) && ( *argv[ i + 1 ] != '-' ) )
		{
			m_iSceneVolumeInit = atoi( argv[ i + 1 ] );
			i++;
		}
	}
	// other initialization tasks are done in BInit
	memset(m_rDevClassChar, 0, sizeof(m_rDevClassChar));
};


//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CMainApplication::~CMainApplication()
{
	// work is done in Shutdown
	dprintf( "Shutdown" );
}


//-----------------------------------------------------------------------------
// Purpose: Helper to get a string from a tracked device property and turn it
//			into a std::string
//-----------------------------------------------------------------------------
std::string GetTrackedDeviceString( vr::IVRSystem *pHmd, vr::TrackedDeviceIndex_t unDevice, vr::TrackedDeviceProperty prop, vr::TrackedPropertyError *peError = NULL )
{
	uint32_t unRequiredBufferLen = pHmd->GetStringTrackedDeviceProperty( unDevice, prop, NULL, 0, peError );
	if( unRequiredBufferLen == 0 )
		return "";

	char *pchBuffer = new char[ unRequiredBufferLen ];
	unRequiredBufferLen = pHmd->GetStringTrackedDeviceProperty( unDevice, prop, pchBuffer, unRequiredBufferLen, peError );
	std::string sResult = pchBuffer;
	delete [] pchBuffer;
	return sResult;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::BInit()
{


	if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) < 0 )
	{
		printf("%s - SDL could not initialize! SDL Error: %s\n", __FUNCTION__, SDL_GetError());
		return false;
	}

	// Loading the SteamVR Runtime
	vr::EVRInitError eError = vr::VRInitError_None;
	m_pHMD = vr::VR_Init( &eError, vr::VRApplication_Scene );

	if ( eError != vr::VRInitError_None )
	{
		m_pHMD = NULL;
		char buf[1024];
		sprintf_s( buf, sizeof( buf ), "Unable to init VR runtime: %s", vr::VR_GetVRInitErrorAsEnglishDescription( eError ) );
		SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "VR_Init Failed", buf, NULL );
		return false;
	}


	m_pRenderModels = (vr::IVRRenderModels *)vr::VR_GetGenericInterface( vr::IVRRenderModels_Version, &eError );
	if( !m_pRenderModels )
	{
		m_pHMD = NULL;
		vr::VR_Shutdown();

		char buf[1024];
		sprintf_s( buf, sizeof( buf ), "Unable to get render model interface: %s", vr::VR_GetVRInitErrorAsEnglishDescription( eError ) );
		SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "VR_Init Failed", buf, NULL );
		return false;
	}

	int nWindowPosX = 0;
	int nWindowPosY = 0;
	m_nWindowWidth = 1920;
	m_nWindowHeight = 1080;
	Uint32 unWindowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN /*| SDL_WINDOW_FULLSCREEN_DESKTOP*/; //rgh: interferes with mode change to 100Hz refresh

	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
	//SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

	SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 0 );
	SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 0 );
	if( m_bDebugOpenGL )
		SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );

	m_pWindow = SDL_CreateWindow( "Geophysics OpenVR SDL", nWindowPosX, nWindowPosY, m_nWindowWidth, m_nWindowHeight, unWindowFlags );
	if (m_pWindow == NULL)
	{
		printf( "%s - Window could not be created! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
		return false;
	}

	m_pContext = SDL_GL_CreateContext(m_pWindow);
	if (m_pContext == NULL)
	{
		printf( "%s - OpenGL context could not be created! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
		return false;
	}

	glewExperimental = GL_TRUE;
	GLenum nGlewError = glewInit();
	if (nGlewError != GLEW_OK)
	{
		printf( "%s - Error initializing GLEW! %s\n", __FUNCTION__, glewGetErrorString( nGlewError ) );
		return false;
	}
	glGetError(); // to clear the error caused deep in GLEW

	if ( SDL_GL_SetSwapInterval( m_bVblank ? 1 : 0 ) < 0 )
	{
		printf( "%s - Warning: Unable to set VSync! SDL Error: %s\n", __FUNCTION__, SDL_GetError() );
		return false;
	}


	m_strDriver = "No Driver";
	m_strDisplay = "No Display";

	m_strDriver = GetTrackedDeviceString( m_pHMD, vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_TrackingSystemName_String );
	m_strDisplay = GetTrackedDeviceString( m_pHMD, vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SerialNumber_String );

	std::string strWindowTitle = "Geophysics OpenVR - " + m_strDriver + " " + m_strDisplay;
	SDL_SetWindowTitle( m_pWindow, strWindowTitle.c_str() );
	
	// cube array
 	m_iSceneVolumeWidth = m_iSceneVolumeInit;
 	m_iSceneVolumeHeight = m_iSceneVolumeInit;
 	m_iSceneVolumeDepth = m_iSceneVolumeInit;
 		
 	m_fScale = 0.04f; //0.15f; //rgh: original too big for room
 	m_fScaleSpacing = 4.0f;
 
 	m_fNearClip = 0.2f;
 	m_fFarClip = 30.0f;//rgh: original 30 too small for our skymap
 

 
// 		m_MillisecondsTimer.start(1, this);
// 		m_SecondsTimer.start(1000, this);
	
	if (!BInitGL())
	{
		printf("%s - Unable to initialize OpenGL!\n", __FUNCTION__);
		return false;
	}

	if (!BInitCompositor())
	{
		printf("%s - Failed to initialize VR Compositor!\n", __FUNCTION__);
		return false;
	}

	return true;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void APIENTRY DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char* message, const void* userParam)
{
	dprintf( "GL Error: %s\n", message );
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::BInitGL()
{
	if( m_bDebugOpenGL )
	{
		glDebugMessageCallback(DebugCallback, nullptr);
		glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE );
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
	}

	if( !CreateAllShaders() )
		return false;

	SetupTexturemaps();
	SetupScene();
	SetupCameras();
	SetupStereoRenderTargets();
	SetupDistortion();
	SetupDepthPeeling();

	SetupRenderModels();

	return true;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::BInitCompositor()
{
	vr::EVRInitError peError = vr::VRInitError_None;

	if ( !vr::VRCompositor() )
	{
		printf( "Compositor initialization failed. See log file for details\n" );
		return false;
	}

	return true;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::Shutdown()
{
	if( m_pHMD )
	{
		vr::VR_Shutdown();
		m_pHMD = NULL;
	}

	for( std::vector< CGLRenderModel * >::iterator i = m_vecRenderModels.begin(); i != m_vecRenderModels.end(); i++ )
	{
		delete (*i);
	}
	m_vecRenderModels.clear();
	
	if (vertdataarray) {
		for (int i = 0; i < NUMLODS; i++)
			if (vertdataarray[i])
				delete[] vertdataarray[i];
		delete[]vertdataarray;
		vertdataarray = 0;
	}
	if (vertindicesarray){
		for (int i = 0; i < NUMLODS; i++)
			if (vertindicesarray[i])
				delete[] vertindicesarray[i];
		delete[] vertindicesarray;
		vertindicesarray = 0;
	}
	if (m_pContext)
	{
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE);
		glDebugMessageCallback(nullptr, nullptr);
		if (m_glSceneVertBuffer) {
			for (int i = 0; i < NUMLODS; i++) {
				glDeleteBuffers(NUMPLY, m_glSceneVertBuffer[i]);
				delete[] (m_glSceneVertBuffer[i]);
			}
			delete[] m_glSceneVertBuffer;
			m_glSceneVertBuffer = nullptr;
		}
		glDeleteBuffers(1, &m_glIDVertBuffer);
		glDeleteBuffers(1, &m_glIDIndexBuffer);

		if ( m_unSceneProgramID )
		{
			glDeleteProgram( m_unSceneProgramID );
		}
		if ( m_unControllerTransformProgramID )
		{
			glDeleteProgram( m_unControllerTransformProgramID );
		}
		if ( m_unRenderModelProgramID )
		{
			glDeleteProgram( m_unRenderModelProgramID );
		}
		if ( m_unLensProgramID )
		{
			glDeleteProgram( m_unLensProgramID );
		}

		glDeleteRenderbuffers( 1, &leftEyeDesc.m_nDepthBufferId );
		glDeleteTextures( 1, &leftEyeDesc.m_nRenderTextureId );
		glDeleteFramebuffers( 1, &leftEyeDesc.m_nRenderFramebufferId );
		glDeleteTextures( 1, &leftEyeDesc.m_nResolveTextureId );
		glDeleteFramebuffers( 1, &leftEyeDesc.m_nResolveFramebufferId );

		glDeleteRenderbuffers( 1, &rightEyeDesc.m_nDepthBufferId );
		glDeleteTextures( 1, &rightEyeDesc.m_nRenderTextureId );
		glDeleteFramebuffers( 1, &rightEyeDesc.m_nRenderFramebufferId );
		glDeleteTextures( 1, &rightEyeDesc.m_nResolveTextureId );
		glDeleteFramebuffers( 1, &rightEyeDesc.m_nResolveFramebufferId );

		if( m_unLensVAO != 0 )
		{
			glDeleteVertexArrays( 1, &m_unLensVAO );
		}
		if( m_unSceneVAO != 0 )
		{
			for (int i = 0; i < NUMLODS; i++) {
				glDeleteVertexArrays(NUMPLY, m_unSceneVAO[i]);
				delete[] m_unSceneVAO[i];
			}
			delete[] m_unSceneVAO;
			m_unSceneVAO = 0;
		}
		if( m_unControllerVAO != 0 )
		{
			glDeleteVertexArrays( 1, &m_unControllerVAO );
		}

		if (m_iTexture != 0) {
			glDeleteTextures(3+ZLAYERS, m_iTexture);
			delete[] m_iTexture;
			m_iTexture = 0;

		}

		if (peelingFramebuffer!=0)
			glDeleteFramebuffers(1, &peelingFramebuffer);
	}

	if( m_pWindow )
	{
		SDL_DestroyWindow(m_pWindow);
		m_pWindow = NULL;
	}

	delete m_uiVertcount;

	SDL_Quit();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::HandleInput()
{
	SDL_Event sdlEvent;
	bool bRet = false;

	float speed = 0.02f;

	while (SDL_PollEvent(&sdlEvent) != 0)
	{
		if (sdlEvent.type == SDL_QUIT)
		{
			bRet = true;
		}
		else if (sdlEvent.type == SDL_KEYDOWN)
		{// q is too near 1, disable
			if (sdlEvent.key.keysym.sym == SDLK_ESCAPE
				/*|| sdlEvent.key.keysym.sym == SDLK_q*/)
			{
				bRet = true;
			}
			if (sdlEvent.key.keysym.sym == SDLK_c)
			{
				m_bShowCubes = !m_bShowCubes;
			} else if (sdlEvent.key.keysym.sym == SDLK_s)
			{
				savetodisk = !savetodisk;
			}
			//rgh: add keyboard navigation here
			if (sdlEvent.key.keysym.sym == SDLK_1) {
				currentset++;
				if (currentset >= NUMPLY / ISOS)
					currentset = 0;
			}
			if (sdlEvent.key.keysym.sym == SDLK_2) {
				currentset--;
				if (currentset < 0)
					currentset = NUMPLY / ISOS -1;
			}
			if (sdlEvent.key.keysym.sym == SDLK_0) {
				currentiso++;
				if (currentiso > ISOS)
					currentiso = 0;
			}
			if (sdlEvent.key.keysym.sym == SDLK_a) {
				Matrix4 tmp = m_mat4HMDPose;
				UserPosition += tmp.invert()*Vector3(0, 0, speed);
				//UserPosition.x += speed;
			}
			if (sdlEvent.key.keysym.sym == SDLK_y) {
				//UserPosition.x -= speed;
				Matrix4 tmp = m_mat4HMDPose;
				UserPosition -= tmp.invert()*Vector3(0, 0, speed);
			}
			if (sdlEvent.key.keysym.sym == SDLK_o) {
				UserPosition[2] -= 0.1f;
				dprintf("%f %f\n", UserPosition[0], UserPosition[2]);
			}
			if (sdlEvent.key.keysym.sym == SDLK_p) {
				UserPosition[2] += 0.1f;
				dprintf("%f %f\n", UserPosition[0], UserPosition[2]);
			}
		}
	}

	// Process SteamVR events
	vr::VREvent_t event;
	while (m_pHMD->PollNextEvent(&event, sizeof(event)))
	{
		ProcessVREvent(event);
	}

	// Process SteamVR controller state
	for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++)
	{
		vr::VRControllerState_t state;
		if (m_pHMD->GetControllerState(unDevice, &state))
		{
			m_rbShowTrackedDevice[unDevice] = state.ulButtonPressed == 0;

			if (!buttonPressed[1][unDevice] && state.ulButtonTouched&vr::ButtonMaskFromId(vr::k_EButton_ApplicationMenu)) {
				buttonPressed[1][unDevice] = true;
				if (firstdevice == -1)
					firstdevice = unDevice;
				savetodisk = !savetodisk;
			}
			else if (buttonPressed[1][unDevice] && 0 == (state.ulButtonTouched&vr::ButtonMaskFromId(vr::k_EButton_ApplicationMenu)))
			{
				buttonPressed[1][unDevice] = false;
			}

			if (!buttonPressed[0][unDevice] && state.ulButtonTouched&vr::ButtonMaskFromId(vr::k_EButton_Grip))
			{
				buttonPressed[0][unDevice] = true;
				if (firstdevice == -1)
					firstdevice = unDevice;
				if (unDevice == firstdevice) {
					currentset--;
					if (currentset < 0)
						currentset = NUMPLY / ISOS - 1;
				} else {
					currentiso++;
					if (currentiso > ISOS)
						currentiso = 0;
				}
			} else if (buttonPressed[0][unDevice] && (state.ulButtonTouched&vr::ButtonMaskFromId(vr::k_EButton_Grip)) == 0)
				buttonPressed[0][unDevice] = false;

			if (state.rAxis[1].x >0.1)
			{
				if (firstdevice == -1)
					firstdevice = unDevice;
				if (unDevice == firstdevice) {
					Matrix4 tmp = m_mat4HMDPose;
					UserPosition += tmp.invert()*Vector3(0, 0, speed);
				}
				else {
					float newtime = videospeed*float(SDL_GetTicks());;
					if (newtime-elapsedtime > 1) {
						elapsedtime = newtime;
						currentset++;
						if (currentset >= NUMPLY / ISOS)
							currentset = 0;
					}
				}
			}
		}
	}

	return bRet;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::RunMainLoop()
{
	bool bQuit = false;

	SDL_StartTextInput();
	SDL_ShowCursor( SDL_DISABLE );

	while ( !bQuit )
	{
		bQuit = HandleInput();
		RenderFrame();
	}

	SDL_StopTextInput();
}


//-----------------------------------------------------------------------------
// Purpose: Processes a single VR event
//-----------------------------------------------------------------------------
void CMainApplication::ProcessVREvent( const vr::VREvent_t & event )
{
	switch (event.eventType)
	{
		case vr::VREvent_TrackedDeviceActivated:
			{
				SetupRenderModelForTrackedDevice(event.trackedDeviceIndex);
				dprintf("Device %u attached. Setting up render model.\n", event.trackedDeviceIndex);
			}
		break;
		case vr::VREvent_TrackedDeviceDeactivated:
			{
				dprintf("Device %u detached.\n", event.trackedDeviceIndex);
			}
		break;
		case vr::VREvent_TrackedDeviceUpdated:
			{
				dprintf("Device %u updated.\n", event.trackedDeviceIndex);
			}
		break;
		/*
		case vr::VREvent_ButtonTouch:
			{
				buttonPressed = true;
			}
		break;
		case vr::VREvent_ButtonUntouch:
		{
			buttonPressed = false;
		}
		break;*/
		/*case vr::VREvent_ButtonPress:
			{
				m_bShowCubes = ~m_bShowCubes;
			}*/
	}
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::RenderFrame()
{
	// for now as fast as possible
	if ( m_pHMD )
	{
		DrawControllers();
		RenderStereoTargets();
		RenderDistortion();

		vr::Texture_t leftEyeTexture = {(void*)leftEyeDesc.m_nResolveTextureId, vr::API_OpenGL, vr::ColorSpace_Gamma };
		vr::VRCompositor()->Submit(vr::Eye_Left, &leftEyeTexture );
		vr::Texture_t rightEyeTexture = {(void*)rightEyeDesc.m_nResolveTextureId, vr::API_OpenGL, vr::ColorSpace_Gamma };
		vr::VRCompositor()->Submit(vr::Eye_Right, &rightEyeTexture );
	}

	if ( m_bVblank && m_bGlFinishHack )
	{
		//$ HACKHACK. From gpuview profiling, it looks like there is a bug where two renders and a present
		// happen right before and after the vsync causing all kinds of jittering issues. This glFinish()
		// appears to clear that up. Temporary fix while I try to get nvidia to investigate this problem.
		// 1/29/2014 mikesart
		glFinish();
	}

	// SwapWindow
	{
		SDL_GL_SwapWindow( m_pWindow );
	}

	// Clear
	{
		// We want to make sure the glFinish waits for the entire present to complete, not just the submission
		// of the command. So, we do a clear here right here so the glFinish will wait fully for the swap.
		glClearColor(BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 1);
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	}

	// Flush and wait for swap.
	if ( m_bVblank )
	{
		glFlush();
		glFinish();
	}

	// Spew out the controller and pose count whenever they change.
	if ( m_iTrackedControllerCount != m_iTrackedControllerCount_Last || m_iValidPoseCount != m_iValidPoseCount_Last )
	{
		m_iValidPoseCount_Last = m_iValidPoseCount;
		m_iTrackedControllerCount_Last = m_iTrackedControllerCount;
		
		dprintf( "PoseCount:%d(%s) Controllers:%d\n", m_iValidPoseCount, m_strPoseClasses.c_str(), m_iTrackedControllerCount );
	}

	UpdateHMDMatrixPose();
}


//-----------------------------------------------------------------------------
// Purpose: Compiles a GL shader program and returns the handle. Returns 0 if
//			the shader couldn't be compiled for some reason.
//-----------------------------------------------------------------------------
GLuint CMainApplication::CompileGLShader( const char *pchShaderName, const char *pchVertexShader, const char *pchFragmentShader )
{
	GLuint unProgramID = glCreateProgram();

	GLuint nSceneVertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource( nSceneVertexShader, 1, &pchVertexShader, NULL);
	glCompileShader( nSceneVertexShader );

	GLint vShaderCompiled = GL_FALSE;
	glGetShaderiv( nSceneVertexShader, GL_COMPILE_STATUS, &vShaderCompiled);
	if ( vShaderCompiled != GL_TRUE)
	{
		dprintf("%s - Unable to compile vertex shader %d!\n", pchShaderName, nSceneVertexShader);

		GLchar mess[3000];
		GLsizei le;
		glGetShaderInfoLog(nSceneVertexShader, 3000, &le, mess);
		dprintf("error messages: %s", mess);

		glDeleteProgram( unProgramID );
		glDeleteShader( nSceneVertexShader );
		return 0;
	}
	glAttachShader( unProgramID, nSceneVertexShader);
	glDeleteShader( nSceneVertexShader ); // the program hangs onto this once it's attached

	GLuint  nSceneFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource( nSceneFragmentShader, 1, &pchFragmentShader, NULL);
	glCompileShader( nSceneFragmentShader );

	GLint fShaderCompiled = GL_FALSE;
	glGetShaderiv( nSceneFragmentShader, GL_COMPILE_STATUS, &fShaderCompiled);
	if (fShaderCompiled != GL_TRUE)
	{
		dprintf("%s - Unable to compile fragment shader %d!\n", pchShaderName, nSceneFragmentShader );
		GLchar mess[3000];
		GLsizei le;
		glGetShaderInfoLog(nSceneFragmentShader, 3000, &le, mess);
		dprintf("error messages: %s", mess);
		glDeleteProgram( unProgramID );
		glDeleteShader( nSceneFragmentShader );
		return 0;	
	}

	glAttachShader( unProgramID, nSceneFragmentShader );
	glDeleteShader( nSceneFragmentShader ); // the program hangs onto this once it's attached

	glLinkProgram( unProgramID );

	GLint programSuccess = GL_TRUE;
	glGetProgramiv( unProgramID, GL_LINK_STATUS, &programSuccess);
	if ( programSuccess != GL_TRUE )
	{
		dprintf("%s - Error linking program %d!\n", pchShaderName, unProgramID);
		glDeleteProgram( unProgramID );
		return 0;
	}

	glUseProgram( unProgramID );
	glUseProgram( 0 );

	return unProgramID;
}


//-----------------------------------------------------------------------------
// Purpose: Creates all the shaders used by HelloVR SDL
//-----------------------------------------------------------------------------
bool CMainApplication::CreateAllShaders()
{
	m_unSceneProgramID = CompileGLShader(
		"Scene",

		// Vertex Shader
		"#version 410\n"
		"uniform mat4 matrix;\n"
		"layout(location = 0) in vec4 position;\n"
		"layout(location = 1) in vec3 normalsIn;\n"
		"layout(location = 2) in vec4 colorIn;\n"
		//		"layout(location = 3) in vec2 uvIn;\n"
		"out vec4 color;\n"
		"out vec3 n;\n"
		"out highp vec4 pos;\n"
		//		"out vec2 uv;\n"
		"void main()\n"
		"{\n"
		"	color = vec4(colorIn.rgba);\n"
		"   n=normalize(normalsIn);\n"
		//		"   uv=uvIn;\n"
		"int i=gl_InstanceID / " GRIDSTR ";\n"
		"int j=gl_InstanceID % " GRIDSTR ";\n"
		"	pos = matrix * (position + vec4 (float(i)*0.15*101.0, 0, float(j)*0.15*101.0, 0));\n"
		"   gl_Position = pos;\n"
		//"	gl_Position = matrix * position;\n"
		"}\n",

		// Fragment Shader
		"#version 410 core\n"
		"uniform sampler2D diffuse;\n" //now extra depth texture for peeling
		"in vec4 color;\n"
		"in vec3 n;\n"
		"in highp vec4 pos;\n"
		"out vec4 outputColor;\n"
		"void main()\n"
		"{\n"
		"vec4 mytex=texture(diffuse, vec2(pos.x/pos.w*0.5+0.5, pos.y/pos.w*0.5+0.5));\n"
		//http://www.gamedev.net/topic/556521-glsl-manual-shadow-map-biasscale/
		//"vec2 d=vec2(dFdx(pos.z), dFdy(pos.z));\n"
		//"highp float m=sqrt(d.x*d.x + d.y*d.y);\n"
		"if ((pos.z/pos.w+1)/2 <= mytex.r+0.0001 ) discard;\n"

		"lowp vec3 nn=normalize(n);"
		"lowp float a=max(0.0, dot(nn, vec3(0,sqrt(2.0)/2.0,sqrt(2.0)/2.0)));\n"
		"lowp float b=max(0.0, dot(nn, vec3(0,0,1)));\n"
		"highp vec4 res=color;\n"
		//"outputColor = vec4(pos.x/pos.w*0.5+0.5, pos.y/pos.w*0.5+0.5, 0,1);\n"
		"	outputColor = vec4 ((res.rgb) * (0.2 + 0.2*a + 0.3*b), color.a);\n" 
		
		"}\n"
		);
	m_nSceneMatrixLocation = glGetUniformLocation( m_unSceneProgramID, "matrix" );
	if( m_nSceneMatrixLocation == -1 )
	{
		dprintf( "Unable to find matrix uniform in scene shader\n" );
		return false;
	}
	/*m_nBlendingIntLocation = glGetUniformLocation(m_unSceneProgramID, "blending");
	if (m_nBlendingIntLocation == -1)
	{
		dprintf("Unable to find blending uniform in scene shader\n");
		return false;
	}*/
	m_unControllerTransformProgramID = CompileGLShader(
		"Controller",

		// vertex shader
		"#version 410\n"
		"uniform mat4 matrix;\n"
		"layout(location = 0) in vec4 position;\n"
		"layout(location = 1) in vec3 v3ColorIn;\n"
		"out vec4 v4Color;\n"
		"void main()\n"
		"{\n"
		"	v4Color.xyz = v3ColorIn; v4Color.a = 1.0;\n"
		"	gl_Position = matrix * position;\n"
		"}\n",

		// fragment shader
		"#version 410\n"
		"in vec4 v4Color;\n"
		"out vec4 outputColor;\n"
		"void main()\n"
		"{\n"
		"   outputColor = v4Color;\n"
		"}\n"
		);
	m_nControllerMatrixLocation = glGetUniformLocation( m_unControllerTransformProgramID, "matrix" );
	if( m_nControllerMatrixLocation == -1 )
	{
		dprintf( "Unable to find matrix uniform in controller shader\n" );
		return false;
	}

	m_unRenderModelProgramID = CompileGLShader( 
		"render model",

		// vertex shader
		"#version 410\n"
		"uniform mat4 matrix;\n"
		"layout(location = 0) in vec4 position;\n"
		"layout(location = 1) in vec3 v3NormalIn;\n"
		"layout(location = 2) in vec2 v2TexCoordsIn;\n"
		"out vec2 v2TexCoord;\n"
		"void main()\n"
		"{\n"
		"	v2TexCoord = v2TexCoordsIn;\n"
		"	gl_Position = matrix * vec4(position.xyz, 1);\n"
		"}\n",

		//fragment shader
		"#version 410 core\n"
		"uniform sampler2D diffuse;\n"
		"in vec2 v2TexCoord;\n"
		"out vec4 outputColor;\n"
		"void main()\n"
		"{\n"
		"   outputColor = texture( diffuse, v2TexCoord);\n"
		"}\n"

		);
	m_nRenderModelMatrixLocation = glGetUniformLocation( m_unRenderModelProgramID, "matrix" );
	if( m_nRenderModelMatrixLocation == -1 )
	{
		dprintf( "Unable to find matrix uniform in render model shader\n" );
		return false;
	}

	m_unLensProgramID = CompileGLShader(
		"Distortion",

		// vertex shader
		"#version 410 core\n"
		"layout(location = 0) in vec4 position;\n"
		"layout(location = 1) in vec2 v2UVredIn;\n"
		"layout(location = 2) in vec2 v2UVGreenIn;\n"
		"layout(location = 3) in vec2 v2UVblueIn;\n"
		"noperspective  out vec2 v2UVred;\n"
		"noperspective  out vec2 v2UVgreen;\n"
		"noperspective  out vec2 v2UVblue;\n"
		"void main()\n"
		"{\n"
		"	v2UVred = v2UVredIn;\n"
		"	v2UVgreen = v2UVGreenIn;\n"
		"	v2UVblue = v2UVblueIn;\n"
		"	gl_Position = position;\n"
		"}\n",

		// fragment shader
		"#version 410 core\n"
		"uniform sampler2D mytexture;\n"

		"noperspective  in vec2 v2UVred;\n"
		"noperspective  in vec2 v2UVgreen;\n"
		"noperspective  in vec2 v2UVblue;\n"

		"out vec4 outputColor;\n"

		"void main()\n"
		"{\n"
		"	float fBoundsCheck = ( (dot( vec2( lessThan( v2UVgreen.xy, vec2(0.05, 0.05)) ), vec2(1.0, 1.0))+dot( vec2( greaterThan( v2UVgreen.xy, vec2( 0.95, 0.95)) ), vec2(1.0, 1.0))) );\n"
		"	if( fBoundsCheck > 1.0 )\n"
		"	{ outputColor = vec4( 0, 0, 0, 1.0 ); }\n"
		"	else\n"
		"	{\n"
		"		float red = texture(mytexture, v2UVred).x;\n"
		"		float green = texture(mytexture, v2UVgreen).y;\n"
		"		float blue = texture(mytexture, v2UVblue).z;\n"
		"		outputColor = vec4( red, green, blue, 1.0  ); }\n"
		"}\n"
		);


	return m_unSceneProgramID != 0 
		&& m_unControllerTransformProgramID != 0
		&& m_unRenderModelProgramID != 0
		&& m_unLensProgramID != 0;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::SetupTexturemaps()
{

	//rgh: textures:	[0] White texture for textureless meshes
	//					[1,2] Depth texture for depth peeling ping pong (needs to be initialized after SetupStereoRenderTargets)
	//					[3..ZLAYERS+2] Colour textures for transparency
	//std::string sExecutableDirectory = Path_StripFilename(Path_GetExecutablePath());
	//std::string strFullPath = Path_MakeAbsolute("../cube_texture.png", sExecutableDirectory);

	m_iTexture = new GLuint[3+ZLAYERS];
	glGenTextures(3+ZLAYERS, m_iTexture);

	//white
	unsigned char data2[4] = { 255, 255, 255, 255 }; //white texture for non-textured meshes
	glBindTexture(GL_TEXTURE_2D, m_iTexture[0]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data2);

	glBindTexture( GL_TEXTURE_2D, 0 );

	GLenum e;
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("opengl error %d, SetupTextureMaps\n", e);

	return ( m_iTexture != 0 && e==GL_NO_ERROR);
}

bool CMainApplication::SetupDepthPeeling()
{
	//https://www.opengl.org/wiki/Common_Mistakes
	//Until this is resolved in NVIDIA's drivers, it is advised to make sure that all textures have mipmap levels, and that all glTexParameteri​ 
	//values are properly set up for the format of the texture. For example, integral textures are not complete if the mag and min filters have any LINEAR fields.

	GLenum e;
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("opengl error %d, start SetupDepthPeeling\n", e);
	GLuint clearColor = 0;
	for (int i = 0; i < 2; i++) {
		glBindTexture(GL_TEXTURE_2D, m_iTexture[1 + i]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		if ((e = glGetError()) != GL_NO_ERROR)
			dprintf("opengl error %d, %s SetupDepthPeeling a\n", e, gluErrorString(e));
		glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, m_nRenderWidth, m_nRenderHeight, 0, 
			GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);

		if ((e = glGetError()) != GL_NO_ERROR)
			dprintf("opengl error %d, %s SetupDepthPeeling b\n", e, gluErrorString(e));

		glClearTexImage(m_iTexture[1], 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, &clearColor);

		if ((e = glGetError()) != GL_NO_ERROR)
			dprintf("opengl error %d, SetupDepthPeeling c\n", e);
	}

	for (int i = 0; i < ZLAYERS; i++) {
		glBindTexture(GL_TEXTURE_2D, m_iTexture[3+i]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_nRenderWidth, m_nRenderHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
	}

	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("opengl error %d, %s SetupDepthPeeling textures end\n", e, gluErrorString(e));

	//now create framebuffer
	GLint dfb;
	glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &dfb);
	glGenFramebuffers(1, &peelingFramebuffer);
	glBindFramebuffer(GL_FRAMEBUFFER, peelingFramebuffer);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error: %d, %s l %d\n", e, gluErrorString(e), __LINE__);

	glBindFramebuffer(GL_FRAMEBUFFER, dfb);



	return (e == GL_NO_ERROR);
}

//-----------------------------------------------------------------------------
// Purpose: create a sea of cubes
//-----------------------------------------------------------------------------
void CMainApplication::SetupScene()
{
	if (!m_pHMD)
		return;
	//rgh: add scene loading here
	vertdataarray = new std::vector<float>*[NUMLODS];
#ifndef INDICESGL32
	vertindicesarray = new std::vector<short>*[NUMLODS];
#else
	vertindicesarray = new std::vector<GLuint>*[NUMLODS];
#endif
	for (int i = 0; i < NUMLODS; i++) {//LODS 100%, 25%, 6%, 2% 
		vertdataarray[i] = new std::vector<float>[NUMPLY];
#ifndef INDICESGL32
		vertindicesarray[i] = new std::vector<short>[NUMPLY];
#else
		vertindicesarray[i] = new std::vector<GLuint>[NUMPLY];
#endif
	}

	Matrix4 matScale;
	matScale.scale(m_fScale, m_fScale, m_fScale);
	Matrix4 matTransform;
	/*matTransform.translate(
		-((float)m_iSceneVolumeWidth * m_fScaleSpacing) / 1.f,
		-((float)m_iSceneVolumeHeight * m_fScaleSpacing) / 1.f,
		-((float)m_iSceneVolumeDepth * m_fScaleSpacing) / 1.f);*/
	matTransform.rotateX(-90);
	Matrix4 mat = matScale * matTransform;

	const char *lods[] = {""};

	m_glSceneVertBuffer = new GLuint*[NUMLODS];
	m_uiVertcount = new unsigned int*[NUMLODS];
	m_unSceneVAO = new unsigned int*[NUMLODS];
	m_unSceneVAOIndices = new unsigned int*[NUMLODS];

	GLenum e;


	glClearColor(0,0,0, 1);
	glClear(GL_COLOR_BUFFER_BIT);
	glDisable(GL_DEPTH_TEST);

	glUseProgram(m_unControllerTransformProgramID);
	float loadingmat[] = { 2, 0, 0, 0,
		0, 2, 0, 0,
		0, 0, 1, 0,
		-1, -1, 0, 1 };

	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s\n", e, gluErrorString(e));
	//glDisable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, m_iTexture[1]);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s\n", e, gluErrorString(e));

	glDisable(GL_CULL_FACE);
	float z = 0.0f; 
	float points[] = {//pos [4], color [3]
		0, 0, z, 1, 1,1,1,
		0, 1, z, 1, 1, 1, 1,
		1, 1, z, 1, 1, 1, 1,
		1, 0, z, 1, 1, 1, 1, };

	//http://stackoverflow.com/questions/21767467/glvertexattribpointer-raising-impossible-gl-invalid-operation
	GLuint myvao;
	glGenVertexArrays(1, &myvao);
	glBindVertexArray(myvao);
	GLuint testBuf;
	glGenBuffers(1, &testBuf);
	glBindBuffer(GL_ARRAY_BUFFER, testBuf);
	glBufferData(GL_ARRAY_BUFFER, 4 * 7 * sizeof(GLfloat), points, GL_STATIC_DRAW);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glDisableVertexAttribArray(2);
	glDisableVertexAttribArray(3);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)0);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)(4 * sizeof(float)));
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	

	GLuint iData[] = { 0, 1, 2,
		2, 3, 0 };

	GLuint indexBufferID;
	glGenBuffers(1, &indexBufferID);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iData), iData, GL_STATIC_DRAW);


	for (int i = 0; i < NUMLODS; i++) {
		m_glSceneVertBuffer[i] = new GLuint[NUMPLY];
		m_uiVertcount[i] = new unsigned int[NUMPLY];
		m_unSceneVAO[i] = new unsigned int[NUMPLY];
		m_unSceneVAOIndices[i] = new unsigned int[NUMPLY];


		glGenBuffers(NUMPLY, m_glSceneVertBuffer[i]);
		glGenVertexArrays(NUMPLY, m_unSceneVAO[i]);
	
		if ((e = glGetError()) != GL_NO_ERROR)
			dprintf("opengl error %d, glGenVertexArrays\n", e);
		// Create and populate the index buffer
		glGenBuffers(NUMPLY, m_unSceneVAOIndices[i]);
		if ((e = glGetError()) != GL_NO_ERROR)
			dprintf("opengl error %d, glGenBuffers\n", e);

	}
	GLsizei stride = sizeof(float) * numComponents; //sizeof(VertexDataScene);

#if 0

	float r = 0, g = 0, b = 0;
	//float quad[] = { -1.0f, -1.0f, 0.0f,   1.0f, -1.0f, 0.0f,		1.0f, 1.0f, 0.0f,    -1.0f, 1.0f, 0.0f};
	//unsigned int quadbuffer;
	//glDisable(GL_DEPTH_TEST);
#endif
	char tmpname[250];
	for (int currentlod = 0; currentlod < NUMLODS; currentlod++) {



		int time = 1;
		for (int p = 0; p < NUMPLY; p++) {
			glBindVertexArray(myvao);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("opengl error %d, l %d\n", e, __LINE__);
			//loadingmat[0]=(float)currentlod/NUMLODS; //xscaling
			loadingmat[0]=2*(float)p/NUMPLY; //yscaling
			glUniformMatrix4fv(m_nControllerMatrixLocation, 1, GL_FALSE, loadingmat);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("opengl error %d, l %d\n", e, __LINE__);
			glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("opengl error %d, l %d\n", e, __LINE__);

#if 0
			r += 0.1f;
			if (r > 1) {
				r = 0;
				g += 0.1f;
			}
			if (g > 1) {
				g = 0;
				b += 0.1f;
			}
			if (b > 1)
				b = 0;
			glClearColor(r, g, b, 1);
			glClear(GL_COLOR_BUFFER_BIT);
#endif
			SDL_GL_SwapWindow(m_pWindow);

			//http://stackoverflow.com/questions/9052224/error4error-c3861-snprintf-identifier-not-found
			sprintf(tmpname, "%s%s%d-%s.ply", PATH, lods[currentlod], time, plyfiles[p % ISOS]);

			vertdataarray[currentlod][p].clear();
			vertindicesarray[currentlod][p].clear();

			Matrix4 matFinal;
			matFinal.translate(translations[p%ISOS][0], translations[p%ISOS][1], translations[p%ISOS][2]);
			matFinal = mat*matFinal;
			if (!AddModelToScene(matFinal, vertdataarray[currentlod][p], vertindicesarray[currentlod][p],
				tmpname, false, isocolours[p%ISOS][0]<0, p%ISOS))
			{
				dprintf("Error loading ply file %s\n", tmpname);
				//m_bShowCubes = false;
				//return; 
			}
#ifndef INDICESGL32
			if (vertdataarray[currentlod][p].size() > 65535 * numComponents)
			{
				dprintf("Mesh has more than 64k vertices (%d), unsupported\n", vertdataarray[currentlod][p].size() / numComponents);
				m_bShowCubes = false;
				return;
			}
#endif
			m_uiVertcount[currentlod][p] = vertindicesarray[currentlod][p].size();  //rgh: now pos, normal, color

			glBindVertexArray(m_unSceneVAO[currentlod][p]);

			glBindBuffer(GL_ARRAY_BUFFER, m_glSceneVertBuffer[currentlod][p]);
			glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertdataarray[currentlod][p].size(), &vertdataarray[currentlod][p][0],
				GL_STATIC_DRAW);

			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("opengl error %d, glBufferData, l %d\n", e, __LINE__);
			int offset = 0;

			//now pos[3], normal[3], color[4], uv[2]
			//pos
			glEnableVertexAttribArray(0);
			glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (const void *)offset);

			if (glGetError() != GL_NO_ERROR)
				dprintf("opengl error attrib pointer 0\n");

			//normal
			offset += 3 * sizeof(GLfloat); //3 floats
			glEnableVertexAttribArray(1);
			glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, (const void *)offset);

			if (glGetError() != GL_NO_ERROR)
				dprintf("opengl error attrib pointer 1\n");

			//color
			offset += 3 * sizeof(GLfloat); //6 floats
			glEnableVertexAttribArray(2);
			glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, stride, (const void *)offset);

			if (glGetError() != GL_NO_ERROR)
				dprintf("opengl error attrib pointer 2\n");

			//uv
			/*offset += 4 * sizeof(GLfloat); //10 floats
			glEnableVertexAttribArray(3);
			glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, stride, (const void *)offset);

			if (glGetError() != GL_NO_ERROR)
			dprintf("opengl error attrib pointer 3\n");*/

			// populate the index buffer
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_unSceneVAOIndices[currentlod][p]);
			glBufferData(GL_ELEMENT_ARRAY_BUFFER, 
#ifndef INDICESGL32
				sizeof(uint16_t)
#else
				sizeof(GLuint)
#endif
				* vertindicesarray[currentlod][p].size(),
				&vertindicesarray[currentlod][p][0], GL_STATIC_DRAW);



			glBindVertexArray(0);
			glDisableVertexAttribArray(0);
			glDisableVertexAttribArray(1);
			glDisableVertexAttribArray(2);
			//glDisableVertexAttribArray(3);

			if (glGetError() != GL_NO_ERROR)
				dprintf("opengl error\n");

			//FIXME: after we go to 64 bits, keep the data in ram
			vertdataarray[currentlod][p].clear();
			vertindicesarray[currentlod][p].clear();
			vertdataarray[currentlod][p].resize(0);
			vertindicesarray[currentlod][p].resize(0);


			if (p % ISOS == ISOS - 1)
				time++;

		}
		delete[] vertdataarray[currentlod];
		delete[] vertindicesarray[currentlod];
		vertdataarray[currentlod] = nullptr;
		vertindicesarray[currentlod] = nullptr;

	} // for each lod
	//glEnable(GL_DEPTH_TEST);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glDeleteBuffers(1, &testBuf);
	glDeleteBuffers(1, &indexBufferID);
	glDeleteVertexArrays(1, &myvao);
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
	glUseProgram(0);
	glDisableVertexAttribArray(0);
	glDisableVertexAttribArray(1);
}


//-----------------------------------------------------------------------------
// Purpose: Load a ply file
//-----------------------------------------------------------------------------


bool CMainApplication::AddModelToScene( Matrix4 mat, std::vector<float> &vertdata, 
#ifndef INDICESGL32
	std::vector<short> & vertindices, 
#else
	std::vector<GLuint> & vertindices,
#endif
	const char * model, bool water, bool colours, int set) 
{

	CurrentVertex=-1;
	CurrentIndex=0;
	 p_ply ply = ply_open(model, NULL, 0, NULL);
	 //p_ply ply = ply_open("Y:\\v2t\\media\\visual_designs\\logos_3d\\v2c\\v2cSchrift.ply", NULL, 0, NULL);
        if (!ply) {
            dprintf("ply returned null: file %s\n", model);
            return false;
        }
        if (!ply_read_header(ply)) {
            dprintf("ply: bad header in ply: file %s\n", model);
            return false;
        }

        int nvertices = ply_set_read_cb(ply, "vertex", "x", vertex_cb, this, 0);
        ply_set_read_cb(ply, "vertex", "y", vertex_cb, this, 1);
        ply_set_read_cb(ply, "vertex", "z", vertex_cb, this, 2);

        ply_set_read_cb(ply, "vertex", "nx", vertex_cb, this, 3);
        ply_set_read_cb(ply, "vertex", "ny", vertex_cb, this, 4);
        ply_set_read_cb(ply, "vertex", "nz", vertex_cb, this, 5);

		ply_set_read_cb(ply, "vertex", "red", vertex_cb, this, 6);
        ply_set_read_cb(ply, "vertex", "green", vertex_cb, this, 7);
        ply_set_read_cb(ply, "vertex", "blue", vertex_cb, this, 8);
        ply_set_read_cb(ply, "vertex", "alpha", vertex_cb, this, 9);

		//ply_set_read_cb(ply, "vertex", "texture_u", vertex_cb, this, 10);
		//ply_set_read_cb(ply, "vertex", "texture_v", vertex_cb, this, 11);

		CubeVertices = new float[nvertices*numComponents]; //xyz, nx, ny, nz, uv, rgba

        int ntriangles = ply_set_read_cb(ply, "face", "vertex_indices", face_cb, NULL, 0);

        CubeIndices=new int[3*ntriangles];

        //dprintf("PLY %s: v=%ld, t=%ld\n", model, nvertices, ntriangles);
        if (!ply_read(ply)) {
            dprintf("Problem in ply_read");
            return false;
        }
        ply_close(ply);

		for (int i = 0; i < 3* ntriangles; i++) {
			vertindices.push_back(CubeIndices[i]);
		}

	
		for (int i = 0; i < nvertices; i++) {
			//pos
			Vector4 V1 = Vector4(CubeVertices[i * numComponents + 0],
				CubeVertices[i * numComponents + 1],
				CubeVertices[i * numComponents + 2], 1);
			Vector4 V = mat * V1;
			vertdata.push_back(V.x);
			vertdata.push_back(V.y);
			vertdata.push_back(V.z);
			//normals (FIXME should transform with inverse transform, but we think the matrix has uniform scaling and inv transpose = m)
			//rgh beware: normals are (nx, ny, nz, 0) to avoid being translated !!!
			V1 = Vector4(CubeVertices[i * numComponents + 3],
				CubeVertices[i * numComponents + 4],
				CubeVertices[i * numComponents + 5], 0);
			V = (mat * V1).normalize();
			vertdata.push_back(V.x);
			vertdata.push_back(V.y);
			vertdata.push_back(V.z);
			//colors (untransformed)
			if (!colours) {
				for (int j = 0; j < 4; j++)
					vertdata.push_back(isocolours[set][j]);
			} else {
				for (int j = 0; j < 4; j++)
					vertdata.push_back(CubeVertices[i * numComponents + 6 + j]);
			}
		}
		delete[] CubeVertices;
		delete[] CubeIndices;
		return true;
}



//-----------------------------------------------------------------------------
// Purpose: Draw all of the controllers as X/Y/Z lines
//-----------------------------------------------------------------------------
void CMainApplication::DrawControllers()
{
	//rgh: the format for the vertarray has changed, now xyz, nxnynz, rgba, uv. Cancel this function until needed. Needs to fix fill of points down
	return;

	// don't draw controllers if somebody else has input focus
	if( m_pHMD->IsInputFocusCapturedByAnotherProcess() )
		return;

	std::vector<float> vertdataarray;

	m_uiControllerVertcount = 0;
	m_iTrackedControllerCount = 0;

	for ( vr::TrackedDeviceIndex_t unTrackedDevice = vr::k_unTrackedDeviceIndex_Hmd + 1; unTrackedDevice < vr::k_unMaxTrackedDeviceCount; ++unTrackedDevice )
	{
		if ( !m_pHMD->IsTrackedDeviceConnected( unTrackedDevice ) )
			continue;

		if( m_pHMD->GetTrackedDeviceClass( unTrackedDevice ) != vr::TrackedDeviceClass_Controller )
			continue;

		m_iTrackedControllerCount += 1;

		if( !m_rTrackedDevicePose[ unTrackedDevice ].bPoseIsValid )
			continue;

		const Matrix4 & mat = m_rmat4DevicePose[unTrackedDevice];

		Vector4 center = mat * Vector4( 0, 0, 0, 1 );

		for ( int i = 0; i < 3; ++i )
		{
			Vector3 color( 0, 0, 0 );
			Vector4 point( 0, 0, 0, 1 );
			point[i] += 0.05f;  // offset in X, Y, Z
			color[i] = 1.0;  // R, G, B
			point = mat * point;
			vertdataarray.push_back( center.x );
			vertdataarray.push_back( center.y );
			vertdataarray.push_back( center.z );

			vertdataarray.push_back( color.x );
			vertdataarray.push_back( color.y );
			vertdataarray.push_back( color.z );
		
			vertdataarray.push_back( point.x );
			vertdataarray.push_back( point.y );
			vertdataarray.push_back( point.z );
		
			vertdataarray.push_back( color.x );
			vertdataarray.push_back( color.y );
			vertdataarray.push_back( color.z );
		
			m_uiControllerVertcount += 2;
		}

		Vector4 start = mat * Vector4( 0, 0, -0.02f, 1 );
		Vector4 end = mat * Vector4( 0, 0, -39.f, 1 );
		Vector3 color( .92f, .92f, .71f );

		vertdataarray.push_back( start.x );vertdataarray.push_back( start.y );vertdataarray.push_back( start.z );
		vertdataarray.push_back( color.x );vertdataarray.push_back( color.y );vertdataarray.push_back( color.z );

		vertdataarray.push_back( end.x );vertdataarray.push_back( end.y );vertdataarray.push_back( end.z );
		vertdataarray.push_back( color.x );vertdataarray.push_back( color.y );vertdataarray.push_back( color.z );
		m_uiControllerVertcount += 2;
	}

	// Setup the VAO the first time through.
	if ( m_unControllerVAO == 0 )
	{
		glGenVertexArrays( 1, &m_unControllerVAO );
		glBindVertexArray( m_unControllerVAO );

		glGenBuffers( 1, &m_glControllerVertBuffer );
		glBindBuffer( GL_ARRAY_BUFFER, m_glControllerVertBuffer );

		GLuint stride = 2 * 3 * sizeof( float );
		GLuint offset = 0;

		glEnableVertexAttribArray( 0 );
		glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, stride, (const void *)offset);

		offset += sizeof( Vector3 );
		glEnableVertexAttribArray( 1 );
		glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, stride, (const void *)offset);

		glBindVertexArray( 0 );
	}

	glBindBuffer( GL_ARRAY_BUFFER, m_glControllerVertBuffer );

	// set vertex data if we have some
	if( vertdataarray.size() > 0 )
	{
		//$ TODO: Use glBufferSubData for this...
		glBufferData( GL_ARRAY_BUFFER, sizeof(float) * vertdataarray.size(), &vertdataarray[0], GL_STREAM_DRAW );
	}
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::SetupCameras()
{
	m_mat4ProjectionLeft = GetHMDMatrixProjectionEye( vr::Eye_Left );
	m_mat4ProjectionRight = GetHMDMatrixProjectionEye( vr::Eye_Right );
	m_mat4eyePosLeft = GetHMDMatrixPoseEye( vr::Eye_Left );
	m_mat4eyePosRight = GetHMDMatrixPoseEye( vr::Eye_Right );
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::CreateFrameBuffer( int nWidth, int nHeight, FramebufferDesc &framebufferDesc )
{
	glGenFramebuffers(1, &framebufferDesc.m_nRenderFramebufferId );
	glBindFramebuffer(GL_FRAMEBUFFER, framebufferDesc.m_nRenderFramebufferId);

	glGenRenderbuffers(1, &framebufferDesc.m_nDepthBufferId);
	glBindRenderbuffer(GL_RENDERBUFFER, framebufferDesc.m_nDepthBufferId);
	glRenderbufferStorage/*Multisample*/(GL_RENDERBUFFER,/* 1, */GL_DEPTH_COMPONENT32, nWidth, nHeight );
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER,	framebufferDesc.m_nDepthBufferId );

	glGenTextures(1, &framebufferDesc.m_nRenderTextureId );
	glBindTexture(GL_TEXTURE_2D/*_MULTISAMPLE*/, framebufferDesc.m_nRenderTextureId );
	//glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 1, GL_RGBA8, nWidth, nHeight, true);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D/*_MULTISAMPLE*/, framebufferDesc.m_nRenderTextureId, 0);

	glGenFramebuffers(1, &framebufferDesc.m_nResolveFramebufferId );
	glBindFramebuffer(GL_FRAMEBUFFER, framebufferDesc.m_nResolveFramebufferId);

	glGenTextures(1, &framebufferDesc.m_nResolveTextureId );
	glBindTexture(GL_TEXTURE_2D, framebufferDesc.m_nResolveTextureId );
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, framebufferDesc.m_nResolveTextureId, 0);

	// check FBO status
	GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	if (status != GL_FRAMEBUFFER_COMPLETE)
	{
		return false;
	}

	glBindFramebuffer( GL_FRAMEBUFFER, 0 );

	return true;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CMainApplication::SetupStereoRenderTargets()
{
	if ( !m_pHMD )
		return false;

	m_pHMD->GetRecommendedRenderTargetSize( &m_nRenderWidth, &m_nRenderHeight );

	CreateFrameBuffer( m_nRenderWidth, m_nRenderHeight, leftEyeDesc );
	CreateFrameBuffer( m_nRenderWidth, m_nRenderHeight, rightEyeDesc );
	
	pixels = new char [m_nRenderWidth*m_nRenderHeight*3];

	return true;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::SetupDistortion()
{
	if ( !m_pHMD )
		return;

	GLushort m_iLensGridSegmentCountH = 43;
	GLushort m_iLensGridSegmentCountV = 43;

	float w = (float)( 1.0/float(m_iLensGridSegmentCountH-1));
	float h = (float)( 1.0/float(m_iLensGridSegmentCountV-1));

	float u, v = 0;

	std::vector<VertexDataLens> vVerts(0);
	VertexDataLens vert;

	//left eye distortion verts
	float Xoffset = -1;
	for( int y=0; y<m_iLensGridSegmentCountV; y++ )
	{
		for( int x=0; x<m_iLensGridSegmentCountH; x++ )
		{
			u = x*w; v = 1-y*h;
			vert.position = Vector2( Xoffset+u, -1+2*y*h );

			vr::DistortionCoordinates_t dc0 = m_pHMD->ComputeDistortion(vr::Eye_Left, u, v);

			vert.texCoordRed = Vector2(dc0.rfRed[0], 1 - dc0.rfRed[1]);
			vert.texCoordGreen =  Vector2(dc0.rfGreen[0], 1 - dc0.rfGreen[1]);
			vert.texCoordBlue = Vector2(dc0.rfBlue[0], 1 - dc0.rfBlue[1]);

			vVerts.push_back( vert );
		}
	}

	//right eye distortion verts
	Xoffset = 0;
	for( int y=0; y<m_iLensGridSegmentCountV; y++ )
	{
		for( int x=0; x<m_iLensGridSegmentCountH; x++ )
		{
			u = x*w; v = 1-y*h;
			vert.position = Vector2( Xoffset+u, -1+2*y*h );

			vr::DistortionCoordinates_t dc0 = m_pHMD->ComputeDistortion( vr::Eye_Right, u, v );

			vert.texCoordRed = Vector2(dc0.rfRed[0], 1 - dc0.rfRed[1]);
			vert.texCoordGreen = Vector2(dc0.rfGreen[0], 1 - dc0.rfGreen[1]);
			vert.texCoordBlue = Vector2(dc0.rfBlue[0], 1 - dc0.rfBlue[1]);

			vVerts.push_back( vert );
		}
	}

	std::vector<GLushort> vIndices;
	GLushort a,b,c,d;

	GLushort offset = 0;
	for( GLushort y=0; y<m_iLensGridSegmentCountV-1; y++ )
	{
		for( GLushort x=0; x<m_iLensGridSegmentCountH-1; x++ )
		{
			a = m_iLensGridSegmentCountH*y+x +offset;
			b = m_iLensGridSegmentCountH*y+x+1 +offset;
			c = (y+1)*m_iLensGridSegmentCountH+x+1 +offset;
			d = (y+1)*m_iLensGridSegmentCountH+x +offset;
			vIndices.push_back( a );
			vIndices.push_back( b );
			vIndices.push_back( c );

			vIndices.push_back( a );
			vIndices.push_back( c );
			vIndices.push_back( d );
		}
	}

	offset = (m_iLensGridSegmentCountH)*(m_iLensGridSegmentCountV);
	for( GLushort y=0; y<m_iLensGridSegmentCountV-1; y++ )
	{
		for( GLushort x=0; x<m_iLensGridSegmentCountH-1; x++ )
		{
			a = m_iLensGridSegmentCountH*y+x +offset;
			b = m_iLensGridSegmentCountH*y+x+1 +offset;
			c = (y+1)*m_iLensGridSegmentCountH+x+1 +offset;
			d = (y+1)*m_iLensGridSegmentCountH+x +offset;
			vIndices.push_back( a );
			vIndices.push_back( b );
			vIndices.push_back( c );

			vIndices.push_back( a );
			vIndices.push_back( c );
			vIndices.push_back( d );
		}
	}
	m_uiIndexSize = vIndices.size();

	glGenVertexArrays( 1, &m_unLensVAO );
	glBindVertexArray( m_unLensVAO );

	glGenBuffers( 1, &m_glIDVertBuffer );
	glBindBuffer( GL_ARRAY_BUFFER, m_glIDVertBuffer );
	glBufferData( GL_ARRAY_BUFFER, vVerts.size()*sizeof(VertexDataLens), &vVerts[0], GL_STATIC_DRAW );

	glGenBuffers( 1, &m_glIDIndexBuffer );
	glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_glIDIndexBuffer );
	glBufferData( GL_ELEMENT_ARRAY_BUFFER, vIndices.size()*sizeof(GLushort), &vIndices[0], GL_STATIC_DRAW );

	glEnableVertexAttribArray( 0 );
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataLens), (void *)offsetof( VertexDataLens, position ) );

	glEnableVertexAttribArray( 1 );
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataLens), (void *)offsetof( VertexDataLens, texCoordRed ) );

	glEnableVertexAttribArray(2);
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataLens), (void *)offsetof( VertexDataLens, texCoordGreen ) );

	glEnableVertexAttribArray(3);
	glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(VertexDataLens), (void *)offsetof( VertexDataLens, texCoordBlue ) );

	

	glBindVertexArray( 0 );

	glDisableVertexAttribArray(0);
	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(2);
	glDisableVertexAttribArray(3);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::RenderStereoTargets()
{
	glClearColor(BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 1);
	//glEnable( GL_MULTISAMPLE );

	// Left Eye
	glBindFramebuffer( GL_FRAMEBUFFER, leftEyeDesc.m_nRenderFramebufferId );
 	glViewport(0, 0, m_nRenderWidth, m_nRenderHeight );
 	RenderScene( vr::Eye_Left );

	//rgh: save to disk
	//this will kill the performance
	char name[100];

	if (savetodisk) {
		sprintf(name, "c:\\temp\\frameL%05d.bmp", framecounter);
		glPixelStorei(GL_PACK_ALIGNMENT, 1);
		glReadPixels(0, 0, m_nRenderWidth, m_nRenderHeight, GL_RGB, GL_UNSIGNED_BYTE, pixels);
		//little endian machine, R and B are flipped
		SDL_Surface *s = SDL_CreateRGBSurfaceFrom(pixels, m_nRenderWidth, m_nRenderHeight, 24, 3 * m_nRenderWidth, 0xff, 0xff00, 0xff0000, 0);
		SDL_SaveBMP(s, name);
	}

 	glBindFramebuffer( GL_FRAMEBUFFER, 0 );
	
	glDisable( GL_MULTISAMPLE );
	 	
 	glBindFramebuffer(GL_READ_FRAMEBUFFER, leftEyeDesc.m_nRenderFramebufferId);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, leftEyeDesc.m_nResolveFramebufferId );

    glBlitFramebuffer( 0, 0, m_nRenderWidth, m_nRenderHeight, 0, 0, m_nRenderWidth, m_nRenderHeight, 
		GL_COLOR_BUFFER_BIT,
 		GL_LINEAR );

 	glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);	

	//glEnable( GL_MULTISAMPLE );

	// Right Eye
	glBindFramebuffer( GL_FRAMEBUFFER, rightEyeDesc.m_nRenderFramebufferId );
 	glViewport(0, 0, m_nRenderWidth, m_nRenderHeight );
 	RenderScene( vr::Eye_Right );
 	glBindFramebuffer( GL_FRAMEBUFFER, 0 );
 	
	glDisable( GL_MULTISAMPLE );

 	glBindFramebuffer(GL_READ_FRAMEBUFFER, rightEyeDesc.m_nRenderFramebufferId );
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, rightEyeDesc.m_nResolveFramebufferId );
	
    glBlitFramebuffer( 0, 0, m_nRenderWidth, m_nRenderHeight, 0, 0, m_nRenderWidth, m_nRenderHeight, 
		GL_COLOR_BUFFER_BIT,
 		GL_LINEAR  );

 	glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0 );

	if (savetodisk) {
		framecounter++;
	}
}

void CMainApplication::PaintGrid(const vr::Hmd_Eye &nEye, int iso) {
	int c=0;
			
	Matrix4 trans;
	Vector3 iPos = Vector3(0, 0, 0);
		
	trans.translate(iPos).translate(UserPosition);
	Matrix4 transform = GetCurrentViewProjectionMatrix(nEye)*trans;
	glUniformMatrix4fv(m_nSceneMatrixLocation, 1, GL_FALSE, transform.get());

	const int currentlod = 0;
	int actualset = (currentset ) % TIMESTEPS;
	glBindVertexArray(m_unSceneVAO[currentlod][ISOS * actualset + iso]);
	glDrawElements(GL_TRIANGLES, m_uiVertcount[currentlod][ISOS * actualset + iso], 
#ifndef INDICESGL32				
		GL_UNSIGNED_SHORT, 
#else
		GL_UNSIGNED_INT,
#endif
				
		0);

	int e;
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error after Paintgrid iso=%d: %d, %s\n", iso, e, gluErrorString(e));

}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::RenderScene(vr::Hmd_Eye nEye)
{
	int e;
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error previous to renderscene: %d, %s\n", e, gluErrorString(e));

	glClearColor(BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 1);
	glDepthMask(GL_TRUE);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);

	if (m_bShowCubes)
	{
		glDisable(GL_CULL_FACE);
		//glCullFace(GL_BACK);

		//iso loop needs to go first; otherwise rendering problems appear in the borders, as the atom is rendered after half its 
		//surroundings


		//isosurface

		if (currentiso == ISOS) {
#if (1)
			glDisable(GL_BLEND);
			glDepthMask(GL_TRUE);
			//do depth peeling
			GLuint clearColor = 0;
			glBindTexture(GL_TEXTURE_2D, m_iTexture[1]);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after bindtexture: %d, %s\n", e, gluErrorString(e));
			glClearTexImage(m_iTexture[1], 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, &clearColor);

			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after clearteximage: %d, %s\n", e, gluErrorString(e));

			GLint dfb;
			glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &dfb);

			for (int zl = 0; zl < ZLAYERS; zl++) {
				glUseProgram(m_unSceneProgramID);

				if ((e = glGetError()) != GL_NO_ERROR)
					dprintf("Gl error after useprogram: %d, %s\n", e, gluErrorString(e));


				glBindFramebuffer(GL_FRAMEBUFFER, peelingFramebuffer);
				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_iTexture[3 + zl], 0);
				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_iTexture[2-zl%2], 0);
				glBindTexture(GL_TEXTURE_2D, m_iTexture[1+zl%2]);
				glClearColor(BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 1);
				glDepthMask(GL_TRUE);
				glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

				for (int i = ISOS - 1; i >= 0; i--) {
					PaintGrid(nEye, i);
				} //for all isos in descending order
				if ((e = glGetError()) != GL_NO_ERROR)
					dprintf("Gl error after paintgrid: %d, %s\n", e, gluErrorString(e));
				RenderAllTrackedRenderModels(nEye);
			} // for zl

			glBindFramebuffer(GL_FRAMEBUFFER, dfb);
			//now blend all together, back to front
			glDisable(GL_DEPTH_TEST);

			glUseProgram(m_unRenderModelProgramID);
			float mat[] = { 1, 0, 0, 0,
				0, 1, 0, 0,
				0, 0, 1, 0,
				0, 0, 0, 1 };

			glUniformMatrix4fv(m_nRenderModelMatrixLocation, 1, GL_FALSE, mat);

			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s\n", e, gluErrorString(e));
			//glDisable(GL_TEXTURE_2D);
			glBindTexture(GL_TEXTURE_2D, m_iTexture[1]);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s\n", e, gluErrorString(e));

			glDisable(GL_CULL_FACE);
			float z = 0.0f; //(m_fNearClip + m_fFarClip) / 2.0f;
			float points[] = {
				-1, -1, z, 1, 0, 0, -1, 0, 0,
				-1, 1, z, 1, 0, 0, -1, 0, 1,
				1, 1, z, 1, 0, 0, -1, 1, 1,
				1, -1, z, 1, 0, 0, -1, 1, 0, };

			GLuint myvao;
			glGenVertexArrays(1, &myvao);
			glBindVertexArray(myvao);
			GLuint testBuf;
			glGenBuffers(1, &testBuf);
			glBindBuffer(GL_ARRAY_BUFFER, testBuf);
			glBufferData(GL_ARRAY_BUFFER, 4 * 9 * sizeof(GLfloat), points, GL_STATIC_DRAW);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);

			glEnableVertexAttribArray(0);
			glEnableVertexAttribArray(1);
			glEnableVertexAttribArray(2);
			glDisableVertexAttribArray(3);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)0);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__); //<- fails ?!
			glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(4 * sizeof(float)));
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(7 * sizeof(float)));
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);

			GLuint iData[] = { 0, 1, 2,
				2, 3, 0 };

			GLuint indexBufferID;
			glGenBuffers(1, &indexBufferID);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iData), iData, GL_STATIC_DRAW);

			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			
			glEnable(GL_BLEND);
			glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

			for (int zl = ZLAYERS - 1; zl >= 0; zl--) {
				glBindTexture(GL_TEXTURE_2D, m_iTexture[3+zl]);
				glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			}

			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glDeleteBuffers(1, &testBuf);
			glDeleteBuffers(1, &indexBufferID);
			glDeleteVertexArrays(1, &myvao);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glUseProgram(0);
			glDisableVertexAttribArray(0);
			glDisableVertexAttribArray(1);
			glDisableVertexAttribArray(2);
#endif

#if 0
	//show colour buffers with the depth peeling (first 5)
			glClearColor(nEye == vr::Eye_Left ? 0.5 : 0, 0, nEye == vr::Eye_Right ? 0.5 : 0, 1);
			glClear(/*GL_COLOR_BUFFER_BIT |*/ GL_DEPTH_BUFFER_BIT);
			glUseProgram(m_unRenderModelProgramID);
			float mat2[] = {.5, 0, 0, 0, 
				0, .5, 0, 0, 
				0, 0, .5, 0, 
				0, 0, 0, 1};
			glUniformMatrix4fv(m_nRenderModelMatrixLocation, 1, GL_FALSE, mat2);

			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s\n", e, gluErrorString(e));
			//glDisable(GL_TEXTURE_2D);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s\n", e, gluErrorString(e));

			glDisable(GL_CULL_FACE);
			glDisable(GL_BLEND);
			float z2 = 0.0f; //(m_fNearClip + m_fFarClip) / 2.0f;
			float points2[] ={
				0, 0, z2, 1,		0,0,-1,		0,0,
				0, 1, z2, 1,		0, 0,-1,	0, 1,
				1, 1, z2, 1,		0, 0, -1,	1, 1,
				1, 0, z2, 1,		0, 0, -1,	1, 0, };

			//http://stackoverflow.com/questions/21767467/glvertexattribpointer-raising-impossible-gl-invalid-operation
			GLuint myvao2;
			glGenVertexArrays(1, &myvao2);
			glBindVertexArray(myvao2);
			GLuint testBuf2;
			glGenBuffers(1,&testBuf2);
			glBindBuffer(GL_ARRAY_BUFFER, testBuf2);
			glBufferData(GL_ARRAY_BUFFER, 4 * 9 * sizeof(GLfloat), points2, GL_STATIC_DRAW);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);

			glEnableVertexAttribArray(0);
			glEnableVertexAttribArray(1);
			glEnableVertexAttribArray(2);
			glDisableVertexAttribArray(3);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 9*sizeof(float), (void*)0);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__); //<- fails ?!
			glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(4 * sizeof(float)));
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(7 * sizeof(float)));
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);


			GLuint iData2[] = { 0, 1, 2,
				2, 3, 0 };

			GLuint indexBufferID2;
			glGenBuffers(1, &indexBufferID2);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID2);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iData2), iData2, GL_STATIC_DRAW);

			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			if (ZLAYERS >2) {
				glBindTexture(GL_TEXTURE_2D, m_iTexture[5]);
				glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			}
			
			mat2[13] = 0.5;
			glUniformMatrix4fv(m_nRenderModelMatrixLocation, 1, GL_FALSE, mat2);
			glBindTexture(GL_TEXTURE_2D, m_iTexture[3]);
			glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			mat2[12] = 0.5;

			if (ZLAYERS >1) {
				glUniformMatrix4fv(m_nRenderModelMatrixLocation, 1, GL_FALSE, mat2);
				glBindTexture(GL_TEXTURE_2D, m_iTexture[4]);
				glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			}
			mat2[13] = 0;
			if (ZLAYERS >3) {
				glUniformMatrix4fv(m_nRenderModelMatrixLocation, 1, GL_FALSE, mat2);
				glBindTexture(GL_TEXTURE_2D, m_iTexture[6]);
				glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			}
			mat2[13] = -0.5;
			if (ZLAYERS >4) {
				glUniformMatrix4fv(m_nRenderModelMatrixLocation, 1, GL_FALSE, mat2);
				glBindTexture(GL_TEXTURE_2D, m_iTexture[7]);
				glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			}
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glDeleteBuffers(1, &testBuf2);
			glDeleteBuffers(1, &indexBufferID2);
			glDeleteVertexArrays(1, &myvao2);
			if ((e = glGetError()) != GL_NO_ERROR)
				dprintf("Gl error after zlayer: %d, %s, l %d\n", e, gluErrorString(e), __LINE__);
			glUseProgram(0);
			glDisableVertexAttribArray(0);
			glDisableVertexAttribArray(1);
			glDisableVertexAttribArray(2);

#endif 
		} // if currentiso
		else {
			glDisable(GL_BLEND);
			glUseProgram(m_unSceneProgramID);
			PaintGrid(nEye, currentiso);
			RenderAllTrackedRenderModels(nEye);
		} //else currentiso =isos


		if ((e = glGetError()) != GL_NO_ERROR)
			dprintf("Gl error after rendering: %d, %s\n", e, gluErrorString(e));
	} //show cubes 

	bool bIsInputCapturedByAnotherProcess = m_pHMD->IsInputFocusCapturedByAnotherProcess();
	/*
	 //this is not initialized in our program, gives opengl error
	if( !bIsInputCapturedByAnotherProcess )
	{
		// draw the controller axis lines
		glUseProgram( m_unControllerTransformProgramID );
		glUniformMatrix4fv( m_nControllerMatrixLocation, 1, GL_FALSE, GetCurrentViewProjectionMatrix( nEye ).get() );
		glBindVertexArray( m_unControllerVAO );
		glDrawArrays( GL_LINES, 0, m_uiControllerVertcount );
		glBindVertexArray( 0 );
	}
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error marker 1: %d, %s\n", e, gluErrorString(e));
		*/

}

void CMainApplication::RenderAllTrackedRenderModels(vr::Hmd_Eye nEye)
{
	// ----- Render Model rendering -----
	glUseProgram(m_unRenderModelProgramID);

	for (uint32_t unTrackedDevice = 0; unTrackedDevice < vr::k_unMaxTrackedDeviceCount; unTrackedDevice++)
	{
		if (!m_rTrackedDeviceToRenderModel[unTrackedDevice] || !m_rbShowTrackedDevice[unTrackedDevice])
			continue;

		const vr::TrackedDevicePose_t & pose = m_rTrackedDevicePose[unTrackedDevice];

		const Matrix4 & matDeviceToTracking = m_rmat4DevicePose[unTrackedDevice];
		Matrix4 matMVP = GetCurrentViewProjectionMatrix(nEye) * matDeviceToTracking;
		glUniformMatrix4fv(m_nRenderModelMatrixLocation, 1, GL_FALSE, matMVP.get());

		m_rTrackedDeviceToRenderModel[unTrackedDevice]->Draw();
	}
	GLuint e;
	if ((e = glGetError()) != GL_NO_ERROR)
		dprintf("Gl error marker 2: %d, %s\n", e, gluErrorString(e));

	//glUseProgram(0);
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::RenderDistortion()
{
	glDisable(GL_DEPTH_TEST);
	glViewport( 0, 0, m_nWindowWidth, m_nWindowHeight );

	glBindVertexArray( m_unLensVAO );
	glUseProgram( m_unLensProgramID );

	//render left lens (first half of index array )
	glBindTexture(GL_TEXTURE_2D, leftEyeDesc.m_nResolveTextureId );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
	glDrawElements( GL_TRIANGLES, m_uiIndexSize/2, GL_UNSIGNED_SHORT, 0 );

	//render right lens (second half of index array )
	glBindTexture(GL_TEXTURE_2D, rightEyeDesc.m_nResolveTextureId  );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
	glDrawElements( GL_TRIANGLES, m_uiIndexSize/2, GL_UNSIGNED_SHORT, (const void *)(m_uiIndexSize) );

	glBindVertexArray( 0 );
	glUseProgram( 0 );
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
Matrix4 CMainApplication::GetHMDMatrixProjectionEye( vr::Hmd_Eye nEye )
{
	if ( !m_pHMD )
		return Matrix4();

	vr::HmdMatrix44_t mat = m_pHMD->GetProjectionMatrix( nEye, m_fNearClip, m_fFarClip, vr::API_OpenGL);

	return Matrix4(
		mat.m[0][0], mat.m[1][0], mat.m[2][0], mat.m[3][0],
		mat.m[0][1], mat.m[1][1], mat.m[2][1], mat.m[3][1], 
		mat.m[0][2], mat.m[1][2], mat.m[2][2], mat.m[3][2], 
		mat.m[0][3], mat.m[1][3], mat.m[2][3], mat.m[3][3]
	);
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
Matrix4 CMainApplication::GetHMDMatrixPoseEye( vr::Hmd_Eye nEye )
{
	if ( !m_pHMD )
		return Matrix4();

	vr::HmdMatrix34_t matEyeRight = m_pHMD->GetEyeToHeadTransform( nEye );
	Matrix4 matrixObj(
		matEyeRight.m[0][0], matEyeRight.m[1][0], matEyeRight.m[2][0], 0.0, 
		matEyeRight.m[0][1], matEyeRight.m[1][1], matEyeRight.m[2][1], 0.0,
		matEyeRight.m[0][2], matEyeRight.m[1][2], matEyeRight.m[2][2], 0.0,
		matEyeRight.m[0][3], matEyeRight.m[1][3], matEyeRight.m[2][3], 1.0f
		);

	return matrixObj.invert();
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
Matrix4 CMainApplication::GetCurrentViewProjectionMatrix( vr::Hmd_Eye nEye )
{
	Matrix4 matMVP;
	if( nEye == vr::Eye_Left )
	{
		matMVP = m_mat4ProjectionLeft * m_mat4eyePosLeft * m_mat4HMDPose;
	}
	else if( nEye == vr::Eye_Right )
	{
		matMVP = m_mat4ProjectionRight * m_mat4eyePosRight *  m_mat4HMDPose;
	}

	return matMVP;
}


//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMainApplication::UpdateHMDMatrixPose()
{
	if ( !m_pHMD )
		return;

	vr::VRCompositor()->WaitGetPoses(m_rTrackedDevicePose, vr::k_unMaxTrackedDeviceCount, NULL, 0 );

	m_iValidPoseCount = 0;
	m_strPoseClasses = "";
	for ( int nDevice = 0; nDevice < vr::k_unMaxTrackedDeviceCount; ++nDevice )
	{
		if ( m_rTrackedDevicePose[nDevice].bPoseIsValid )
		{
			m_iValidPoseCount++;
			m_rmat4DevicePose[nDevice] = ConvertSteamVRMatrixToMatrix4( m_rTrackedDevicePose[nDevice].mDeviceToAbsoluteTracking );
			if (m_rDevClassChar[