File: model.cpp

package info (click to toggle)
megaglest 3.9.1-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 18,172 kB
  • ctags: 26,052
  • sloc: cpp: 140,512; ansic: 66,187; python: 3,761; sh: 2,986; perl: 1,899; php: 1,247; objc: 1,111; makefile: 259; sql: 139
file content (2202 lines) | stat: -rw-r--r-- 78,608 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
// ==============================================================
//	This file is part of Glest Shared Library (www.glest.org)
//
//	Copyright (C) 2001-2008 MartiƱo Figueroa
//
//	You can redistribute this code and/or modify it under
//	the terms of the GNU General Public License as published
//	by the Free Software Foundation; either version 2 of the
//	License, or (at your option) any later version
// ==============================================================

#include "model.h"

#include <cstdio>
#include <cassert>
#include <stdexcept>

#include "interpolation.h"
#include "conversion.h"
#include "util.h"
#include "platform_common.h"
#include "opengl.h"
#include "platform_util.h"
#include <memory>
#include <map>
#include <vector>
#include "leak_dumper.h"

using namespace Shared::Platform;
using namespace Shared::PlatformCommon;
using namespace Shared::Graphics::Gl;

using namespace std;
using namespace Shared::Util;

namespace Shared{ namespace Graphics{

using namespace Util;

// Utils methods for endianness conversion
void toEndianFileHeader(FileHeader &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		for(unsigned int i = 0; i < 3; ++i) {
			header.id[i] = Shared::PlatformByteOrder::toCommonEndian(header.id[i]);
		}
		header.version = Shared::PlatformByteOrder::toCommonEndian(header.version);
	}
}
void fromEndianFileHeader(FileHeader &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		for(unsigned int i = 0; i < 3; ++i) {
			header.id[i] = Shared::PlatformByteOrder::fromCommonEndian(header.id[i]);
		}
		header.version = Shared::PlatformByteOrder::fromCommonEndian(header.version);
	}
}

void toEndianModelHeader(ModelHeader &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		header.type = Shared::PlatformByteOrder::toCommonEndian(header.type);
		header.meshCount = Shared::PlatformByteOrder::toCommonEndian(header.meshCount);
	}
}
void fromEndianModelHeader(ModelHeader &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		header.type = Shared::PlatformByteOrder::toCommonEndian(header.type);
		header.meshCount = Shared::PlatformByteOrder::toCommonEndian(header.meshCount);
	}
}

void toEndianMeshHeader(MeshHeader &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		for(unsigned int i = 0; i < meshNameSize; ++i) {
			header.name[i] = Shared::PlatformByteOrder::toCommonEndian(header.name[i]);
		}
		header.frameCount = Shared::PlatformByteOrder::toCommonEndian(header.frameCount);
		header.vertexCount = Shared::PlatformByteOrder::toCommonEndian(header.vertexCount);
		header.indexCount = Shared::PlatformByteOrder::toCommonEndian(header.indexCount);
		for(unsigned int i = 0; i < 3; ++i) {
			header.diffuseColor[i] = Shared::PlatformByteOrder::toCommonEndian(header.diffuseColor[i]);
			header.specularColor[i] = Shared::PlatformByteOrder::toCommonEndian(header.specularColor[i]);
		}
		header.specularPower = Shared::PlatformByteOrder::toCommonEndian(header.specularPower);
		header.opacity = Shared::PlatformByteOrder::toCommonEndian(header.opacity);
		header.properties = Shared::PlatformByteOrder::toCommonEndian(header.properties);
		header.textures = Shared::PlatformByteOrder::toCommonEndian(header.textures);
	}
}

void fromEndianMeshHeader(MeshHeader &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		for(unsigned int i = 0; i < meshNameSize; ++i) {
			header.name[i] = Shared::PlatformByteOrder::fromCommonEndian(header.name[i]);
		}
		header.frameCount = Shared::PlatformByteOrder::fromCommonEndian(header.frameCount);
		header.vertexCount = Shared::PlatformByteOrder::fromCommonEndian(header.vertexCount);
		header.indexCount = Shared::PlatformByteOrder::fromCommonEndian(header.indexCount);
		for(unsigned int i = 0; i < 3; ++i) {
			header.diffuseColor[i] = Shared::PlatformByteOrder::fromCommonEndian(header.diffuseColor[i]);
			header.specularColor[i] = Shared::PlatformByteOrder::fromCommonEndian(header.specularColor[i]);
		}
		header.specularPower = Shared::PlatformByteOrder::fromCommonEndian(header.specularPower);
		header.opacity = Shared::PlatformByteOrder::fromCommonEndian(header.opacity);
		header.properties = Shared::PlatformByteOrder::fromCommonEndian(header.properties);
		header.textures = Shared::PlatformByteOrder::fromCommonEndian(header.textures);
	}
}

void toEndianModelHeaderV3(ModelHeaderV3 &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		header.meshCount = Shared::PlatformByteOrder::toCommonEndian(header.meshCount);
	}
}
void fromEndianModelHeaderV3(ModelHeaderV3 &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		header.meshCount = Shared::PlatformByteOrder::fromCommonEndian(header.meshCount);
	}
}

void toEndianMeshHeaderV3(MeshHeaderV3 &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		header.vertexFrameCount = Shared::PlatformByteOrder::toCommonEndian(header.vertexFrameCount);
		header.normalFrameCount = Shared::PlatformByteOrder::toCommonEndian(header.normalFrameCount);
		header.texCoordFrameCount = Shared::PlatformByteOrder::toCommonEndian(header.texCoordFrameCount);
		header.colorFrameCount = Shared::PlatformByteOrder::toCommonEndian(header.colorFrameCount);
		header.pointCount = Shared::PlatformByteOrder::toCommonEndian(header.pointCount);
		header.indexCount = Shared::PlatformByteOrder::toCommonEndian(header.indexCount);
		header.properties = Shared::PlatformByteOrder::toCommonEndian(header.properties);
		for(unsigned int i = 0; i < 64; ++i) {
			header.texName[i] = Shared::PlatformByteOrder::toCommonEndian(header.texName[i]);
		}
	}
}

void fromEndianMeshHeaderV3(MeshHeaderV3 &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		header.vertexFrameCount = Shared::PlatformByteOrder::fromCommonEndian(header.vertexFrameCount);
		header.normalFrameCount = Shared::PlatformByteOrder::fromCommonEndian(header.normalFrameCount);
		header.texCoordFrameCount = Shared::PlatformByteOrder::fromCommonEndian(header.texCoordFrameCount);
		header.colorFrameCount = Shared::PlatformByteOrder::fromCommonEndian(header.colorFrameCount);
		header.pointCount = Shared::PlatformByteOrder::fromCommonEndian(header.pointCount);
		header.indexCount = Shared::PlatformByteOrder::fromCommonEndian(header.indexCount);
		header.properties = Shared::PlatformByteOrder::fromCommonEndian(header.properties);
		for(unsigned int i = 0; i < 64; ++i) {
			header.texName[i] = Shared::PlatformByteOrder::fromCommonEndian(header.texName[i]);
		}
	}
}

void toEndianMeshHeaderV2(MeshHeaderV2 &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		header.vertexFrameCount = Shared::PlatformByteOrder::toCommonEndian(header.vertexFrameCount);
		header.normalFrameCount = Shared::PlatformByteOrder::toCommonEndian(header.normalFrameCount);
		header.texCoordFrameCount = Shared::PlatformByteOrder::toCommonEndian(header.texCoordFrameCount);
		header.colorFrameCount = Shared::PlatformByteOrder::toCommonEndian(header.colorFrameCount);
		header.pointCount = Shared::PlatformByteOrder::toCommonEndian(header.pointCount);
		header.indexCount = Shared::PlatformByteOrder::toCommonEndian(header.indexCount);
		header.hasTexture = Shared::PlatformByteOrder::toCommonEndian(header.hasTexture);
		header.primitive = Shared::PlatformByteOrder::toCommonEndian(header.primitive);
		header.cullFace = Shared::PlatformByteOrder::toCommonEndian(header.cullFace);

		for(unsigned int i = 0; i < 64; ++i) {
			header.texName[i] = Shared::PlatformByteOrder::toCommonEndian(header.texName[i]);
		}
	}
}

void fromEndianMeshHeaderV2(MeshHeaderV2 &header) {
	static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
	if(bigEndianSystem == true) {
		header.vertexFrameCount = Shared::PlatformByteOrder::fromCommonEndian(header.vertexFrameCount);
		header.normalFrameCount = Shared::PlatformByteOrder::fromCommonEndian(header.normalFrameCount);
		header.texCoordFrameCount = Shared::PlatformByteOrder::fromCommonEndian(header.texCoordFrameCount);
		header.colorFrameCount = Shared::PlatformByteOrder::fromCommonEndian(header.colorFrameCount);
		header.pointCount = Shared::PlatformByteOrder::fromCommonEndian(header.pointCount);
		header.indexCount = Shared::PlatformByteOrder::fromCommonEndian(header.indexCount);
		header.hasTexture = Shared::PlatformByteOrder::fromCommonEndian(header.hasTexture);
		header.primitive = Shared::PlatformByteOrder::fromCommonEndian(header.primitive);
		header.cullFace = Shared::PlatformByteOrder::fromCommonEndian(header.cullFace);

		for(unsigned int i = 0; i < 64; ++i) {
			header.texName[i] = Shared::PlatformByteOrder::fromCommonEndian(header.texName[i]);
		}
	}
}

// =====================================================
//	class Mesh
// =====================================================

// ==================== constructor & destructor ====================

Mesh::Mesh() {
	textureManager = NULL;
	frameCount= 0;
	vertexCount= 0;
	indexCount= 0;
	texCoordFrameCount = 0;
	opacity = 0.0f;
	specularPower = 0.0f;

	vertices= NULL;
	normals= NULL;
	texCoords= NULL;
	tangents= NULL;
	indices= NULL;
	interpolationData= NULL;

	for(int i=0; i<meshTextureCount; ++i){
		textures[i]= NULL;
		texturesOwned[i]=false;
	}

	twoSided= false;
	customColor= false;
	noSelect= false;

	textureFlags=0;

	hasBuiltVBOs = false;
	// Vertex Buffer Object Names
	m_nVBOVertices	= 0;
	m_nVBOTexCoords	= 0;
	m_nVBONormals	= 0;
	m_nVBOIndexes	= 0;
}

