summaryrefslogtreecommitdiff
path: root/materialsystem/ctexturecompositor.cpp
blob: 88683b18d7279bc809a6c1f54087adb864f5d59e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
//========= Copyright Valve Corporation, All rights reserved. ================================== //
//
// Purpose: 
//
//============================================================================================== //

#include "pch_materialsystem.h"
#include "ctexturecompositor.h"

#include "materialsystem/itexture.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/combineoperations.h"
#include "texturemanager.h"

#define MATSYS_INTERNAL // Naughty!
#include "cmaterialsystem.h"

#include "tier0/memdbgon.h"

#ifndef _WINDOWS
#define sscanf_s sscanf
#endif

// If this is 0 or unset, we won't use the caching functionality.
#define WITH_TEX_COMPOSITE_CACHE 1

#ifdef STAGING_ONLY // Always should remain staging only.
	ConVar r_texcomp_dump( "r_texcomp_dump", "0", FCVAR_NONE, "Whether we should dump the textures to disk or not. 1: Save all; 2: Save Final; 3: Save Final with name suitable for scripting; 4: Save Final and skip saving workshop icons." );
#endif

const int cMaxSelectors = 16;

// Ugh, this is annoying and matches TF's enums. That's lame. We should workaround this.
enum { Neutral = 0, Red = 2, Blue = 3 };

static int s_nDumpCount = 0;
static CInterlockedInt s_nCompositeCount = 0;

void ComputeTextureMatrixFromRectangle( VMatrix* pOutMat, const Vector2D& bl, const Vector2D& tl, const Vector2D& tr );
bool HasCycle( CTextureCompositorTemplate* pStartTempl );
CTextureCompositorTemplate* Advance( CTextureCompositorTemplate* pTmpl, int nSteps );
void PrintMinimumCycle( CTextureCompositorTemplate* pStartTempl );

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
struct CTCStageResult_t
{
	ITexture* m_pTexture;
	ITexture* m_pRenderTarget;

	float m_fAdjustBlackPoint;
	float m_fAdjustWhitePoint;
	float m_fAdjustGamma;

	matrix3x4_t m_mUvAdjust;

	inline CTCStageResult_t() 
	: m_pTexture(NULL)
	, m_pRenderTarget(NULL)
	, m_fAdjustBlackPoint(0.0f)
	, m_fAdjustWhitePoint(1.0f)
	, m_fAdjustGamma(1.0f)
	{
		SetIdentityMatrix( m_mUvAdjust );
	}

	inline void Cleanup( CTextureCompositor* _comp )
	{
		if ( m_pRenderTarget )
			_comp->ReleaseCompositorRenderTarget( m_pRenderTarget );

		m_pTexture = NULL;
		m_pRenderTarget = NULL;
	}
};

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
class CTCStage : public IAsyncTextureOperationReceiver
{
public:
	CTCStage();

protected:
	// Called by Release()
	virtual ~CTCStage();

public:
	// IAsyncTextureOperationReceiver
	virtual int AddRef() OVERRIDE;
	virtual int Release() OVERRIDE;
	virtual int GetRefCount() const OVERRIDE { return m_nReferenceCount; }
	virtual void OnAsyncCreateComplete( ITexture* pTex, void* pExtraArgs ) OVERRIDE { } 
	virtual void OnAsyncFindComplete( ITexture* pTex, void* pExtraArgs ) OVERRIDE { }
	virtual void OnAsyncMapComplete( ITexture* pTex, void* pExtraArgs, void* pMemory, int pPitch ) OVERRIDE { }
	virtual void OnAsyncReadbackBegin( ITexture* pDst, ITexture* pSrc, void* pExtraArgs ) OVERRIDE { }


	// Our stuff.
	void Resolve( bool bFirstTime, CTextureCompositor* _comp );
	inline ECompositeResolveStatus GetResolveStatus() const { return m_ResolveStatus; }
	inline const CTCStageResult_t& GetResult() const { Assert( GetResolveStatus() == ECRS_Complete ); return m_Result; }

	bool HasTeamSpecifics() const;
	void ComputeRandomValues( int* pCurIndex, CUniformRandomStream* pRNGs, int nRNGCount );

	inline void SetFirstChild( CTCStage* _stage ) { m_pFirstChild = _stage; }
	inline void SetNextSibling( CTCStage* _stage ) { m_pNextSibling = _stage; }

	inline CTCStage* GetFirstChild() { return m_pFirstChild; }
	inline CTCStage* GetNextSibling() { return m_pNextSibling; }

	inline const CTCStage* GetFirstChild() const { return m_pFirstChild; }
	inline const CTCStage* GetNextSibling() const { return m_pNextSibling; }

	void AppendChildren( const CUtlVector< CTCStage* >& _children )
	{
		// Do these in reverse order, they will wind up in the right order 
		FOR_EACH_VEC_BACK( _children, i )
		{
			CTCStage* childStage = _children[i];
			childStage->SetNextSibling( GetFirstChild() );
			SetFirstChild( childStage );
		}
	}

	void CleanupChildResults( CTextureCompositor* _comp );

	// Render a quad with _mat using _inputs to _destRT
	void Render( ITexture* _destRT, IMaterial* _mat, const CUtlVector<CTCStageResult_t>& _inputs, CTextureCompositor* _comp, bool bClear ); 

	void Cleanup( CTextureCompositor* _comp );

	// Does this stage target a render target or a texture? 
	virtual bool DoesTargetRenderTarget() const = 0;

	inline void SetResult( const CTCStageResult_t& _result )
	{
		Assert( m_ResolveStatus != ECRS_Complete );
		m_Result = _result;
		m_ResolveStatus = ECRS_Complete;
	}

protected:

	inline void SetResolveStatus( ECompositeResolveStatus _status )
	{
		m_ResolveStatus = _status;
	}

	// This function is called only once during the first ResolveTraversal, and is
	// for the compositor to request its textures. Textures should not be requested
	// before this or they can be held waaaay too long.
	virtual void RequestTextures() = 0;

	// This function will be called during Resolve traversal. At the point when this is called,
	// all of this node's children will have had their resolve completed. Our siblings will
	// not have resolved yet.
	virtual void ResolveThis( CTextureCompositor* _comp ) = 0;

	// This function is called during HasTeamSpecifics traversal. 
	virtual bool HasTeamSpecificsThis() const = 0;

	virtual bool ComputeRandomValuesThis( CUniformRandomStream* pRNG ) = 0;

private:
	CInterlockedInt m_nReferenceCount;

	CTCStage* m_pFirstChild;
	CTCStage* m_pNextSibling;

	CTCStageResult_t m_Result;
	ECompositeResolveStatus m_ResolveStatus;
};

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
typedef void ( *ParseSingleKV )( KeyValues* _kv, void* _dest );
struct ParseTableEntry
{
	const char* keyName;
	ParseSingleKV parseFunc;
	size_t structOffset;
};

// ------------------------------------------------------------------------------------------------
struct Range
{
	float low;
	float high;

	Range( )
	: low( 0 )
	, high( 0 )
	{ } 

	Range( float _l, float _h )
	: low( _l )
	, high( _h )
	{ } 
};

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void ParseBoolFromKV( KeyValues* _kv, void* _pDest )
{
	bool* realDest = ( bool* ) _pDest;
	( *realDest ) = _kv->GetBool();
}

// ------------------------------------------------------------------------------------------------
template<int N>
void ParseIntVectorFromKV( KeyValues* _kv, void* _pDest )
{
	CCopyableUtlVector<int>* realDest = ( CCopyableUtlVector<int>* ) _pDest;
	const int parsedValue = _kv->GetInt();
	if ( realDest->Size() < N )
	{
		realDest->AddToTail( parsedValue );
	}
	else
	{
		DevWarning( "Too many numbers (>%d), ignoring the value '%d'.\n", N, parsedValue );
	}
}

// ------------------------------------------------------------------------------------------------
template< class T >
CUtlString AsStringT( const T& _val )
{
#ifdef _WIN32
	// Not sure why linux is unhappy here. Error messages unhelpful. Thanks, GCC.
	static_assert( false, "Must add specialization for typename T" );
#endif
	return CUtlString( "" );
}

// ------------------------------------------------------------------------------------------------
template<>
CUtlString AsStringT< int >( const int& _val )
{
	char buffer[ 12 ];
	V_sprintf_safe( buffer, "%d", _val );
	return CUtlString( buffer );
}

// ------------------------------------------------------------------------------------------------
template< class T >
void ParseTFromKV( KeyValues* _kv, void* _pDest )
{
#ifdef _WIN32
	// Not sure why linux is unhappy here. Error messages unhelpful. Thanks, GCC.
	static_assert( false, "Must add specialization for typename T" );
#endif
}

// ------------------------------------------------------------------------------------------------
template<>
void ParseTFromKV< int >( KeyValues* _kv, void* _pDest )
{
	int* realDest = ( int* ) _pDest;
	( *realDest ) = _kv->GetInt();
}

// ------------------------------------------------------------------------------------------------
template<>
void ParseTFromKV< Vector2D >( KeyValues* _kv, void* _pDest )
{
	Vector2D* realDest = ( Vector2D* ) _pDest;
	Vector2D tmpDest;
	int count = sscanf_s( _kv->GetString(), "%f %f", &tmpDest.x, &tmpDest.y );
	if  ( count != 2 )
	{
		Error( "Expected exactly two values, %d were provided.\n", count );
		return;
	}

	*realDest = tmpDest;
}

// ------------------------------------------------------------------------------------------------
template< class T, int N = INT_MAX >
void ParseVectorFromKV( KeyValues* _kv, void* _pDest )
{
	CCopyableUtlVector< T >* realDest = ( CCopyableUtlVector< T >* ) _pDest;
	
	T parsedValue = T();
	ParseTFromKV<T>( _kv, &parsedValue );

	if ( realDest->Size() < N )
	{
		realDest->AddToTail( parsedValue );
	}
	else
	{
		DevWarning( "Too many entries (>%d), ignoring the value '%s'.\n", N, AsStringT( parsedValue ).Get() );
	}
}

// ------------------------------------------------------------------------------------------------
void ParseRangeFromKV( KeyValues* _kv, void* _pDest )
{
	Range* realDest = ( Range* ) _pDest;
	Range tmpDest;

	int count = sscanf_s( _kv->GetString(), "%f %f", &tmpDest.low, &tmpDest.high );
	switch (count)
	{
	case 1:
		// If we parse one, use the same value for low and high.
		( *realDest ).low = tmpDest.low;
		( *realDest ).high = tmpDest.low;
		break;
	case 2:
		// If we parse two, they're both correct.
		( *realDest ).low = tmpDest.low;
		( *realDest ).high = tmpDest.high;
		break;

		// error cases
	case EOF:
	case 0:
	default:
		Error( "Incorrect number of numbers while parsing, using defaults. This error message should be improved\n" );
	};
}

// ------------------------------------------------------------------------------------------------
void ParseInverseRangeFromKV( KeyValues* _kv, void* _pDest )
{
	const float kSubstValue = 0.00001;
	ParseRangeFromKV( _kv, _pDest );
	Range* realDest = ( Range* ) _pDest;

	if ( realDest->low != 0.0f )
	{
		( *realDest ).low = 1.0f / realDest->low;
	}
	else
	{
		Error( "Specified 0.0 for low value, that is illegal in this field. Substituting %.5f\n", kSubstValue );
		( *realDest ).low = kSubstValue;
	}

	if ( realDest->high != 0.0f )
	{
		( *realDest ).high = 1.0f / realDest->high;
	}
	else
	{
		Error( "Specified 0.0 for high value, that is illegal in this field. Substituting %.5f\n", kSubstValue );
		( *realDest ).high = kSubstValue;
	}
}

// ------------------------------------------------------------------------------------------------
template < int Div >
void ParseRangeThenDivideBy( KeyValues *_kv, void* _pDest )
{
	static_assert( Div != 0, "Cannot specify a divisor of 0." );
	float fDiv = (float) Div;

	ParseRangeFromKV( _kv, _pDest );
	Range* realDest = ( Range* ) _pDest;

	( *realDest ).low  = ( *realDest ).low  / fDiv;
	( *realDest ).high = ( *realDest ).high / fDiv;
}

// ------------------------------------------------------------------------------------------------
void ParseStringFromKV( KeyValues* _kv, void* _pDest )
{
	CUtlString* realDest = ( CUtlString* ) _pDest;
	(*realDest) = _kv->GetString();
}

// ------------------------------------------------------------------------------------------------
struct TextureStageParameters
{
	CUtlString m_pTexFilename;
	CUtlString m_pTexRedFilename;
	CUtlString m_pTexBlueFilename;
	Range m_AdjustBlack;
	Range m_AdjustOffset;
	Range m_AdjustGamma;

	Range m_Rotation;
	Range m_TranslateU;
	Range m_TranslateV;
	Range m_ScaleUV;
	bool m_AllowFlipU;
	bool m_AllowFlipV;
	bool m_Evaluate;

