summaryrefslogtreecommitdiff
path: root/indra/newview/lltexlayer.cpp
blob: b376eed8143c58c56b3d236fc6345735164304da (plain)
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
/** 
 * @file lltexlayer.cpp
 * @brief A texture layer. Used for avatars.
 *
 * $LicenseInfo:firstyear=2002&license=viewergpl$
 * 
 * Copyright (c) 2002-2009, Linden Research, Inc.
 * 
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 * 
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 * 
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 * 
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "imageids.h"
#include "llagent.h"
#include "llcrc.h"
#include "lldir.h"
#include "llglheaders.h"
#include "llimagebmp.h"
#include "llimagej2c.h"
#include "llimagetga.h"
#include "llpolymorph.h"
#include "llquantize.h"
#include "lltexlayer.h"
#include "llui.h"
#include "llvfile.h"
#include "llviewerimagelist.h"
#include "llviewerimagelist.h"
#include "llviewerregion.h"
#include "llviewerstats.h"
#include "llviewerwindow.h"
#include "llvoavatar.h"
#include "llxmltree.h"
#include "pipeline.h"
#include "v4coloru.h"
#include "llrender.h"
#include "llassetuploadresponders.h"

//#include "../tools/imdebug/imdebug.h"

using namespace LLVOAvatarDefines;

// static
S32 LLTexLayerSetBuffer::sGLByteCount = 0;
S32 LLTexLayerSetBuffer::sGLBumpByteCount = 0;

//-----------------------------------------------------------------------------
// LLBakedUploadData()
//-----------------------------------------------------------------------------
LLBakedUploadData::LLBakedUploadData( LLVOAvatar* avatar, LLTexLayerSetBuffer* layerset_buffer, const LLUUID & id ) : 
	mAvatar( avatar ),
	mLayerSetBuffer( layerset_buffer ),
	mID(id)
{ 
	mStartTime = LLFrameTimer::getTotalTime();		// Record starting time
	for( S32 i = 0; i < WT_COUNT; i++ )
	{
		LLWearable* wearable = gAgent.getWearable( (EWearableType)i);
		if( wearable )
		{
			mWearableAssets[i] = wearable->getID();
		}
	}
}

//-----------------------------------------------------------------------------
// LLTexLayerSetBuffer
// The composite image that a LLTexLayerSet writes to.  Each LLTexLayerSet has one.
//-----------------------------------------------------------------------------
LLTexLayerSetBuffer::LLTexLayerSetBuffer( LLTexLayerSet* owner, S32 width, S32 height, BOOL has_bump )
	:
	// ORDER_LAST => must render these after the hints are created.
	LLDynamicTexture( width, height, 4, LLDynamicTexture::ORDER_LAST, TRUE ), 
	mNeedsUpdate( TRUE ),
	mNeedsUpload( FALSE ),
	mUploadPending( FALSE ), // Not used for any logic here, just to sync sending of updates
	mTexLayerSet( owner )	
{
	LLTexLayerSetBuffer::sGLByteCount += getSize();
	mHasBump = has_bump ;
	mBumpTex = NULL ;

	createBumpTexture() ;
}

LLTexLayerSetBuffer::~LLTexLayerSetBuffer()
{
	LLTexLayerSetBuffer::sGLByteCount -= getSize();

	if( mBumpTex.notNull())
	{
		mBumpTex = NULL ;
		LLImageGL::sGlobalTextureMemory -= mWidth * mHeight * 4;
		LLTexLayerSetBuffer::sGLBumpByteCount -= mWidth * mHeight * 4;
	}
}
//virtual 
void LLTexLayerSetBuffer::restoreGLTexture() 
{	
	createBumpTexture() ;
	LLDynamicTexture::restoreGLTexture() ;
}

//virtual 
void LLTexLayerSetBuffer::destroyGLTexture() 
{
	if( mBumpTex.notNull() )
	{
		mBumpTex = NULL ;
		LLImageGL::sGlobalTextureMemory -= mWidth * mHeight * 4;
		LLTexLayerSetBuffer::sGLBumpByteCount -= mWidth * mHeight * 4;
	}

	LLDynamicTexture::destroyGLTexture() ;
}

void LLTexLayerSetBuffer::createBumpTexture()
{
	if( mHasBump )
	{
		LLGLSUIDefault gls_ui;
		mBumpTex = new LLImageGL(FALSE) ;
		if(!mBumpTex->createGLTexture())
		{
			mBumpTex = NULL ;
			return ;
		}

		gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, mBumpTex->getTexName());
		stop_glerror();

		gGL.getTexUnit(0)->setTextureAddressMode(LLTexUnit::TAM_CLAMP);

		gGL.getTexUnit(0)->setTextureFilteringOption(LLTexUnit::TFO_BILINEAR);

		LLImageGL::setManualImage(GL_TEXTURE_2D, 0, GL_RGBA8, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
		stop_glerror();

		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);

		LLImageGL::sGlobalTextureMemory += mWidth * mHeight * 4;
		LLTexLayerSetBuffer::sGLBumpByteCount += mWidth * mHeight * 4;
	}
}

// static
void LLTexLayerSetBuffer::dumpTotalByteCount()
{
	llinfos << "Composite System GL Buffers: " << (LLTexLayerSetBuffer::sGLByteCount/1024) << "KB" << llendl;
	llinfos << "Composite System GL Bump Buffers: " << (LLTexLayerSetBuffer::sGLBumpByteCount/1024) << "KB" << llendl;
}

void LLTexLayerSetBuffer::requestUpdate()
{
	mNeedsUpdate = TRUE;

	// If we're in the middle of uploading a baked texture, we don't care about it any more.
	// When it's downloaded, ignore it.
	mUploadID.setNull();
}

void LLTexLayerSetBuffer::requestUpload()
{
	if (!mNeedsUpload)
	{
		mNeedsUpload = TRUE;
		mUploadPending = TRUE;
	}
}

void LLTexLayerSetBuffer::cancelUpload()
{
	if (mNeedsUpload)
	{
		mNeedsUpload = FALSE;
	}
	mUploadPending = FALSE;
}

void LLTexLayerSetBuffer::pushProjection()
{
	glMatrixMode(GL_PROJECTION);
	gGL.pushMatrix();
	glLoadIdentity();
	glOrtho(0.0f, mWidth, 0.0f, mHeight, -1.0f, 1.0f);

	glMatrixMode(GL_MODELVIEW);
	gGL.pushMatrix();
	glLoadIdentity();
}

void LLTexLayerSetBuffer::popProjection()
{
	glMatrixMode(GL_PROJECTION);
	gGL.popMatrix();

	glMatrixMode(GL_MODELVIEW);
	gGL.popMatrix();
}

BOOL LLTexLayerSetBuffer::needsRender()
{
	LLVOAvatar* avatar = mTexLayerSet->getAvatar();
	BOOL upload_now = mNeedsUpload && mTexLayerSet->isLocalTextureDataFinal();
	BOOL needs_update = gAgent.mNumPendingQueries == 0 && (mNeedsUpdate || upload_now) && !avatar->mAppearanceAnimating;
	if (needs_update)
	{
		BOOL invalid_skirt = avatar->getBakedTE(mTexLayerSet) == TEX_SKIRT_BAKED && !avatar->isWearingWearableType(WT_SKIRT);
		if (invalid_skirt)
		{
			// we were trying to create a skirt texture
			// but we're no longer wearing a skirt...
			needs_update = FALSE;
			cancelUpload();
		}
		else
		{
			needs_update &= (avatar->isSelf() || (avatar->isVisible() && !avatar->isCulled()));
			needs_update &= mTexLayerSet->isLocalTextureDataAvailable();
		}
	}
	return needs_update;
}

void LLTexLayerSetBuffer::preRender(BOOL clear_depth)
{
	// Set up an ortho projection
	pushProjection();
	
	// keep depth buffer, we don't need to clear it
	LLDynamicTexture::preRender(FALSE);
}

void LLTexLayerSetBuffer::postRender(BOOL success)
{
	popProjection();

	LLDynamicTexture::postRender(success);
}

BOOL LLTexLayerSetBuffer::render()
{
	U8* baked_bump_data = NULL;

	// Default color mask for tex layer render
	gGL.setColorMask(true, true);

	// do we need to upload, and do we have sufficient data to create an uploadable composite?
	// When do we upload the texture if gAgent.mNumPendingQueries is non-zero?
	BOOL upload_now = (gAgent.mNumPendingQueries == 0 && mNeedsUpload && mTexLayerSet->isLocalTextureDataFinal());
	BOOL success = TRUE;

	// Composite bump
	if( mBumpTex.notNull() )
	{
		// Composite the bump data
		success &= mTexLayerSet->renderBump( mOrigin.mX, mOrigin.mY, mWidth, mHeight );
		stop_glerror();

		if (success)
		{
			LLGLSUIDefault gls_ui;

			// read back into texture (this is done externally for the color data)
			gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, mBumpTex->getTexName());
			stop_glerror();

			glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mOrigin.mX, mOrigin.mY, mWidth, mHeight);
			stop_glerror();

			// if we need to upload the data, read it back into a buffer
			if( upload_now )
			{
				baked_bump_data = new U8[ mWidth * mHeight * 4 ];
				glReadPixels(mOrigin.mX, mOrigin.mY, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, baked_bump_data );
				stop_glerror();
			}
		}
	}

	// Composite the color data
	LLGLSUIDefault gls_ui;
	success &= mTexLayerSet->render( mOrigin.mX, mOrigin.mY, mWidth, mHeight );
	gGL.flush();

	if( upload_now )
	{
		if (!success)
		{
			delete [] baked_bump_data;
			llinfos << "Failed attempt to bake " << mTexLayerSet->getBodyRegion() << llendl;
			mUploadPending = FALSE;
		}
		else
		{
			readBackAndUpload(baked_bump_data);
		}
	}

	// reset GL state
	gGL.setColorMask(true, true);
	gGL.setSceneBlendType(LLRender::BT_ALPHA);

	// we have valid texture data now
	mTexture->setGLTextureCreated(true);
	mNeedsUpdate = FALSE;

	return success;
}

bool LLTexLayerSetBuffer::isInitialized(void) const
{
	return mTexture.notNull() && mTexture->isGLTextureCreated();
}

BOOL LLTexLayerSetBuffer::updateImmediate()
{
	mNeedsUpdate = TRUE;
	BOOL result = FALSE;

	if (needsRender())
	{
		preRender(FALSE);
		result = render();
		postRender(result);
	}

	return result;
}

void LLTexLayerSetBuffer::readBackAndUpload(U8* baked_bump_data)
{
	// pointers for storing data to upload
	U8* baked_color_data = new U8[ mWidth * mHeight * 4 ];
	
	glReadPixels(mOrigin.mX, mOrigin.mY, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, baked_color_data );
	stop_glerror();

	llinfos << "Baked " << mTexLayerSet->getBodyRegion() << llendl;
	LLViewerStats::getInstance()->incStat(LLViewerStats::ST_TEX_BAKES);

	llassert( gAgent.getAvatarObject() == mTexLayerSet->getAvatar() );

	// We won't need our caches since we're baked now.  (Techically, we won't 
	// really be baked until this image is sent to the server and the Avatar
	// Appearance message is received.)
	mTexLayerSet->deleteCaches();

	LLGLSUIDefault gls_ui;

	LLPointer<LLImageRaw> baked_mask_image = new LLImageRaw(mWidth, mHeight, 1 );
	U8* baked_mask_data = baked_mask_image->getData(); 

	mTexLayerSet->gatherAlphaMasks(baked_mask_data, mWidth, mHeight);
//	imdebug("lum b=8 w=%d h=%d %p", mWidth, mHeight, baked_mask_data);


	// writes into baked_color_data
	const char* comment_text = NULL;

	S32 baked_image_components = mBumpTex.notNull() ? 5 : 4; // red green blue [bump] clothing
	LLPointer<LLImageRaw> baked_image = new LLImageRaw( mWidth, mHeight, baked_image_components );
	U8* baked_image_data = baked_image->getData();
	
	if( mBumpTex.notNull() )
	{
		comment_text = LINDEN_J2C_COMMENT_PREFIX "RGBHM"; // 5 channels: rgb, heightfield/alpha, mask

		// Hide the alpha for the eyelashes in a corner of the bump map
		if (mTexLayerSet->getBodyRegion() == "head")
		{
			S32 i = 0;
			for( S32 u = 0; u < mWidth; u++ )
			{
				for( S32 v = 0; v < mHeight; v++ )
				{
					baked_image_data[5*i + 0] = baked_color_data[4*i + 0];
					baked_image_data[5*i + 1] = baked_color_data[4*i + 1];
					baked_image_data[5*i + 2] = baked_color_data[4*i + 2];
					baked_image_data[5*i + 3] = baked_color_data[4*i + 3]; // alpha should be correct for eyelashes.
					baked_image_data[5*i + 4] = baked_mask_data[i];
					i++;
				}
			}
		}
		else
		{
			S32 i = 0;
			for( S32 u = 0; u < mWidth; u++ )
			{
				for( S32 v = 0; v < mHeight; v++ )
				{
					baked_image_data[5*i + 0] = baked_color_data[4*i + 0];
					baked_image_data[5*i + 1] = baked_color_data[4*i + 1];
					baked_image_data[5*i + 2] = baked_color_data[4*i + 2];
					baked_image_data[5*i + 3] = 255; // reserve for alpha 
					baked_image_data[5*i + 4] = baked_mask_data[i];
					i++;
				}
			}
		}
	}
	else
	{	
		if (mTexLayerSet->getBodyRegion() == "skirt" || mTexLayerSet->getBodyRegion() == "hair")
		{
			S32 i = 0;
			for( S32 u = 0; u < mWidth; u++ )
			{
				for( S32 v = 0; v < mHeight; v++ )
				{
					baked_image_data[4*i + 0] = baked_color_data[4*i + 0];
					baked_image_data[4*i + 1] = baked_color_data[4*i + 1];
					baked_image_data[4*i + 2] = baked_color_data[4*i + 2];
					baked_image_data[4*i + 3] = baked_color_data[4*i + 3];  // Use alpha, not bump
					i++;
				}
			}
		}
		else
		{
			S32 i = 0;
			for( S32 u = 0; u < mWidth; u++ )
			{
				for( S32 v = 0; v < mHeight; v++ )
				{
					baked_image_data[4*i + 0] = baked_color_data[4*i + 0];
					baked_image_data[4*i + 1] = baked_color_data[4*i + 1];
					baked_image_data[4*i + 2] = baked_color_data[4*i + 2];
					baked_image_data[4*i + 3] = 255; // eyes should have no mask - reserve for alpha 
					i++;
				}
			}
		}
	}
	
	LLPointer<LLImageJ2C> compressedImage = new LLImageJ2C;
	compressedImage->setRate(0.f);
	LLTransactionID tid;
	LLAssetID asset_id;
	tid.generate();
	asset_id = tid.makeAssetID(gAgent.getSecureSessionID());

	BOOL res = false;
	if( compressedImage->encode(baked_image, comment_text))
	{
		res = LLVFile::writeFile(compressedImage->getData(), compressedImage->getDataSize(),
								 gVFS, asset_id, LLAssetType::AT_TEXTURE);
		if (res)
		{
			LLPointer<LLImageJ2C> integrity_test = new LLImageJ2C;
			BOOL valid = FALSE;
			S32 file_size;
			U8* data = LLVFile::readFile(gVFS, asset_id, LLAssetType::AT_TEXTURE, &file_size);
			if (data)
			{
				valid = integrity_test->validate(data, file_size); // integrity_test will delete 'data'
			}
			else
			{
				integrity_test->setLastError("Unable to read entire file");
			}
			
			if( valid )
			{
				// baked_upload_data is owned by the responder and deleted after the request completes
				LLBakedUploadData* baked_upload_data = new LLBakedUploadData( gAgent.getAvatarObject(), this, asset_id );
				mUploadID = asset_id;
				
				// upload the image
				std::string url = gAgent.getRegion()->getCapability("UploadBakedTexture");

				if(!url.empty()
					&& !LLPipeline::sForceOldBakedUpload) // Toggle the debug setting UploadBakedTexOld to change between the new caps method and old method
				{
					llinfos << "Baked texture upload via capability of " << mUploadID << " to " << url << llendl;

					LLSD body = LLSD::emptyMap();
					LLHTTPClient::post(url, body, new LLSendTexLayerResponder(body, mUploadID, LLAssetType::AT_TEXTURE, baked_upload_data));
					// Responder will call LLTexLayerSetBuffer::onTextureUploadComplete()
				} 
				else
				{
					llinfos << "Baked texture upload via Asset Store." <<  llendl;
					// gAssetStorage->storeAssetData(mTransactionID, LLAssetType::AT_IMAGE_JPEG, &uploadCallback, (void *)this, FALSE);
					gAssetStorage->storeAssetData(tid,
												  LLAssetType::AT_TEXTURE,
												  LLTexLayerSetBuffer::onTextureUploadComplete,
												  baked_upload_data,
												  TRUE,		// temp_file
												  TRUE,		// is_priority
												  TRUE);	// store_local
				}
		
				mNeedsUpload = FALSE;
			}
			else
			{
				mUploadPending = FALSE;
				llinfos << "unable to create baked upload file: corrupted" << llendl;
				LLVFile file(gVFS, asset_id, LLAssetType::AT_TEXTURE, LLVFile::WRITE);
				file.remove();
			}
		}
	}
	if (!res)
	{
		mUploadPending = FALSE;
		llinfos << "unable to create baked upload file" << llendl;
	}

	delete [] baked_color_data;
	delete [] baked_bump_data;
}


// static
void LLTexLayerSetBuffer::onTextureUploadComplete(const LLUUID& uuid, void* userdata, S32 result, LLExtStat ext_status) // StoreAssetData callback (not fixed)
{
	LLBakedUploadData* baked_upload_data = (LLBakedUploadData*)userdata;

	LLVOAvatar* avatar = gAgent.getAvatarObject();

	if (0 == result && avatar && !avatar->isDead())
	{
		// Sanity check: only the user's avatar should be uploading textures.
		if( baked_upload_data->mAvatar == avatar )
		{
			// Because the avatar is still valid, it's layerset buffers should be valid also.
			LLTexLayerSetBuffer* layerset_buffer = baked_upload_data->mLayerSetBuffer;
			layerset_buffer->mUploadPending = FALSE;
			
			if (layerset_buffer->mUploadID.isNull())
			{
				// The upload got canceled, we should be in the process of baking a new texture
				// so request an upload with the new data
				layerset_buffer->requestUpload();
			}
			else if( baked_upload_data->mID == layerset_buffer->mUploadID )
			{
				// This is the upload we're currently waiting for.
				layerset_buffer->mUploadID.setNull();

				if( result >= 0 )
				{
					ETextureIndex baked_te = avatar->getBakedTE( layerset_buffer->mTexLayerSet );
					U64 now = LLFrameTimer::getTotalTime();		// Record starting time
					llinfos << "Baked texture upload took " << (S32)((now - baked_upload_data->mStartTime) / 1000) << " ms" << llendl;
					avatar->setNewBakedTexture( baked_te, uuid );
				}
				else
				{
					llinfos << "Baked upload failed. Reason: " << result << llendl;
					// *FIX: retry upload after n seconds, asset server could be busy
				}
			}
			else
			{
				llinfos << "Received baked texture out of date, ignored." << llendl;
			}

			avatar->dirtyMesh();
		}
	}
	else
	{
		// Baked texture failed to upload, but since we didn't set the new baked texture, it means that they'll
		// try and rebake it at some point in the future (after login?)
		llwarns << "Baked upload failed" << llendl;
	}

	delete baked_upload_data;
}

void LLTexLayerSetBuffer::bindBumpTexture( U32 stage )
{
	if( mBumpTex.notNull() ) 
	{
		gGL.getTexUnit(stage)->bindManual(LLTexUnit::TT_TEXTURE, mBumpTex->getTexName());
		gGL.getTexUnit(0)->activate();
	
		if( mLastBindTime != LLImageGL::sLastFrameTime )
		{
			mLastBindTime = LLImageGL::sLastFrameTime;
			LLImageGL::updateBoundTexMem(mWidth * mHeight * 4);
		}
	}
	else
	{
		gGL.getTexUnit(stage)->unbind(LLTexUnit::TT_TEXTURE);
		gGL.getTexUnit(0)->activate();
	}
}


//-----------------------------------------------------------------------------
// LLTexLayerSet
// An ordered set of texture layers that get composited into a single texture.
//-----------------------------------------------------------------------------

LLTexLayerSetInfo::LLTexLayerSetInfo( )
	:
	mBodyRegion( "" ),
	mWidth( 512 ),
	mHeight( 512 ),
	mClearAlpha( TRUE )
{
}

LLTexLayerSetInfo::~LLTexLayerSetInfo( )
{
	std::for_each(mLayerInfoList.begin(), mLayerInfoList.end(), DeletePointer());
}

BOOL LLTexLayerSetInfo::parseXml(LLXmlTreeNode* node)
{
	llassert( node->hasName( "layer_set" ) );
	if( !node->hasName( "layer_set" ) )
	{
		return FALSE;
	}

	// body_region
	static LLStdStringHandle body_region_string = LLXmlTree::addAttributeString("body_region");
	if( !node->getFastAttributeString( body_region_string, mBodyRegion ) )
	{
		llwarns << "<layer_set> is missing body_region attribute" << llendl;
		return FALSE;
	}

	// width, height
	static LLStdStringHandle width_string = LLXmlTree::addAttributeString("width");
	if( !node->getFastAttributeS32( width_string, mWidth ) )
	{
		return FALSE;
	}

	static LLStdStringHandle height_string = LLXmlTree::addAttributeString("height");
	if( !node->getFastAttributeS32( height_string, mHeight ) )
	{
		return FALSE;
	}

	// Optional alpha component to apply after all compositing is complete.
	static LLStdStringHandle alpha_tga_file_string = LLXmlTree::addAttributeString("alpha_tga_file");
	node->getFastAttributeString( alpha_tga_file_string, mStaticAlphaFileName );

	static LLStdStringHandle clear_alpha_string = LLXmlTree::addAttributeString("clear_alpha");
	node->getFastAttributeBOOL( clear_alpha_string, mClearAlpha );

	// <layer>
	for (LLXmlTreeNode* child = node->getChildByName( "layer" );
		 child;
		 child = node->getNextNamedChild())
	{
		LLTexLayerInfo* info = new LLTexLayerInfo();
		if( !info->parseXml( child ))
		{
			delete info;
			return FALSE;
		}
		mLayerInfoList.push_back( info );		
	}
	return TRUE;
}

//-----------------------------------------------------------------------------
// LLTexLayerSet
// An ordered set of texture layers that get composited into a single texture.
//-----------------------------------------------------------------------------

BOOL LLTexLayerSet::sHasCaches = FALSE;

LLTexLayerSet::LLTexLayerSet( LLVOAvatar* avatar )
	:
	mComposite( NULL ),
	mAvatar( avatar ),
	mUpdatesEnabled( FALSE ),
	mHasBump( FALSE ),
	mInfo( NULL )
{
}

LLTexLayerSet::~LLTexLayerSet()
{
	std::for_each(mLayerList.begin(), mLayerList.end(), DeletePointer());
	delete mComposite;
}

//-----------------------------------------------------------------------------
// setInfo
//-----------------------------------------------------------------------------

BOOL LLTexLayerSet::setInfo(LLTexLayerSetInfo *info)
{
	llassert(mInfo == NULL);
	mInfo = info;
	//mID = info->mID; // No ID

	LLTexLayerSetInfo::layer_info_list_t::iterator iter;
	mLayerList.reserve(info->mLayerInfoList.size());
	for (iter = info->mLayerInfoList.begin(); iter != info->mLayerInfoList.end(); iter++)
	{
		LLTexLayer* layer = new LLTexLayer( this );
		if (!layer->setInfo(*iter))
		{
			mInfo = NULL;
			return FALSE;
		}
		mLayerList.push_back( layer );
	}

	requestUpdate();

	stop_glerror();

	return TRUE;
}

#if 0 // obsolete
//-----------------------------------------------------------------------------
// parseData
//-----------------------------------------------------------------------------

BOOL LLTexLayerSet::parseData(LLXmlTreeNode* node)
{
	LLTexLayerSetInfo *info = new LLTexLayerSetInfo;

	if (!info->parseXml(node))
	{
		delete info;
		return FALSE;
	}
	if (!setInfo(info))
	{
		delete info;
		return FALSE;
	}
	return TRUE;
}
#endif

void LLTexLayerSet::deleteCaches()
{
	for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
	{
		LLTexLayer* layer = *iter;
		layer->deleteCaches();
	}
}

// Returns TRUE if at least one packet of data has been received for each of the textures that this layerset depends on.
BOOL LLTexLayerSet::isLocalTextureDataAvailable()
{
	return mAvatar->isLocalTextureDataAvailable( this );
}


// Returns TRUE if all of the data for the textures that this layerset depends on have arrived.
BOOL LLTexLayerSet::isLocalTextureDataFinal()
{
	return mAvatar->isLocalTextureDataFinal( this );
}


BOOL LLTexLayerSet::render( S32 x, S32 y, S32 width, S32 height )
{
	BOOL success = TRUE;

	LLGLSUIDefault gls_ui;
	LLGLDepthTest gls_depth(GL_FALSE, GL_FALSE);
	gGL.setColorMask(true, true);

	// composite color layers
	for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
	{
		LLTexLayer* layer = *iter;
		if( layer->getRenderPass() == RP_COLOR )
		{
			gGL.flush();
			success &= layer->render( x, y, width, height );
			gGL.flush();
		}
	}

	// (Optionally) replace alpha with a single component image from a tga file.
	if( !getInfo()->mStaticAlphaFileName.empty() )
	{
		LLGLSNoAlphaTest gls_no_alpha_test;
		gGL.flush();
		gGL.setColorMask(false, true);
		gGL.setSceneBlendType(LLRender::BT_REPLACE);

		{
			LLImageGL* image_gl = gTexStaticImageList.getImageGL( getInfo()->mStaticAlphaFileName, TRUE );
			if( image_gl )
			{
				LLGLSUIDefault gls_ui;
				gGL.getTexUnit(0)->bind(image_gl);
				gGL.getTexUnit(0)->setTextureBlendType( LLTexUnit::TB_REPLACE );
				gl_rect_2d_simple_tex( width, height );
			}
			else
			{
				success = FALSE;
			}
		}
		gGL.flush();
		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);

		gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
		gGL.setColorMask(true, true);
		gGL.setSceneBlendType(LLRender::BT_ALPHA);
	}
	else 
	if( getInfo()->mClearAlpha )
	{
		// Set the alpha channel to one (clean up after previous blending)
		LLGLDisable no_alpha(GL_ALPHA_TEST);
		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
		gGL.color4f( 0.f, 0.f, 0.f, 1.f );
		gGL.flush();
		gGL.setColorMask(false, true);

		gl_rect_2d_simple( width, height );
		
		gGL.flush();
		gGL.setColorMask(true, true);
	}
	stop_glerror();

	return success;
}

BOOL LLTexLayerSet::renderBump( S32 x, S32 y, S32 width, S32 height )
{
	BOOL success = TRUE;

	LLGLSUIDefault gls_ui;
	LLGLDepthTest gls_depth(GL_FALSE, GL_FALSE);

	//static S32 bump_layer_count = 1;

	for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
	{
		LLTexLayer* layer = *iter;
		if( layer->getRenderPass() == RP_BUMP )
		{
			success &= layer->render( x, y, width, height );
		}
	}

	// Set the alpha channel to one (clean up after previous blending)
	LLGLDisable no_alpha(GL_ALPHA_TEST);
	gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
	gGL.color4f( 0.f, 0.f, 0.f, 1.f );
	gGL.setColorMask(false, true);

	gl_rect_2d_simple( width, height );
	
	gGL.setColorMask(true, true);
	stop_glerror();

	return success;
}

void LLTexLayerSet::requestUpdate()
{
	if( mUpdatesEnabled )
	{
		createComposite();
		mComposite->requestUpdate(); 
	}
}

void LLTexLayerSet::requestUpload()
{
	createComposite();
	mComposite->requestUpload();
}

void LLTexLayerSet::cancelUpload()
{
	if(mComposite)
	{
		mComposite->cancelUpload();
	}
}

void LLTexLayerSet::createComposite()
{
	if( !mComposite )
	{
		S32 width = mInfo->mWidth;
		S32 height = mInfo->mHeight;
		// Composite other avatars at reduced resolution
		if( !mAvatar->isSelf() )
		{
			width /= 2;
			height /= 2;
		}
		mComposite = new LLTexLayerSetBuffer( this, width, height, mHasBump );
	}
}

void LLTexLayerSet::destroyComposite()
{
	if( mComposite )
	{
		delete mComposite;
		mComposite = NULL;
	}
}

void LLTexLayerSet::setUpdatesEnabled( BOOL b )
{
	mUpdatesEnabled = b; 
}


void LLTexLayerSet::updateComposite()
{
	createComposite();
	mComposite->updateImmediate();
}

LLTexLayerSetBuffer* LLTexLayerSet::getComposite()
{
	createComposite();
	return mComposite;
}

void LLTexLayerSet::gatherAlphaMasks(U8 *data, S32 width, S32 height)
{
	S32 size = width * height;

	memset(data, 255, width * height);

	for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
	{
		LLTexLayer* layer = *iter;
		U8* alphaData = layer->getAlphaData();
		if (!alphaData && layer->hasAlphaParams())
		{
			LLColor4 net_color;
			layer->findNetColor( &net_color );
			layer->invalidateMorphMasks();
			layer->renderAlphaMasks(mComposite->getOriginX(), mComposite->getOriginY(), width, height, &net_color);
			alphaData = layer->getAlphaData();
		}
		if (alphaData)
		{
			for( S32 i = 0; i < size; i++ )
			{
				U8 curAlpha = data[i];
				U16 resultAlpha = curAlpha;
				resultAlpha *= (alphaData[i] + 1);
				resultAlpha = resultAlpha >> 8;
				data[i] = (U8)resultAlpha;
			}
		}
	}
}

void LLTexLayerSet::applyMorphMask(U8* tex_data, S32 width, S32 height, S32 num_components)
{
	for( layer_list_t::iterator iter = mLayerList.begin(); iter != mLayerList.end(); iter++ )
	{
		LLTexLayer* layer = *iter;
		layer->applyMorphMask(tex_data, width, height, num_components);
	}
}

//-----------------------------------------------------------------------------
// LLTexLayerInfo
//-----------------------------------------------------------------------------
LLTexLayerInfo::LLTexLayerInfo( )
	:
	mWriteAllChannels( FALSE ),
	mRenderPass( RP_COLOR ),
	mFixedColor( 0.f, 0.f, 0.f, 0.f ),
	mLocalTexture( -1 ),
	mStaticImageIsMask( FALSE ),
	mUseLocalTextureAlphaOnly( FALSE )
{
}

LLTexLayerInfo::~LLTexLayerInfo( )
{
	std::for_each(mColorInfoList.begin(), mColorInfoList.end(), DeletePointer());
	std::for_each(mAlphaInfoList.begin(), mAlphaInfoList.end(), DeletePointer());
}

BOOL LLTexLayerInfo::parseXml(LLXmlTreeNode* node)
{
	llassert( node->hasName( "layer" ) );

	// name attribute
	static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
	if( !node->getFastAttributeString( name_string, mName ) )
	{
		return FALSE;
	}
	
	static LLStdStringHandle write_all_channels_string = LLXmlTree::addAttributeString("write_all_channels");
	node->getFastAttributeBOOL( write_all_channels_string, mWriteAllChannels );

	std::string render_pass_name;
	static LLStdStringHandle render_pass_string = LLXmlTree::addAttributeString("render_pass");
	if( node->getFastAttributeString( render_pass_string, render_pass_name ) )
	{
		if( render_pass_name == "bump" )
		{
			mRenderPass = RP_BUMP;
		}
	}

	// Note: layers can have either a "global_color" attrib, a "fixed_color" attrib, or a <param_color> child.
	// global color attribute (optional)
	static LLStdStringHandle global_color_string = LLXmlTree::addAttributeString("global_color");
	node->getFastAttributeString( global_color_string, mGlobalColor );

	// color attribute (optional)
	LLColor4U color4u;
	static LLStdStringHandle fixed_color_string = LLXmlTree::addAttributeString("fixed_color");
	if( node->getFastAttributeColor4U( fixed_color_string, color4u ) )
	{
		mFixedColor.setVec( color4u );
	}

		// <texture> optional sub-element
	for (LLXmlTreeNode* texture_node = node->getChildByName( "texture" );
		 texture_node;
		 texture_node = node->getNextNamedChild())
	{
		std::string local_texture;
		static LLStdStringHandle tga_file_string = LLXmlTree::addAttributeString("tga_file");
		static LLStdStringHandle local_texture_string = LLXmlTree::addAttributeString("local_texture");
		static LLStdStringHandle file_is_mask_string = LLXmlTree::addAttributeString("file_is_mask");
		static LLStdStringHandle local_texture_alpha_only_string = LLXmlTree::addAttributeString("local_texture_alpha_only");
		if( texture_node->getFastAttributeString( tga_file_string, mStaticImageFileName ) )
		{
			texture_node->getFastAttributeBOOL( file_is_mask_string, mStaticImageIsMask );
		}
		else if( texture_node->getFastAttributeString( local_texture_string, local_texture ) )
		{
			texture_node->getFastAttributeBOOL( local_texture_alpha_only_string, mUseLocalTextureAlphaOnly );

			if( "upper_shirt" == local_texture )
			{
				mLocalTexture = TEX_UPPER_SHIRT;
			}
			else if( "upper_bodypaint" == local_texture )
			{
				mLocalTexture = TEX_UPPER_BODYPAINT;
			}
			else if( "lower_pants" == local_texture )
			{
				mLocalTexture = TEX_LOWER_PANTS;
			}
			else if( "lower_bodypaint" == local_texture )
			{
				mLocalTexture = TEX_LOWER_BODYPAINT;
			}
			else if( "lower_shoes" == local_texture )
			{
				mLocalTexture = TEX_LOWER_SHOES;
			}
			else if( "head_bodypaint" == local_texture )
			{
				mLocalTexture = TEX_HEAD_BODYPAINT;
			}
			else if( "lower_socks" == local_texture )
			{
				mLocalTexture = TEX_LOWER_SOCKS;
			}
			else if( "upper_jacket" == local_texture )
			{
				mLocalTexture = TEX_UPPER_JACKET;
			}
			else if( "lower_jacket" == local_texture )
			{
				mLocalTexture = TEX_LOWER_JACKET;
			}
			else if( "upper_gloves" == local_texture )
			{
				mLocalTexture = TEX_UPPER_GLOVES;
			}
			else if( "upper_undershirt" == local_texture )
			{
				mLocalTexture = TEX_UPPER_UNDERSHIRT;
			}
			else if( "lower_underpants" == local_texture )
			{
				mLocalTexture = TEX_LOWER_UNDERPANTS;
			}
			else if( "eyes_iris" == local_texture )
			{
				mLocalTexture = TEX_EYES_IRIS;
			}
			else if( "skirt" == local_texture )
			{
				mLocalTexture = TEX_SKIRT;
			}			
			else if( "hair_grain" == local_texture )
			{
				mLocalTexture = TEX_HAIR;
			}
			else
			{
				llwarns << "<texture> element has invalid local_texure attribute: " << mName << " " << local_texture << llendl;
				return FALSE;
			}
		}
		else	
		{
			llwarns << "<texture> element is missing a required attribute. " << mName << llendl;
			return FALSE;
		}
	}

	for (LLXmlTreeNode* maskNode = node->getChildByName( "morph_mask" );
		 maskNode;
		 maskNode = node->getNextNamedChild())
	{
		std::string morph_name;
		static LLStdStringHandle morph_name_string = LLXmlTree::addAttributeString("morph_name");
		if (maskNode->getFastAttributeString(morph_name_string, morph_name))
		{
			BOOL invert = FALSE;
			static LLStdStringHandle invert_string = LLXmlTree::addAttributeString("invert");
			maskNode->getFastAttributeBOOL(invert_string, invert);			
			mMorphNameList.push_back(std::pair<std::string,BOOL>(morph_name,invert));
		}
	}

	// <param> optional sub-element (color or alpha params)
	for (LLXmlTreeNode* child = node->getChildByName( "param" );
		 child;
		 child = node->getNextNamedChild())
	{
		if( child->getChildByName( "param_color" ) )
		{
			// <param><param_color/></param>
			LLTexParamColorInfo* info = new LLTexParamColorInfo( );
			if (!info->parseXml(child))
			{
				delete info;
				return FALSE;
			}
			mColorInfoList.push_back( info );
		}
		else if( child->getChildByName( "param_alpha" ) )
		{
			// <param><param_alpha/></param>
			LLTexLayerParamAlphaInfo* info = new LLTexLayerParamAlphaInfo( );
			if (!info->parseXml(child))
			{
				delete info;
				return FALSE;
			}
 			mAlphaInfoList.push_back( info );
		}
	}
	
	return TRUE;
}

//-----------------------------------------------------------------------------
// LLTexLayer
// A single texture layer, consisting of:
//		* color, consisting of either
//			* one or more color parameters (weighted colors)
//			* a reference to a global color
//			* a fixed color with non-zero alpha
//			* opaque white (the default)
//		* (optional) a texture defined by either
//			* a GUID
//			* a texture entry index (TE)
//		* (optional) one or more alpha parameters (weighted alpha textures)
//-----------------------------------------------------------------------------
LLTexLayer::LLTexLayer( LLTexLayerSet* layer_set )
	:
	mTexLayerSet( layer_set ),
	mMorphMasksValid( FALSE ),
	mStaticImageInvalid( FALSE ),
	mInfo( NULL )
{
}

LLTexLayer::~LLTexLayer()
{
	// mParamAlphaList and mParamColorList are LLViewerVisualParam's and get
	// deleted with ~LLCharacter()
	//std::for_each(mParamAlphaList.begin(), mParamAlphaList.end(), DeletePointer());
	//std::for_each(mParamColorList.begin(), mParamColorList.end(), DeletePointer());
	
	for( alpha_cache_t::iterator iter = mAlphaCache.begin();
		 iter != mAlphaCache.end(); iter++ )
	{
		U8* alpha_data = iter->second;
		delete [] alpha_data;
	}
}

//-----------------------------------------------------------------------------
// setInfo
//-----------------------------------------------------------------------------

BOOL LLTexLayer::setInfo(LLTexLayerInfo* info)
{
	llassert(mInfo == NULL);
	mInfo = info;
	//mID = info->mID; // No ID

	if (info->mRenderPass == RP_BUMP)
		mTexLayerSet->setBump(TRUE);

	{
		LLTexLayerInfo::morph_name_list_t::iterator iter;
		for (iter = mInfo->mMorphNameList.begin(); iter != mInfo->mMorphNameList.end(); iter++)
		{
			// *FIX: we assume that the referenced visual param is a
			// morph target, need a better way of actually looking
			// this up.
			LLPolyMorphTarget *morph_param;
			std::string *name = &(iter->first);
			morph_param = (LLPolyMorphTarget *)(getTexLayerSet()->getAvatar()->getVisualParam(name->c_str()));
			if (morph_param)
			{
				BOOL invert = iter->second;
				addMaskedMorph(morph_param, invert);
			}
		}
	}

	{
		LLTexLayerInfo::color_info_list_t::iterator iter;
		mParamColorList.reserve(mInfo->mColorInfoList.size());
		for (iter = mInfo->mColorInfoList.begin(); iter != mInfo->mColorInfoList.end(); iter++)
		{
			LLTexParamColor* param_color = new LLTexParamColor( this );
			if (!param_color->setInfo(*iter))
			{
				mInfo = NULL;
				return FALSE;
			}
			mParamColorList.push_back( param_color );
		}
	}
	{
		LLTexLayerInfo::alpha_info_list_t::iterator iter;
		mParamAlphaList.reserve(mInfo->mAlphaInfoList.size());
		for (iter = mInfo->mAlphaInfoList.begin(); iter != mInfo->mAlphaInfoList.end(); iter++)
		{
			LLTexLayerParamAlpha* param_alpha = new LLTexLayerParamAlpha( this );
			if (!param_alpha->setInfo(*iter))
			{
				mInfo = NULL;
				return FALSE;
			}
			mParamAlphaList.push_back( param_alpha );
		}
	}
	
	return TRUE;
}

#if 0 // obsolete
//-----------------------------------------------------------------------------
// parseData
//-----------------------------------------------------------------------------
BOOL LLTexLayer::parseData( LLXmlTreeNode* node )
{
	LLTexLayerInfo *info = new LLTexLayerInfo;

	if (!info->parseXml(node))
	{
		delete info;
		return FALSE;
	}
	if (!setInfo(info))
	{
		delete info;
		return FALSE;
	}
	return TRUE;
}
#endif

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


void LLTexLayer::deleteCaches()
{
	for( alpha_list_t::iterator iter = mParamAlphaList.begin();
		 iter != mParamAlphaList.end(); iter++ )
	{
		LLTexLayerParamAlpha* param = *iter;
		param->deleteCaches();
	}
	mStaticImageRaw = NULL;
}

BOOL LLTexLayer::render( S32 x, S32 y, S32 width, S32 height )
{
	LLGLEnable color_mat(GL_COLOR_MATERIAL);
	gPipeline.disableLights();

	BOOL success = TRUE;
	
	BOOL color_specified = FALSE;
	BOOL alpha_mask_specified = FALSE;

	LLColor4 net_color;
	color_specified = findNetColor( &net_color );

	// If you can't see the layer, don't render it.
	if( is_approx_zero( net_color.mV[VW] ) )
	{
		return success;
	}

	alpha_list_t::iterator iter = mParamAlphaList.begin();
	if( iter != mParamAlphaList.end() )
	{
		// If we have alpha masks, but we're skipping all of them, skip the whole layer.
		// However, we can't do this optimization if we have morph masks that need updating.
		if( mMaskedMorphs.empty() )
		{
			BOOL skip_layer = TRUE;

			while( iter != mParamAlphaList.end() )
			{
				LLTexLayerParamAlpha* param = *iter;
		
				if( !param->getSkip() )
				{
					skip_layer = FALSE;
					break;
				}

				iter++;
			} 

			if( skip_layer )
			{
				return success;
			}
		}

		renderAlphaMasks( x, y, width, height, &net_color );
		alpha_mask_specified = TRUE;
		gGL.flush();
		gGL.blendFunc(LLRender::BF_DEST_ALPHA, LLRender::BF_ONE_MINUS_DEST_ALPHA);
	}

	gGL.color4fv( net_color.mV);

	if( getInfo()->mWriteAllChannels )
	{
		gGL.flush();
		gGL.setSceneBlendType(LLRender::BT_REPLACE);
	}

	if( (getInfo()->mLocalTexture != -1) && !getInfo()->mUseLocalTextureAlphaOnly )
	{
		{
			LLImageGL* image_gl = NULL;
			if( mTexLayerSet->getAvatar()->getLocalTextureGL((ETextureIndex)getInfo()->mLocalTexture, &image_gl ) )
			{
				if( image_gl )
				{
					LLGLDisable alpha_test(getInfo()->mWriteAllChannels ? GL_ALPHA_TEST : 0);

					LLTexUnit::eTextureAddressMode old_mode = image_gl->getAddressMode();
					
					gGL.getTexUnit(0)->bind(image_gl);
					gGL.getTexUnit(0)->setTextureAddressMode(LLTexUnit::TAM_CLAMP);

					gl_rect_2d_simple_tex( width, height );

					gGL.getTexUnit(0)->setTextureAddressMode(old_mode);
					gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
				}
			}
			else
			{
				success = FALSE;
			}
		}
	}

	if( !getInfo()->mStaticImageFileName.empty() )
	{
		{
			LLImageGL* image_gl = gTexStaticImageList.getImageGL( getInfo()->mStaticImageFileName, getInfo()->mStaticImageIsMask );
			if( image_gl )
			{
				gGL.getTexUnit(0)->bind(image_gl);
				gl_rect_2d_simple_tex( width, height );
				gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
			}
			else
			{
				success = FALSE;
			}
		}
	}

	if( ((-1 == getInfo()->mLocalTexture) ||
		 getInfo()->mUseLocalTextureAlphaOnly) &&
		getInfo()->mStaticImageFileName.empty() &&
		color_specified )
	{
		LLGLDisable no_alpha(GL_ALPHA_TEST);
		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
		gGL.color4fv( net_color.mV);
		gl_rect_2d_simple( width, height );
	}

	if( alpha_mask_specified || getInfo()->mWriteAllChannels )
	{
		// Restore standard blend func value
		gGL.flush();
		gGL.setSceneBlendType(LLRender::BT_ALPHA);
		stop_glerror();
	}

	if( !success )
	{
		llinfos << "LLTexLayer::render() partial: " << getInfo()->mName << llendl;
	}
	return success;
}

U8*	LLTexLayer::getAlphaData()
{
	LLCRC alpha_mask_crc;
	const LLUUID& uuid = mTexLayerSet->getAvatar()->getLocalTextureID((ETextureIndex)getInfo()->mLocalTexture);
	alpha_mask_crc.update((U8*)(&uuid.mData), UUID_BYTES);

	for( alpha_list_t::iterator iter = mParamAlphaList.begin(); iter != mParamAlphaList.end(); iter++ )
	{
		LLTexLayerParamAlpha* param = *iter;
		F32 param_weight = param->getWeight();
		alpha_mask_crc.update((U8*)&param_weight, sizeof(F32));
	}

	U32 cache_index = alpha_mask_crc.getCRC();

	alpha_cache_t::iterator iter2 = mAlphaCache.find(cache_index);
	return (iter2 == mAlphaCache.end()) ? 0 : iter2->second;
}

BOOL LLTexLayer::findNetColor( LLColor4* net_color )
{
	// Color is either:
	//	* one or more color parameters (weighted colors)  (which may make use of a global color or fixed color)
	//	* a reference to a global color
	//	* a fixed color with non-zero alpha
	//	* opaque white (the default)

	if( !mParamColorList.empty() )
	{
		if( !getGlobalColor().empty() )
		{
			net_color->setVec( mTexLayerSet->getAvatar()->getGlobalColor( getInfo()->mGlobalColor ) );
		}
		else
		if( getInfo()->mFixedColor.mV[VW] )
		{
			net_color->setVec( getInfo()->mFixedColor );
		}
		else
		{
			net_color->setVec( 0.f, 0.f, 0.f, 0.f );
		}
		
		for( color_list_t::iterator iter = mParamColorList.begin();
			 iter != mParamColorList.end(); iter++ )
		{
			LLTexParamColor* param = *iter;
			LLColor4 param_net = param->getNetColor();
			switch( param->getOperation() )
			{
			case OP_ADD:
				*net_color += param_net;
				break;
			case OP_MULTIPLY:
				net_color->mV[VX] *= param_net.mV[VX];
				net_color->mV[VY] *= param_net.mV[VY];
				net_color->mV[VZ] *= param_net.mV[VZ];
				net_color->mV[VW] *= param_net.mV[VW];
				break;
			case OP_BLEND:
				net_color->setVec( lerp(*net_color, param_net, param->getWeight()) );
				break;
			default:
				llassert(0);
				break;
			}
		}
		return TRUE;
	}

	if( !getGlobalColor().empty() )
	{
		net_color->setVec( mTexLayerSet->getAvatar()->getGlobalColor( getGlobalColor() ) );
		return TRUE;
	}

	if( getInfo()->mFixedColor.mV[VW] )
	{
		net_color->setVec( getInfo()->mFixedColor );
		return TRUE;
	}

	net_color->setToWhite();

	return FALSE; // No need to draw a separate colored polygon
}


BOOL LLTexLayer::renderAlphaMasks( S32 x, S32 y, S32 width, S32 height, LLColor4* colorp )
{
	BOOL success = TRUE;

	llassert( !mParamAlphaList.empty() );

	gGL.setColorMask(false, true);

	alpha_list_t::iterator iter = mParamAlphaList.begin();
	LLTexLayerParamAlpha* first_param = *iter;

	// Note: if the first param is a mulitply, multiply against the current buffer's alpha
	if( !first_param || !first_param->getMultiplyBlend() )
	{
		LLGLDisable no_alpha(GL_ALPHA_TEST);
		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
	
		// Clear the alpha
		gGL.flush();
		gGL.setSceneBlendType(LLRender::BT_REPLACE);

		gGL.color4f( 0.f, 0.f, 0.f, 0.f );
		gl_rect_2d_simple( width, height );
	}

	// Accumulate alphas
	LLGLSNoAlphaTest gls_no_alpha_test;
	gGL.color4f( 1.f, 1.f, 1.f, 1.f );

	for( iter = mParamAlphaList.begin(); iter != mParamAlphaList.end(); iter++ )
	{
		LLTexLayerParamAlpha* param = *iter;
		success &= param->render( x, y, width, height );
	}

	// Approximates a min() function
	gGL.flush();
	gGL.blendFunc(LLRender::BF_DEST_ALPHA, LLRender::BF_ZERO);

	// Accumulate the alpha component of the texture
	if( getInfo()->mLocalTexture != -1 )
	{
		{
			LLImageGL* image_gl = NULL;
			if( mTexLayerSet->getAvatar()->getLocalTextureGL((ETextureIndex)getInfo()->mLocalTexture, &image_gl ) )
			{
				if( image_gl && (image_gl->getComponents() == 4) )
				{
					LLGLSNoAlphaTest gls_no_alpha_test;

					LLTexUnit::eTextureAddressMode old_mode = image_gl->getAddressMode();
					
					gGL.getTexUnit(0)->bind(image_gl);
					gGL.getTexUnit(0)->setTextureAddressMode(LLTexUnit::TAM_CLAMP);

					gl_rect_2d_simple_tex( width, height );

					gGL.getTexUnit(0)->setTextureAddressMode(old_mode);
					gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
				}
			}
			else
			{
				success = FALSE;
			}
		}
	}

	if( !getInfo()->mStaticImageFileName.empty() )
	{
		{
			LLImageGL* image_gl = gTexStaticImageList.getImageGL( getInfo()->mStaticImageFileName, getInfo()->mStaticImageIsMask );
			if( image_gl )
			{
				if(	(image_gl->getComponents() == 4) ||
					( (image_gl->getComponents() == 1) && getInfo()->mStaticImageIsMask ) )
				{
					LLGLSNoAlphaTest gls_no_alpha_test;
					gGL.getTexUnit(0)->bind(image_gl);
					gl_rect_2d_simple_tex( width, height );
					gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
				}
			}
			else
			{
				success = FALSE;
			}
		}
	}

	// Draw a rectangle with the layer color to multiply the alpha by that color's alpha.
	// Note: we're still using gGL.blendFunc( GL_DST_ALPHA, GL_ZERO );
	if( colorp->mV[VW] != 1.f )
	{
		LLGLDisable no_alpha(GL_ALPHA_TEST);
		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
		gGL.color4fv( colorp->mV );
		gl_rect_2d_simple( width, height );
	}


	LLGLSUIDefault gls_ui;

	gGL.setColorMask(true, true);
	
	if (!mMorphMasksValid && !mMaskedMorphs.empty())
	{
		LLCRC alpha_mask_crc;
		const LLUUID& uuid = mTexLayerSet->getAvatar()->getLocalTextureID((ETextureIndex)getInfo()->mLocalTexture);
		alpha_mask_crc.update((U8*)(&uuid.mData), UUID_BYTES);
		
		for( alpha_list_t::iterator iter = mParamAlphaList.begin(); iter != mParamAlphaList.end(); iter++ )
		{
			LLTexLayerParamAlpha* param = *iter;
			F32 param_weight = param->getWeight();
			alpha_mask_crc.update((U8*)&param_weight, sizeof(F32));
		}

		U32 cache_index = alpha_mask_crc.getCRC();

		alpha_cache_t::iterator iter2 = mAlphaCache.find(cache_index);
		U8* alpha_data;
		if (iter2 != mAlphaCache.end())
		{
			alpha_data = iter2->second;
		}
		else
		{
			// clear out a slot if we have filled our cache
			S32 max_cache_entries = getTexLayerSet()->getAvatar()->isSelf() ? 4 : 1;
			while ((S32)mAlphaCache.size() >= max_cache_entries)
			{
				iter2 = mAlphaCache.begin(); // arbitrarily grab the first entry
				alpha_data = iter2->second;
				delete [] alpha_data;
				mAlphaCache.erase(iter2);
			}
			alpha_data = new U8[width * height];
			mAlphaCache[cache_index] = alpha_data;
			glReadPixels(x, y, width, height, GL_ALPHA, GL_UNSIGNED_BYTE, alpha_data);
		}
		
		getTexLayerSet()->getAvatar()->dirtyMesh();

		mMorphMasksValid = TRUE;

		for( morph_list_t::iterator iter3 = mMaskedMorphs.begin();
			 iter3 != mMaskedMorphs.end(); iter3++ )
		{
			LLMaskedMorph* maskedMorph = &(*iter3);
			maskedMorph->mMorphTarget->applyMask(alpha_data, width, height, 1, maskedMorph->mInvert);
		}
	}

	return success;
}

void LLTexLayer::applyMorphMask(U8* tex_data, S32 width, S32 height, S32 num_components)
{
	for( morph_list_t::iterator iter = mMaskedMorphs.begin();
		 iter != mMaskedMorphs.end(); iter++ )
	{
		LLMaskedMorph* maskedMorph = &(*iter);
		maskedMorph->mMorphTarget->applyMask(tex_data, width, height, num_components, maskedMorph->mInvert);
	}
}

// Returns TRUE on success.
BOOL LLTexLayer::renderImageRaw( U8* in_data, S32 in_width, S32 in_height, S32 in_components, S32 width, S32 height, BOOL is_mask )
{
	if (!in_data)
	{
		return FALSE;
	}
	GLenum format_options[4] = { GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RGB, GL_RGBA };
	GLenum format = format_options[in_components-1];
	if( is_mask )
	{
		llassert( 1 == in_components );
		format = GL_ALPHA;
	}

	if( (in_width != SCRATCH_TEX_WIDTH) || (in_height != SCRATCH_TEX_HEIGHT) )
	{
		LLGLSNoAlphaTest gls_no_alpha_test;

		GLenum internal_format_options[4] = { GL_LUMINANCE8, GL_LUMINANCE8_ALPHA8, GL_RGB8, GL_RGBA8 };
		GLenum internal_format = internal_format_options[in_components-1];
		if( is_mask )
		{
			llassert( 1 == in_components );
			internal_format = GL_ALPHA8;
		}
		
		U32 name = 0;
		LLImageGL::generateTextures(1, &name );
		stop_glerror();

		gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, name);
		stop_glerror();

		LLImageGL::setManualImage(
			GL_TEXTURE_2D, 0, internal_format, 
			in_width, in_height,
			format, GL_UNSIGNED_BYTE, in_data );
		stop_glerror();

		gGL.getTexUnit(0)->setTextureFilteringOption(LLTexUnit::TFO_BILINEAR);
		
		gGL.getTexUnit(0)->setTextureAddressMode(LLTexUnit::TAM_CLAMP);

		gl_rect_2d_simple_tex( width, height );

		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);

		LLImageGL::deleteTextures(1, &name );
		stop_glerror();
	}
	else
	{
		LLGLSNoAlphaTest gls_no_alpha_test;

		if( !mTexLayerSet->getAvatar()->bindScratchTexture(format) )
		{
			return FALSE;
		}

		glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, in_width, in_height, format, GL_UNSIGNED_BYTE, in_data );
		stop_glerror();

		gl_rect_2d_simple_tex( width, height );

		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
	}

	return TRUE;
}

void LLTexLayer::requestUpdate()
{
	mTexLayerSet->requestUpdate();
}

void LLTexLayer::addMaskedMorph(LLPolyMorphTarget* morph_target, BOOL invert)
{ 
	mMaskedMorphs.push_front(LLMaskedMorph(morph_target, invert));
}

void LLTexLayer::invalidateMorphMasks()
{
	mMorphMasksValid = FALSE;
}

//-----------------------------------------------------------------------------
// LLTexLayerParamAlphaInfo
//-----------------------------------------------------------------------------
LLTexLayerParamAlphaInfo::LLTexLayerParamAlphaInfo( )
	:
	mMultiplyBlend( FALSE ),
	mSkipIfZeroWeight( FALSE ),
	mDomain( 0.f )
{
}

BOOL LLTexLayerParamAlphaInfo::parseXml(LLXmlTreeNode* node)
{
	llassert( node->hasName( "param" ) && node->getChildByName( "param_alpha" ) );

	if( !LLViewerVisualParamInfo::parseXml(node) )
		return FALSE;

	LLXmlTreeNode* param_alpha_node = node->getChildByName( "param_alpha" );
	if( !param_alpha_node )
	{
		return FALSE;
	}

	static LLStdStringHandle tga_file_string = LLXmlTree::addAttributeString("tga_file");
	if( param_alpha_node->getFastAttributeString( tga_file_string, mStaticImageFileName ) )
	{
		// Don't load the image file until it's actually needed.
	}
//	else
//	{
//		llwarns << "<param_alpha> element is missing tga_file attribute." << llendl;
//	}
	
	static LLStdStringHandle multiply_blend_string = LLXmlTree::addAttributeString("multiply_blend");
	param_alpha_node->getFastAttributeBOOL( multiply_blend_string, mMultiplyBlend );

	static LLStdStringHandle skip_if_zero_string = LLXmlTree::addAttributeString("skip_if_zero");
	param_alpha_node->getFastAttributeBOOL( skip_if_zero_string, mSkipIfZeroWeight );

	static LLStdStringHandle domain_string = LLXmlTree::addAttributeString("domain");
	param_alpha_node->getFastAttributeF32( domain_string, mDomain );

	return TRUE;
}

//-----------------------------------------------------------------------------
// LLTexLayerParamAlpha
//-----------------------------------------------------------------------------

// static 
LLTexLayerParamAlpha::param_alpha_ptr_list_t LLTexLayerParamAlpha::sInstances;

// static 
void LLTexLayerParamAlpha::dumpCacheByteCount()
{
	S32 gl_bytes = 0;
	getCacheByteCount( &gl_bytes );
	llinfos << "Processed Alpha Texture Cache GL:" << (gl_bytes/1024) << "KB" << llendl;
}

// static 
void LLTexLayerParamAlpha::getCacheByteCount( S32* gl_bytes )
{
	*gl_bytes = 0;

	for( param_alpha_ptr_list_t::iterator iter = sInstances.begin();
		 iter != sInstances.end(); iter++ )
	{
		LLTexLayerParamAlpha* instance = *iter;
		LLImageGL* image_gl = instance->mCachedProcessedImageGL;
		if( image_gl )
		{
			S32 bytes = (S32)image_gl->getWidth() * image_gl->getHeight() * image_gl->getComponents();

			if( image_gl->getHasGLTexture() )
			{
				*gl_bytes += bytes;
			}
		}
	}
}

LLTexLayerParamAlpha::LLTexLayerParamAlpha( LLTexLayer* layer )
	:
	mCachedProcessedImageGL( NULL ),
	mTexLayer( layer ),
	mNeedsCreateTexture( FALSE ),
	mStaticImageInvalid( FALSE ),
	mAvgDistortionVec(1.f, 1.f, 1.f),
	mCachedEffectiveWeight(0.f)
{
	sInstances.push_front( this );
}

LLTexLayerParamAlpha::~LLTexLayerParamAlpha()
{
	deleteCaches();
	sInstances.remove( this );
}

//-----------------------------------------------------------------------------
// setInfo()
//-----------------------------------------------------------------------------
BOOL LLTexLayerParamAlpha::setInfo(LLTexLayerParamAlphaInfo *info)
{
	llassert(mInfo == NULL);
	if (info->mID < 0)
		return FALSE;
	mInfo = info;
	mID = info->mID;

	mTexLayer->getTexLayerSet()->getAvatar()->addVisualParam( this );
	setWeight(getDefaultWeight(), FALSE );
	
	return TRUE;
}

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

void LLTexLayerParamAlpha::deleteCaches()
{
	mStaticImageTGA = NULL; // deletes image
	mCachedProcessedImageGL = NULL;
	mStaticImageRaw = NULL;
	mNeedsCreateTexture = FALSE;
}

void LLTexLayerParamAlpha::setWeight(F32 weight, BOOL set_by_user)
{
	if (mIsAnimating)
	{
		return;
	}
	F32 min_weight = getMinWeight();
	F32 max_weight = getMaxWeight();
	F32 new_weight = llclamp(weight, min_weight, max_weight);
	U8 cur_u8 = F32_to_U8( mCurWeight, min_weight, max_weight );
	U8 new_u8 = F32_to_U8( new_weight, min_weight, max_weight );
	if( cur_u8 != new_u8)
	{
		mCurWeight = new_weight;

		LLVOAvatar* avatar = mTexLayer->getTexLayerSet()->getAvatar();
		if( avatar->getSex() & getSex() )
		{
			if ( gAgent.cameraCustomizeAvatar() )
			{
				set_by_user = FALSE;
			}
			avatar->invalidateComposite( mTexLayer->getTexLayerSet(), set_by_user );
			mTexLayer->invalidateMorphMasks();
			avatar->updateMeshTextures();
		}
	}
}

void LLTexLayerParamAlpha::setAnimationTarget(F32 target_value, BOOL set_by_user)
{ 
	mTargetWeight = target_value; 
	setWeight(target_value, set_by_user); 
	mIsAnimating = TRUE;
	if (mNext)
	{
		mNext->setAnimationTarget(target_value, set_by_user);
	}
}

void LLTexLayerParamAlpha::animate(F32 delta, BOOL set_by_user)
{
	if (mNext)
	{
		mNext->animate(delta, set_by_user);
	}
}

BOOL LLTexLayerParamAlpha::getSkip()
{
	LLVOAvatar *avatar = mTexLayer->getTexLayerSet()->getAvatar();

	if( getInfo()->mSkipIfZeroWeight )
	{
		F32 effective_weight = ( avatar->getSex() & getSex() ) ? mCurWeight : getDefaultWeight();
		if (is_approx_zero( effective_weight )) 
		{
			return TRUE;
		}
	}

	EWearableType type = (EWearableType)getWearableType();
	if( (type != WT_INVALID) && !avatar->isWearingWearableType( type ) )
	{
		return TRUE;
	}

	return FALSE;
}


BOOL LLTexLayerParamAlpha::render( S32 x, S32 y, S32 width, S32 height )
{
	BOOL success = TRUE;

	F32 effective_weight = ( mTexLayer->getTexLayerSet()->getAvatar()->getSex() & getSex() ) ? mCurWeight : getDefaultWeight();
	BOOL weight_changed = effective_weight != mCachedEffectiveWeight;
	if( getSkip() )
	{
		return success;
	}

	gGL.flush();
	if( getInfo()->mMultiplyBlend )
	{
		gGL.blendFunc(LLRender::BF_DEST_ALPHA, LLRender::BF_ZERO); // Multiplication: approximates a min() function
	}
	else
	{
		gGL.setSceneBlendType(LLRender::BT_ADD);  // Addition: approximates a max() function
	}

	if( !getInfo()->mStaticImageFileName.empty() && !mStaticImageInvalid)
	{
		if( mStaticImageTGA.isNull() )
		{
			// Don't load the image file until we actually need it the first time.  Like now.
			mStaticImageTGA = gTexStaticImageList.getImageTGA( getInfo()->mStaticImageFileName );  
			// We now have something in one of our caches
			LLTexLayerSet::sHasCaches |= mStaticImageTGA.notNull() ? TRUE : FALSE;

			if( mStaticImageTGA.isNull() )
			{
				llwarns << "Unable to load static file: " << getInfo()->mStaticImageFileName << llendl;
				mStaticImageInvalid = TRUE; // don't try again.
				return FALSE;
			}
		}

		const S32 image_tga_width = mStaticImageTGA->getWidth();
		const S32 image_tga_height = mStaticImageTGA->getHeight(); 
		if(	!mCachedProcessedImageGL ||
			(mCachedProcessedImageGL->getWidth() != image_tga_width) ||
			(mCachedProcessedImageGL->getHeight() != image_tga_height) ||
			(weight_changed) )
		{
//			llinfos << "Building Cached Alpha: " << mName << ": (" << mStaticImageRaw->getWidth() << ", " << mStaticImageRaw->getHeight() << ") " << effective_weight << llendl;
			mCachedEffectiveWeight = effective_weight;

			if( !mCachedProcessedImageGL )
			{
				mCachedProcessedImageGL = new LLImageGL( image_tga_width, image_tga_height, 1, FALSE);

				// We now have something in one of our caches
				LLTexLayerSet::sHasCaches |= mCachedProcessedImageGL ? TRUE : FALSE;

				mCachedProcessedImageGL->setExplicitFormat( GL_ALPHA8, GL_ALPHA );
			}

			// Applies domain and effective weight to data as it is decoded. Also resizes the raw image if needed.
			mStaticImageRaw = NULL;
			mStaticImageRaw = new LLImageRaw;
			mStaticImageTGA->decodeAndProcess( mStaticImageRaw, getInfo()->mDomain, effective_weight );
			mNeedsCreateTexture = TRUE;
		}

		if( mCachedProcessedImageGL )
		{
			{
				// Create the GL texture, and then hang onto it for future use.
				if( mNeedsCreateTexture )
				{
					mCachedProcessedImageGL->createGLTexture(0, mStaticImageRaw);
					mNeedsCreateTexture = FALSE;
					gGL.getTexUnit(0)->bind(mCachedProcessedImageGL);
					mCachedProcessedImageGL->setAddressMode(LLTexUnit::TAM_CLAMP);
				}

				LLGLSNoAlphaTest gls_no_alpha_test;
				gGL.getTexUnit(0)->bind(mCachedProcessedImageGL);
				gl_rect_2d_simple_tex( width, height );
				gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
				stop_glerror();
			}
		}

		// Don't keep the cache for other people's avatars
		// (It's not really a "cache" in that case, but the logic is the same)
		if( !mTexLayer->getTexLayerSet()->getAvatar()->isSelf() )
		{
			mCachedProcessedImageGL = NULL;
		}
	}
	else
	{
		LLGLDisable no_alpha(GL_ALPHA_TEST);
		gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
		gGL.color4f( 0.f, 0.f, 0.f, effective_weight );
		gl_rect_2d_simple( width, height );
	}

	return success;
}

//-----------------------------------------------------------------------------
// LLTexGlobalColorInfo
//-----------------------------------------------------------------------------

LLTexGlobalColorInfo::LLTexGlobalColorInfo()
{
}


LLTexGlobalColorInfo::~LLTexGlobalColorInfo()
{
	for_each(mColorInfoList.begin(), mColorInfoList.end(), DeletePointer());
}

BOOL LLTexGlobalColorInfo::parseXml(LLXmlTreeNode* node)
{
	// name attribute
	static LLStdStringHandle name_string = LLXmlTree::addAttributeString("name");
	if( !node->getFastAttributeString( name_string, mName ) )
	{
		llwarns << "<global_color> element is missing name attribute." << llendl;
		return FALSE;
	}
	// <param> sub-element
	for (LLXmlTreeNode* child = node->getChildByName( "param" );
		 child;
		 child = node->getNextNamedChild())
	{
		if( child->getChildByName( "param_color" ) )
		{
			// <param><param_color/></param>
			LLTexParamColorInfo* info = new LLTexParamColorInfo();
			if (!info->parseXml(child))
			{
				delete info;
				return FALSE;
			}
			mColorInfoList.push_back( info );
		}
	}
	return TRUE;
}

//-----------------------------------------------------------------------------
// LLTexGlobalColor
//-----------------------------------------------------------------------------

LLTexGlobalColor::LLTexGlobalColor( LLVOAvatar* avatar )
	:
	mAvatar( avatar ),
	mInfo( NULL )
{
}


LLTexGlobalColor::~LLTexGlobalColor()
{
	// mParamList are LLViewerVisualParam's and get deleted with ~LLCharacter()
	//std::for_each(mParamList.begin(), mParamList.end(), DeletePointer());
}

BOOL LLTexGlobalColor::setInfo(LLTexGlobalColorInfo *info)
{
	llassert(mInfo == NULL);
	mInfo = info;
	//mID = info->mID; // No ID

	LLTexGlobalColorInfo::color_info_list_t::iterator iter;
	mParamList.reserve(mInfo->mColorInfoList.size());
	for (iter = mInfo->mColorInfoList.begin(); iter != mInfo->mColorInfoList.end(); iter++)
	{
		LLTexParamColor* param_color = new LLTexParamColor( this );
		if (!param_color->setInfo(*iter))
		{
			mInfo = NULL;
			return FALSE;
		}
		mParamList.push_back( param_color );
	}
	
	return TRUE;
}

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

LLColor4 LLTexGlobalColor::getColor()
{
	// Sum of color params
	if( !mParamList.empty() )
	{
		LLColor4 net_color( 0.f, 0.f, 0.f, 0.f );
		
		for( param_list_t::iterator iter = mParamList.begin();
			 iter != mParamList.end(); iter++ )
		{
			LLTexParamColor* param = *iter;
			LLColor4 param_net = param->getNetColor();
			switch( param->getOperation() )
			{
			case OP_ADD:
				net_color += param_net;
				break;
			case OP_MULTIPLY:
				net_color.mV[VX] *= param_net.mV[VX];
				net_color.mV[VY] *= param_net.mV[VY];
				net_color.mV[VZ] *= param_net.mV[VZ];
				net_color.mV[VW] *= param_net.mV[VW];
				break;
			case OP_BLEND:
				net_color = lerp(net_color, param_net, param->getWeight());
				break;
			default:
				llassert(0);
				break;
			}
		}
	
		net_color.mV[VX] = llclampf( net_color.mV[VX] );
		net_color.mV[VY] = llclampf( net_color.mV[VY] );
		net_color.mV[VZ] = llclampf( net_color.mV[VZ] );
		net_color.mV[VW] = llclampf( net_color.mV[VW] );

		return net_color;
	}
	return LLColor4( 1.f, 1.f, 1.f, 1.f );
}

//-----------------------------------------------------------------------------
// LLTexParamColorInfo
//-----------------------------------------------------------------------------
LLTexParamColorInfo::LLTexParamColorInfo()
	:
	mOperation( OP_ADD ),
	mNumColors( 0 )
{
}

BOOL LLTexParamColorInfo::parseXml(LLXmlTreeNode *node)
{
	llassert( node->hasName( "param" ) && node->getChildByName( "param_color" ) );

	if (!LLViewerVisualParamInfo::parseXml(node))
		return FALSE;

	LLXmlTreeNode* param_color_node = node->getChildByName( "param_color" );
	if( !param_color_node )
	{
		return FALSE;
	}

	std::string op_string;
	static LLStdStringHandle operation_string = LLXmlTree::addAttributeString("operation");
	if( param_color_node->getFastAttributeString( operation_string, op_string ) )
	{
		LLStringUtil::toLower(op_string);
		if		( op_string == "add" ) 		mOperation = OP_ADD;
		else if	( op_string == "multiply" )	mOperation = OP_MULTIPLY;
		else if	( op_string == "blend" )	mOperation = OP_BLEND;
	}

	mNumColors = 0;

	LLColor4U color4u;
	for (LLXmlTreeNode* child = param_color_node->getChildByName( "value" );
		 child;
		 child = param_color_node->getNextNamedChild())
	{
		if( (mNumColors < MAX_COLOR_VALUES) )
		{
			static LLStdStringHandle color_string = LLXmlTree::addAttributeString("color");
			if( child->getFastAttributeColor4U( color_string, color4u ) )
			{
				mColors[ mNumColors ].setVec(color4u);
				mNumColors++;
			}
		}
	}
	if( !mNumColors )
	{
		llwarns << "<param_color> is missing <value> sub-elements" << llendl;
		return FALSE;
	}

	if( (mOperation == OP_BLEND) && (mNumColors != 1) )
	{
		llwarns << "<param_color> with operation\"blend\" must have exactly one <value>" << llendl;
		return FALSE;
	}
	
	return TRUE;
}

//-----------------------------------------------------------------------------
// LLTexParamColor
//-----------------------------------------------------------------------------
LLTexParamColor::LLTexParamColor( LLTexGlobalColor* tex_global_color )
	:
	mAvgDistortionVec(1.f, 1.f, 1.f),
	mTexGlobalColor( tex_global_color ),
	mTexLayer( NULL ),
	mAvatar( tex_global_color->getAvatar() )
{
}

LLTexParamColor::LLTexParamColor( LLTexLayer* layer )
	:
	mAvgDistortionVec(1.f, 1.f, 1.f),
	mTexGlobalColor( NULL ),
	mTexLayer( layer ),
	mAvatar( layer->getTexLayerSet()->getAvatar() )
{
}


LLTexParamColor::~LLTexParamColor()
{
}

//-----------------------------------------------------------------------------
// setInfo()
//-----------------------------------------------------------------------------

BOOL LLTexParamColor::setInfo(LLTexParamColorInfo *info)
{
	llassert(mInfo == NULL);
	if (info->mID < 0)
		return FALSE;
	mID = info->mID;
	mInfo = info;

	mAvatar->addVisualParam( this );
	setWeight( getDefaultWeight(), FALSE );

	return TRUE;
}

LLColor4 LLTexParamColor::getNetColor()
{
	llassert( getInfo()->mNumColors >= 1 );

	F32 effective_weight = ( mAvatar && (mAvatar->getSex() & getSex()) ) ? mCurWeight : getDefaultWeight();

	S32 index_last = getInfo()->mNumColors - 1;
	F32 scaled_weight = effective_weight * index_last;
	S32 index_start = (S32) scaled_weight;
	S32 index_end = index_start + 1;
	if( index_start == index_last )
	{
		return getInfo()->mColors[index_last];
	}
	else
	{
		F32 weight = scaled_weight - index_start;
		const LLColor4 *start = &getInfo()->mColors[ index_start ];
		const LLColor4 *end   = &getInfo()->mColors[ index_end ];
		return LLColor4( 
			(1.f - weight) * start->mV[VX] + weight * end->mV[VX],
			(1.f - weight) * start->mV[VY] + weight * end->mV[VY],
			(1.f - weight) * start->mV[VZ] + weight * end->mV[VZ],
			(1.f - weight) * start->mV[VW] + weight * end->mV[VW] );
	}
}

void LLTexParamColor::setWeight(F32 weight, BOOL set_by_user)
{
	if (mIsAnimating)
	{
		return;
	}
	F32 min_weight = getMinWeight();
	F32 max_weight = getMaxWeight();
	F32 new_weight = llclamp(weight, min_weight, max_weight);
	U8 cur_u8 = F32_to_U8( mCurWeight, min_weight, max_weight );
	U8 new_u8 = F32_to_U8( new_weight, min_weight, max_weight );
	if( cur_u8 != new_u8)
	{
		mCurWeight = new_weight;

		if( getInfo()->mNumColors <= 0 )
		{
			// This will happen when we set the default weight the first time.
			return;
		}

		if( mAvatar->getSex() & getSex() )
		{
			if( mTexGlobalColor )
			{
				mAvatar->onGlobalColorChanged( mTexGlobalColor, set_by_user );
			}
			else
			if( mTexLayer )
			{
				mAvatar->invalidateComposite( mTexLayer->getTexLayerSet(), set_by_user );
			}
		}
//		llinfos << "param " << mName << " = " << new_weight << llendl;
	}
}

void LLTexParamColor::setAnimationTarget(F32 target_value, BOOL set_by_user)
{ 
	// set value first then set interpolating flag to ignore further updates
	mTargetWeight = target_value; 
	setWeight(target_value, set_by_user);
	mIsAnimating = TRUE;
	if (mNext)
	{
		mNext->setAnimationTarget(target_value, set_by_user);
	}
}

void LLTexParamColor::animate(F32 delta, BOOL set_by_user)
{
	if (mNext)
	{
		mNext->animate(delta, set_by_user);
	}
}


//-----------------------------------------------------------------------------
// LLTexStaticImageList
//-----------------------------------------------------------------------------

// static
LLTexStaticImageList gTexStaticImageList;
LLStringTable LLTexStaticImageList::sImageNames(16384);

LLTexStaticImageList::LLTexStaticImageList()
	:
	mGLBytes( 0 ),
	mTGABytes( 0 )
{}

LLTexStaticImageList::~LLTexStaticImageList()
{
	deleteCachedImages();
}

void LLTexStaticImageList::dumpByteCount()
{
	llinfos << "Avatar Static Textures " <<
		"KB GL:" << (mGLBytes / 1024) <<
		"KB TGA:" << (mTGABytes / 1024) << "KB" << llendl;
}

void LLTexStaticImageList::deleteCachedImages()
{
	if( mGLBytes || mTGABytes )
	{
		llinfos << "Clearing Static Textures " <<
			"KB GL:" << (mGLBytes / 1024) <<
			"KB TGA:" << (mTGABytes / 1024) << "KB" << llendl;

		//mStaticImageLists uses LLPointers, clear() will cause deletion
		
		mStaticImageListTGA.clear();
		mStaticImageListGL.clear();
		
		mGLBytes = 0;
		mTGABytes = 0;
	}
}

// Note: in general, for a given image image we'll call either getImageTga() or getImageGL().
// We call getImageTga() if the image is used as an alpha gradient.
// Otherwise, we call getImageGL()

// Returns an LLImageTGA that contains the encoded data from a tga file named file_name.
// Caches the result to speed identical subsequent requests.
LLImageTGA* LLTexStaticImageList::getImageTGA(const std::string& file_name)
{
	const char *namekey = sImageNames.addString(file_name);
	image_tga_map_t::iterator iter = mStaticImageListTGA.find(namekey);
	if( iter != mStaticImageListTGA.end() )
	{
		return iter->second;
	}
	else
	{
		std::string path;
		path = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,file_name);
		LLPointer<LLImageTGA> image_tga = new LLImageTGA( path );
		if( image_tga->getDataSize() > 0 )
		{
			mStaticImageListTGA[ namekey ] = image_tga;
			mTGABytes += image_tga->getDataSize();
			return image_tga;
		}
		else
		{
			return NULL;
		}
	}
}



// Returns a GL Image (without a backing ImageRaw) that contains the decoded data from a tga file named file_name.
// Caches the result to speed identical subsequent requests.
LLImageGL* LLTexStaticImageList::getImageGL(const std::string& file_name, BOOL is_mask )
{
	LLPointer<LLImageGL> image_gl;
	const char *namekey = sImageNames.addString(file_name);

	image_gl_map_t::iterator iter = mStaticImageListGL.find(namekey);
	if( iter != mStaticImageListGL.end() )
	{
		image_gl = iter->second;
	}
	else
	{
		image_gl = new LLImageGL( FALSE );
		LLPointer<LLImageRaw> image_raw = new LLImageRaw;
		if( loadImageRaw( file_name, image_raw ) )
		{
			if( (image_raw->getComponents() == 1) && is_mask )
			{
				// Note: these are static, unchanging images so it's ok to assume
				// that once an image is a mask it's always a mask.
				image_gl->setExplicitFormat( GL_ALPHA8, GL_ALPHA );
			}
			image_gl->createGLTexture(0, image_raw);

			gGL.getTexUnit(0)->bind(image_gl);
			image_gl->setAddressMode(LLTexUnit::TAM_CLAMP);

			mStaticImageListGL [ namekey ] = image_gl;
			mGLBytes += (S32)image_gl->getWidth() * image_gl->getHeight() * image_gl->getComponents();
		}
		else
		{
			image_gl = NULL;
		}
	}

	return image_gl;
}

// Reads a .tga file, decodes it, and puts the decoded data in image_raw.
// Returns TRUE if successful.
BOOL LLTexStaticImageList::loadImageRaw( const std::string& file_name, LLImageRaw* image_raw )
{
	BOOL success = FALSE;
	std::string path;
	path = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,file_name);
	LLPointer<LLImageTGA> image_tga = new LLImageTGA( path );
	if( image_tga->getDataSize() > 0 )
	{
		// Copy data from tga to raw.
		success = image_tga->decode( image_raw );
	}

	return success;
}

//-----------------------------------------------------------------------------
// LLMaskedMorph()
//-----------------------------------------------------------------------------
LLMaskedMorph::LLMaskedMorph( LLPolyMorphTarget *morph_target, BOOL invert ) : mMorphTarget(morph_target), mInvert(invert)
{
	morph_target->addPendingMorphMask();
}