Mesh::~Mesh() {
	end();
}

void Mesh::init() {
	try {
		vertices= new Vec3f[frameCount*vertexCount];
	}
	catch(bad_alloc& ba) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Error on line: %d size: %d msg: %s\n",__LINE__,(frameCount*vertexCount),ba.what());
		throw megaglest_runtime_error(szBuf);
	}
	try {
		normals= new Vec3f[frameCount*vertexCount];
	}
	catch(bad_alloc& ba) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Error on line: %d size: %d msg: %s\n",__LINE__,(frameCount*vertexCount),ba.what());
		throw megaglest_runtime_error(szBuf);
	}
	try {
		texCoords= new Vec2f[vertexCount];
	}
	catch(bad_alloc& ba) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Error on line: %d size: %d msg: %s\n",__LINE__,vertexCount,ba.what());
		throw megaglest_runtime_error(szBuf);
	}
	try {
		indices= new uint32[indexCount];
	}
	catch(bad_alloc& ba) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Error on line: %d size: %d msg: %s\n",__LINE__,indexCount,ba.what());
		throw megaglest_runtime_error(szBuf);
	}
}

void Mesh::end() {
	ReleaseVBOs();

	delete [] vertices;
	vertices=NULL;
	delete [] normals;
	normals=NULL;
	delete [] texCoords;
	texCoords=NULL;
	delete [] tangents;
	tangents=NULL;
	delete [] indices;
	indices=NULL;

	cleanupInterpolationData();

	if(textureManager != NULL) {
		for(int i = 0; i < meshTextureCount; ++i) {
			if(texturesOwned[i] == true && textures[i] != NULL) {
				//printf("Deleting Texture [%s] i = %d\n",textures[i]->getPath().c_str(),i);
				textureManager->endTexture(textures[i]);
				textures[i] = NULL;
			}
		}
	}
	textureManager = NULL;
}

// ========================== shadows & interpolation =========================

void Mesh::buildInterpolationData(){
	if(interpolationData != NULL) {
		printf("**WARNING possible memory leak [Mesh::buildInterpolationData()]\n");
	}
	interpolationData= new InterpolationData(this);
}

void Mesh::cleanupInterpolationData() {
	delete interpolationData;
	interpolationData=NULL;
}

void Mesh::updateInterpolationData(float t, bool cycle) {
	if(interpolationData != NULL) {
		interpolationData->update(t, cycle);
	}
}

void Mesh::updateInterpolationVertices(float t, bool cycle) {
	if(interpolationData != NULL) {
		interpolationData->updateVertices(t, cycle);
	}
}

void Mesh::BuildVBOs() {
	if(getVBOSupported() == true) {
		if(hasBuiltVBOs == false) {
			//printf("In [%s::%s Line: %d] setting up a VBO...\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);

			// Generate And Bind The Vertex Buffer
			glGenBuffersARB( 1,(GLuint*) &m_nVBOVertices );					// Get A Valid Name
			glBindBufferARB( GL_ARRAY_BUFFER_ARB, m_nVBOVertices );			// Bind The Buffer
			// Load The Data
			glBufferDataARB( GL_ARRAY_BUFFER_ARB,  sizeof(Vec3f)*frameCount*vertexCount, vertices, GL_STATIC_DRAW_ARB );
			glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

			// Generate And Bind The Texture Coordinate Buffer
			glGenBuffersARB( 1, (GLuint*)&m_nVBOTexCoords );					// Get A Valid Name
			glBindBufferARB( GL_ARRAY_BUFFER_ARB, m_nVBOTexCoords );		// Bind The Buffer
			// Load The Data
			glBufferDataARB( GL_ARRAY_BUFFER_ARB, sizeof(Vec2f)*vertexCount, texCoords, GL_STATIC_DRAW_ARB );
			glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

			// Generate And Bind The Normal Buffer
			glGenBuffersARB( 1, (GLuint*)&m_nVBONormals );					// Get A Valid Name
			glBindBufferARB( GL_ARRAY_BUFFER_ARB, m_nVBONormals );			// Bind The Buffer
			// Load The Data
			glBufferDataARB( GL_ARRAY_BUFFER_ARB,  sizeof(Vec3f)*frameCount*vertexCount, normals, GL_STATIC_DRAW_ARB );
			glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

			// Generate And Bind The Index Buffer
			glGenBuffersARB( 1, (GLuint*)&m_nVBOIndexes );					// Get A Valid Name
			glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, m_nVBOIndexes );			// Bind The Buffer
			// Load The Data
			glBufferDataARB( GL_ELEMENT_ARRAY_BUFFER_ARB,  sizeof(uint32)*indexCount, indices, GL_STATIC_DRAW_ARB );
			glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);

			// Our Copy Of The Data Is No Longer Necessary, It Is Safe In The Graphics Card
			delete [] vertices; vertices = NULL;
			delete [] texCoords; texCoords = NULL;
			delete [] normals; normals = NULL;
			delete [] indices; indices = NULL;

			delete interpolationData;
			interpolationData = NULL;

			hasBuiltVBOs = true;
		}
	}
}

void Mesh::ReleaseVBOs() {
	if(getVBOSupported() == true) {
		if(hasBuiltVBOs == true) {
			glDeleteBuffersARB( 1, (GLuint*)&m_nVBOVertices );					// Get A Valid Name
			glDeleteBuffersARB( 1, (GLuint*)&m_nVBOTexCoords );					// Get A Valid Name
			glDeleteBuffersARB( 1, (GLuint*)&m_nVBONormals );					// Get A Valid Name
			glDeleteBuffersARB( 1, (GLuint*)&m_nVBOIndexes );					// Get A Valid Name
			hasBuiltVBOs = false;
		}
	}
}

// ==================== load ====================

string Mesh::findAlternateTexture(vector<string> conversionList, string textureFile) {
	string result = textureFile;
	string fileExt = extractExtension(textureFile);

	for(unsigned int i = 0; i < conversionList.size(); ++i) {
		string convertTo = conversionList[i];
		if(fileExt != convertTo) {
			string alternateTexture = textureFile;
			replaceAll(alternateTexture, "." + fileExt, "." + convertTo);
			if(fileExists(alternateTexture) == true) {
				result = alternateTexture;
				break;
			}
		}
	}
	return result;
}