	TextureStageParameters()
	: m_AdjustBlack( 0, 0 )
	, m_AdjustOffset( 1, 1 )
	, m_AdjustGamma( 1, 1 )
	, m_Rotation( 0 , 0 )
	, m_TranslateU( 0, 0 )
	, m_TranslateV( 0, 0 )
	, m_ScaleUV( 1, 1 )
	, m_AllowFlipU( false )
	, m_AllowFlipV( false )
	, m_Evaluate( true )
	{ }
};

// ------------------------------------------------------------------------------------------------
const ParseTableEntry cTextureStageParametersParseTable[] = 
{
	{ "texture",			ParseStringFromKV,				offsetof( TextureStageParameters, m_pTexFilename ) },
	{ "texture_red",		ParseStringFromKV,				offsetof( TextureStageParameters, m_pTexRedFilename ) },
	{ "texture_blue",		ParseStringFromKV,				offsetof( TextureStageParameters, m_pTexBlueFilename ) },
	{ "adjust_black",		ParseRangeThenDivideBy<255>,	offsetof( TextureStageParameters, m_AdjustBlack ) },
	{ "adjust_offset",		ParseRangeThenDivideBy<255>,	offsetof( TextureStageParameters, m_AdjustOffset ) },
	{ "adjust_gamma",		ParseInverseRangeFromKV,		offsetof( TextureStageParameters, m_AdjustGamma ) },
	{ "rotation",			ParseRangeFromKV,				offsetof( TextureStageParameters, m_Rotation ) },
	{ "translate_u",		ParseRangeFromKV,				offsetof( TextureStageParameters, m_TranslateU ) },
	{ "translate_v",		ParseRangeFromKV,				offsetof( TextureStageParameters, m_TranslateV ) },
	{ "scale_uv",			ParseRangeFromKV,				offsetof( TextureStageParameters, m_ScaleUV ) },
	{ "flip_u",				ParseBoolFromKV,				offsetof( TextureStageParameters, m_AllowFlipU ) },
	{ "flip_v",				ParseBoolFromKV,				offsetof( TextureStageParameters, m_AllowFlipV ) },
	{ "evaluate?", 			ParseBoolFromKV,				offsetof( TextureStageParameters, m_Evaluate ) },

	{ 0, 0 }
};

 // ------------------------------------------------------------------------------------------------
 // ------------------------------------------------------------------------------------------------
 // ------------------------------------------------------------------------------------------------
class CTCTextureStage : public CTCStage
{
public:
	CTCTextureStage( const TextureStageParameters& _tsp, uint32 nTexCompositeCreateFlags ) 
	: m_Parameters( _tsp ) 
	, m_pTex( NULL )
	, m_pTexRed( NULL )
	, m_pTexBlue( NULL )
	{ 
	}

	virtual ~CTCTextureStage()
	{
		SafeRelease( &m_pTex );	
		SafeRelease( &m_pTexBlue );
		SafeRelease( &m_pTexRed );
	}

	virtual void OnAsyncFindComplete( ITexture* pTex, void* pExtraArgs ) 
	{ 
		switch ( ( int ) pExtraArgs )
		{
		case Neutral:
			SafeAssign( &m_pTex, pTex ); 
			break;
		case Red:
			SafeAssign( &m_pTexRed, pTex );
			break;
		case Blue:
			SafeAssign( &m_pTexBlue, pTex );
			break;
		default:
			Assert( !"Unexpected value passed to OnAsyncFindComplete" );
			break;
		};
	}

	virtual bool DoesTargetRenderTarget() const { return false; }

protected:
	bool AreTexturesLoaded() const
	{
		if ( !m_Parameters.m_pTexFilename.IsEmpty() && !m_pTex ) 
			return false;

		if ( !m_Parameters.m_pTexRedFilename.IsEmpty() && !m_pTexRed )
			return false;

		if ( !m_Parameters.m_pTexBlueFilename.IsEmpty() && !m_pTexBlue )
			return false;

		return true;
	}

	ITexture* GetTeamSpecificTexture( int nTeam )
	{
		if ( nTeam == Red && m_pTexRed )
			return m_pTexRed;

		if ( nTeam == Blue && m_pTexBlue )
			return m_pTexBlue;

		return m_pTex;
	}

	virtual void RequestTextures()
	{
		if ( !m_Parameters.m_pTexFilename.IsEmpty() )
			materials->AsyncFindTexture( m_Parameters.m_pTexFilename.Get(), TEXTURE_GROUP_RUNTIME_COMPOSITE, this, ( void* ) Neutral, false, TEXTUREFLAGS_IMMEDIATE_CLEANUP );
		if ( !m_Parameters.m_pTexRedFilename.IsEmpty() )
			materials->AsyncFindTexture( m_Parameters.m_pTexRedFilename.Get(), TEXTURE_GROUP_RUNTIME_COMPOSITE, this, ( void* ) Red, false, TEXTUREFLAGS_IMMEDIATE_CLEANUP );
		if ( !m_Parameters.m_pTexBlueFilename.IsEmpty() )
			materials->AsyncFindTexture( m_Parameters.m_pTexBlueFilename.Get(), TEXTURE_GROUP_RUNTIME_COMPOSITE, this, ( void* ) Blue, false, TEXTUREFLAGS_IMMEDIATE_CLEANUP );	
	}

	virtual void ResolveThis( CTextureCompositor* _comp )
	{
		tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

		// We shouldn't have any children, we're going to ignore them anyways.
		Assert( GetFirstChild() == NULL );

		ECompositeResolveStatus resolveStatus = GetResolveStatus();
		// If we're done, we're done.
		if ( resolveStatus == ECRS_Complete || resolveStatus == ECRS_Error )
			return;

		if ( resolveStatus == ECRS_Scheduled )
			SetResolveStatus( ECRS_PendingTextureLoads );

		// Someone is misusing this node if this assert fires.
		Assert( GetResolveStatus() == ECRS_PendingTextureLoads );

		// When the texture has finished loading, this will be set to the texture we should use.
		if ( !AreTexturesLoaded() )
			return;

		if ( !m_pTex && !m_pTexRed && !m_pTexBlue )
		{
			_comp->Error( false, "Invalid texture_lookup node, must specify at least texture (or texture_red and texture_blue) or all of them.\n" );
			return;
		}

		if ( m_pTex && m_pTex->IsError() )
		{
			_comp->Error( false, "Failed to load texture '%s', this is non-recoverable.\n", m_Parameters.m_pTexFilename.Get() );
			return;
		}

		if ( m_pTexRed && m_pTexRed->IsError() )
		{
			_comp->Error( false, "Failed to load texture_red '%s', this is non-recoverable.\n", m_Parameters.m_pTexRedFilename.Get() );
			return;
		}

		if ( m_pTexBlue && m_pTexBlue->IsError() )
		{
			_comp->Error( false, "Failed to load texture_blue '%s', this is non-recoverable.\n", m_Parameters.m_pTexBlueFilename.Get() );
			return;
		}

		CTCStageResult_t res;
		res.m_pTexture = GetTeamSpecificTexture( _comp->GetTeamNumber() );
		res.m_fAdjustBlackPoint = m_fAdjustBlack;
		res.m_fAdjustWhitePoint = m_fAdjustWhite;
		res.m_fAdjustGamma      = m_fAdjustGamma;
		// Store the matrix into the uv adjustment matrix
		m_mTextureAdjust.Set3x4( res.m_mUvAdjust );

		SetResult( res );

		CleanupChildResults( _comp );
		tmMessage( TELEMETRY_LEVEL0, TMMF_ICON_NOTE, "Completed: %s", __FUNCTION__ );
	}

	virtual bool HasTeamSpecificsThis() const OVERRIDE
	{
		return !m_Parameters.m_pTexBlueFilename.IsEmpty();
	}

	virtual bool ComputeRandomValuesThis( CUniformRandomStream* pRNG ) OVERRIDE
	{
		// If you change the order of these random numbers being generated, or add new ones, you will
		// change the look of existing players' weapons! Don't do that.
		const bool shouldFlipU = m_Parameters.m_AllowFlipU ? pRNG->RandomInt( 0, 1 ) != 0 : false;
		const bool shouldFlipV = m_Parameters.m_AllowFlipV ? pRNG->RandomInt( 0, 1 ) != 0 : false;
		const float translateU = pRNG->RandomFloat( m_Parameters.m_TranslateU.low, m_Parameters.m_TranslateU.high );
		const float translateV = pRNG->RandomFloat( m_Parameters.m_TranslateV.low, m_Parameters.m_TranslateV.high );
		const float rotation = pRNG->RandomFloat( m_Parameters.m_Rotation.low, m_Parameters.m_Rotation.high );
		const float scaleUV = pRNG->RandomFloat( m_Parameters.m_ScaleUV.low, m_Parameters.m_ScaleUV.high );

		const float adjustBlack = pRNG->RandomFloat( m_Parameters.m_AdjustBlack.low, m_Parameters.m_AdjustBlack.high );
		const float adjustOffset = pRNG->RandomFloat( m_Parameters.m_AdjustOffset.low, m_Parameters.m_AdjustOffset.high );
		const float adjustGamma = pRNG->RandomFloat( m_Parameters.m_AdjustGamma.low, m_Parameters.m_AdjustGamma.high );
		const float adjustWhite = adjustBlack + adjustOffset;

		m_fAdjustBlack = adjustBlack;
		m_fAdjustWhite = adjustWhite;
		m_fAdjustGamma = adjustGamma;

		const float finalScaleU = scaleUV * ( shouldFlipU ? -1.0f : 1.0f );
		const float finalScaleV = scaleUV * ( shouldFlipV ? -1.0f : 1.0f );

		MatrixBuildRotateZ( m_mTextureAdjust, rotation );
		m_mTextureAdjust = m_mTextureAdjust.Scale( Vector( finalScaleU, finalScaleV, 1.0f ) );
		MatrixTranslate( m_mTextureAdjust, Vector( translateU, translateV, 0 ) );
		// Copy W into Z because we're doing a texture matrix.
		m_mTextureAdjust[ 0 ][ 2 ] = m_mTextureAdjust[ 0 ][ 3 ];
		m_mTextureAdjust[ 1 ][ 2 ] = m_mTextureAdjust[ 1 ][ 3 ];
		m_mTextureAdjust[ 2 ][ 2 ] = 1.0f;

		return true;
	}


private:
	TextureStageParameters m_Parameters;
	ITexture* m_pTex;
	ITexture* m_pTexRed;
	ITexture* m_pTexBlue;

	// Random values here
	float m_fAdjustBlack;
	float m_fAdjustWhite;
	float m_fAdjustGamma;
	VMatrix m_mTextureAdjust;
};

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

// Keep in sync with CombineOperation
const char* cCombineMaterialName[] =
{
	"dev/CompositorMultiply",
	"dev/CompositorAdd",
	"dev/CompositorLerp",

	"dev/CompositorSelect",

	"\0 ECO_Legacy_Lerp_FirstPass", // Procedural; starting with \0 will skip precaching
	"\0 ECO_Legacy_Lerp_SecondPass", // Procedural; starting with \0 will skip precaching

	"dev/CompositorBlend",

	"\0 ECO_LastPrecacheMaterial", // 

	"CompositorError",

	NULL
};

static_assert( ARRAYSIZE( cCombineMaterialName ) == ECO_COUNT + 1, "cCombineMaterialName and ECombineOperation are out of sync." );

// ------------------------------------------------------------------------------------------------
struct CombineStageParameters
{
	ECombineOperation m_CombineOp;
	Range m_AdjustBlack;
	Range m_AdjustOffset;
	Range m_AdjustGamma;

	Range m_Rotation;
	Range m_TranslateU;
	Range m_TranslateV;
	Range m_ScaleUV;

	bool m_AllowFlipU;
	bool m_AllowFlipV;
	bool m_Evaluate;

	CombineStageParameters()
	: m_CombineOp( ECO_Error )
	, m_AdjustBlack( 0, 0 )
	, m_AdjustOffset( 1, 1 )
	, m_AdjustGamma( 1, 1 )
	, m_Rotation( 0 , 0 )
	, m_TranslateU( 0, 0 )
	, m_TranslateV( 0, 0 )
	, m_ScaleUV( 1, 1 )
	, m_AllowFlipU( false )
	, m_AllowFlipV( false )
	, m_Evaluate( true )
	{ }

};

// ------------------------------------------------------------------------------------------------
void ParseOperationFromKV( KeyValues* _kv, void* _pDest )
{
	ECombineOperation* realDest = ( ECombineOperation* ) _pDest;
	const char* opStr = _kv->GetString();

	if ( V_stricmp( "multiply", opStr ) == 0 )
		(*realDest) = ECO_Multiply;
	else if ( V_stricmp( "add", opStr ) == 0 )
		(*realDest) = ECO_Add;
	else if ( V_stricmp( "lerp", opStr) == 0 )
		(*realDest) = ECO_Lerp;
	else
		(*realDest) = ECO_Error;
}