void Mesh::loadV2(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
		bool deletePixMapAfterLoad, std::map<string,vector<pair<string, string> > > *loadedFileList,
		string sourceLoader,string modelFile) {
	this->textureManager = textureManager;
	//read header
	MeshHeaderV2 meshHeader;
	size_t readBytes = fread(&meshHeader, sizeof(MeshHeaderV2), 1, f);
	if(readBytes != 1) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianMeshHeaderV2(meshHeader);

	if(meshHeader.normalFrameCount != meshHeader.vertexFrameCount) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Old v2 model: vertex frame count different from normal frame count [v = %d, n = %d] meshIndex = %d modelFile [%s]",meshHeader.vertexFrameCount,meshHeader.normalFrameCount,meshIndex,modelFile.c_str());
		throw megaglest_runtime_error(szBuf,true);
	}

	if(meshHeader.texCoordFrameCount != 1) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Old v2 model: texture coord frame count is not 1 [t = %d] meshIndex = %d modelFile [%s]",meshHeader.texCoordFrameCount,meshIndex,modelFile.c_str());
		throw megaglest_runtime_error(szBuf,true);
	}

	//init
	frameCount= meshHeader.vertexFrameCount;
	vertexCount= meshHeader.pointCount;
	indexCount= meshHeader.indexCount;
	texCoordFrameCount = meshHeader.texCoordFrameCount;

	init();

	//misc
	twoSided= false;
	customColor= false;
	noSelect= false;

	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Load v2, this = %p Found meshHeader.hasTexture = %d, texName [%s] mtDiffuse = %d meshIndex = %d modelFile [%s]\n",this,meshHeader.hasTexture,toLower(reinterpret_cast<char*>(meshHeader.texName)).c_str(),mtDiffuse,meshIndex,modelFile.c_str());

	textureFlags= 0;
	if(meshHeader.hasTexture) {
		textureFlags= 1;
	}

	//texture
	if(meshHeader.hasTexture && textureManager!=NULL){
		texturePaths[mtDiffuse]= toLower(reinterpret_cast<char*>(meshHeader.texName));
		string texPath= dir;
        if(texPath != "") {
        	endPathWithSlash(texPath);
        }
		texPath += texturePaths[mtDiffuse];

		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] v2 model texture [%s] meshIndex = %d modelFile [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,texPath.c_str(),meshIndex,modelFile.c_str());

		textures[mtDiffuse]= dynamic_cast<Texture2D*>(textureManager->getTexture(texPath));
		if(textures[mtDiffuse] == NULL) {
			if(fileExists(texPath) == false) {
				vector<string> conversionList;
				conversionList.push_back("png");
				conversionList.push_back("jpg");
				conversionList.push_back("tga");
				conversionList.push_back("bmp");
				texPath = findAlternateTexture(conversionList, texPath);
			}
			if(fileExists(texPath) == true) {
				if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] v2 model texture [%s] meshIndex = %d modelFile [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,texPath.c_str(),meshIndex,modelFile.c_str());

				textures[mtDiffuse]= textureManager->newTexture2D();
				textures[mtDiffuse]->load(texPath);
				if(loadedFileList) {
					(*loadedFileList)[texPath].push_back(make_pair(sourceLoader,sourceLoader));
				}
				texturesOwned[mtDiffuse]=true;
				textures[mtDiffuse]->init(textureManager->getTextureFilter(),textureManager->getMaxAnisotropy());
				if(deletePixMapAfterLoad == true) {
					textures[mtDiffuse]->deletePixels();
				}
			}
			else {
				SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error v2 model is missing texture [%s] meshIndex = %d modelFile [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,texPath.c_str(),meshIndex,modelFile.c_str());
			}
		}
	}

	//read data
	readBytes = fread(vertices, sizeof(Vec3f)*frameCount*vertexCount, 1, f);
	if(readBytes != 1 && (frameCount * vertexCount) != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianVecArray<Vec3f>(vertices, frameCount*vertexCount);

	readBytes = fread(normals, sizeof(Vec3f)*frameCount*vertexCount, 1, f);
	if(readBytes != 1 && (frameCount * vertexCount) != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianVecArray<Vec3f>(normals, frameCount*vertexCount);

	if(textureFlags & (1<<mtDiffuse)) {
		readBytes = fread(texCoords, sizeof(Vec2f)*vertexCount, 1, f);
		if(readBytes != 1 && vertexCount != 0) {
			char szBuf[8096]="";
			snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
			throw megaglest_runtime_error(szBuf);
		}
		fromEndianVecArray<Vec2f>(texCoords, vertexCount);
	}
	readBytes = fread(&diffuseColor, sizeof(Vec3f), 1, f);
	if(readBytes != 1) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianVecArray<Vec3f>(&diffuseColor, 1);

	readBytes = fread(&opacity, sizeof(float32), 1, f);
	if(readBytes != 1) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	opacity = Shared::PlatformByteOrder::fromCommonEndian(opacity);

	int seek_result = fseek(f, sizeof(Vec4f)*(meshHeader.colorFrameCount-1), SEEK_CUR);
	if(seek_result != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fseek returned failure = %d [%u] on line: %d.",seek_result,indexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	readBytes = fread(indices, sizeof(uint32)*indexCount, 1, f);
	if(readBytes != 1 && indexCount != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u] on line: %d.",readBytes,indexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	Shared::PlatformByteOrder::fromEndianTypeArray<uint32>(indices, indexCount);
}

void Mesh::loadV3(int meshIndex, const string &dir, FILE *f,
		TextureManager *textureManager,bool deletePixMapAfterLoad,
		std::map<string,vector<pair<string, string> > > *loadedFileList,
		string sourceLoader,string modelFile) {
	this->textureManager = textureManager;

	//read header
	MeshHeaderV3 meshHeader;
	size_t readBytes = fread(&meshHeader, sizeof(MeshHeaderV3), 1, f);
	if(readBytes != 1) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianMeshHeaderV3(meshHeader);

	if(meshHeader.normalFrameCount != meshHeader.vertexFrameCount) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Old v3 model: vertex frame count different from normal frame count [v = %d, n = %d] meshIndex = %d modelFile [%s]",meshHeader.vertexFrameCount,meshHeader.normalFrameCount,meshIndex,modelFile.c_str());
		throw megaglest_runtime_error(szBuf,true);
	}

	//init
	frameCount= meshHeader.vertexFrameCount;
	vertexCount= meshHeader.pointCount;
	indexCount= meshHeader.indexCount;
	texCoordFrameCount = meshHeader.texCoordFrameCount;

	init();

	//misc
	twoSided= (meshHeader.properties & mp3TwoSided) != 0;
	customColor= (meshHeader.properties & mp3CustomColor) != 0;
	noSelect = false;

	textureFlags= 0;
	if((meshHeader.properties & mp3NoTexture) != mp3NoTexture) {
		textureFlags= 1;
	}

	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Load v3, this = %p Found meshHeader.properties = %d, textureFlags = %d, texName [%s] mtDiffuse = %d meshIndex = %d modelFile [%s]\n",this,meshHeader.properties,textureFlags,toLower(reinterpret_cast<char*>(meshHeader.texName)).c_str(),mtDiffuse,meshIndex,modelFile.c_str());

	//texture
	if((meshHeader.properties & mp3NoTexture) != mp3NoTexture && textureManager!=NULL){
		texturePaths[mtDiffuse]= toLower(reinterpret_cast<char*>(meshHeader.texName));

		string texPath= dir;
        if(texPath != "") {
        	endPathWithSlash(texPath);
        }
		texPath += texturePaths[mtDiffuse];

		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] v3 model texture [%s] meshIndex = %d modelFile [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,texPath.c_str(),meshIndex,modelFile.c_str());

		textures[mtDiffuse]= dynamic_cast<Texture2D*>(textureManager->getTexture(texPath));
		if(textures[mtDiffuse] == NULL) {
			if(fileExists(texPath) == false) {
				vector<string> conversionList;
				conversionList.push_back("png");
				conversionList.push_back("jpg");
				conversionList.push_back("tga");
				conversionList.push_back("bmp");
				texPath = findAlternateTexture(conversionList, texPath);
			}

			if(fileExists(texPath) == true) {
				if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] v3 model texture [%s] meshIndex = %d modelFile [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,texPath.c_str(),meshIndex,modelFile.c_str());

				textures[mtDiffuse]= textureManager->newTexture2D();
				textures[mtDiffuse]->load(texPath);
				if(loadedFileList) {
					(*loadedFileList)[texPath].push_back(make_pair(sourceLoader,sourceLoader));
				}

				texturesOwned[mtDiffuse]=true;
				textures[mtDiffuse]->init(textureManager->getTextureFilter(),textureManager->getMaxAnisotropy());
				if(deletePixMapAfterLoad == true) {
					textures[mtDiffuse]->deletePixels();
				}
			}
			else {
				SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error v3 model is missing texture [%s] meshHeader.properties = %d meshIndex = %d modelFile [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,texPath.c_str(),meshHeader.properties,meshIndex,modelFile.c_str());
			}
		}
	}

	//read data
	readBytes = fread(vertices, sizeof(Vec3f)*frameCount*vertexCount, 1, f);
	if(readBytes != 1 && (frameCount * vertexCount) != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianVecArray<Vec3f>(vertices, frameCount*vertexCount);

	readBytes = fread(normals, sizeof(Vec3f)*frameCount*vertexCount, 1, f);
	if(readBytes != 1 && (frameCount * vertexCount) != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianVecArray<Vec3f>(normals, frameCount*vertexCount);

	if(textureFlags & (1<<mtDiffuse)) {
		for(unsigned int i=0; i<meshHeader.texCoordFrameCount; ++i){
			readBytes = fread(texCoords, sizeof(Vec2f)*vertexCount, 1, f);
			if(readBytes != 1 && vertexCount != 0) {
				char szBuf[8096]="";
				snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
				throw megaglest_runtime_error(szBuf);
			}
			fromEndianVecArray<Vec2f>(texCoords, vertexCount);
		}
	}
	readBytes = fread(&diffuseColor, sizeof(Vec3f), 1, f);
	if(readBytes != 1) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianVecArray<Vec3f>(&diffuseColor, 1);

	readBytes = fread(&opacity, sizeof(float32), 1, f);
	if(readBytes != 1) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	opacity = Shared::PlatformByteOrder::fromCommonEndian(opacity);

	int seek_result = fseek(f, sizeof(Vec4f)*(meshHeader.colorFrameCount-1), SEEK_CUR);
	if(seek_result != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fseek returned failure = %d [%u] on line: %d.",seek_result,indexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}

	readBytes = fread(indices, sizeof(uint32)*indexCount, 1, f);
	if(readBytes != 1 && indexCount != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u] on line: %d.",readBytes,indexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	Shared::PlatformByteOrder::fromEndianTypeArray<uint32>(indices, indexCount);
}

Texture2D* Mesh::loadMeshTexture(int meshIndex, int textureIndex,
		TextureManager *textureManager, string textureFile,
		int textureChannelCount, bool &textureOwned, bool deletePixMapAfterLoad,
		std::map<string,vector<pair<string, string> > > *loadedFileList,
		string sourceLoader,string modelFile) {

	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s] #1 load texture [%s] modelFile [%s]\n",__FUNCTION__,textureFile.c_str(),modelFile.c_str());

	Texture2D* texture = dynamic_cast<Texture2D*>(textureManager->getTexture(textureFile));
	if(texture == NULL) {
		if(fileExists(textureFile) == false) {
			vector<string> conversionList;
			conversionList.push_back("png");
			conversionList.push_back("jpg");
			conversionList.push_back("tga");
			conversionList.push_back("bmp");
			textureFile = findAlternateTexture(conversionList, textureFile);

			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s] #2 load texture [%s]\n",__FUNCTION__,textureFile.c_str());
		}

		if(fileExists(textureFile) == true) {
			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s] #3 load texture [%s] modelFile [%s]\n",__FUNCTION__,textureFile.c_str(),modelFile.c_str());
			//if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s] texture exists loading [%s]\n",__FUNCTION__,textureFile.c_str());

			texture = textureManager->newTexture2D();
			if(textureChannelCount != -1) {
				texture->getPixmap()->init(textureChannelCount);
			}
			texture->load(textureFile);
			if(loadedFileList) {
				(*loadedFileList)[textureFile].push_back(make_pair(sourceLoader,sourceLoader));
			}

			//if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s] texture loaded [%s]\n",__FUNCTION__,textureFile.c_str());

			textureOwned = true;
			texture->init(textureManager->getTextureFilter(),textureManager->getMaxAnisotropy());
			if(deletePixMapAfterLoad == true) {
				texture->deletePixels();
			}

			//if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s] texture inited [%s]\n",__FUNCTION__,textureFile.c_str());
		}
		else {
			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s] #3 cannot load texture [%s] modelFile [%s]\n",__FUNCTION__,textureFile.c_str(),modelFile.c_str());
			SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error v4 model is missing texture [%s] textureFlags = %d meshIndex = %d textureIndex = %d modelFile [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,textureFile.c_str(),textureFlags,meshIndex,textureIndex,modelFile.c_str());
		}
	}

	return texture;
}