// ------------------------------------------------------------------------------------------------
const ParseTableEntry cCombineStageParametersParseTable[] = 
{
	{ "adjust_black",	ParseRangeThenDivideBy<255>,	offsetof( CombineStageParameters, m_AdjustBlack ) },
	{ "adjust_offset",	ParseRangeThenDivideBy<255>,	offsetof( CombineStageParameters, m_AdjustOffset ) },
	{ "adjust_gamma",	ParseInverseRangeFromKV,		offsetof( CombineStageParameters, m_AdjustGamma ) },
	{ "rotation",		ParseRangeFromKV,				offsetof( CombineStageParameters, m_Rotation ) },
	{ "translate_u",	ParseRangeFromKV,				offsetof( CombineStageParameters, m_TranslateU ) },
	{ "translate_v",	ParseRangeFromKV,				offsetof( CombineStageParameters, m_TranslateV ) },
	{ "scale_uv",		ParseRangeFromKV,				offsetof( CombineStageParameters, m_ScaleUV ) },
	{ "flip_u",			ParseBoolFromKV,				offsetof( CombineStageParameters, m_AllowFlipU ) },
	{ "flip_v",			ParseBoolFromKV,				offsetof( CombineStageParameters, m_AllowFlipV ) },
	{ "evaluate?", 		ParseBoolFromKV,				offsetof( CombineStageParameters, m_Evaluate ) },

	{ 0, 0 }
};

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
class CTCCombineStage : public CTCStage 
{
public:
	CTCCombineStage( const CombineStageParameters& _csp, uint32 nTexCompositeCreateFlags )
	: m_Parameters( _csp ) 
	, m_pMaterial( NULL )
	{ 
		Assert( m_Parameters.m_CombineOp >= 0 && m_Parameters.m_CombineOp < ECO_COUNT );

		SafeAssign( &m_pMaterial, materials->FindMaterial( cCombineMaterialName[ m_Parameters.m_CombineOp ], TEXTURE_GROUP_RUNTIME_COMPOSITE ) );
	} 

	virtual ~CTCCombineStage() 
	{ 
		SafeRelease( &m_pMaterial );
	} 

	virtual bool DoesTargetRenderTarget() const { return true; }


protected:
	virtual void RequestTextures() { /* No textures here */ }

	virtual void ResolveThis( CTextureCompositor* _comp )
	{
		tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

		ECompositeResolveStatus resolveStatus = GetResolveStatus();
		// If we're done, we're done.
		if ( resolveStatus == ECRS_Complete || resolveStatus == ECRS_Error )
			return;

		if ( resolveStatus == ECRS_Scheduled )
			SetResolveStatus( ECRS_PendingTextureLoads );

		// Someone is misusing this node if this assert fires.
		Assert( GetResolveStatus() == ECRS_PendingTextureLoads );

		for ( CTCStage* child = GetFirstChild(); child; child = child->GetNextSibling() )
		{
			// If any child isn't ready to go, we're not ready to go.
			if ( child->GetResolveStatus() != ECRS_Complete )
				return;
		}
		
		ITexture* pRenderTarget = _comp->AllocateCompositorRenderTarget();

		CUtlVector<CTCStageResult_t> results;
		uint childCount = 0;
		for ( CTCStage* child = GetFirstChild(); child; child = child->GetNextSibling() )
		{
			results.AddToTail( child->GetResult() );
			++childCount;
		}

		// TODO: If there are more than 8 children, need to split them into multiple groups here. Skip it for now.

		Render( pRenderTarget, m_pMaterial, results, _comp, true );

		CTCStageResult_t res;
		res.m_pRenderTarget = pRenderTarget;
		res.m_fAdjustBlackPoint = m_fAdjustBlack;
		res.m_fAdjustWhitePoint = m_fAdjustWhite;
		res.m_fAdjustGamma      = m_fAdjustGamma;

		SetResult( res );

		// As soon as we have scheduled the read of a child render target, we can release that 
		// texture back to the pool for use by another stage. Everything is pipelined, so this just
		// works.
		CleanupChildResults( _comp );
		tmMessage( TELEMETRY_LEVEL0, TMMF_ICON_NOTE, "Completed: %s", __FUNCTION__ );
	}

	virtual bool HasTeamSpecificsThis() const OVERRIDE{ return false; }

	virtual bool ComputeRandomValuesThis( CUniformRandomStream* pRNG ) OVERRIDE
	{
		const float adjustBlack = pRNG->RandomFloat( m_Parameters.m_AdjustBlack.low, m_Parameters.m_AdjustBlack.high );
		const float adjustOffset = pRNG->RandomFloat( m_Parameters.m_AdjustOffset.low, m_Parameters.m_AdjustOffset.high );
		const float adjustGamma = pRNG->RandomFloat( m_Parameters.m_AdjustGamma.low, m_Parameters.m_AdjustGamma.high );
		const float adjustWhite = adjustBlack + adjustOffset;

		m_fAdjustBlack = adjustBlack;
		m_fAdjustWhite = adjustWhite;
		m_fAdjustGamma = adjustGamma;

		return true;
	}

private:
	CombineStageParameters m_Parameters;
	IMaterial* m_pMaterial;

	float m_fAdjustBlack;
	float m_fAdjustWhite;
	float m_fAdjustGamma;
};

// ------------------------------------------------------------------------------------------------
struct SelectStageParameters
{
	CUtlString m_pTexFilename;
	CCopyableUtlVector<int> m_Select;
	bool m_Evaluate;

	SelectStageParameters()
	: m_Evaluate( true )
	{ 
	}
};

// ------------------------------------------------------------------------------------------------
const ParseTableEntry cSelectStageParametersParseTable[] = 
{
	{ "groups",		ParseStringFromKV,							offsetof( SelectStageParameters, m_pTexFilename ) },
	{ "select",		ParseVectorFromKV< int, cMaxSelectors >,	offsetof( SelectStageParameters, m_Select ) },
	{ "evaluate?", 	ParseBoolFromKV,							offsetof( SelectStageParameters, m_Evaluate ) },

	{ 0, 0 }
};

 // ------------------------------------------------------------------------------------------------
 // ------------------------------------------------------------------------------------------------
 // ------------------------------------------------------------------------------------------------
class CTCSelectStage : public CTCStage
{
public:
	CTCSelectStage( const SelectStageParameters& _ssp, uint32 nTexCompositeCreateFlags ) 
	: m_Parameters( _ssp ) 
	, m_pMaterial( NULL ) 
	, m_pTex( NULL )
	{ 
		SafeAssign( &m_pMaterial, materials->FindMaterial( cCombineMaterialName[ ECO_Select ], TEXTURE_GROUP_RUNTIME_COMPOSITE ) );
	}
	virtual ~CTCSelectStage() 
	{ 
		SafeRelease( &m_pMaterial );
		SafeRelease( &m_pTex );
	}

	virtual void OnAsyncFindComplete( ITexture* pTex, void* pExtraArgs ) { SafeAssign( &m_pTex, pTex ); }

	virtual bool DoesTargetRenderTarget() const { return true; }


protected:
	virtual void RequestTextures() 
	{
		materials->AsyncFindTexture( m_Parameters.m_pTexFilename.Get(), TEXTURE_GROUP_RUNTIME_COMPOSITE, this, NULL, false, TEXTUREFLAGS_IMMEDIATE_CLEANUP );
	}

	virtual void ResolveThis( CTextureCompositor* _comp )
	{
		tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

		// We shouldn't have any children, we're going to ignore them anyways.
		Assert( GetFirstChild() == NULL );

		ECompositeResolveStatus resolveStatus = GetResolveStatus();
		// If we're done, we're done.
		if ( resolveStatus == ECRS_Complete || resolveStatus == ECRS_Error )
			return;

		if ( resolveStatus == ECRS_Scheduled )
			SetResolveStatus( ECRS_PendingTextureLoads );

		// Someone is misusing this node if this assert fires.
		Assert( GetResolveStatus() == ECRS_PendingTextureLoads );

		// When the texture has finished loading, this will be set to the texture we should use.
		if ( m_pTex == NULL )
			return;

		if ( m_pTex->IsError() )
		{
			_comp->Error( false, "Failed to load texture %s, this is non-recoverable.\n", m_Parameters.m_pTexFilename.Get() );
			return;
		}

		ITexture* pRenderTarget = _comp->AllocateCompositorRenderTarget();

		char buffer[128];
		for ( int i = 0; i < cMaxSelectors; ++i )
		{
			bool bFound = false;

			V_snprintf( buffer, ARRAYSIZE( buffer ), "$selector%d", i );
			IMaterialVar* pVar = m_pMaterial->FindVar( buffer, &bFound );
			Assert(bFound);
			if ( i < m_Parameters.m_Select.Size() )
				pVar->SetIntValue( m_Parameters.m_Select[i] );
			else
				pVar->SetIntValue( 0 );
		}

		CTCStageResult_t inRes;
		inRes.m_pTexture = m_pTex;
		CUtlVector<CTCStageResult_t> fakeResults;
		fakeResults.AddToTail( inRes );
		Render( pRenderTarget, m_pMaterial, fakeResults, _comp, true );

		CTCStageResult_t outRes;
		outRes.m_pRenderTarget = pRenderTarget;
		SetResult( outRes );

		CleanupChildResults( _comp );
		tmMessage( TELEMETRY_LEVEL0, TMMF_ICON_NOTE, "Completed: %s", __FUNCTION__ );
	}

	virtual bool HasTeamSpecificsThis() const OVERRIDE { return false; }

	virtual bool ComputeRandomValuesThis( CUniformRandomStream* pRNG ) OVERRIDE
	{
		// No RNG here.
		return false;
	}

private:
	SelectStageParameters m_Parameters;
	IMaterial* m_pMaterial;
	ITexture* m_pTex;
};

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
struct Sticker_t
{
	float m_fWeight;				// Random likelihood this one is to be selected
	CUtlString m_baseFilename;	// Name of the base file for the sticker (the albedo). 
	CUtlString m_specFilename;	// Name of the specular file for the sticker, or if blank we will assume it is baseFilename + _spec + baseExtension
	
	Sticker_t()
	: m_fWeight( 1.0 )
	{ }
};

// ------------------------------------------------------------------------------------------------
template<>
void ParseTFromKV< Sticker_t >( KeyValues* _kv, void* _pDest )
{
	Sticker_t* realDest = ( Sticker_t* ) _pDest;
	Sticker_t tmpDest;

	tmpDest.m_fWeight = _kv->GetFloat( "weight", 1.0 );
	tmpDest.m_baseFilename = _kv->GetString( "base" );
	KeyValues* pSpec = _kv->FindKey( "spec" );
	if ( pSpec ) 
		tmpDest.m_specFilename = pSpec->GetString();	
	else
	{
		CUtlString specPath = tmpDest.m_baseFilename.StripExtension() 
							+ "_s" 
							+ tmpDest.m_baseFilename.GetExtension();

		tmpDest.m_specFilename = specPath;
	}

	*realDest = tmpDest;
}

// ------------------------------------------------------------------------------------------------
template <>
CUtlString AsStringT< Sticker_t >( const Sticker_t& _val )
{
	char buffer[ 80 ];
	V_sprintf_safe( buffer, "[ weight %.2f; base \"%s\"; spec \"%s\" ]", _val.m_fWeight, _val.m_baseFilename.Get(), _val.m_specFilename.Get() );
	return CUtlString( buffer );
}

// ------------------------------------------------------------------------------------------------
template< class T >
struct Settable_t
{
	T m_val;
	bool m_bSet;

	Settable_t()
	: m_val( T() )
	, m_bSet( false )
	{ }
};

// ------------------------------------------------------------------------------------------------
template < class T >
void ParseSettable( KeyValues *_kv, void* _pDest )
{
	Settable_t<T> *pSettable = ( Settable_t<T>* )_pDest;

	ParseTFromKV<T>( _kv, &pSettable->m_val );
	( *pSettable ).m_bSet = true;
}

// ------------------------------------------------------------------------------------------------
struct ApplyStickerStageParameters
{
	CCopyableUtlVector< Sticker_t > m_possibleStickers; 

	Settable_t< Vector2D > m_vDestBL;
	Settable_t< Vector2D > m_vDestTL;
	Settable_t< Vector2D > m_vDestTR;

	Range m_AdjustBlack;
	Range m_AdjustOffset;
	Range m_AdjustGamma;
	bool m_Evaluate;

	ApplyStickerStageParameters()
	: m_AdjustBlack( 0, 0 )
	, m_AdjustOffset( 1, 1 )
	, m_AdjustGamma( 1, 1 )
	, m_Evaluate( true )
	{ }
};