void Mesh::load(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
				bool deletePixMapAfterLoad,std::map<string,vector<pair<string, string> > > *loadedFileList,
				string sourceLoader,string modelFile) {
	this->textureManager = textureManager;
	
	//read header
	MeshHeader meshHeader;
	size_t readBytes = fread(&meshHeader, sizeof(MeshHeader), 1, f);
	if(readBytes != 1) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianMeshHeader(meshHeader);

	name = reinterpret_cast<char*>(meshHeader.name);

	//printf("Load, Found meshTextureCount = %d, meshHeader.textures = %d\n",meshTextureCount,meshHeader.textures);

	//init
	frameCount= meshHeader.frameCount;
	vertexCount= meshHeader.vertexCount;
	indexCount= meshHeader.indexCount;

	init();

	//properties
	customColor= (meshHeader.properties & mpfCustomColor) != 0;
	twoSided= (meshHeader.properties & mpfTwoSided) != 0;
	noSelect= (meshHeader.properties & mpfNoSelect) != 0;

	//material
	diffuseColor= Vec3f(meshHeader.diffuseColor);
	specularColor= Vec3f(meshHeader.specularColor);
	specularPower= meshHeader.specularPower;
	opacity= meshHeader.opacity;
	if(opacity==0){
		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("found a mesh with opacity=0 in header, using opacity=1 to see it now \n");
		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("file: %s\n",modelFile.c_str());
		opacity=1.0f;
	}
	textureFlags= meshHeader.textures;

	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Load v4, this = %p Found meshHeader.textures = %d meshIndex = %d\n",this,meshHeader.textures,meshIndex);

	//maps
	uint32 flag= 1;
	for(int i = 0; i < meshTextureCount; ++i) {
		if(meshHeader.textures & flag) {
			uint8 cMapPath[mapPathSize+1];
			memset(&cMapPath[0],0,mapPathSize+1);
			readBytes = fread(cMapPath, mapPathSize, 1, f);
			cMapPath[mapPathSize] = 0;
			if(readBytes != 1 && mapPathSize != 0) {
				char szBuf[8096]="";
				snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u] on line: %d.",readBytes,mapPathSize,__LINE__);
				throw megaglest_runtime_error(szBuf);
			}
			Shared::PlatformByteOrder::fromEndianTypeArray<uint8>(cMapPath, mapPathSize);

			char mapPathString[mapPathSize+1]="";
			memset(&mapPathString[0],0,mapPathSize+1);
			memcpy(&mapPathString[0],reinterpret_cast<char*>(cMapPath),mapPathSize);
			string mapPath= toLower(mapPathString);

			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("mapPath [%s] meshHeader.textures = %d flag = %d (meshHeader.textures & flag) = %d meshIndex = %d i = %d\n",mapPath.c_str(),meshHeader.textures,flag,(meshHeader.textures & flag),meshIndex,i);

			string mapFullPath= dir;
			if(mapFullPath != "") {
				endPathWithSlash(mapFullPath);
			}
			mapFullPath += mapPath;
			if(textureManager) {
				textures[i] = loadMeshTexture(meshIndex, i, textureManager, mapFullPath,
						meshTextureChannelCount[i],texturesOwned[i],
						deletePixMapAfterLoad, loadedFileList, sourceLoader,modelFile);
			}
		}
		flag *= 2;
	}

	//read data
	readBytes = fread(vertices, sizeof(Vec3f)*frameCount*vertexCount, 1, f);
	if(readBytes != 1 && (frameCount * vertexCount) != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianVecArray<Vec3f>(vertices, frameCount*vertexCount);

	readBytes = fread(normals, sizeof(Vec3f)*frameCount*vertexCount, 1, f);
	if(readBytes != 1 && (frameCount * vertexCount) != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	fromEndianVecArray<Vec3f>(normals, frameCount*vertexCount);

	if(meshHeader.textures!=0){
		readBytes = fread(texCoords, sizeof(Vec2f)*vertexCount, 1, f);
		if(readBytes != 1 && vertexCount != 0) {
			char szBuf[8096]="";
			snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u][%u] on line: %d.",readBytes,frameCount,vertexCount,__LINE__);
			throw megaglest_runtime_error(szBuf);
		}
		fromEndianVecArray<Vec2f>(texCoords, vertexCount);
	}
	readBytes = fread(indices, sizeof(uint32)*indexCount, 1, f);
	if(readBytes != 1 && indexCount != 0) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u] on line: %d.",readBytes,indexCount,__LINE__);
		throw megaglest_runtime_error(szBuf);
	}
	Shared::PlatformByteOrder::fromEndianTypeArray<uint32>(indices, indexCount);

	//tangents
	if(textures[mtNormal]!=NULL){
		computeTangents();
	}
}

void Mesh::save(int meshIndex, const string &dir, FILE *f, TextureManager *textureManager,
		string convertTextureToFormat, std::map<string,int> &textureDeleteList,
		bool keepsmallest,string modelFile) {
	MeshHeader meshHeader;
	memset(&meshHeader, 0, sizeof(struct MeshHeader));

	strncpy((char*)meshHeader.name, (char*)name.c_str(), name.length());
	meshHeader.frameCount= frameCount;
	meshHeader.vertexCount= vertexCount;
	meshHeader.indexCount = indexCount;

	//material
	memcpy((float32*)meshHeader.diffuseColor, (float32*)diffuseColor.ptr(), sizeof(float32) * 3);
	memcpy((float32*)meshHeader.specularColor, (float32*)specularColor.ptr(), sizeof(float32) * 3);
	meshHeader.specularPower = specularPower;
	meshHeader.opacity = opacity;

	//properties
	meshHeader.properties = 0;
	if(customColor) {
		meshHeader.properties |= mpfCustomColor;
	}
	if(twoSided) {
		meshHeader.properties |= mpfTwoSided;
	}
	if(noSelect) {
		meshHeader.properties |= mpfNoSelect;
	}

	meshHeader.textures = textureFlags;
	fwrite(&meshHeader, sizeof(MeshHeader), 1, f);

	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Save, this = %p, Found meshTextureCount = %d, meshHeader.textures = %d meshIndex = %d\n",this,meshTextureCount,meshHeader.textures,meshIndex);

	//maps
	uint32 flag= 1;
	for(int i = 0; i < meshTextureCount; ++i) {
		if((meshHeader.textures & flag)) {
			uint8 cMapPath[mapPathSize];
			memset(&cMapPath[0],0,mapPathSize);

			Texture2D *texture = textures[i];

			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Save, [%d] mesh texture ptr [%p]\n",i,texture);

			if(texture != NULL) {
				string file = toLower(texture->getPath());

				if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Save, Found mesh texture [%s]\n",file.c_str());

				if(toLower(convertTextureToFormat) != "" &&
					EndsWith(file, "." + convertTextureToFormat) == false) {
					long originalSize 	= getFileSize(file);
					long newSize 		= originalSize;

					string fileExt = extractExtension(file);
					replaceAll(file, "." + fileExt, "." + convertTextureToFormat);

					if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Save, Convert from [%s] to [%s]\n",texture->getPath().c_str(),file.c_str());

					if(convertTextureToFormat == "tga") {
						texture->getPixmap()->saveTga(file);
						newSize = getFileSize(file);
						if(keepsmallest == false || newSize <= originalSize) {
							textureDeleteList[texture->getPath()] = textureDeleteList[texture->getPath()] + 1;
						}
						else {
							printf("Texture will not be converted, keeping smallest texture [%s]\n",texture->getPath().c_str());
							textureDeleteList[file] = textureDeleteList[file] + 1;
						}
					}
					else if(convertTextureToFormat == "bmp") {
						texture->getPixmap()->saveBmp(file);
						newSize = getFileSize(file);
						if(keepsmallest == false || newSize <= originalSize) {
							textureDeleteList[texture->getPath()] = textureDeleteList[texture->getPath()] + 1;
						}
						else {
							printf("Texture will not be converted, keeping smallest texture [%s]\n",texture->getPath().c_str());
							textureDeleteList[file] = textureDeleteList[file] + 1;
						}
					}
					else if(convertTextureToFormat == "jpg") {
						texture->getPixmap()->saveJpg(file);
						newSize = getFileSize(file);
						if(keepsmallest == false || newSize <= originalSize) {
							textureDeleteList[texture->getPath()] = textureDeleteList[texture->getPath()] + 1;
						}
						else {
							printf("Texture will not be converted, keeping smallest texture [%s]\n",texture->getPath().c_str());
							textureDeleteList[file] = textureDeleteList[file] + 1;
						}
					}
					else  if(convertTextureToFormat == "png") {
						texture->getPixmap()->savePng(file);
						newSize = getFileSize(file);
						if(keepsmallest == false || newSize <= originalSize) {
							textureDeleteList[texture->getPath()] = textureDeleteList[texture->getPath()] + 1;
						}
						else {
							printf("Texture will not be converted, keeping smallest texture [%s]\n",texture->getPath().c_str());
							textureDeleteList[file] = textureDeleteList[file] + 1;
						}
					}
					else {
						throw megaglest_runtime_error("Unsupported texture format: [" + convertTextureToFormat + "]");
					}

					//textureManager->endTexture(texture);
					if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Save, load new texture [%s] originalSize [%ld] newSize [%ld]\n",file.c_str(),originalSize,newSize);

					if(keepsmallest == false || newSize <= originalSize) {
						texture = loadMeshTexture(meshIndex, i, textureManager,file,
													meshTextureChannelCount[i],
													texturesOwned[i],
													false,
													NULL,
													"",
													modelFile);
					}
				}

				file = extractFileFromDirectoryPath(texture->getPath());

				if(file.length() > mapPathSize) {
					throw megaglest_runtime_error("file.length() > mapPathSize, file.length() = " + intToStr(file.length()));
				}
				else if(file.length() == 0) {
					throw megaglest_runtime_error("file.length() == 0");
				}

				if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Save, new texture file [%s]\n",file.c_str());

				memset(&cMapPath[0],0,mapPathSize);
				memcpy(&cMapPath[0],file.c_str(),file.length());
			}

			fwrite(cMapPath, mapPathSize, 1, f);
		}
		flag*= 2;
	}

	//read data
	fwrite(vertices, sizeof(Vec3f)*frameCount*vertexCount, 1, f);
	fwrite(normals, sizeof(Vec3f)*frameCount*vertexCount, 1, f);
	if(meshHeader.textures != 0) {
		fwrite(texCoords, sizeof(Vec2f)*vertexCount, 1, f);
	}
	fwrite(indices, sizeof(uint32)*indexCount, 1, f);
}

void Mesh::computeTangents(){
	delete [] tangents;
	try {
		tangents= new Vec3f[vertexCount];
	}
	catch(bad_alloc& ba) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Error on line: %d size: %d msg: %s\n",__LINE__,vertexCount,ba.what());
		throw megaglest_runtime_error(szBuf);
	}

	for(unsigned int i=0; i<vertexCount; ++i){
		tangents[i]= Vec3f(0.f);
	}

	for(unsigned int i=0; i<indexCount; i+=3){
		for(int j=0; j<3; ++j){
			uint32 i0= indices[i+j];
			uint32 i1= indices[i+(j+1)%3];
			uint32 i2= indices[i+(j+2)%3];

			Vec3f p0= vertices[i0];
			Vec3f p1= vertices[i1];
			Vec3f p2= vertices[i2];

			float u0= texCoords[i0].x;
			float u1= texCoords[i1].x;
			float u2= texCoords[i2].x;

			float v0= texCoords[i0].y;
			float v1= texCoords[i1].y;
			float v2= texCoords[i2].y;

			tangents[i0]+=
				((p2-p0)*(v1-v0)-(p1-p0)*(v2-v0))/
				((u2-u0)*(v1-v0)-(u1-u0)*(v2-v0));
		}
	}

	for(unsigned int i=0; i<vertexCount; ++i){
		/*Vec3f binormal= normals[i].cross(tangents[i]);
		tangents[i]+= binormal.cross(normals[i]);*/
		tangents[i].normalize();
	}
}