// ------------------------------------------------------------------------------------------------
const ParseTableEntry cApplyStickerStageParametersParseTable[] = 
{
	{ "sticker",			ParseVectorFromKV< Sticker_t >, offsetof( ApplyStickerStageParameters, m_possibleStickers ) },
	{ "dest_bl",			ParseSettable< Vector2D >,		offsetof( ApplyStickerStageParameters, m_vDestBL ) },
	{ "dest_tl",			ParseSettable< Vector2D >,		offsetof( ApplyStickerStageParameters, m_vDestTL ) },
	{ "dest_tr",			ParseSettable< Vector2D >,		offsetof( ApplyStickerStageParameters, m_vDestTR ) },
	{ "adjust_black",		ParseRangeThenDivideBy< 255 >,	offsetof( ApplyStickerStageParameters, m_AdjustBlack ) },
	{ "adjust_offset",		ParseRangeThenDivideBy< 255 >,	offsetof( ApplyStickerStageParameters, m_AdjustOffset ) },
	{ "adjust_gamma",		ParseInverseRangeFromKV,		offsetof( ApplyStickerStageParameters, m_AdjustGamma ) },
	{ "evaluate?", 			ParseBoolFromKV,				offsetof( ApplyStickerStageParameters, m_Evaluate ) },

	{ 0, 0 }
};

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
class CTCApplyStickerStage : public CTCStage 
{
	enum { Albedo = 0, Specular = 1 };

public:
	CTCApplyStickerStage( const ApplyStickerStageParameters& _assp, uint32 nTexCompositeCreateFlags )
	: m_Parameters( _assp ) 
	, m_pMaterial( NULL )
	, m_pTex( NULL )
	, m_pTexSpecular( NULL )
	, m_nChoice( 0 )
	{ 
		SafeAssign( &m_pMaterial, materials->FindMaterial( cCombineMaterialName[ ECO_Blend ], TEXTURE_GROUP_RUNTIME_COMPOSITE ) );
	} 

	virtual ~CTCApplyStickerStage() 
	{ 
		SafeRelease( &m_pTex );
		SafeRelease( &m_pTexSpecular );
		SafeRelease( &m_pMaterial );
	} 

	virtual bool DoesTargetRenderTarget() const { return true; }

protected:
	bool AreTexturesLoaded() const
	{
		if ( !m_Parameters.m_possibleStickers[ m_nChoice ].m_baseFilename.IsEmpty() && !m_pTex )
			return false;

		if ( !m_Parameters.m_possibleStickers[ m_nChoice ].m_specFilename.IsEmpty() && !m_pTexSpecular )
			return false;

		return true;
	}

	virtual void RequestTextures()
	{
		if ( !m_Parameters.m_possibleStickers[ m_nChoice ].m_baseFilename.IsEmpty() )
			materials->AsyncFindTexture( m_Parameters.m_possibleStickers[ m_nChoice ].m_baseFilename.Get(), TEXTURE_GROUP_RUNTIME_COMPOSITE, this, ( void* ) Albedo, false, TEXTUREFLAGS_IMMEDIATE_CLEANUP );

		if ( !m_Parameters.m_possibleStickers[ m_nChoice ].m_specFilename.IsEmpty() )
			materials->AsyncFindTexture( m_Parameters.m_possibleStickers[ m_nChoice ].m_specFilename.Get(), TEXTURE_GROUP_RUNTIME_COMPOSITE, this, ( void* ) Specular, false, TEXTUREFLAGS_IMMEDIATE_CLEANUP );	
	}

	virtual void ResolveThis( CTextureCompositor* _comp )
	{
		tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

		ECompositeResolveStatus resolveStatus = GetResolveStatus();
		// If we're done, we're done.
		if ( resolveStatus == ECRS_Complete || resolveStatus == ECRS_Error )
			return;

		if ( resolveStatus == ECRS_Scheduled )
			SetResolveStatus( ECRS_PendingTextureLoads );

		// Someone is misusing this node if this assert fires.
		Assert( GetResolveStatus() == ECRS_PendingTextureLoads );

		CTCStage* pChild = GetFirstChild();
		if ( pChild != NULL && pChild->GetResolveStatus() != ECRS_Complete )
			return;

		if ( !AreTexturesLoaded() )
			return;

		// Ensure we only have zero or one direct children.
		Assert( !pChild || pChild->GetNextSibling() == NULL );

		// We expect exactly one or zero children. If we have a child, use its render target to render to, otherwise 
		// Get one and use that.
		ITexture* pRenderTarget = _comp->AllocateCompositorRenderTarget();
		
		CUtlVector<CTCStageResult_t> results;

		// If we have a child, great! Use it. If not, 
		if ( pChild )
			results.AddToTail( pChild->GetResult() );
		else
		{
			CTCStageResult_t fakeRes;					
			fakeRes.m_pTexture = materials->FindTexture( "black", TEXTURE_GROUP_RUNTIME_COMPOSITE );
		}

		CTCStageResult_t baseTex, specTex;
		baseTex.m_pTexture = m_pTex;
		m_mTextureAdjust.Set3x4( baseTex.m_mUvAdjust );
		results.AddToTail( baseTex );

		specTex.m_pTexture = m_pTexSpecular;
		m_mTextureAdjust.Set3x4( specTex.m_mUvAdjust );
		results.AddToTail( specTex );

		Render( pRenderTarget, m_pMaterial, results, _comp, pChild == NULL );

		CTCStageResult_t res;
		res.m_pRenderTarget = pRenderTarget;
		res.m_fAdjustBlackPoint = m_fAdjustBlack;
		res.m_fAdjustWhitePoint = m_fAdjustWhite;
		res.m_fAdjustGamma      = m_fAdjustGamma;

		SetResult( res );

		// As soon as we have scheduled the read of a child render target, we can release that 
		// texture back to the pool for use by another stage. Everything is pipelined, so this just
		// works.
		CleanupChildResults( _comp );
		tmMessage( TELEMETRY_LEVEL0, TMMF_ICON_NOTE, "Completed: %s", __FUNCTION__ );
	}

	virtual bool HasTeamSpecificsThis() const OVERRIDE{ return false; }

	virtual bool ComputeRandomValuesThis( CUniformRandomStream* pRNG ) OVERRIDE
	{
		float m_fTotalWeight = 0;
		FOR_EACH_VEC( m_Parameters.m_possibleStickers, i )
		{
			m_fTotalWeight += m_Parameters.m_possibleStickers[ i ].m_fWeight;		
		}

		float fWeight = pRNG->RandomFloat( 0.0f, m_fTotalWeight );
		FOR_EACH_VEC( m_Parameters.m_possibleStickers, i )
		{
			const float thisWeight = m_Parameters.m_possibleStickers[ i ].m_fWeight;
			if ( fWeight < thisWeight )
			{
				m_nChoice = i;
				break;
			}
			else
			{
				fWeight -= thisWeight;
			}
		}
		
		const float adjustBlack = pRNG->RandomFloat( m_Parameters.m_AdjustBlack.low, m_Parameters.m_AdjustBlack.high );
		const float adjustOffset = pRNG->RandomFloat( m_Parameters.m_AdjustOffset.low, m_Parameters.m_AdjustOffset.high );
		const float adjustGamma = pRNG->RandomFloat( m_Parameters.m_AdjustGamma.low, m_Parameters.m_AdjustGamma.high );
		const float adjustWhite = adjustBlack + adjustOffset;

		m_fAdjustBlack = adjustBlack;
		m_fAdjustWhite = adjustWhite;
		m_fAdjustGamma = adjustGamma;
		
		ComputeTextureMatrixFromRectangle( &m_mTextureAdjust, m_Parameters.m_vDestBL.m_val, m_Parameters.m_vDestTL.m_val, m_Parameters.m_vDestTR.m_val );
		return true;
	}

	virtual void OnAsyncFindComplete( ITexture* pTex, void* pExtraArgs )
	{
		switch ( ( int ) pExtraArgs )
		{
		case Albedo:
			SafeAssign( &m_pTex, pTex );
			break;
		case Specular:
			// It's okay if this is the case, we just need to substitute with the black texture.
			if ( pTex->IsError() )
			{
				pTex = materials->FindTexture( "black", TEXTURE_GROUP_RUNTIME_COMPOSITE );
			}
			SafeAssign( &m_pTexSpecular, pTex );
			break;
		default:
			Assert( !"Unexpected value passed to OnAsyncFindComplete" );
			break;
		};
	}

private:
	ApplyStickerStageParameters m_Parameters;
	IMaterial* m_pMaterial;
	ITexture* m_pTex;
	ITexture* m_pTexSpecular;
	int m_nChoice;

	float m_fAdjustBlack;
	float m_fAdjustWhite;
	float m_fAdjustGamma;
	VMatrix m_mTextureAdjust;
};

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// This is a procedural stage we use to copy the results of a composite into a texture so we can 
// release the render targets back to a pool to be used later.
class CTCCopyStage : public CTCStage
{
public:
	CTCCopyStage()
	: m_pTex( NULL )
	{
	
	}

	~CTCCopyStage()
	{
		SafeRelease( &m_pTex );
	}

	virtual void OnAsyncCreateComplete( ITexture* pTex, void* pExtraArgs ) 
	{ 
		SafeAssign( &m_pTex, pTex ); 
		tmMessage( TELEMETRY_LEVEL0, TMMF_ICON_NOTE, "Completed: %s", __FUNCTION__ );
	}

	virtual bool DoesTargetRenderTarget() const { return false; }

private:
	virtual void RequestTextures() { /* No input textures */ }

	virtual void ResolveThis( CTextureCompositor* _comp )
	{
		tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

		ECompositeResolveStatus resolveStatus = GetResolveStatus();

		// If we're done, we're done.
		if ( resolveStatus == ECRS_Complete || resolveStatus == ECRS_Error )
			return;

		if ( resolveStatus == ECRS_Scheduled )
			SetResolveStatus( ECRS_PendingTextureLoads );

		Assert( GetFirstChild() != NULL );

		// Can't move forward until the child is done.
		if ( GetFirstChild()->GetResolveStatus() != ECRS_Complete )
			return;

		// Compositing has completed!
		if ( m_pTex ) 
		{
			if ( m_pTex->IsError() )
			{
				_comp->Error( false, "Error occurred copying render target to texture. This is fatal." );
				return;
			}

			CTCStageResult_t res;
			res.m_pTexture = m_pTex;

#ifdef STAGING_ONLY
			if ( r_texcomp_dump.GetInt() == 2 )
			{
				char buffer[128];
				V_snprintf( buffer, ARRAYSIZE(buffer), "composite_%s_result_%02d.tga", _comp->GetName().Get(), s_nDumpCount++ );
				GetFirstChild()->GetResult().m_pRenderTarget->SaveToFile( buffer );
			}
#endif

			SetResult( res );
			return;
		}

		if ( resolveStatus == ECRS_PendingComposites )
			return;

		ImageFormat fmt = IMAGE_FORMAT_DXT5_RUNTIME;

		if ( _comp->GetCreateFlags() & TEX_COMPOSITE_CREATE_FLAGS_NO_COMPRESSION ) 
			fmt = IMAGE_FORMAT_RGBA8888;

		bool bGenMipmaps = !( _comp->GetCreateFlags() & TEX_COMPOSITE_CREATE_FLAGS_NO_MIPMAPS );

		// We want to do this once only.
		char buffer[_MAX_PATH];
		_comp->GetTextureName( buffer, ARRAYSIZE( buffer ) );

		int nCreateFlags = TEXTUREFLAGS_IMMEDIATE_CLEANUP 
					     | TEXTUREFLAGS_TRILINEAR
						 | TEXTUREFLAGS_ANISOTROPIC;

#if defined( STAGING_ONLY )
		#if WITH_TEX_COMPOSITE_CACHE
			if ( r_texcomp_dump.GetInt() == 0 && ( _comp->GetCreateFlags() & TEX_COMPOSITE_CREATE_FLAGS_FORCE ) == 0 )
				nCreateFlags = 0;
		#endif
#endif

		CMatRenderContextPtr pRenderContext( materials );
		pRenderContext->AsyncCreateTextureFromRenderTarget( GetFirstChild()->GetResult().m_pRenderTarget, buffer, fmt, bGenMipmaps, nCreateFlags, this, NULL );

		SetResolveStatus( ECRS_PendingComposites );
		// Don't clean up here just yet, we'll get cleaned up when the composite is totally complete.
		tmMessage( TELEMETRY_LEVEL0, TMMF_ICON_NOTE, "Begun: %s", __FUNCTION__ );
	}

	virtual bool HasTeamSpecificsThis() const OVERRIDE { return false; }

	virtual bool ComputeRandomValuesThis( CUniformRandomStream* pRNG ) OVERRIDE
	{
		// No RNG here.
		return false;
	}

	ITexture* m_pTex;
	CUtlString m_FinalTextureName;
	uint32 m_nTexCompositeCreateFlags;
};

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
CTextureCompositor::CTextureCompositor( int _width, int _height, int nTeam, const char* pCompositeName, uint64 nRandomSeed, uint32 nTexCompositeCreateFlags )
: m_nReferenceCount( 0 )
, m_nWidth( _width )
, m_nHeight( _height )
, m_nTeam( nTeam )
, m_nRandomSeed( nRandomSeed )
, m_pRootStage( NULL )
, m_ResolveStatus( ECRS_Idle )
, m_bError( false )
, m_bFatal( false )
, m_nRenderTargetsAllocated( 0 )
, m_CompositeName( pCompositeName )
, m_nTexCompositeCreateFlags( nTexCompositeCreateFlags )
, m_bHasTeamSpecifics( false )
, m_nCompositePaintKitId( 0 )
{

}

// ------------------------------------------------------------------------------------------------
CTextureCompositor::~CTextureCompositor()
{
	tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );
	Assert ( m_nReferenceCount == 0 );

	// Have to clean up the stages before cleaning up the render target pool, because cleanup up
	// stages will throw things back to the render target pool.
	SafeRelease( &m_pRootStage );

	FOR_EACH_VEC( m_RenderTargetPool, i )
	{
		RenderTarget_t& rt = m_RenderTargetPool[ i ];
		SafeRelease( &rt.m_pRT );
	}
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::Restart()
{
	Assert(!"TODO! Need to clone the root node, then cleanup the old root and start the new work.");

	// CTCStage* clone = m_pRootStage->Clone();
	SafeRelease( &m_pRootStage );
	// m_pRootStage = clone;

	m_ResolveStatus = ECRS_Scheduled;

	// Kick it off again
	m_pRootStage->Resolve( true, this );
	m_ResolveStatus = ECRS_PendingTextureLoads;
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::Shutdown()
{
	// If this thing is a template, then it's a faker and doesn't have an m_pRootStage. This is 
	// only true during startup when we're just verifying that the templates look sane--later
	// they should have real data.
	if ( m_pRootStage )
		m_pRootStage->Cleanup( this );

	// These should match now.
	Assert( m_nRenderTargetsAllocated == m_RenderTargetPool.Count() );
}

// ------------------------------------------------------------------------------------------------
int CTextureCompositor::AddRef()
{
	return ++m_nReferenceCount;
}

// ------------------------------------------------------------------------------------------------
int CTextureCompositor::Release()
{
	int retVal = --m_nReferenceCount;
	Assert( retVal >= 0 ); 
	if ( retVal == 0 ) 
	{
		Shutdown();
		delete this;	
	}

	return retVal;
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::Update()
{
	tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

	Assert( m_pRootStage );

	if ( m_bError )
	{
		if ( !m_bFatal )
		{
			m_bError = false;
			Restart();
		}
		else
			m_ResolveStatus = ECRS_Error;		
		return;	
	}

	if ( m_pRootStage->GetResolveStatus() != ECRS_Complete )
		m_pRootStage->Resolve( false, this );

	if ( m_pRootStage->GetResolveStatus() == ECRS_Complete )
	{
		#ifdef STAGING_ONLY
			// One time, go ahead and dump out the texture if we're supposed to right here, at completion time.
			if ( ( r_texcomp_dump.GetInt() == 3 || r_texcomp_dump.GetInt() == 4 ) && m_ResolveStatus != ECRS_Complete )
			{
				char filename[_MAX_PATH];
				V_sprintf_safe( filename, "%s.tga", m_CompositeName.Get() );
				m_pRootStage->GetResult().m_pTexture->SaveToFile( filename );
			}
		#endif

		m_ResolveStatus = ECRS_Complete;

#ifdef RAD_TELEMETRY_ENABLED
		char buffer[ 256 ];
		GetTextureName( buffer, ARRAYSIZE( buffer ) );
		tmEndTimeSpan( TELEMETRY_LEVEL0, m_nCompositePaintKitId, 0, "Composite: %s", tmDynamicString( TELEMETRY_LEVEL0, buffer ) );
#endif
	}
}

// ------------------------------------------------------------------------------------------------
ITexture* CTextureCompositor::GetResultTexture() const
{
	Assert( m_pRootStage && m_pRootStage->GetResolveStatus() == ECRS_Complete );
	Assert( m_pRootStage->GetResult().m_pTexture );
	return m_pRootStage->GetResult().m_pTexture;
}

// ------------------------------------------------------------------------------------------------
ECompositeResolveStatus CTextureCompositor::GetResolveStatus() const
{
	return m_ResolveStatus;
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::ScheduleResolve( )
{
	tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

	Assert( m_pRootStage );
	Assert( m_ResolveStatus == ECRS_Idle );

	#if WITH_TEX_COMPOSITE_CACHE
		if ( ( GetCreateFlags() & TEX_COMPOSITE_CREATE_FLAGS_FORCE ) == 0)
		{
			char buffer[ _MAX_PATH ];
			GetTextureName( buffer, ARRAYSIZE( buffer ) );

			// I think there's a race condition here, add a flag to FindTexture that says only if loaded, and bumps ref?
			if ( materials->IsTextureLoaded( buffer ) )
			{
				ITexture* resTexture = materials->FindTexture( buffer, TEXTURE_GROUP_RUNTIME_COMPOSITE, false, 0 );
				if ( resTexture && resTexture->IsError() == false )
				{
					m_pRootStage->OnAsyncCreateComplete( resTexture, NULL );
					CTCStageResult_t res;
					res.m_pTexture = resTexture;
					m_pRootStage->SetResult( res );

					m_ResolveStatus = ECRS_Complete;
					return;
				}
			}
		}
	#endif

	#ifdef RAD_TELEMETRY_ENABLED
		m_nCompositePaintKitId = ++s_nCompositeCount;
		char buffer[256];
		GetTextureName( buffer, ARRAYSIZE( buffer ) );
		tmBeginTimeSpan( TELEMETRY_LEVEL0, m_nCompositePaintKitId, 0, "Composite: %s", tmDynamicString( TELEMETRY_LEVEL0, buffer ) );
	#endif

	m_ResolveStatus = ECRS_Scheduled;

	// Naughty.
	extern CMaterialSystem g_MaterialSystem;
	g_MaterialSystem.ScheduleTextureComposite( this );
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::Resolve()
{
	tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

	// We can actually get in multiply times for the same one because of the way EconItemView works.
	// So if that's the case, bail.
	if ( m_ResolveStatus != ECRS_Scheduled )
		return;

	m_pRootStage->Resolve( true, this );

	// Update our resolve status
	m_ResolveStatus = ECRS_PendingTextureLoads;
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::Error( bool _retry, const char* _debugDevMsg, ... )
{
	m_bError = true;
	m_bFatal = !_retry;

	va_list args;
	va_start( args, _debugDevMsg );
	WarningV( _debugDevMsg, args );
	va_end( args );
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::SetRootStage( CTCStage* rootStage )
{
	SafeAssign( &m_pRootStage, rootStage );

	// After we set a root, compute everyone's RNG values. Do this once, early, to ensure the values are stable.
	uint32 seedhi = 0;
	uint32 seedlo = 0;
	GetSeed( &seedhi, &seedlo );

	CUniformRandomStream streams[2];
	streams[0].SetSeed( seedhi );
	streams[1].SetSeed( seedlo );
	
	int currentIndex = 0;

	m_pRootStage->ComputeRandomValues( &currentIndex, streams, ARRAYSIZE( streams ) );
}

// ------------------------------------------------------------------------------------------------
// TODO: Need to accept format and depth status
ITexture* CTextureCompositor::AllocateCompositorRenderTarget( )
{
	tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

	FOR_EACH_VEC( m_RenderTargetPool, i )
	{
		const RenderTarget_t& rt = m_RenderTargetPool[ i ];
		if ( rt.m_nWidth == m_nWidth && rt.m_nHeight == m_nHeight )
		{
			ITexture* retVal = rt.m_pRT;
			m_RenderTargetPool.Remove( i );
			return retVal;
		}
	}

	// Lie to the material system that we are asking for this allocation way back at the beginning of time.
	// This used to matter to GPUs for perf, but hasn't in a long time.
	materials->OverrideRenderTargetAllocation( true );
	ITexture* retVal = materials->CreateNamedRenderTargetTextureEx( "", m_nWidth, m_nHeight, RT_SIZE_LITERAL_PICMIP, IMAGE_FORMAT_RGBA8888, MATERIAL_RT_DEPTH_NONE, TEXTUREFLAGS_IMMEDIATE_CLEANUP );
	Assert( retVal );
	materials->OverrideRenderTargetAllocation( false );

	// Used to count how many we actually allocated so we can verify we cleaned them all up at 
	// shutdown
	++m_nRenderTargetsAllocated;
	return retVal;
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::ReleaseCompositorRenderTarget( ITexture* _tex )
{
	Assert( _tex );
	int w = _tex->GetMappingWidth();
	int h = _tex->GetMappingHeight();

	RenderTarget_t rt = { w, h, _tex };
	m_RenderTargetPool.AddToTail( rt );
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::GetTextureName( char* pOutBuffer, int nBufferLen ) const
{
	uint32 seedhi = 0;
	uint32 seedlo = 0;
	GetSeed( &seedhi, &seedlo );

	Assert( m_pRootStage != NULL );
	if ( m_pRootStage->HasTeamSpecifics() )
		V_snprintf( pOutBuffer, nBufferLen, "proc/texcomp/%s_flags%08x_seedhi%08x_seedlo%08x_team%d_w%d_h%d", GetName().Get(), GetCreateFlags(), seedhi, seedlo, m_nTeam, m_nWidth, m_nHeight	);
	else
		V_snprintf( pOutBuffer, nBufferLen, "proc/texcomp/%s_flags%08x_seedhi%08x_seedlo%08x_w%d_h%d", GetName().Get(), GetCreateFlags(), seedhi, seedlo, m_nWidth, m_nHeight	);
}

// ------------------------------------------------------------------------------------------------
void CTextureCompositor::GetSeed( uint32* pOutHi, uint32* pOutLo ) const
{
	tmZone( TELEMETRY_LEVEL2, TMZF_NONE, "%s", __FUNCTION__ );

	Assert( pOutHi && pOutLo );
	( *pOutHi ) = 0;
	( *pOutLo ) = 0;

	// This is most definitely not the most efficient way to do this.
	for ( int i = 0; i < 32; ++i ) 
	{
		( *pOutHi ) |= (uint32)( ( m_nRandomSeed & ( uint64( 1 ) << ( ( 2 * i ) + 0 ) ) ) >> i );
		( *pOutLo ) |= (uint32)( ( m_nRandomSeed & ( uint64( 1 ) << ( ( 2 * i ) + 1 ) ) ) >> ( i + 1 ) );
	}
}

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
CTCStage::CTCStage() 
: m_nReferenceCount( 1 ) // This is 1 because the common case is to assign these as children, and we don't want to play with refs there.
, m_pFirstChild( NULL )
, m_pNextSibling( NULL )
, m_ResolveStatus( ECRS_Idle )
{ }

// ------------------------------------------------------------------------------------------------
CTCStage::~CTCStage() 
{ 
	Assert ( m_nReferenceCount == 0 );
	SafeRelease( &m_pFirstChild ); 
	SafeRelease( &m_pNextSibling );
}

// ------------------------------------------------------------------------------------------------
int CTCStage::AddRef() 
{ 
	return ++m_nReferenceCount; 
}

// ------------------------------------------------------------------------------------------------
int CTCStage::Release() 
{ 
	int retVal = --m_nReferenceCount;
	if ( retVal == 0 )
		delete this; 
	return retVal;
}

// ------------------------------------------------------------------------------------------------
void CTCStage::Resolve( bool bFirstTime, CTextureCompositor* _comp )
{

	if ( m_pFirstChild )
		m_pFirstChild->Resolve( bFirstTime, _comp );

	// Update our status, which may be updated below. Only do this the first time through.
	if ( bFirstTime ) 
	{
		m_ResolveStatus = ECRS_Scheduled;
		// Request textures here. We used to request in the constructor, but it caused us
		// to potentially hold all paintkitted textures for all time. That's bad for Mac,
		// where we are super memory constrained.
		RequestTextures();
	}
	
	ResolveThis( _comp );

	if ( m_pNextSibling )
		m_pNextSibling->Resolve( bFirstTime, _comp );
}

// ------------------------------------------------------------------------------------------------
bool CTCStage::HasTeamSpecifics( ) const
{
	if ( m_pFirstChild && m_pFirstChild->HasTeamSpecifics() )
		return true;

	if ( HasTeamSpecificsThis() )
		return true;

	return m_pNextSibling && m_pNextSibling->HasTeamSpecifics();
}

// ------------------------------------------------------------------------------------------------
void CTCStage::ComputeRandomValues( int* pCurIndex, CUniformRandomStream* pRNGs, int nRNGCount )
{
	Assert( pCurIndex != NULL );
	Assert( pRNGs != NULL );
	Assert( nRNGCount != 0 );

	// We do a depth-first traversal here, but we hit ourselves first.
	if ( ComputeRandomValuesThis( &pRNGs[*pCurIndex] ) )
	{
		// Switch which RNG the next person will use.
		( *pCurIndex ) = ( ( *pCurIndex ) + 1 ) % nRNGCount;
	}

	if ( m_pFirstChild )
		m_pFirstChild->ComputeRandomValues( pCurIndex, pRNGs, nRNGCount );

	if ( m_pNextSibling )
		m_pNextSibling->ComputeRandomValues( pCurIndex, pRNGs, nRNGCount );
}

// ------------------------------------------------------------------------------------------------
void CTCStage::CleanupChildResults( CTextureCompositor* _comp )
{
	// This does not recurse. We call it as we move through the tree to clean up our 
	// first-generation children.
	for ( CTCStage* child = GetFirstChild(); child; child = child->GetNextSibling() )
	{
		child->m_Result.Cleanup( _comp );
		child->m_Result = CTCStageResult_t();
	}
}

// ------------------------------------------------------------------------------------------------
void CTCStage::Render( ITexture* _destRT, IMaterial* _mat, const CUtlVector<CTCStageResult_t>& _inputs, CTextureCompositor* _comp, bool bClear )
{
	tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

	CUtlVector< IMaterialVar* > varsToClean;
	bool bFound = false;
	char buffer[128];
	FOR_EACH_VEC( _inputs, i )
	{
		const CTCStageResult_t& stageParams = _inputs[ i ];

		Assert( stageParams.m_pTexture || stageParams.m_pRenderTarget );
		ITexture* inTex = stageParams.m_pTexture 
			            ? stageParams.m_pTexture 
						: stageParams.m_pRenderTarget;

		V_snprintf( buffer, ARRAYSIZE( buffer ), "$srctexture%d", i );

		// Set the texture
		IMaterialVar* var = _mat->FindVar( buffer, &bFound );
		Assert( bFound );
		var->SetTextureValue( inTex );
		varsToClean.AddToTail( var );

		// And the levels parameters
		V_snprintf( buffer, ARRAYSIZE(buffer), "$texadjustlevels%d", i );
		var = _mat->FindVar( buffer, &bFound );
		Assert(bFound);
		var->SetVecValue( stageParams.m_fAdjustBlackPoint, stageParams.m_fAdjustWhitePoint, stageParams.m_fAdjustGamma );

		// And the expected transform
		V_snprintf( buffer, ARRAYSIZE(buffer), "$textransform%d", i );
		var = _mat->FindVar( buffer, &bFound );
		Assert(bFound);
		var->SetMatrixValue( stageParams.m_mUvAdjust );
	}

	IMaterialVar* var = _mat->FindVar( "$textureinputcount", &bFound );
	Assert( bFound );
	var->SetIntValue( _inputs.Count() );

	CMatRenderContextPtr pRenderContext( materials );

	int w = _destRT->GetActualWidth();
	int h = _destRT->GetActualHeight();

	pRenderContext->PushRenderTargetAndViewport( _destRT, 0, 0, w, h );
 
	if ( bClear )
	{
		pRenderContext->ClearColor4ub( 0, 0, 0, 255 );
		pRenderContext->ClearBuffers( true, false, false );
	}

	// Perform the render!
	pRenderContext->DrawScreenSpaceQuad( _mat );

#ifdef STAGING_ONLY
	if (r_texcomp_dump.GetInt() == 1)
	{
		FOR_EACH_VEC(_inputs, i)
		{
			if (_inputs[i].m_pTexture)
			{
				V_snprintf(buffer, ARRAYSIZE(buffer), "composite_%s_input_%02d_in%01d_%08x.tga", _comp->GetName().Get(), s_nDumpCount, i, (int) this);
				_inputs[i].m_pTexture->SaveToFile(buffer);
			}
		}

		V_snprintf(buffer, ARRAYSIZE(buffer), "composite_%s_result_%02d_%08x.tga", _comp->GetName().Get(), s_nDumpCount++, (int) this);
		_destRT->SaveToFile(buffer);
	}
#endif

	// Restore previous state
	pRenderContext->PopRenderTargetAndViewport();

	// After rendering, clean up the leftover texture references or they will be there for a long
	// time.
	FOR_EACH_VEC( varsToClean, i )
	{
		varsToClean[ i ]->SetUndefined();
	}
}

// ------------------------------------------------------------------------------------------------
void CTCStage::Cleanup( CTextureCompositor* _comp )
{
	if ( m_pFirstChild )
		m_pFirstChild->Cleanup( _comp );

	m_Result.Cleanup( _comp );

	if ( m_pNextSibling )
		m_pNextSibling->Cleanup( _comp );
}

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
typedef bool ( *TBuildNodeFromKVFunc )( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags );
bool TexStageFromKV( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags );
template<int Type> bool CombineStageFromKV( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags );
bool SelectStageFromKV( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags );
bool ApplyStickerStageFromKV( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags );

struct NodeDefinitionEntry
{
	const char* keyName;
	TBuildNodeFromKVFunc buildFunc;
};

NodeDefinitionEntry cNodeParseTable[] = 
{
	{ "texture_lookup",		TexStageFromKV },

	{ "combine_add",		CombineStageFromKV<ECO_Add> },
	{ "combine_lerp",		CombineStageFromKV<ECO_Lerp> },
	{ "combine_multiply",	CombineStageFromKV<ECO_Multiply> },

	{ "select",				SelectStageFromKV },

	{ "apply_sticker",		ApplyStickerStageFromKV },

	{ 0, 0 }
};

// ------------------------------------------------------------------------------------------------
template<typename S>
void ParseIntoStruct( S* _outStruct, CUtlVector< KeyValues *>* _leftovers, KeyValues* _kv, uint32 nTexCompositeCreateFlags, const ParseTableEntry* _entries )
{
	Assert( _leftovers );

	const char* keyName = _kv->GetName();
	keyName;

	FOR_EACH_SUBKEY( _kv, thisKey )
	{
		bool parsed = false;
		for ( int e = 0; _entries[e].keyName; ++e )
		{
			if ( V_stricmp( _entries[e].keyName, thisKey->GetName() ) == 0 )
			{
				// If we're instancing, go ahead and run the parse function. If we're just doing template verification
				// then the right hand side may still have variables that need to be expanded, so just verify that the
				// left hand side is sane.
				if ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY ) == 0 )
				{
					void* pDest = ((unsigned char*)_outStruct) + _entries[e].structOffset;
					_entries[e].parseFunc( thisKey, pDest );
				}
				parsed = true;
				break;
			}
		}

		if ( !parsed )
		{
			( *_leftovers ).AddToTail( thisKey );		
		}
	}
}

// ------------------------------------------------------------------------------------------------
bool ParseNodes( CUtlVector< CTCStage* >* _outStages, const CUtlVector< KeyValues *>& _kvs, uint32 nTexCompositeCreateFlags )
{
	tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

	bool anyFails = false;

	FOR_EACH_VEC( _kvs, thisKey )
	{
		KeyValues *thisKV = _kvs[ thisKey ];

		bool parsed = false;
		for ( int e = 0; cNodeParseTable[ e ].keyName; ++e )
		{			
			if ( V_stricmp( cNodeParseTable[ e ].keyName, thisKV->GetName() ) == 0 )
			{
				CTCStage* pNewStage = NULL;
				if ( !cNodeParseTable[ e ].buildFunc( &pNewStage, thisKV->GetName(), thisKV, nTexCompositeCreateFlags ) )
					anyFails = true;

				(*_outStages).AddToTail( pNewStage );
				parsed = true;
				break;
			}
		}

		if (!parsed)
		{
			DevWarning( "Compositor Error: Unexpected key '%s' while parsing definition.\n", thisKV->GetName() );
			anyFails = true;
		}
	}

	return !anyFails;
}

// ------------------------------------------------------------------------------------------------
bool TexStageFromKV( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags )
{
	Assert( ppOutStage != NULL );

	TextureStageParameters tsp;
	CUtlVector< KeyValues* > leftovers;
	CUtlVector< CTCStage* > childNodes;
	ParseIntoStruct( &tsp, &leftovers, _kv, nTexCompositeCreateFlags, cTextureStageParametersParseTable );
	if ( !ParseNodes( &childNodes, leftovers, nTexCompositeCreateFlags ) )
		return false;

	if ( !( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_SCHEMA_ONLY ) )
	{
		( *ppOutStage ) = new CTCTextureStage( tsp, nTexCompositeCreateFlags );
		( *ppOutStage )->AppendChildren( childNodes );
	}

	return true;
}

// ------------------------------------------------------------------------------------------------
template <int Type>
bool CombineStageFromKV( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags )
{
	Assert( ppOutStage != NULL );

	static_assert( Type >= 0 && Type < ECO_Error, "Invalid type, you need to update the enum." );
	CombineStageParameters csp;
	csp.m_CombineOp = (ECombineOperation) Type;

	CUtlVector< KeyValues* > leftovers;
	CUtlVector< CTCStage* > childNodes;
	ParseIntoStruct( &csp, &leftovers, _kv, nTexCompositeCreateFlags, cCombineStageParametersParseTable );
	if ( !ParseNodes( &childNodes, leftovers, nTexCompositeCreateFlags  ) )
		return false;

	if ( !( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_SCHEMA_ONLY ) )
	{
		( *ppOutStage ) = new CTCCombineStage( csp, nTexCompositeCreateFlags );
		( *ppOutStage )->AppendChildren( childNodes );
	}

	return true;
}

// ------------------------------------------------------------------------------------------------
bool SelectStageFromKV( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags )
{
	Assert( ppOutStage != NULL );

	SelectStageParameters ssp;
	CUtlVector< KeyValues* > leftovers;
	CUtlVector< CTCStage* > childNodes;
	ParseIntoStruct( &ssp, &leftovers, _kv, nTexCompositeCreateFlags, cSelectStageParametersParseTable );
	if ( !ParseNodes( &childNodes, leftovers, nTexCompositeCreateFlags  ) )
		return false;

	if ( !( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_SCHEMA_ONLY ) )
	{
		( *ppOutStage ) = new CTCSelectStage( ssp, nTexCompositeCreateFlags );
		( *ppOutStage )->AppendChildren( childNodes );
	}
	
	return true;
}

// ------------------------------------------------------------------------------------------------
bool ApplyStickerStageFromKV( CTCStage** ppOutStage, const char* _key, KeyValues* _kv, uint32 nTexCompositeCreateFlags )
{
	Assert( ppOutStage != NULL );

	ApplyStickerStageParameters assp;
	CUtlVector< KeyValues* > leftovers;
	CUtlVector< CTCStage* > childNodes;
	ParseIntoStruct( &assp, &leftovers, _kv, nTexCompositeCreateFlags, cApplyStickerStageParametersParseTable );
	if ( !ParseNodes( &childNodes, leftovers, nTexCompositeCreateFlags ) )
		return false;

	// These stages can have exactly one child. 
	if ( childNodes.Count() > 1 )
		return false;

	int setCount = 0;
	if ( assp.m_vDestBL.m_bSet ) ++setCount;
	if ( assp.m_vDestTL.m_bSet ) ++setCount;
	if ( assp.m_vDestTR.m_bSet ) ++setCount;
	if ( setCount != 3 )
		return false;

	if ( !( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_SCHEMA_ONLY ) )
	{
		( *ppOutStage ) = new CTCApplyStickerStage( assp, nTexCompositeCreateFlags );
		( *ppOutStage )->AppendChildren( childNodes );
	}
	
	return true;
}

// ------------------------------------------------------------------------------------------------
const char *GetCombinedMaterialName( ECombineOperation eMaterial )
{
	Assert( eMaterial >= ECO_FirstPrecacheMaterial && eMaterial < ECO_COUNT );
	return cCombineMaterialName[eMaterial];
}

// ------------------------------------------------------------------------------------------------
KeyValues* ResolveTemplate( const char* pRootName, KeyValues* pValues, uint32 nTexCompositeCreateFlags, bool *pInOutAllocdNew )
{
	Assert( pRootName != NULL && pValues != NULL && pInOutAllocdNew != NULL );

	const char* pTemplateName = NULL;
	bool bImplementsTemplate = false;
	bool bHasOtherNodes = false;

	// First, figure out if the tree is sensible.
	FOR_EACH_SUBKEY( pValues, pChild )
	{
		const char* pChildName = pChild->GetName();
		if ( V_stricmp( pChildName, "implements" ) == 0 )
		{
			if ( bImplementsTemplate )
			{
				Warning( "ERROR[%s]: implements field can only appear once, seen a second time as 'implements \"%s\"\n", pRootName, pChild->GetString() );
				return NULL;			
			}

			bImplementsTemplate = true;
			pTemplateName = pChild->GetString();
		}
		else if ( pChildName && pChildName[0] != '$' )
		{
			bHasOtherNodes = true;
		}
	}

	if ( bImplementsTemplate && bHasOtherNodes )
	{
		Warning( "ERROR[%s]: if using 'implements', can only have variable definitions--other fields not allowed.\n", pRootName );
		return NULL;
	}
	
	// If we're not doing templates, we're all finished. 
	if ( !bImplementsTemplate )
		return pValues;

	KeyValues* pNewKV = NULL;

	if ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY ) == 0 )
	{
		CTextureCompositorTemplate* pTmpl = TextureManager()->FindTextureCompositorTemplate( pTemplateName );
		if ( !pTmpl )
		{
			Warning( "ERROR[%s]: Couldn't find template named '%s'.\n", pRootName, pTemplateName );
			return NULL;
		}

		Assert( pTmpl->GetKV() );

		// If the verify flag isn't set, we're instancing the template so do all the logic.
		if  ( pTmpl->ImplementsTemplate() )
		{
			pNewKV = ResolveTemplate( pRootName, pTmpl->GetKV(), nTexCompositeCreateFlags, pInOutAllocdNew );
		}
		else
		{
			// The root-most template will allocate the memory for all of us.
			pNewKV = pTmpl->GetKV()->MakeCopy();
			pNewKV->SetName( pRootName );
			( *pInOutAllocdNew ) = true;
		}
	}
	else
	{
		// Just return the original KV back to the caller, who just wants a success code here. 
		return pValues;	
	}

	// Now, copy any child var definitions from pValues into pNewKV. Because of the recursive call stack, 
	// this has the net effect that more concrete templates will write their values later than more remote templates.
	FOR_EACH_SUBKEY( pValues, pChild )
	{
		const char* pChildName = pChild->GetName();
		if ( pChildName && pChildName[0] == '$' )
		{
			pNewKV->AddSubKey( pChild->MakeCopy() );
		}
	}

	// Success!
	return pNewKV;
}

// ------------------------------------------------------------------------------------------------
typedef CUtlDict< const char* > VariableDefs_t;
KeyValues* ExtractVariableDefinitions( VariableDefs_t* pOutVarDefs, const char* pRootName, KeyValues* pKeyValues )
{
	Assert( pOutVarDefs );

	FOR_EACH_SUBKEY( pKeyValues, pChild )
	{
		const char* pChildName = pChild->GetName();
		if ( pChildName[0] == '$' )
		{
			if ( pChild->GetFirstTrueSubKey() )
			{
				Warning( "ERROR[%s]: All variable definitions must be simple strings, '%s' was a full subtree.\n", pRootName, pChildName );
				return NULL;
			}

			int ndx = ( *pOutVarDefs ).Find( pChildName + 1 );
			if ( pOutVarDefs->IsValidIndex( ndx ) )
				( *pOutVarDefs )[ ndx ] = pChild->GetString();
			else
				( *pOutVarDefs ).Insert( pChildName + 1, pChild->GetString() );
		}
	}

	return pKeyValues;
}

// ------------------------------------------------------------------------------------------------
CUtlString GetErrorTrail( CUtlVector< const char* >& errorStack )
{
	if ( errorStack.Count() == 0 )
		return CUtlString( "" );

	const int stackLength = errorStack.Count();
	const int stackLengthMinusOne = stackLength - 1;

	const char* cStageSep = " -> ";
	const int cStageSepStrLen = V_strlen( cStageSep );

	int totalStrLength = 0;

	for ( int i = 0; i < stackLength; ++i ) 
	{
		totalStrLength += V_strlen( errorStack[ i ] );
	}

	totalStrLength += stackLengthMinusOne * cStageSepStrLen;

	CUtlString retStr;
	retStr.SetLength( totalStrLength );

	char* pDstOrig = retStr.GetForModify(); pDstOrig;
	char* pDst = retStr.GetForModify();

	int destPos = 0;
	for ( int i = 0; i < stackLength; ++i )
	{
		// Copy the string
		const char* pSrc = errorStack[ i ];
		while ( ( *pDst++ = *pSrc++ ) != 0 ) 
			++destPos;
		--pDst;

		if ( i < stackLengthMinusOne )
		{
			// Now copy our separator
			pSrc = cStageSep;
			while ( ( *pDst++ = *pSrc++ ) != 0 )
				++destPos;
			--pDst;
		}
	}

	Assert( destPos == totalStrLength );
	Assert( pDst - retStr.Get() == totalStrLength );
	// SetLength above already included the +1 to length for the null terminator.
	*pDst = '\0';

	return retStr;
}

// ------------------------------------------------------------------------------------------------
enum ParseMode
{
	Copy,
	DetermineStringForReplace,
};

// ------------------------------------------------------------------------------------------------
// Returns the number of characters written into pOutBuffer or -1 if there was an error. 
int SubstituteVarsRecursive( char* pOutBuffer, int* pOutSubsts, CUtlVector< const char* >& errorStack, const char* pStr, uint32 nTexCompositeCreateFlags, const VariableDefs_t& varDefs )
{
	ParseMode mode = Copy;
	char* pCurVariable = NULL;

	char* pDst = pOutBuffer;

	int srcPos = 0;
	int dstPos = 0;
	while ( pStr[ srcPos ] != 0 )
	{
		const char* srcC = pStr + srcPos;

		switch ( mode )
		{
		case Copy:
			if ( srcC[ 0 ] == '$' && srcC[ 1 ] == '[' )
			{
				mode = DetermineStringForReplace;
				srcPos += 2;
				pCurVariable = const_cast< char* >( pStr + srcPos );
				continue;
			}
			else if ( pOutBuffer )
			{
				pDst[ dstPos++ ] = pStr[ srcPos++ ];
			}
			else
			{
				++dstPos;
				++srcPos;
			}

			break;

		case DetermineStringForReplace:
			if ( srcC[ 0 ] == ']' )
			{
				// Make a modification so we can just do the lookup from this buffer.
				pCurVariable[ srcC - pCurVariable ] = 0;

				// Lookup our substitution value.
				int ndx = varDefs.Find( pCurVariable );
				const char* pSubstText = NULL;

				if ( ndx != varDefs.InvalidIndex() )
				{
					pSubstText = varDefs[ ndx ];	
				}
				else if ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY ) != 0 )
				{
					pSubstText = ""; // It's fine to run into these when verifying the template only.
				}
				else
				{
					Warning( "ERROR[%s]: Couldn't find variable named $%s that was requested to be substituted.\n", ( const char* ) GetErrorTrail( errorStack ), pCurVariable );

					// Restore the string first. 
					pCurVariable[ srcC - pCurVariable ] = ']';

					return -1;
				}

				// Put it back.
				pCurVariable[ srcC - pCurVariable ] = ']';

				int charsWritten = SubstituteVarsRecursive( pOutBuffer ? &pDst[ dstPos ] : NULL, pOutSubsts, errorStack, pSubstText, nTexCompositeCreateFlags, varDefs );
				if ( charsWritten < 0 )
					return -1;

				++( *pOutSubsts );
				dstPos += charsWritten;
				++srcPos;

				mode = Copy;
			}
			else
			{
				++srcPos;
			}

			break;
		}
	}

	if ( mode == DetermineStringForReplace )
	{
		Warning( "ERROR[%s]: Variable $[%s missing closing bracket ].\n", ( const char* ) GetErrorTrail( errorStack ), pCurVariable );
		return -1;
	}

	return dstPos;
}

// ------------------------------------------------------------------------------------------------
// Returns true if successful, false otherwise.
bool SubstituteVars( CUtlString* pOutStr, int* pOutSubsts, CUtlVector< const char* >& errorStack, const char* pStr, uint32 nTexCompositeCreateFlags, const VariableDefs_t& varDefs )
{
	Assert( pOutStr != NULL && pOutSubsts != NULL && pStr != NULL );

	( *pOutSubsts ) = 0;
	
	// Even though this involves a traversal, we're saving a malloc by walking this thing once looking for the start token. 
	const char* pFirstRepl = V_strstr( pStr, "$[" );

	// No substitutions, so bail out now.
	if ( pFirstRepl == NULL )
	{
		( *pOutStr ) = pStr;		
		return true;
	}

	// We could do this as we go, but we're trying to avoid re-mallocing memory repeatedly in here so process once
	// to find out what the size is. 
	int expectedLen = SubstituteVarsRecursive( NULL, pOutSubsts, errorStack, pStr, nTexCompositeCreateFlags, varDefs );
	if ( expectedLen < 0 )
		return false;

	// We don't need to actually write the string, and we shouldn't. If we're just verifying, exit now with success.
	if ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY ) != 0 )
		return true;

	CUtlString& outStr = ( *pOutStr );
	outStr.SetLength( expectedLen ); // SetLength does +1 to the length for us.

	int finalLen = SubstituteVarsRecursive( outStr.GetForModify(), pOutSubsts, errorStack, pStr, nTexCompositeCreateFlags, varDefs );

	if ( finalLen < 0 )
		return false;

	// Otherwise things have gone horribly wrong.
	Assert( outStr.Length() == expectedLen );
	Assert( expectedLen == finalLen );

	// Success!
	return true;
}