void Mesh::deletePixels() {
	for(int i = 0; i < meshTextureCount; ++i) {
		if(textures[i] != NULL) {
			textures[i]->deletePixels();
		}
	}
}

// ===============================================
//	class Model
// ===============================================

// ==================== constructor & destructor ====================

Model::Model() {
	if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) {
		throw megaglest_runtime_error("Loading graphics in headless server mode not allowed!");
	}

	meshCount		= 0;
	meshes			= NULL;
	fileVersion		= 0;
	textureManager	= NULL;
	lastTData		= -1;
	lastCycleData	= false;
	lastTVertex		= -1;
	lastCycleVertex	= false;
}

Model::~Model() {
	if(meshes) delete [] meshes;
	meshes = NULL;
}

// ==================== data ====================

void Model::buildInterpolationData() const{
	for(unsigned int i=0; i<meshCount; ++i){
		meshes[i].buildInterpolationData();
	}
}

void Model::updateInterpolationData(float t, bool cycle) {
	if(lastTData != t || lastCycleData != cycle) {
		for(unsigned int i = 0; i < meshCount; ++i) {
			meshes[i].updateInterpolationData(t, cycle);
		}
		lastTData 		= t;
		lastCycleData 	= cycle;
	}
}

void Model::updateInterpolationVertices(float t, bool cycle) {
	if(lastTVertex != t || lastCycleVertex != cycle) {
		for(unsigned int i = 0; i < meshCount; ++i) {
			meshes[i].updateInterpolationVertices(t, cycle);
		}
		lastTVertex 	= t;
		lastCycleVertex = cycle;
	}
}

// ==================== get ====================

uint32 Model::getTriangleCount() const {
	uint32 triangleCount= 0;
	for(uint32 i = 0; i < meshCount; ++i) {
		triangleCount += meshes[i].getIndexCount()/3;
	}
	return triangleCount;
}

uint32 Model::getVertexCount() const {
	uint32 vertexCount= 0;
	for(uint32 i = 0; i < meshCount; ++i) {
		vertexCount += meshes[i].getVertexCount();
	}
	return vertexCount;
}

// ==================== io ====================

void Model::load(const string &path, bool deletePixMapAfterLoad,
		std::map<string,vector<pair<string, string> > > *loadedFileList, string *sourceLoader) {

	this->sourceLoader = (sourceLoader != NULL ? *sourceLoader : "");
	this->fileName = path;

	if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) {
		return;
	}
	string extension= path.substr(path.find_last_of('.') + 1);
	if(extension=="g3d" || extension=="G3D") {
		loadG3d(path,deletePixMapAfterLoad,loadedFileList, this->sourceLoader);
	}
	else {
		throw megaglest_runtime_error("Unknown model format: " + extension);
	}
}

void Model::save(const string &path, string convertTextureToFormat,
		bool keepsmallest) {
	string extension= path.substr(path.find_last_of('.')+1);
	if(extension=="g3d" ||extension=="G3D") {
		saveG3d(path,convertTextureToFormat,keepsmallest);
	}
	else {
		throw megaglest_runtime_error("Unknown model format: " + extension);
	}
}

//load a model from a g3d file
void Model::loadG3d(const string &path, bool deletePixMapAfterLoad,
		std::map<string,vector<pair<string, string> > > *loadedFileList,
		string sourceLoader) {

    try{
#ifdef WIN32
		FILE *f= _wfopen(utf8_decode(path).c_str(), L"rb");
#else
		FILE *f=fopen(path.c_str(),"rb");
#endif
		if (f == NULL) {
		    printf("In [%s::%s] cannot load file = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,path.c_str());
			throw megaglest_runtime_error("Error opening g3d model file [" + path + "]",true);
		}

		if(loadedFileList) {
			(*loadedFileList)[path].push_back(make_pair(sourceLoader,sourceLoader));
		}

		string dir= extractDirectoryPathFromFile(path);

		//file header
		FileHeader fileHeader;
		size_t readBytes = fread(&fileHeader, sizeof(FileHeader), 1, f);
		if(readBytes != 1) {
			fclose(f);
			char szBuf[8096]="";
			snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
			throw megaglest_runtime_error(szBuf);
		}
		fromEndianFileHeader(fileHeader);

		char fileId[4] = "";
		memset(&fileId[0],0,4);
		memcpy(&fileId[0],reinterpret_cast<char*>(fileHeader.id),3);

		if(strncmp(fileId, "G3D", 3) != 0) {
			fclose(f);
			f = NULL;
		    printf("In [%s::%s] file = [%s] fileheader.id = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,path.c_str(),fileId);
			throw megaglest_runtime_error("Not a valid G3D model",true);
		}
		fileVersion= fileHeader.version;

		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Load model, fileVersion = %d\n",fileVersion);

		//version 4
		if(fileHeader.version == 4) {
			//model header
			ModelHeader modelHeader;
			readBytes = fread(&modelHeader, sizeof(ModelHeader), 1, f);
			if(readBytes != 1) {
				char szBuf[8096]="";
				snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " on line: %d.",readBytes,__LINE__);
				throw megaglest_runtime_error(szBuf);
			}
			fromEndianModelHeader(modelHeader);

			meshCount= modelHeader.meshCount;

			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("meshCount = %d\n",meshCount);

			if(modelHeader.type != mtMorphMesh) {
				throw megaglest_runtime_error("Invalid model type");
			}

			//load meshes
			try {
				meshes= new Mesh[meshCount];
			}
			catch(bad_alloc& ba) {
				char szBuf[8096]="";
				snprintf(szBuf,8096,"Error on line: %d size: %d msg: %s\n",__LINE__,meshCount,ba.what());
				throw megaglest_runtime_error(szBuf);
			}

			for(uint32 i = 0; i < meshCount; ++i) {
				meshes[i].load(i, dir, f, textureManager,deletePixMapAfterLoad,
						loadedFileList,sourceLoader,path);
				meshes[i].buildInterpolationData();
			}
		}
		//version 3
		else if(fileHeader.version == 3) {
			readBytes = fread(&meshCount, sizeof(meshCount), 1, f);
			if(readBytes != 1 && meshCount != 0) {
				char szBuf[8096]="";
				snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u] on line: %d.",readBytes,meshCount,__LINE__);
				throw megaglest_runtime_error(szBuf);
			}
			meshCount = Shared::PlatformByteOrder::fromCommonEndian(meshCount);

			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("meshCount = %u\n",meshCount);

			try {
				meshes= new Mesh[meshCount];
			}
			catch(bad_alloc& ba) {
				char szBuf[8096]="";
				snprintf(szBuf,8096,"Error on line: %d size: %d msg: %s\n",__LINE__,meshCount,ba.what());
				throw megaglest_runtime_error(szBuf);
			}

			for(uint32 i = 0; i < meshCount; ++i) {
				meshes[i].loadV3(i, dir, f, textureManager,deletePixMapAfterLoad,
						loadedFileList,sourceLoader,path);
				meshes[i].buildInterpolationData();
			}
		}
		//version 2
		else if(fileHeader.version == 2) {
			readBytes = fread(&meshCount, sizeof(meshCount), 1, f);
			if(readBytes != 1 && meshCount != 0) {
				char szBuf[8096]="";
				snprintf(szBuf,8096,"fread returned wrong size = " MG_SIZE_T_SPECIFIER " [%u] on line: %d.",readBytes,meshCount,__LINE__);
				throw megaglest_runtime_error(szBuf);
			}
			meshCount = Shared::PlatformByteOrder::fromCommonEndian(meshCount);


			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("meshCount = %d\n",meshCount);

			try {
				meshes= new Mesh[meshCount];
			}
			catch(bad_alloc& ba) {
				char szBuf[8096]="";
				snprintf(szBuf,8096,"Error on line: %d size: %d msg: %s\n",__LINE__,meshCount,ba.what());
				throw megaglest_runtime_error(szBuf);
			}

			for(uint32 i = 0; i < meshCount; ++i){
				meshes[i].loadV2(i,dir, f, textureManager,deletePixMapAfterLoad,
						loadedFileList,sourceLoader,path);
				meshes[i].buildInterpolationData();
			}
		}
		else {
			throw megaglest_runtime_error("Invalid model version: "+ intToStr(fileHeader.version));
		}

		fclose(f);

		autoJoinMeshFrames();
    }
    catch(megaglest_runtime_error& ex) {
    	//printf("1111111 ex.wantStackTrace() = %d\n",ex.wantStackTrace());
		SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
		//printf("2222222\n");
		throw megaglest_runtime_error("Exception caught loading 3d file: " + path +"\n"+ ex.what(),!ex.wantStackTrace());
    }
	catch(exception &e){
		//abort();
		SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what());
		throw megaglest_runtime_error("Exception caught loading 3d file: " + path +"\n"+ e.what());
	}
}

//save a model to a g3d file
void Model::saveG3d(const string &path, string convertTextureToFormat,
		bool keepsmallest) {
	string tempModelFilename = path + "cvt";

#ifdef WIN32
	FILE *f= _wfopen(utf8_decode(tempModelFilename).c_str(), L"wb");
#else
	FILE *f= fopen(tempModelFilename.c_str(), "wb");
#endif
	if(f == NULL) {
		throw megaglest_runtime_error("Cant open file for writing: [" + tempModelFilename + "]");
	}

	convertTextureToFormat = toLower(convertTextureToFormat);

	//file header
	FileHeader fileHeader;
	fileHeader.id[0]= 'G';
	fileHeader.id[1]= '3';
	fileHeader.id[2]= 'D';
	fileHeader.version= 4;

	fwrite(&fileHeader, sizeof(FileHeader), 1, f);

	// file versions
	if(fileHeader.version == 4 || fileHeader.version == 3 || fileHeader.version == 2) {
		//model header
		ModelHeader modelHeader;
		modelHeader.meshCount = meshCount;
		modelHeader.type = mtMorphMesh;

		fwrite(&modelHeader, sizeof(ModelHeader), 1, f);

		std::map<string,int> textureDeleteList;
		for(uint32 i = 0; i < meshCount; ++i) {
			meshes[i].save(i,tempModelFilename, f, textureManager,
					convertTextureToFormat,textureDeleteList,
					keepsmallest,path);
		}

		removeFile(path);
		if(renameFile(tempModelFilename,path) == true) {
			// Now delete old textures since they were converted to a new format
			for(std::map<string,int>::iterator iterMap = textureDeleteList.begin();
				iterMap != textureDeleteList.end(); ++iterMap) {
				removeFile(iterMap->first);
			}
		}
	}
	else {
		throw megaglest_runtime_error("Invalid model version: "+ intToStr(fileHeader.version));
	}

	fclose(f);
}