// ------------------------------------------------------------------------------------------------
bool ResolveAllVariablesRecursive( CUtlVector< const char* >& errorStack, const VariableDefs_t& varDefs, KeyValues* pKeyValues, uint32 nTexCompositeCreateFlags, CUtlString& tmpStr )
{
	// hope for the best
	bool success = true;

	FOR_EACH_SUBKEY( pKeyValues, pChild )
	{
		if ( pChild->GetName()[ 0 ] == '$' )
			continue;

		errorStack.AddToTail( pChild->GetName() );

		if ( pChild->GetFirstSubKey() )
		{
			if ( !ResolveAllVariablesRecursive( errorStack, varDefs, pChild, nTexCompositeCreateFlags, tmpStr ) )
				success = false;
		}
		else 
		{
			int nSubsts = 0;
			if ( !SubstituteVars( &tmpStr, &nSubsts, errorStack, pChild->GetString(), nTexCompositeCreateFlags, varDefs ) )
				success = false;

			// Did we do any substitutions?
			if ( nSubsts > 0 && ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY ) == 0 ) )
				pChild->SetStringValue( tmpStr );
		}

		errorStack.RemoveMultipleFromTail( 1 );
	}
	
	return success;
}

// ------------------------------------------------------------------------------------------------
KeyValues* ResolveAllVariables( const char* pRootName, const VariableDefs_t& varDefs, KeyValues* pKeyValues, uint32 nTexCompositeCreateFlags, bool *pInOutAllocdNew )
{
	KeyValuesAD kvad_onError( ( KeyValues* ) nullptr );

	// Let's just assume first that if we have any vars, we will need to substitute them.
	// But if we're just verifying the template, no need.
	if ( !( *pInOutAllocdNew ) && varDefs.Count() > 0 && ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY ) == 0 ) )
	{
		pKeyValues = pKeyValues->MakeCopy();
		kvad_onError.Assign( pKeyValues );
		( *pInOutAllocdNew ) = true;
	}

	CUtlString str;

	CUtlVector< const char* > errorStack;
	errorStack.AddToHead( pRootName );

	if ( !ResolveAllVariablesRecursive( errorStack, varDefs, pKeyValues, nTexCompositeCreateFlags, str ) )
		return NULL;

	kvad_onError.Assign( NULL );
	return pKeyValues;
}