void Model::deletePixels() {
	for(uint32 i = 0; i < meshCount; ++i) {
		meshes[i].deletePixels();
	}
}

class MeshContainer {
protected:
	int indexValue;
	std::vector<Mesh *> meshes;

public:

	MeshContainer() {
		this->indexValue = -1;
	}
	void add(int index, Mesh *mesh) {
		if(this->indexValue < 0) {
			this->indexValue = index;
		}
		meshes.push_back(mesh);
	}
	int index() {
		return indexValue;
	}
	int size() {
		return (int)meshes.size();
	}
	std::vector<Mesh *>  get() {
		return meshes;
	}
};

void Mesh::setVertices(Vec3f *data, uint32 count) {
	delete [] this->vertices;
	this->vertices = data;

	this->vertexCount = count;
}
void Mesh::setNormals(Vec3f *data, uint32 count) {
	delete [] this->normals;
	this->normals = data;

	this->vertexCount = count;
}

void Mesh::setTexCoords(Vec2f *data, uint32 count) {
	delete [] this->texCoords;
	this->texCoords = data;

	this->vertexCount = count;
}

void Mesh::setIndices(uint32 *data, uint32 count) {
	delete [] this->indices;
	this->indices = data;

	this->indexCount = count;
}

void Mesh::copyInto(Mesh *dest, bool ignoreInterpolationData,
								bool destinationOwnsTextures) {

	for(int index = 0; index < meshTextureCount; ++index){
		dest->textures[index] 		= this->textures[index];
		dest->texturesOwned[index] 	= this->texturesOwned[index];
		dest->texturePaths[index] 	= this->texturePaths[index];

		if(destinationOwnsTextures == true) {
			this->texturesOwned[index] = false;
		}
	}

	dest->name = this->name;
	//vertex data counts
	dest->frameCount 			= this->frameCount;
	dest->vertexCount 			= this->vertexCount;
	dest->indexCount 			= this->indexCount;
	dest->texCoordFrameCount 	= this->texCoordFrameCount;

	//vertex data
	if(dest->vertices != NULL) {
		delete [] dest->vertices;
		dest->vertices = NULL;
	}
	if(this->vertices != NULL) {
		dest->vertices = new Vec3f[this->frameCount * this->vertexCount];
		memcpy(&dest->vertices[0],&this->vertices[0],this->frameCount * this->vertexCount * sizeof(Vec3f));
	}

	if(dest->normals != NULL) {
		delete [] dest->normals;
		dest->normals = NULL;
	}
	if(this->normals != NULL) {
		dest->normals = new Vec3f[this->frameCount * this->vertexCount];
		memcpy(&dest->normals[0],&this->normals[0],this->frameCount * this->vertexCount * sizeof(Vec3f));
	}

	if(dest->texCoords != NULL) {
		delete [] dest->texCoords;
		dest->texCoords = NULL;
	}
	if(this->texCoords != NULL) {
		dest->texCoords = new Vec2f[this->vertexCount];
		memcpy(&dest->texCoords[0],&this->texCoords[0],this->vertexCount * sizeof(Vec2f));
	}

	if(dest->tangents != NULL) {
		delete [] dest->tangents;
		dest->tangents = NULL;
	}
	if(this->tangents != NULL) {
		dest->tangents = new Vec3f[this->vertexCount];
		memcpy(&dest->tangents[0],&this->tangents[0],this->vertexCount * sizeof(Vec3f));
	}

	if(dest->indices != NULL) {
		delete [] dest->indices;
		dest->indices = NULL;
	}
	if(this->indices != NULL) {
		dest->indices = new uint32[this->indexCount];
		memcpy(&dest->indices[0],&this->indices[0],this->indexCount * sizeof(uint32));
	}

	//material data
	dest->diffuseColor 	= this->diffuseColor;
	dest->specularColor = this->specularColor;
	dest->specularPower = this->specularPower;
	dest->opacity 		= this->opacity;

	//properties
	dest->twoSided 		= this->twoSided;
	dest->customColor 	= this->customColor;
	dest->noSelect 		= this->noSelect;

	dest->textureFlags 	= this->textureFlags;

	if(ignoreInterpolationData == false) {
		dest->interpolationData = this->interpolationData;
	}
	dest->textureManager = this->textureManager;

	// Vertex Buffer Object Names
	dest->hasBuiltVBOs 		= this->hasBuiltVBOs;
	dest->m_nVBOVertices 	= this-> m_nVBOVertices;
	dest->m_nVBOTexCoords 	= this->m_nVBOTexCoords;
	dest->m_nVBONormals 	= this->m_nVBONormals;
	dest->m_nVBOIndexes 	= this->m_nVBOIndexes;
}

void Model::autoJoinMeshFrames() {

/*
	print "auto-joining compatible meshes..."
        meshes = {}
        for mesh in self.meshes:
            key = (mesh.texture,mesh.frame_count,mesh.twoSided|mesh.customColour)
            if key in meshes:
                meshes[key].append(mesh)
            else:
                meshes[key] = [mesh]
        for joinable in meshes.values():
            if len(joinable) < 2: continue
            base = joinable[0]
            print "\tjoining to",base
            for mesh in joinable[1:]:
                if base.index_count+mesh.index_count > 0xffff:
                    base = mesh
                    print "\tjoining to",base
                    continue
                print "\t\t",mesh
                for a,b in zip(base.frames,mesh.frames):
                    a.vertices.extend(b.vertices)
                    a.normals.extend(b.normals)
                if base.texture:
                    base.textures.extend(mesh.textures)
                base.indices.extend(index+base.vertex_count for index in mesh.indices)
                base.vertex_count += mesh.vertex_count
                base.index_count += mesh.index_count
                self.meshes.remove(mesh)
*/



	bool haveJoinedMeshes = false;

	// First looks for meshes with same texture in the same frame
	std::map<std::string,MeshContainer> joinedMeshes;
	for(uint32 index = 0; index < meshCount; ++index) {
		Mesh &mesh = meshes[index];

		// Duplicate mesh vertices are considered to be those with the same
		// 1. texture 2. framecount 3. twosided flag value 4. same custom texture color

//		It's possible the texture is missing and will be NULL
//		if(mesh.getTextureFlags() & 1) {
//			printf("Mesh has textures:\n");
//			for(unsigned int meshTexIndex = 0; meshTexIndex < meshTextureCount; ++meshTexIndex) {
//				printf("Mesh texture index: %d [%p] [%s]\n",meshTexIndex,mesh.getTexture(meshTexIndex),(mesh.getTexture(meshTexIndex) != NULL ? mesh.getTexture(meshTexIndex)->getPath().c_str() : "n/a"));
//			}
//		}
		string mesh_key = ((mesh.getTextureFlags() & 1) && mesh.getTexture(0) ? mesh.getTexture(0)->getPath() : "none");
		       mesh_key += string("_") + intToStr(mesh.getFrameCount()) +
		    		       string("_") + intToStr(mesh.getTwoSided()) +
				           string("_") + intToStr(mesh.getCustomTexture()) +
				           string("_") + intToStr(mesh.getNoSelect()) +
				           string("_") + floatToStr(mesh.getOpacity()) +
				           string("_") + mesh.getDiffuseColor().getString() +
				           string("_") + mesh.getSpecularColor().getString() +
				           string("_") + floatToStr(mesh.getSpecularPower());

		joinedMeshes[mesh_key].add(index,&mesh);
		if(haveJoinedMeshes == false && joinedMeshes[mesh_key].size() > 1) {
			haveJoinedMeshes = true;
		}
	}
	if(haveJoinedMeshes == true) {
		//printf("*** Detected Joined meshes for model [%s]\n",fileName.c_str());

		// We have mesh data to join we now create a list in the same order
		// as the original meshes but each index will have 1 or more meshes
		// This is done to maintain original mesh ordering
		std::map<int, std::vector<Mesh *> > orderedMeshes;
		for(std::map<std::string,MeshContainer >::iterator iterMap = joinedMeshes.begin();
				iterMap != joinedMeshes.end(); ++iterMap) {
			orderedMeshes[iterMap->second.index()] = iterMap->second.get();

			//if(iterMap->second.size() > 1) {
			//	printf("Key [%s] joined meshes: %d\n",iterMap->first.c_str(),iterMap->second.size());
			//}
		}

		// Now the real work of creating a new list of joined mesh data
		Mesh *joinedMeshList = new Mesh[joinedMeshes.size()];

		int index = 0;
		for(std::map<int, std::vector<Mesh *> >::iterator iterMap = orderedMeshes.begin();
				iterMap != orderedMeshes.end(); ++iterMap) {
			//printf("Join index: %d joincount: %d\n",index,iterMap->second.size());

			Mesh *base = &joinedMeshList[index];

			// Deep copy mesh data
			iterMap->second[0]->copyInto(base, true, true);

			if(iterMap->second.size() > 1) {
				// Time to join mesh data for this mesh
				for(unsigned int joinIndex = 1;
						joinIndex < iterMap->second.size(); ++joinIndex) {
					Mesh *mesh = iterMap->second[joinIndex];
					//if(base->getIndexCount() + mesh->getIndexCount() > 0xffff) {
					//	printf("Not exactly sure what this IF statement is for?\n");
					//	mesh->copyInto(base, true, true);
					//}
					//else {
						// Need to add verticies for each from from mesh to base
						uint32 originalBaseVertexCount = base->getVertexCount();

						uint32 newVertexCount =
								base->getVertexCount() + mesh->getVertexCount();

						uint32 newVertexFrameCount =
								(base->getFrameCount() * newVertexCount);

						Vec3f *joined_vertices = new Vec3f[newVertexFrameCount];
						Vec3f *joined_normals = new Vec3f[newVertexFrameCount];
						uint32 join_index = 0;

						// Join mesh vertices and normals
						for(unsigned int frameIndex = 0;
								frameIndex < base->getFrameCount(); ++frameIndex) {
							uint32 baseIndex = frameIndex * originalBaseVertexCount;
							uint32 meshIndex = frameIndex * mesh->getVertexCount();
							//uint32 appendBaseJoinIndex = frameIndex * newVertexCount;

							// first original mesh values get copied
							memcpy(&joined_vertices[join_index],
									&base->getVertices()[baseIndex],
									originalBaseVertexCount * sizeof(Vec3f));
							memcpy(&joined_normals[join_index],
									&base->getNormals()[baseIndex],
									originalBaseVertexCount * sizeof(Vec3f));
							join_index += originalBaseVertexCount;

							// second joined mesh values get copied
							memcpy(&joined_vertices[join_index],
									&mesh->getVertices()[meshIndex],
									mesh->getVertexCount() * sizeof(Vec3f));
							memcpy(&joined_normals[join_index],
									&mesh->getNormals()[meshIndex],
									mesh->getVertexCount() * sizeof(Vec3f));
							join_index += mesh->getVertexCount();
						}

						// update vertex and normal buffers with joined mesh data
						base->setVertices(joined_vertices, newVertexCount);
						base->setNormals(joined_normals, newVertexCount);

						// If we have texture coords join them
						if(base->getTextureFlags() & 1) {
							Vec2f *joined_texCoords = new Vec2f[newVertexCount];

							// update texture coord buffers with joined mesh data
							memcpy(&joined_texCoords[0],
									&base->getTexCoords()[0],
									originalBaseVertexCount * sizeof(Vec2f));
							memcpy(&joined_texCoords[originalBaseVertexCount],
									&mesh->getTexCoords()[0],
									mesh->getVertexCount() * sizeof(Vec2f));

							base->setTexCoords(joined_texCoords, newVertexCount);
						}

						// update index buffers with joined mesh data
						uint32 newindexCount = base->getIndexCount() + mesh->getIndexCount();
						uint32 *joined_indexes = new uint32[newindexCount];

						uint32 join_index_index = 0;
						memcpy(&joined_indexes[join_index_index],
								&base->getIndices()[0],
								base->getIndexCount() * sizeof(uint32));
						join_index_index += base->getIndexCount();

						for(unsigned int meshIndex = 0;
								meshIndex < mesh->getIndexCount(); ++meshIndex) {
							uint32 index_value = mesh->getIndices()[meshIndex];

							// join index values
							joined_indexes[join_index_index] = index_value + originalBaseVertexCount;
							join_index_index++;
						}
						base->setIndices(joined_indexes, newindexCount);
					//}
				}
			}
			base->buildInterpolationData();

			index++;
		}

		delete [] meshes;
		meshes = joinedMeshList;
		meshCount = (uint32)joinedMeshes.size();
	}
}

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

bool PixelBufferWrapper::isPBOEnabled 	= false;
int PixelBufferWrapper::index 			= 0;
vector<unsigned int> PixelBufferWrapper::pboIds;

PixelBufferWrapper::PixelBufferWrapper(int pboCount,int bufferSize) {
	//if(isGlExtensionSupported("GL_ARB_pixel_buffer_object") == true &&
	if(GLEW_ARB_pixel_buffer_object) {
		PixelBufferWrapper::isPBOEnabled = true;
		cleanup();
		// For some wacky reason this fails in VC++ 2008
		//pboIds.reserve(pboCount);
		//glGenBuffersARB(pboCount, (GLuint*)&pboIds[0]);
		//

		for(int i = 0; i < pboCount; ++i) {
			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("PBO Gen i = %d\n",i);

			pboIds.push_back(0);
			glGenBuffersARB(1, (GLuint*)&pboIds[i]);
			// create pixel buffer objects, you need to delete them when program exits.
			// glBufferDataARB with NULL pointer reserves only memory space.
			glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[i]);
			glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, bufferSize, 0, GL_STREAM_READ_ARB);
		}
		glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
	}
}

Pixmap2D *PixelBufferWrapper::getPixelBufferFor(int x,int y,int w,int h, int colorComponents) {
	Pixmap2D *pixmapScreenShot = NULL;
	if(PixelBufferWrapper::isPBOEnabled == true) {
	    // increment current index first then get the next index
	    // "index" is used to read pixels from a framebuffer to a PBO
	    // "nextIndex" is used to process pixels in the other PBO
	    index = (index + 1) % 2;

	    // pbo index used for next frame
	    //int nextIndex = (index + 1) % 2;

	    // read framebuffer ///////////////////////////////
		// copy pixels from framebuffer to PBO
		// Use offset instead of pointer.
		// OpenGL should perform asynch DMA transfer, so glReadPixels() will return immediately.
		glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[index]);
	    //glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[nextIndex]);

		//glPixelStorei(GL_PACK_ALIGNMENT, 1);
		glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		//glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

		// measure the time reading framebuffer
		//t1.stop();
		//readTime = t1.getElapsedTimeInMilliSec();

		// process pixel data /////////////////////////////
		//t1.start();

		// map the PBO that contain framebuffer pixels before processing it
		//glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[nextIndex]);
		glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[index]);
		GLubyte* src = (GLubyte*)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);
		if(src) {
			pixmapScreenShot = new Pixmap2D(w, h, colorComponents);
			memcpy(pixmapScreenShot->getPixels(),src,pixmapScreenShot->getPixelByteCount());
			glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);     // release pointer to the mapped buffer
			//pixmapScreenShot->save("debugPBO.png");
		}

		// measure the time reading framebuffer
		//t1.stop();
		//processTime = t1.getElapsedTimeInMilliSec();
		glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
	}

	return pixmapScreenShot;
}

void PixelBufferWrapper::begin() {
	if(PixelBufferWrapper::isPBOEnabled == true) {
		// set the framebuffer to read
		//glReadBuffer(GL_FRONT);
	}
}

void PixelBufferWrapper::end() {
	if(PixelBufferWrapper::isPBOEnabled == true) {
		// set the framebuffer to read
		//glReadBuffer(GL_BACK);
	}
}

void PixelBufferWrapper::cleanup() {
	if(PixelBufferWrapper::isPBOEnabled == true) {
		if(pboIds.empty() == false) {
			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("PBO Delete size = %d\n",(int)pboIds.size());

			glDeleteBuffersARB((int)pboIds.size(), &pboIds[0]);
			pboIds.clear();

			glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
		}
	}
}

PixelBufferWrapper::~PixelBufferWrapper() {
	cleanup();
}

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

int BaseColorPickEntity::bufferSizeRequired = -1;
const unsigned int BaseColorPickEntity::p = 64007;
const unsigned int BaseColorPickEntity::k = 43067;
unsigned int BaseColorPickEntity::nextColorRGB = BaseColorPickEntity::k;

unsigned char BaseColorPickEntity::nextColorID[COLOR_COMPONENTS] = { 1, 1, 1, 0 };
auto_ptr<PixelBufferWrapper> BaseColorPickEntity::pbo;

map<string,bool> BaseColorPickEntity::usedColorIDList;
bool BaseColorPickEntity::trackColorUse = true;

vector<vector<unsigned char> > BaseColorPickEntity::nextColorIDReuseList;

bool BaseColorPickEntity::using_loop_method = false;

BaseColorPickEntity::BaseColorPickEntity() {
	if(BaseColorPickEntity::bufferSizeRequired != -1) {
		BaseColorPickEntity::init(BaseColorPickEntity::bufferSizeRequired);
	}
	uniqueColorID[0] = 0;
	uniqueColorID[1] = 0;
	uniqueColorID[2] = 0;
	uniqueColorID[3] = 0;
	assign_color();
}

bool BaseColorPickEntity::get_next_assign_color(unsigned char *assign_to) {
	 
	 if(assign_to == NULL) {
		 throw megaglest_runtime_error("assign_to == NULL");
	 }

	 if(BaseColorPickEntity::using_loop_method == true) {
		 assign_color_using_loop(assign_to);
	 }
	 else {
		 assign_color_using_prime(assign_to);
	 }

	 bool isDuplicate = false;
	 if(BaseColorPickEntity::trackColorUse == true) {
		 string color_key = getColorDescription();
		 //printf("Assigned color [%s]\n",color_key.c_str());

		 if(usedColorIDList.find(color_key) == usedColorIDList.end()) {
			 usedColorIDList[color_key] = true;

			 //printf("Color added to used list [%s] usedColorIDList = %d nextColorIDReuseList = %d!\n",color_key.c_str(),(int)usedColorIDList.size(),(int)nextColorIDReuseList.size());
		 }
		 else {
			 isDuplicate = true;
			 printf("Line ref: %d *WARNING* color [%s] used count: %d using_loop: %d ALREADY in history list!\n",__LINE__,color_key.c_str(),(int)usedColorIDList.size(),BaseColorPickEntity::using_loop_method);
		 }
	 }
	 return isDuplicate;
}

void BaseColorPickEntity::assign_color() {
	get_next_assign_color(&uniqueColorID[0]);
}

void BaseColorPickEntity::assign_color_using_prime(unsigned char *assign_to) {
	 nextColorRGB = (nextColorRGB * k) % p;
	 
	 // nextColorID is a 16-bit (hi)colour (for players with 16-bit display depths)
	 // we expand it to true-color for use with OpenGL
	 
	 const unsigned int
	 	r = (nextColorRGB >> 11) & ((1<<5)-1),
	 	g = (nextColorRGB >> 5) & ((1<<6)-1),
	 	b = nextColorRGB & ((1<<5)-1);

	 assign_to[0] = r << 3;
	 assign_to[1] = g << 2;
	 assign_to[2] = b << 3;
}