// ------------------------------------------------------------------------------------------------
// Perform all template expansion and variable substitution here. What should be output 
// should look like v1.0 paintkits without templates or variables. Return NULL
// if var substitution fails or if we can't resolve a template or something 
// (after outputting a meaningful error message, of course).
KeyValues* ParseTopLevelIntoKV( const char* pRootName, KeyValues* pValues, uint32 nTexCompositeCreateFlags, bool *pOutAllocdNew )
{
	Assert( pRootName != NULL );
	Assert( pOutAllocdNew != NULL );
	if ( !pValues )
		return NULL;

	bool bRequiresCleanup = false;
	KeyValues* pExpandedKV = NULL;
	KeyValuesAD autoCleanup_pExpandedKV( pExpandedKV );
	VariableDefs_t varDefs;

	pExpandedKV = ResolveTemplate( pRootName, pValues, nTexCompositeCreateFlags, &bRequiresCleanup );
	if ( pExpandedKV == NULL )
		return NULL;

	if ( bRequiresCleanup )
	{
		Assert( autoCleanup_pExpandedKV == nullptr || autoCleanup_pExpandedKV == pExpandedKV );
		autoCleanup_pExpandedKV.Assign( pExpandedKV );
	}

	pExpandedKV = ExtractVariableDefinitions( &varDefs, pRootName, pExpandedKV );
	if ( pExpandedKV == NULL )
		return NULL;

	// Only resolve the variables if we're instantiating. During verification time, we'll
	// just check that the keys are sensible and we can skip this.
	pExpandedKV = ResolveAllVariables( pRootName, varDefs, pExpandedKV, nTexCompositeCreateFlags, &bRequiresCleanup);
	if ( pExpandedKV == NULL )
		return NULL;

	Assert( bRequiresCleanup || varDefs.Count() == 0 || ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY ) != 0 ) );
	varDefs.RemoveAll(); // These won't be valid after we cleanup the tree to remove variable definitions.

	if ( bRequiresCleanup )
	{
		KeyValues* pChild = pExpandedKV->GetFirstSubKey();

		while ( pChild )
		{
			const char* pChildName = pChild->GetName();
			if ( pChildName[ 0 ] == '$' )
			{
				KeyValues* pNext = pChild->GetNextKey();

				pExpandedKV->RemoveSubKey( pChild );
				pChild->deleteThis();
				pChild = pNext;
			}
			else
				pChild = pChild->GetNextKey();
		}
	}


	// We don't need to clean up the KeyValues we created, so clear the AD.
	autoCleanup_pExpandedKV.Assign( NULL );

	( *pOutAllocdNew ) = bRequiresCleanup;
	return pExpandedKV;	
}