void BaseColorPickEntity::assign_color_using_loop(unsigned char *assign_to) {
	if(nextColorIDReuseList.empty() == false) {
		//printf("Color being reused [%u.%u.%u] usedColorIDList = %d nextColorIDReuseList = %d!\n",nextColorIDReuseList.back()[0],nextColorIDReuseList.back()[1],nextColorIDReuseList.back()[2],(int)usedColorIDList.size(),(int)nextColorIDReuseList.size());

		assign_to[0] = nextColorIDReuseList.back()[0];
		assign_to[1] = nextColorIDReuseList.back()[1];
		assign_to[2] = nextColorIDReuseList.back()[2];

		nextColorIDReuseList.pop_back();

		string color_key = getColorDescription();
		if(usedColorIDList.find(color_key) == usedColorIDList.end()) {
			//usedColorIDList[color_key] = true;
			//printf("Color added to used list [%s] usedColorIDList = %d nextColorIDReuseList = %d!\n",color_key.c_str(),(int)usedColorIDList.size(),(int)nextColorIDReuseList.size());
		}
		else {
			printf("Line ref: %d *WARNING* color [%s] ALREADY FOUND in history list!\n",__LINE__,color_key.c_str());
			assign_color_using_loop(assign_to);
		}
	}
	else {
		assign_to[0] = nextColorID[0];
		assign_to[1] = nextColorID[1];
		assign_to[2] = nextColorID[2];

		const int colorSpacing = 8;

		if((int)(nextColorID[0] + colorSpacing) <= 255) {
			nextColorID[0] += colorSpacing;
		}
		else {
			nextColorID[0] = 1;
			if((int)(nextColorID[1] + colorSpacing) <= 255) {
				nextColorID[1] += colorSpacing;
			}
			else {
				nextColorID[1] = 1;
				if((int)(nextColorID[2] + colorSpacing) <= 255) {
					nextColorID[2] += colorSpacing;
				}
				else {

					printf("Color rolled over on 3rd level usedColorIDList = %d!\n",(int)usedColorIDList.size());

					nextColorID[0] = 1;
					nextColorID[1] = 1;
					nextColorID[2] = 1;


				//               nextColorID[2] = 1;
				//               nextColorID[3]+=colorSpacing;
				//
				//               if(nextColorID[3] > 255) {
				//                   nextColorID[0] = 1;
				//                   nextColorID[1] = 1;
				//                   nextColorID[2] = 1;
				//                   nextColorID[3] = 1;
				//               }
				}
			}
		}
	}
}

void BaseColorPickEntity::recycleUniqueColor() {

	vector<unsigned char> reUseColor;
	reUseColor.push_back(uniqueColorID[0]);
	reUseColor.push_back(uniqueColorID[1]);
	reUseColor.push_back(uniqueColorID[2]);
	nextColorIDReuseList.push_back(reUseColor);

	//printf("RECYCLE Color [%u.%u.%u] usedColorIDList = %d nextColorIDReuseList = %d!\n",reUseColor[0],reUseColor[1],reUseColor[2],(int)usedColorIDList.size(),(int)nextColorIDReuseList.size());

	if(usedColorIDList.empty() == false) {
		string color_key = getColorDescription();
		if(usedColorIDList.find(color_key) != usedColorIDList.end()) {
			usedColorIDList.erase(color_key);

			//printf("REMOVING used Color [%s] usedColorIDList = %d nextColorIDReuseList = %d!\n",color_key.c_str(),(int)usedColorIDList.size(),(int)nextColorIDReuseList.size());
		}
		else {
			printf("Line ref: %d *WARNING* color [%s] used count: %d NOT FOUND in history list!\n",__LINE__,color_key.c_str(),(int)usedColorIDList.size());
		}
	}
}

void BaseColorPickEntity::resetUniqueColors() {
   BaseColorPickEntity::nextColorRGB = BaseColorPickEntity::k;

   BaseColorPickEntity::nextColorID[0] = 1;
   BaseColorPickEntity::nextColorID[1] = 1;
   BaseColorPickEntity::nextColorID[2] = 1;

   usedColorIDList.clear();
   nextColorIDReuseList.clear();
}
void BaseColorPickEntity::init(int bufferSize) {
	 if(BaseColorPickEntity::pbo.get() == NULL) {
		 BaseColorPickEntity::bufferSizeRequired = bufferSize;
		 BaseColorPickEntity::pbo.reset(new PixelBufferWrapper(2,BaseColorPickEntity::bufferSizeRequired));
	 }
}

void BaseColorPickEntity::cleanupPBO() {
	BaseColorPickEntity::pbo.reset(0);
}

string BaseColorPickEntity::getColorDescription() const {
	char szBuf[100]="";
	snprintf(szBuf,100,"%d.%d.%d",uniqueColorID[0],uniqueColorID[1],uniqueColorID[2]);
	string result = szBuf;
	return result;
}

void BaseColorPickEntity::beginPicking() {
	// turn off texturing, lighting and fog
	//glClearColor (0.0,0.0,0.0,0.0);
	//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	//reset current background. This is neeeded to get a proper black background!
	//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glClear(GL_COLOR_BUFFER_BIT);

	glPushAttrib(GL_ENABLE_BIT);
	//glEnable(GL_DEPTH_TEST);
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_FOG);
	glDisable(GL_LIGHTING);
	glDisable(GL_BLEND);
	glDisable(GL_MULTISAMPLE);
	glDisable(GL_DITHER);
	glDisable(GL_POLYGON_OFFSET_FILL);
	glDisable(GL_NORMALIZE);

	//glPushAttrib(GL_TEXTURE_2D | GL_LIGHTING | GL_BLEND | GL_MULTISAMPLE | GL_DITHER);
	//glPushAttrib(GL_ENABLE_BIT | GL_LIGHTING_BIT | GL_POLYGON_BIT | GL_CURRENT_BIT | GL_TEXTURE_BIT | GL_NORMALIZE | GL_BLEND | GL_POLYGON_OFFSET_FILL);
}

void BaseColorPickEntity::endPicking() {
	// turn off texturing, lighting and fog
	//glEnable(GL_TEXTURE_2D);
	//glEnable(GL_FOG);
	//glEnable(GL_LIGHTING);

	//glEnable(GL_BLEND);
	//glEnable(GL_MULTISAMPLE);
	//glEnable(GL_DITHER);
	glPopAttrib();
}

vector<int> BaseColorPickEntity::getPickedList(int x,int y,int w,int h,
						const vector<BaseColorPickEntity *> &rendererModels) {
	vector<int> pickedModels;
	pickedModels.reserve(rendererModels.size());

	//printf("In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
	static auto_ptr<Pixmap2D> cachedPixels;

	if(rendererModels.empty() == false) {
		if(PixelBufferWrapper::getIsPBOEnable() == true) {
				Pixmap2D *pixmapScreenShot = BaseColorPickEntity::pbo->getPixelBufferFor(x,y,w,h, COLOR_COMPONENTS);
				//pixmapScreenShot->saveTga("/tmp/toll.tga"); //### for debugging
				cachedPixels.reset(pixmapScreenShot);
		}
		else {
				Pixmap2D *pixmapScreenShot = new Pixmap2D(w, h, COLOR_COMPONENTS);
				//glPixelStorei(GL_PACK_ALIGNMENT, 1);
				glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixmapScreenShot->getPixels());
				//pixmapScreenShot->saveTga("/tmp/toll.tga");
				cachedPixels.reset(pixmapScreenShot);
				//glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
		}
		unsigned char *pixelBuffer = cachedPixels->getPixels();

		map<int,bool> modelAlreadyPickedList;
		map<unsigned char,map<unsigned char, map<unsigned char,bool> > > colorAlreadyPickedList;

		int skipSteps=4;
		//unsigned char *oldpixel = &pixelBuffer[0];

		// now we check the screenshot if we find pixels in color of unit identity
		// to speedup we only check every "skipSteps" line and pixel in a row if we find such a color.
		// this is exact enough for MG purpose
		for(int hh = 0; hh < h && pickedModels.size() < rendererModels.size(); hh=hh+skipSteps) {
			for(int ww=0;ww < w && pickedModels.size() < rendererModels.size(); ww=ww+skipSteps){

				int index = (hh*w+ww) * COLOR_COMPONENTS;
				unsigned char *pixel = &pixelBuffer[index];
				//printf("pixel[0]=%d pixel[1]=%d pixel[2]=%d\n",pixel[0],pixel[1],pixel[2]);
				if(pixel[0]==0 && pixel[1]==0 && pixel[2]==0)
				{
					continue;
				}
//				if(index>0)
//				{
//					oldpixel = &pixelBuffer[index-1*COLOR_COMPONENTS];
//					if(memcmp(pixel,oldpixel,3)) continue;
//				}

				// Skip duplicate scanned colors
				map<unsigned char,map<unsigned char, map<unsigned char,bool> > >::const_iterator iterFind1 = colorAlreadyPickedList.find(pixel[0]);
				if(iterFind1 != colorAlreadyPickedList.end()) {
					map<unsigned char, map<unsigned char,bool> >::const_iterator iterFind2 = iterFind1->second.find(pixel[1]);
					if(iterFind2 != iterFind1->second.end()) {
						map<unsigned char,bool>::const_iterator iterFind3 = iterFind2->second.find(pixel[2]);
						if(iterFind3 != iterFind2->second.end()) {
							continue;
						}
					}
				}

				for(unsigned int i = 0; i < rendererModels.size(); ++i) {
					// Skip models already selected
					if(modelAlreadyPickedList.find(i) != modelAlreadyPickedList.end()) {
						continue;
					}
					const BaseColorPickEntity *model = rendererModels[i];

					if( model != NULL && model->isUniquePickingColor(pixel) == true) {
						//printf("Found match pixel [%d.%d.%d] for model [%s] ptr [%p][%s]\n",pixel[0],pixel[1],pixel[2],model->getColorDescription().c_str(), model,model->getUniquePickName().c_str());

						pickedModels.push_back(i);
						modelAlreadyPickedList[i]=true;
						colorAlreadyPickedList[pixel[0]][pixel[1]][pixel[2]]=true;
						break;
					}
				}
			}
		}

		//printf("In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
		//delete pixmapScreenShot;
	}
	//printf("In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
	return pickedModels;
}

bool BaseColorPickEntity::isUniquePickingColor(unsigned char *pixel) const {
	bool result = false;
	if( uniqueColorID[0] == pixel[0] &&
		uniqueColorID[1] == pixel[1] &&
		uniqueColorID[2] == pixel[2]) {
		//uniqueColorID[3] == pixel[3]) {
		result = true;
	}

	return result;
}

void BaseColorPickEntity::setUniquePickingColor() const {

	 glColor3ub(uniqueColorID[0],
			 	uniqueColorID[1],
			 	uniqueColorID[2]);

/*
	 glColor3f(	uniqueColorID[0] / 255.0f,
			 	uniqueColorID[1] / 255.0f,
			 	uniqueColorID[2] / 255.0f);
			 	//uniqueColorID[3] / 255.0f);
			 	 *
			 	 */
}


}}//end namespace