// ------------------------------------------------------------------------------------------------
bool HasTemplateOrVariables( const char** ppOutTemplateName, KeyValues* pKV)
{
	Assert( ppOutTemplateName );

	bool retVal = false;
	( *ppOutTemplateName ) = NULL;

	FOR_EACH_SUBKEY( pKV, pChild )
	{
		const char* pName = pChild->GetName();
		if ( V_stricmp( pName, "implements" ) == 0 )	
		{
			( *ppOutTemplateName ) = pChild->GetString();
			retVal = true;
		}

		if ( pName[ 0 ] == '$' )
			retVal = true;
	}

	return retVal;
}

// ------------------------------------------------------------------------------------------------
CTextureCompositor* CreateTextureCompositor( int _w, int _h, const char* pCompositeName, int nTeamNum, uint64 nRandomSeed, KeyValues* _stageDesc, uint32 nTexCompositeCreateFlags )
{
	TM_ZONE_DEFAULT( TELEMETRY_LEVEL0 );

	#ifdef STAGING_ONLY
		if ( r_texcomp_dump.GetInt() == 3 || r_texcomp_dump.GetInt() == 4 )
		{
			// Skip compression because it breaks saving render targets out
			// Also don't pollute the cache (or use it)
			nTexCompositeCreateFlags |= ( TEX_COMPOSITE_CREATE_FLAGS_NO_COMPRESSION | TEX_COMPOSITE_CREATE_FLAGS_FORCE );
		}
	#endif

	CUtlVector< CTCStage* > vecStage;
	CUtlVector< KeyValues* > kvs;

	KeyValuesAD kvAutoCleanup( (KeyValues*) nullptr );

	bool bRequiresCleanup = false;

	if ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_LOG_NODES_ONLY ) != 0 )
	{
		DevMsg( 0, "%s\n{\n", pCompositeName );
		KeyValuesDumpAsDevMsg( _stageDesc, 1, 0 );
		DevMsg( 0, "}\n" );
	}

	_stageDesc = ParseTopLevelIntoKV( pCompositeName, _stageDesc, nTexCompositeCreateFlags, &bRequiresCleanup );
	if ( !_stageDesc ) 
	{
		if ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_LOG_NODES_ONLY ) != 0 )
			Msg( "ERROR[%s]: Failed to create compositor, errors above.\n", pCompositeName );

		return NULL;
	}

	// Set ourselves up for future cleanup.
	if ( bRequiresCleanup )
		kvAutoCleanup.Assign( _stageDesc );

	if ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_LOG_NODES_ONLY )
	{
		if ( bRequiresCleanup )
		{
			DevMsg( 0, "With expansion:\n%s\n{\n", pCompositeName );
			KeyValuesDumpAsDevMsg( _stageDesc, 1, 0 );
			DevMsg( 0, "}\n" );
		}
		return NULL;
	}

	const char* pTemplateName = NULL;
	// If we're just doing a template verification, and we still have keys or values that look like template stuff, bail out now. 
	if ( HasTemplateOrVariables( &pTemplateName, _stageDesc ) && ( ( nTexCompositeCreateFlags & TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY ) != 0 ) )
	{
		CTextureCompositor* pComp = new CTextureCompositor( _w, _h, nTeamNum, pCompositeName, nRandomSeed, nTexCompositeCreateFlags );
		if ( pTemplateName )
			pComp->SetTemplate( pTemplateName );
		return pComp;
	}
	
	KeyValues* kv = _stageDesc->GetFirstTrueSubKey();
	if ( !kv )
		return NULL;

	kvs.AddToTail( kv );
	
	if ( !ParseNodes( &vecStage, kvs, nTexCompositeCreateFlags  ) )
	{
		FOR_EACH_VEC( vecStage, i )
		{
			SafeRelease( &vecStage[ i ] );
		}
	
		return NULL;
	}

	// Should only get 1 here.
	Assert( vecStage.Count() == 1 );

	CTCStage* rootStage = vecStage[ 0 ];

	// Need to add a copy as the new root.
	CTCStage* copyStage = new CTCCopyStage;
	copyStage->SetFirstChild( rootStage );
	rootStage = copyStage;

	CTextureCompositor* texCompositor = new CTextureCompositor( _w, _h, nTeamNum, pCompositeName, nRandomSeed, nTexCompositeCreateFlags );
	if ( pTemplateName )
		texCompositor->SetTemplate( pTemplateName );

	texCompositor->SetRootStage( rootStage );

	SafeRelease( &rootStage );

	return texCompositor;
}

// ------------------------------------------------------------------------------------------------
CTextureCompositorTemplate* CTextureCompositorTemplate::Create( const char* pName, KeyValues* pTmplDesc )
{
	if ( !pName || !pTmplDesc )
		return NULL;

	CTextureCompositor* texCompositor = CreateTextureCompositor( 1, 1, pName, 2, 0, pTmplDesc, TEX_COMPOSITE_CREATE_FLAGS_VERIFY_SCHEMA_ONLY | TEX_COMPOSITE_CREATE_FLAGS_VERIFY_TEMPLATE_ONLY );

	if ( texCompositor )
	{
		CTextureCompositorTemplate* pTemplate = new CTextureCompositorTemplate( pName, pTmplDesc );
		if ( texCompositor->UsesTemplate() )
		{
			pTemplate->SetImplementsName( texCompositor->GetTemplateName() );
		}
		// Bump then release the ref.
		texCompositor->AddRef();
		texCompositor->Release();

		return pTemplate;
	}

	return NULL;
}

// ------------------------------------------------------------------------------------------------
CTextureCompositorTemplate::~CTextureCompositorTemplate()
{
	// We don't own the KV we were created with--don't delete it.
}

// ------------------------------------------------------------------------------------------------
bool CTextureCompositorTemplate::ResolveDependencies() const
{
	// If we don't reference another template, then our verification was validated at construction 
	// time.
	if ( m_ImplementsName.IsEmpty() )
		return true;

	CTextureCompositorTemplate* pImplementsTmpl = TextureManager()->FindTextureCompositorTemplate( m_ImplementsName );

	// If we couldn't find our child, then we are not okay.
	if ( pImplementsTmpl == NULL )
	{
		Warning( "ERROR[paintkit_template %s]: Couldn't find template '%s' which we claim to implement.\n", (const char*) m_Name, (const char*)m_ImplementsName );
		return false;
	}

	return true;
}

// ------------------------------------------------------------------------------------------------
bool CTextureCompositorTemplate::HasDependencyCycles()
{
	// Uses Floyd's algorithm to determine if there's a cycle. 
	TM_ZONE_DEFAULT( TELEMETRY_LEVEL1 );

	if ( HasCycle( this ) )
	{
		// Print the cycle. This also marks the nodes as having been tested for cycles.
		PrintMinimumCycle( this );
		return true;
	}
	else
	{
		// Mark everything in this lineage as having been tested for cycles. 
		CTextureCompositorTemplate* pTmpl = this;
		while ( pTmpl != NULL )
		{
			if ( pTmpl->HasCheckedForCycles() )
				break;

			pTmpl->SetCheckedForCycles( true );
			pTmpl = Advance( pTmpl, 1 );
		}
	}

	return false;
}

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
void ComputeTextureMatrixFromRectangle( VMatrix* pOutMat, const Vector2D& bl, const Vector2D& tl, const Vector2D& tr )
{
	Assert( pOutMat != NULL );

	Vector2D leftEdge = bl - tl;
	Vector2D topEdge = tr - tl;
	Vector2D topEdgePerpLeft( -topEdge.y, topEdge.x );

	float magLeftEdge = leftEdge.Length();
	float magTopEdge = topEdge.Length();

	float xScalar = ( topEdgePerpLeft.Dot( leftEdge ) > 0 ) ? 1 : -1;


	// Simplification of acos( ( A . L ) / ( mag( A ) * mag( L ) )
	// Because A is ( 0, 1), which means A . L is just L.y
	// and mag( A ) * mag( L ) is just mag( L )
	float rotationD = RAD2DEG( acos( leftEdge.y / magLeftEdge ) ) 
		            * ( leftEdge.x < 0 ? 1 : -1 );
	
	VMatrix tmpMat;
	tmpMat.Identity();
	MatrixTranslate( tmpMat, Vector( tl.x, tl.y, 0 ) );
	MatrixRotate( tmpMat, Vector( 0, 0, 1 ), rotationD );
	tmpMat = tmpMat.Scale( Vector( xScalar * magTopEdge, magLeftEdge, 1.0f ) );
	MatrixInverseGeneral( tmpMat, *pOutMat );
	
	// Copy W into Z because this is a 2-D matrix.
	( *pOutMat )[ 0 ][ 2 ] = ( *pOutMat )[ 0 ][ 3 ];
	( *pOutMat )[ 1 ][ 2 ] = ( *pOutMat )[ 1 ][ 3 ];
	( *pOutMat )[ 2 ][ 2 ] = 1.0f;
}

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
CTextureCompositorTemplate* Advance( CTextureCompositorTemplate* pTmpl, int nSteps )
{
	Assert( pTmpl != NULL );

	for ( int i = 0; i < nSteps; ++i ) 
	{
		if ( pTmpl->ImplementsTemplate() )
		{
			pTmpl = TextureManager()->FindTextureCompositorTemplate( pTmpl->GetImplementsName() );
		}
		else
			return NULL;
	}

	return pTmpl;
}

// ------------------------------------------------------------------------------------------------
bool HasCycle( CTextureCompositorTemplate* pStartTempl )
{
	Assert( pStartTempl != NULL );

	CTextureCompositorTemplate* pTortoise = pStartTempl;
	CTextureCompositorTemplate* pHare = Advance( pStartTempl, 1 );

	while ( pHare != NULL )
	{
		Assert( pTortoise != NULL ); // pTortoise should never be NULL unless pHare already is.

		if ( pTortoise == pHare )
			return true;

		// There may still actually be a cycle here, but we've already reported it if so,
		// so go ahead and bail out and say "no cycle found."
		if ( pTortoise->HasCheckedForCycles() || pHare->HasCheckedForCycles() )
			return false;

		pTortoise = Advance( pTortoise, 1 );
		pHare = Advance( pHare, 1 );
	}

	return false;
}

// ------------------------------------------------------------------------------------------------
void PrintMinimumCycle( CTextureCompositorTemplate* pTmpl )
{
	TM_ZONE_DEFAULT( TELEMETRY_LEVEL1 );

	const char* pFirstNodeName = pTmpl->GetName();
	// Also mark the nodes as having been cycle-tested to save execution of retesting the same templates.

	// Finding a minimum cycle is O( n log n ) using a map, but we only do this when there's an error.
	CUtlMap< CTextureCompositorTemplate*, int > cycles( DefLessFunc( CTextureCompositorTemplate* ) );
	CUtlLinkedList< const char* > cycleBuilder;

	while ( pTmpl != NULL)
	{
		// Add before we bail so that the first looping element is in the list twice.
		cycleBuilder.AddToTail( pTmpl->GetName() );

		if ( cycles.IsValidIndex( cycles.Find( pTmpl ) ) )
			break;

		pTmpl->SetCheckedForCycles( true );
		cycles.Insert( pTmpl );
		pTmpl = Advance( pTmpl, 1 );
	}

	// If this hits, we didn't actually have a cycle. What?
	Assert( pTmpl );

	Warning( "ERROR[paintkit_template %s]: Detected cycle in paintkit template dependency chain: ", pFirstNodeName );
	FOR_EACH_LL( cycleBuilder, i )
	{
		Warning( "%s -> ", cycleBuilder[ i ] );
	}

	Warning( "...\n" );
}