summaryrefslogtreecommitdiff
path: root/engine/l_studio.cpp
blob: ef96ab929d3305111b545871397f3de29fc6d317 (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
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// models are the only shared resource between a client and server running
// on the same machine.
//===========================================================================//

#include "render_pch.h"
#include "client.h"
#include "gl_model_private.h"
#include "studio.h"
#include "phyfile.h"
#include "cdll_int.h"
#include "istudiorender.h"
#include "client_class.h"
#include "float.h"
#include "materialsystem/imaterialsystemhardwareconfig.h"
#include "materialsystem/ivballoctracker.h"
#include "modelloader.h"
#include "lightcache.h"
#include "studio_internal.h"
#include "cdll_engine_int.h"
#include "vphysics_interface.h"
#include "utllinkedlist.h"
#include "studio.h"
#include "icliententitylist.h"
#include "engine/ivmodelrender.h"
#include "optimize.h"
#include "icliententity.h"
#include "sys_dll.h"
#include "debugoverlay.h"
#include "enginetrace.h"
#include "l_studio.h"
#include "filesystem_engine.h"
#include "ModelInfo.h"
#include "cl_main.h"
#include "tier0/vprof.h"
#include "r_decal.h"
#include "vstdlib/random.h"
#include "datacache/idatacache.h"
#include "materialsystem/materialsystem_config.h"
#include "materialsystem/itexture.h"
#include "IHammer.h"
#if defined( _WIN32 ) && !defined( _X360 )
#include <xmmintrin.h>
#endif
#include "staticpropmgr.h"
#include "materialsystem/hardwaretexels.h"
#include "materialsystem/hardwareverts.h"
#include "tier1/callqueue.h"
#include "filesystem/IQueuedLoader.h"
#include "tier2/tier2.h"
#include "tier1/UtlSortVector.h"
#include "tier1/lzmaDecoder.h"
#include "ipooledvballocator.h"
#include "shaderapi/ishaderapi.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

// #define VISUALIZE_TIME_AVERAGE 1

extern ConVar r_flashlight_version2;

//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
void R_StudioInitLightingCache( void );
float Engine_WorldLightDistanceFalloff( const dworldlight_t *wl, const Vector& delta, bool bNoRadiusCheck = false );
void SetRootLOD_f( IConVar *var, const char *pOldString, float flOldValue );
void r_lod_f( IConVar *var, const char *pOldValue, float flOldValue );
void FlushLOD_f();

class CColorMeshData;
static void CreateLightmapsFromData(CColorMeshData* _colorMeshData);


//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------

ConVar r_drawmodelstatsoverlay( "r_drawmodelstatsoverlay", "0", FCVAR_CHEAT );
ConVar r_drawmodelstatsoverlaydistance( "r_drawmodelstatsoverlaydistance", "500", FCVAR_CHEAT );
ConVar r_drawmodellightorigin( "r_DrawModelLightOrigin", "0", FCVAR_CHEAT );
extern ConVar r_worldlights;
ConVar r_lod( "r_lod", "-1", 0, "", r_lod_f );
static ConVar r_entity( "r_entity", "-1", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );
static ConVar r_lightaverage( "r_lightaverage", "1", 0, "Activates/deactivate light averaging" );
static ConVar r_lightinterp( "r_lightinterp", "5", FCVAR_CHEAT, "Controls the speed of light interpolation, 0 turns off interpolation" );
static ConVar r_eyeglintlodpixels( "r_eyeglintlodpixels", "20.0", FCVAR_CHEAT, "The number of pixels wide an eyeball has to be before rendering an eyeglint.  Is a floating point value." );
ConVar r_rootlod( "r_rootlod", "0", FCVAR_MATERIAL_SYSTEM_THREAD | FCVAR_ARCHIVE, "Root LOD", true, 0, true, MAX_NUM_LODS-1, SetRootLOD_f );
static ConVar r_decalstaticprops( "r_decalstaticprops", "1", 0, "Decal static props test" );
static ConCommand r_flushlod( "r_flushlod", FlushLOD_f, "Flush and reload LODs." );
ConVar r_debugrandomstaticlighting( "r_debugrandomstaticlighting", "0", FCVAR_CHEAT, "Set to 1 to randomize static lighting for debugging.  Must restart for change to take affect." );
ConVar r_proplightingfromdisk( "r_proplightingfromdisk", "1", FCVAR_CHEAT, "0=Off, 1=On, 2=Show Errors" );
static ConVar r_itemblinkmax( "r_itemblinkmax", ".3", FCVAR_CHEAT );
static ConVar r_itemblinkrate( "r_itemblinkrate", "4.5", FCVAR_CHEAT );
static ConVar r_proplightingpooling( "r_proplightingpooling", "-1.0", FCVAR_CHEAT, "0 - off, 1 - static prop color meshes are allocated from a single shared vertex buffer (on hardware that supports stream offset)" );

//-----------------------------------------------------------------------------
// StudioRender config 
//-----------------------------------------------------------------------------
static ConVar	r_showenvcubemap( "r_showenvcubemap", "0", FCVAR_CHEAT );
static ConVar	r_eyemove		( "r_eyemove", "1", FCVAR_ARCHIVE ); // look around
static ConVar	r_eyeshift_x	( "r_eyeshift_x", "0", FCVAR_ARCHIVE ); // eye X position
static ConVar	r_eyeshift_y	( "r_eyeshift_y", "0", FCVAR_ARCHIVE ); // eye Y position
static ConVar	r_eyeshift_z	( "r_eyeshift_z", "0", FCVAR_ARCHIVE ); // eye Z position
static ConVar	r_eyesize		( "r_eyesize", "0", FCVAR_ARCHIVE ); // adjustment to iris textures
static ConVar	mat_softwareskin( "mat_softwareskin", "0", FCVAR_CHEAT );
static ConVar	r_nohw			( "r_nohw", "0", FCVAR_CHEAT );
static ConVar	r_nosw			( "r_nosw", "0", FCVAR_CHEAT );
static ConVar	r_teeth			( "r_teeth", "1" );
static ConVar	r_drawentities	( "r_drawentities", "1", FCVAR_CHEAT );
static ConVar	r_flex			( "r_flex", "1" );
static ConVar	r_eyes			( "r_eyes", "1" );
static ConVar	r_skin			( "r_skin", "0", FCVAR_CHEAT );
static ConVar	r_modelwireframedecal ( "r_modelwireframedecal", "0", FCVAR_CHEAT );
static ConVar	r_maxmodeldecal ( "r_maxmodeldecal", "50" );

static StudioRenderConfig_t s_StudioRenderConfig;

void UpdateStudioRenderConfig( void )
{
	// This can happen during initialization
	if ( !g_pMaterialSystemConfig || !g_pStudioRender )
		return;

	memset( &s_StudioRenderConfig, 0, sizeof(s_StudioRenderConfig) );

	s_StudioRenderConfig.bEyeMove = !!r_eyemove.GetInt();
	s_StudioRenderConfig.fEyeShiftX = r_eyeshift_x.GetFloat();
	s_StudioRenderConfig.fEyeShiftY = r_eyeshift_y.GetFloat();
	s_StudioRenderConfig.fEyeShiftZ = r_eyeshift_z.GetFloat();
	s_StudioRenderConfig.fEyeSize = r_eyesize.GetFloat();	
	if ( IsPC() && ( mat_softwareskin.GetInt() || ShouldDrawInWireFrameMode() ) )
	{
		s_StudioRenderConfig.bSoftwareSkin = true;
	}
	else
	{
		s_StudioRenderConfig.bSoftwareSkin = false;
	}
	s_StudioRenderConfig.bNoHardware = !!r_nohw.GetInt();
	s_StudioRenderConfig.bNoSoftware = !!r_nosw.GetInt();
	s_StudioRenderConfig.bTeeth = !!r_teeth.GetInt();
	s_StudioRenderConfig.drawEntities = r_drawentities.GetInt();
	s_StudioRenderConfig.bFlex = !!r_flex.GetInt();
	s_StudioRenderConfig.bEyes = !!r_eyes.GetInt();
	s_StudioRenderConfig.bWireframe = ShouldDrawInWireFrameMode();
	s_StudioRenderConfig.bDrawNormals = mat_normals.GetBool();
	s_StudioRenderConfig.skin = r_skin.GetInt();
	s_StudioRenderConfig.maxDecalsPerModel = r_maxmodeldecal.GetInt();
	s_StudioRenderConfig.bWireframeDecals = r_modelwireframedecal.GetInt() != 0;
	
	s_StudioRenderConfig.fullbright = g_pMaterialSystemConfig->nFullbright;
	s_StudioRenderConfig.bSoftwareLighting = g_pMaterialSystemConfig->bSoftwareLighting;

	s_StudioRenderConfig.bShowEnvCubemapOnly = r_showenvcubemap.GetInt() ? true : false;
	s_StudioRenderConfig.fEyeGlintPixelWidthLODThreshold = r_eyeglintlodpixels.GetFloat();

	g_pStudioRender->UpdateConfig( s_StudioRenderConfig );
}

void R_InitStudio( void )
{
#ifndef SWDS
	R_StudioInitLightingCache();
#endif
}

//-----------------------------------------------------------------------------
// Converts world lights to materialsystem lights
//-----------------------------------------------------------------------------

#define MIN_LIGHT_VALUE 0.03f

bool WorldLightToMaterialLight( dworldlight_t* pWorldLight, LightDesc_t& light )
{
	// BAD
	light.m_Attenuation0 = 0.0f;
	light.m_Attenuation1 = 0.0f;
	light.m_Attenuation2 = 0.0f;

	switch(pWorldLight->type)
	{
	case emit_spotlight:
		light.m_Type = MATERIAL_LIGHT_SPOT;
		light.m_Attenuation0 = pWorldLight->constant_attn;
		light.m_Attenuation1 = pWorldLight->linear_attn;
		light.m_Attenuation2 = pWorldLight->quadratic_attn;
		light.m_Theta = 2.0 * acos( pWorldLight->stopdot );
		light.m_Phi = 2.0 * acos( pWorldLight->stopdot2 );
		light.m_ThetaDot = pWorldLight->stopdot;
		light.m_PhiDot = pWorldLight->stopdot2;
		light.m_Falloff = pWorldLight->exponent ? pWorldLight->exponent : 1.0f;
		break;

	case emit_surface:
		// A 180 degree spotlight
		light.m_Type = MATERIAL_LIGHT_SPOT;
		light.m_Attenuation2 = 1.0;
		light.m_Theta = M_PI;
		light.m_Phi = M_PI;
		light.m_ThetaDot = 0.0f;
		light.m_PhiDot = 0.0f;
		light.m_Falloff = 1.0f;
		break;

	case emit_point:
		light.m_Type = MATERIAL_LIGHT_POINT;
		light.m_Attenuation0 = pWorldLight->constant_attn;
		light.m_Attenuation1 = pWorldLight->linear_attn;
		light.m_Attenuation2 = pWorldLight->quadratic_attn;
		break;

	case emit_skylight:
		light.m_Type = MATERIAL_LIGHT_DIRECTIONAL;
		break;

	// NOTE: Can't do quake lights in hardware (x-r factor)
	case emit_quakelight:	// not supported
	case emit_skyambient:	// doesn't factor into local lighting
		// skip these
		return false;
	}

	// No attenuation case..
	if ((light.m_Attenuation0 == 0.0f) && (light.m_Attenuation1 == 0.0f) &&
		(light.m_Attenuation2 == 0.0f))
	{
		light.m_Attenuation0 = 1.0f;
	}

	// renormalize light intensity...
	memcpy( &light.m_Position, &pWorldLight->origin, 3 * sizeof(float) );
	memcpy( &light.m_Direction, &pWorldLight->normal, 3 * sizeof(float) );
	light.m_Color[0] = pWorldLight->intensity[0];
	light.m_Color[1] = pWorldLight->intensity[1];
	light.m_Color[2] = pWorldLight->intensity[2];

	// Make it stop when the lighting gets to min%...
	float intensity = sqrtf( DotProduct( light.m_Color, light.m_Color ) );

	// Compute the light range based on attenuation factors
	if (pWorldLight->radius != 0)
	{
		light.m_Range = pWorldLight->radius;
	}
	else
	{
		// FALLBACK: older lights use this
		if (light.m_Attenuation2 == 0.0f)
		{
			if (light.m_Attenuation1 == 0.0f)
			{
				light.m_Range = sqrtf(FLT_MAX);
			}
			else
			{
				light.m_Range = (intensity / MIN_LIGHT_VALUE - light.m_Attenuation0) / light.m_Attenuation1;
			}
		}
		else
		{
			float a = light.m_Attenuation2;
			float b = light.m_Attenuation1;
			float c = light.m_Attenuation0 - intensity / MIN_LIGHT_VALUE;
			float discrim = b * b - 4 * a * c;
			if (discrim < 0.0f)
				light.m_Range = sqrtf(FLT_MAX);
			else
			{
				light.m_Range = (-b + sqrtf(discrim)) / (2.0f * a);
				if (light.m_Range < 0)
					light.m_Range = 0;
			}
		}
	}
	light.m_Flags = LIGHTTYPE_OPTIMIZATIONFLAGS_DERIVED_VALUES_CALCED;
	if( light.m_Attenuation0 != 0.0f )
	{
		light.m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0;
	}
	if( light.m_Attenuation1 != 0.0f )
	{
		light.m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION1;
	}
	if( light.m_Attenuation2 != 0.0f )
	{
		light.m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION2;
	}
	return true;
}


//-----------------------------------------------------------------------------
// Sets the hardware lighting state
//-----------------------------------------------------------------------------

static void R_SetNonAmbientLightingState( int numLights, dworldlight_t *locallight[MAXLOCALLIGHTS],
										  int *pNumLightDescs, LightDesc_t *pLightDescs, bool bUpdateStudioRenderLights )
{
	Assert( numLights >= 0 && numLights <= MAXLOCALLIGHTS );

	// convert dworldlight_t's to LightDesc_t's and send 'em down to g_pStudioRender->
	*pNumLightDescs = 0;

	LightDesc_t *pLightDesc;
	for ( int i = 0; i < numLights; i++)
	{
		pLightDesc = &pLightDescs[*pNumLightDescs];
		if (!WorldLightToMaterialLight( locallight[i], *pLightDesc ))
			continue;

		// Apply lightstyle
		float bias = LightStyleValue( locallight[i]->style );

		// Deal with overbrighting + bias
		pLightDesc->m_Color[0] *= bias;
		pLightDesc->m_Color[1] *= bias;
		pLightDesc->m_Color[2] *= bias;

		*pNumLightDescs += 1;
		Assert( *pNumLightDescs <= MAXLOCALLIGHTS );
	}

	if ( bUpdateStudioRenderLights )
	{
		g_pStudioRender->SetLocalLights( *pNumLightDescs, pLightDescs );
	}
}


//-----------------------------------------------------------------------------
// Computes the center of the studio model for illumination purposes
//-----------------------------------------------------------------------------
void R_ComputeLightingOrigin( IClientRenderable *pRenderable, studiohdr_t* pStudioHdr, const matrix3x4_t &matrix, Vector& center )
{
	int nAttachmentIndex = pStudioHdr->IllumPositionAttachmentIndex();
	if ( nAttachmentIndex <= 0 )
	{
		VectorTransform( pStudioHdr->illumposition, matrix, center );
	}
	else
	{
		matrix3x4_t attachment;
		pRenderable->GetAttachment( nAttachmentIndex, attachment );
		VectorTransform( pStudioHdr->illumposition, attachment, center );
	}
}



#if 0
// garymct - leave this in here for now. . we might need this for bumped models
void R_StudioCalculateVirtualLightAndLightCube( Vector& mid, Vector& virtualLightPosition,
											   Vector& virtualLightColor, Vector* lightBoxColor )
{
	int i, j;
	Vector delta;
	float dist2, ratio;
	byte  *pvis;
	float t;
	static ConVar bumpLightBlendRatioMin( "bump_light_blend_ratio_min", "0.00002" );
	static ConVar bumpLightBlendRatioMax( "bump_light_blend_ratio_max", "0.00004" );

	if ( g_pMaterialSystemConfig->nFullbright == 1 )
		return;
	
	VectorClear( virtualLightPosition );
	VectorClear( virtualLightColor );
	for( i = 0; i < 6; i++ )
		{
		VectorClear( lightBoxColor[i] );
	}
	byte pvs[MAX_MAP_LEAFS/8];
	pvis = CM_Vis( pvs, sizeof(pvs), CM_LeafCluster( CM_PointLeafnum( mid ), DVIS_PVS );

	float sumBumpBlendParam = 0;
	for (i = 0; i < host_state.worldbrush->numworldlights; i++)
	{
		dworldlight_t *wl = &host_state.worldbrush->worldlights[i];

		if (wl->cluster < 0)
			continue;

		// only do it if the entity can see into the lights leaf
		if (!BIT_SET( pvis, (wl->cluster)))
			continue;
	
		// hack: for this test, only deal with point light sources.
		if( wl->type != emit_point )
			continue;

		// check distance
		VectorSubtract( wl->origin, mid, delta );
		dist2 = DotProduct( delta, delta );
		
		ratio = R_WorldLightDistanceFalloff( wl, delta );
		
		VectorNormalize( delta );
		
		ratio = ratio * R_WorldLightAngle( wl, wl->normal, delta, delta );

		float bumpBlendParam; // 0.0 = all cube, 1.0 = all bump 
		
		// lerp
		bumpBlendParam = 
			( ratio - bumpLightBlendRatioMin.GetFloat() ) / 
			( bumpLightBlendRatioMax.GetFloat() - bumpLightBlendRatioMin.GetFloat() );
	
		if( bumpBlendParam > 0.0 )
		{
			// Get the bit that goes into the bump light
			sumBumpBlendParam += bumpBlendParam;
			VectorMA( virtualLightPosition, bumpBlendParam, wl->origin, virtualLightPosition );
			VectorMA( virtualLightColor, bumpBlendParam, wl->intensity, virtualLightColor );
		}

		if( bumpBlendParam < 1.0f )
		{
			// Get the bit that goes into the cube
			float cubeBlendParam;
			cubeBlendParam = 1.0f - bumpBlendParam;
			if( cubeBlendParam < 0.0f )
			{
				cubeBlendParam = 0.0f;
			}
			for (j = 0; j < numBoxDir; j++)
			{
				t = DotProduct( r_boxdir[j], delta );
				if (t > 0)
				{
					VectorMA( lightBoxColor[j], ratio * t * cubeBlendParam, wl->intensity, lightBoxColor[j] );
				}
			}
		}
	}
	// Get the final virtual light position and color.
	VectorMultiply( virtualLightPosition, 1.0f / sumBumpBlendParam, virtualLightPosition );
	VectorMultiply( virtualLightColor, 1.0f / sumBumpBlendParam, virtualLightColor );
}
#endif


// TODO: move cone calcs to position
// TODO: cone clipping calc's wont work for boxlight since the player asks for a single point.  Not sure what the volume is.
float Engine_WorldLightDistanceFalloff( const dworldlight_t *wl, const Vector& delta, bool bNoRadiusCheck )
{
	float falloff;

	switch (wl->type)
	{
		case emit_surface:
#if 1
			// Cull out stuff that's too far
			if (wl->radius != 0)
			{
				if ( DotProduct( delta, delta ) > (wl->radius * wl->radius))
					return 0.0f;
			}

			return InvRSquared(delta);
#else
			// 1/r*r
			falloff = DotProduct( delta, delta );
			if (falloff < 1)
				return 1.f;
			else
				return 1.f / falloff;
#endif

			break;

		case emit_skylight:
			return 1.f;
			break;

		case emit_quakelight:
			// X - r;
			falloff = wl->linear_attn - FastSqrt( DotProduct( delta, delta ) );
			if (falloff < 0)
				return 0.f;

			return falloff;
			break;

		case emit_skyambient:
			return 1.f;
			break;

		case emit_point:
		case emit_spotlight:	// directional & positional
			{
				float dist2, dist;

				dist2 = DotProduct( delta, delta );
				dist = FastSqrt( dist2 );

				// Cull out stuff that's too far
				if (!bNoRadiusCheck && (wl->radius != 0) && (dist > wl->radius))
					return 0.f;

				return 1.f / (wl->constant_attn + wl->linear_attn * dist + wl->quadratic_attn * dist2);
			}

			break;
		default:
			// Bug: need to return an error
			break;
	}
	return 1.f;
}

/*
  light_normal (lights normal translated to same space as other normals)
  surface_normal
  light_direction_normal | (light_pos - vertex_pos) |
*/
float Engine_WorldLightAngle( const dworldlight_t *wl, const Vector& lnormal, const Vector& snormal, const Vector& delta )
{
	float dot, dot2, ratio = 0;

	switch (wl->type)
	{
		case emit_surface:
			dot = DotProduct( snormal, delta );
			if (dot < 0)
				return 0;

			dot2 = -DotProduct (delta, lnormal);
			if (dot2 <= ON_EPSILON/10)
				return 0; // behind light surface

			return dot * dot2;

		case emit_point:
			dot = DotProduct( snormal, delta );
			if (dot < 0)
				return 0;
			return dot;

		case emit_spotlight:
//			return 1.0; // !!!
			dot = DotProduct( snormal, delta );
			if (dot < 0)
				return 0;

			dot2 = -DotProduct (delta, lnormal);
			if (dot2 <= wl->stopdot2)
				return 0; // outside light cone

			ratio = dot;
			if (dot2 >= wl->stopdot)
				return ratio;	// inside inner cone

			if ((wl->exponent == 1) || (wl->exponent == 0))
			{
				ratio *= (dot2 - wl->stopdot2) / (wl->stopdot - wl->stopdot2);
			}
			else
			{
				ratio *= pow((dot2 - wl->stopdot2) / (wl->stopdot - wl->stopdot2), wl->exponent );
			}
			return ratio;

		case emit_skylight:
			dot2 = -DotProduct( snormal, lnormal );
			if (dot2 < 0)
				return 0;
			return dot2;

		case emit_quakelight:
			// linear falloff
			dot = DotProduct( snormal, delta );
			if (dot < 0)
				return 0;
			return dot;

		case emit_skyambient:
			// not supported
			return 1;

		default:
			// Bug: need to return an error
			break;
	} 
	return 0;
}

//-----------------------------------------------------------------------------
// Allocator for color mesh vertex buffers (for use with static props only).
// It uses a trivial allocation scheme, which assumes that allocations and
// deallocations are not interleaved (you do all allocs, then all deallocs).
//-----------------------------------------------------------------------------
class CPooledVBAllocator_ColorMesh : public IPooledVBAllocator
{
public:

	CPooledVBAllocator_ColorMesh();
	virtual ~CPooledVBAllocator_ColorMesh();

	// Allocate the shared mesh (vertex buffer)
	virtual bool			Init( VertexFormat_t format, int numVerts );
	// Free the shared mesh (after Deallocate is called for all sub-allocs)
	virtual void			Clear();

	// Get the shared mesh (vertex buffer) from which sub-allocations are made
	virtual IMesh			*GetSharedMesh() { return m_pMesh; }

	// Get a pointer to the start of the vertex buffer data
	virtual void			*GetVertexBufferBase() { return m_pVertexBufferBase; }
	virtual int				GetNumVertsAllocated() { return m_totalVerts; } 

	// Allocate a sub-range of 'numVerts' from free space in the shared vertex buffer
	// (returns the byte offset from the start of the VB to the new allocation)
	virtual int				Allocate( int numVerts );
	// Deallocate an existing allocation
	virtual void			Deallocate( int offset, int numVerts );

private:

	// Assert/warn that the allocator is in a clear/empty state (returns FALSE if not)
	bool					CheckIsClear( void );

	IMesh		*m_pMesh;				// The shared mesh (vertex buffer) from which sub-allocations are made
	void		*m_pVertexBufferBase;	// A pointer to the start of the vertex buffer data
	int			m_totalVerts;			// The number of verts in the shared vertex buffer
	int			m_vertexSize;			// The stride of the shared vertex buffer

	int			m_numAllocations;		// The number of extant allocations
	int			m_numVertsAllocated;	// The number of vertices in extant allocations
	int			m_nextFreeOffset;		// The offset to be returned by the next call to Allocate()
	// (incremented as a simple stack)
	bool		m_bStartedDeallocation;	// This is set when Deallocate() is called for the first time,
	// at which point Allocate() cannot be called again until all
	// extant allocations have been deallocated.
};

struct colormeshparams_t
{
	int					m_nMeshes;
	int					m_nTotalVertexes;
	// Given memory alignment (VBs must be 4-KB aligned on X360, for example), it can be more efficient
	// to allocate many color meshes out of a single shared vertex buffer (using vertex 'stream offset')
	IPooledVBAllocator *m_pPooledVBAllocator;
	int					m_nVertexes[256];
	FileNameHandle_t	m_fnHandle;
};

class CColorMeshData
{
public:
	void DestroyResource()
	{
		g_pFileSystem->AsyncFinish( m_hAsyncControlVertex, true );
		g_pFileSystem->AsyncRelease( m_hAsyncControlVertex );

		g_pFileSystem->AsyncFinish( m_hAsyncControlTexel, true );
		g_pFileSystem->AsyncRelease( m_hAsyncControlTexel );

		// release the array of meshes
		CMatRenderContextPtr pRenderContext( materials );

		for ( int i=0; i<m_nMeshes; i++ )
		{
			if ( m_pMeshInfos[i].m_pPooledVBAllocator )
			{
				// Let the pooling allocator dealloc this sub-range of the shared vertex buffer
				m_pMeshInfos[i].m_pPooledVBAllocator->Deallocate( m_pMeshInfos[i].m_nVertOffsetInBytes, m_pMeshInfos[i].m_nNumVerts );
			}
			else
			{
				// Free this standalone mesh
				pRenderContext->DestroyStaticMesh( m_pMeshInfos[i].m_pMesh );
			}

			if (m_pMeshInfos[i].m_pLightmap)
			{
				m_pMeshInfos[i].m_pLightmap->Release();
				m_pMeshInfos[i].m_pLightmap = NULL;
			}

			if (m_pMeshInfos[i].m_pLightmapData)
			{
				delete [] m_pMeshInfos[i].m_pLightmapData->m_pTexelData;
				delete m_pMeshInfos[i].m_pLightmapData;
			}
		}


		delete [] m_pMeshInfos;
		delete [] m_ppTargets;
		delete this;
	}

	CColorMeshData *GetData()
	{ 
		return this; 
	}

	unsigned int Size()
	{ 
		// TODO: This is wrong because we don't currently account for the size of the textures we create. 
		// However, that data isn't available until way after this query is made, so just live with 
		// this for now I guess?
		return m_nTotalSize; 
	}

	static CColorMeshData *CreateResource( const colormeshparams_t &params )
	{
		CColorMeshData *data = new CColorMeshData;

		data->m_bHasInvalidVB = false;
		data->m_bColorMeshValid = false;
		data->m_bColorTextureValid = false;
		data->m_bColorTextureCreated = false;
		data->m_bNeedsRetry = false;
		data->m_hAsyncControlVertex = NULL;
		data->m_hAsyncControlTexel = NULL;
		data->m_fnHandle = params.m_fnHandle;
		
		data->m_nTotalSize = params.m_nMeshes * sizeof( IMesh* ) + params.m_nTotalVertexes * 4;
		data->m_nMeshes = params.m_nMeshes;
		data->m_pMeshInfos = new ColorMeshInfo_t[params.m_nMeshes];
		Q_memset( data->m_pMeshInfos, 0, params.m_nMeshes*sizeof( ColorMeshInfo_t ) );
		data->m_ppTargets = new unsigned char *[params.m_nMeshes];

		CMeshBuilder meshBuilder;
		CMatRenderContextPtr pRenderContext( materials );
	
		for ( int i=0; i<params.m_nMeshes; i++ )
		{
			VertexFormat_t vertexFormat = VERTEX_SPECULAR;

			data->m_pMeshInfos[i].m_pMesh				= NULL;
			data->m_pMeshInfos[i].m_pPooledVBAllocator	= params.m_pPooledVBAllocator;
			data->m_pMeshInfos[i].m_nVertOffsetInBytes	= 0;
			data->m_pMeshInfos[i].m_nNumVerts			= params.m_nVertexes[i];
			data->m_pMeshInfos[i].m_pLightmapData		= NULL;
			data->m_pMeshInfos[i].m_pLightmap		= NULL;

			if ( params.m_pPooledVBAllocator != NULL )
			{
				// Allocate a portion of a single, shared VB for each color mesh
				data->m_pMeshInfos[i].m_nVertOffsetInBytes = params.m_pPooledVBAllocator->Allocate( params.m_nVertexes[i] );
				
				if ( data->m_pMeshInfos[i].m_nVertOffsetInBytes == -1 )
				{
					// Failed (fall back to regular allocations)
					data->m_pMeshInfos[i].m_pPooledVBAllocator = NULL;
					data->m_pMeshInfos[i].m_nVertOffsetInBytes = 0;
				}
				else
				{
					// Set up the mesh+data pointers
					data->m_pMeshInfos[i].m_pMesh	= params.m_pPooledVBAllocator->GetSharedMesh();
					data->m_ppTargets[i]			= ( (unsigned char *)params.m_pPooledVBAllocator->GetVertexBufferBase() ) + data->m_pMeshInfos[i].m_nVertOffsetInBytes;
				}
			}

			if ( data->m_pMeshInfos[i].m_pMesh == NULL )
			{
				if ( g_VBAllocTracker )
					g_VBAllocTracker->TrackMeshAllocations( "CColorMeshData::CreateResource" );

				// Allocate a standalone VB per color mesh
				data->m_pMeshInfos[i].m_pMesh = pRenderContext->CreateStaticMesh( vertexFormat, TEXTURE_GROUP_STATIC_VERTEX_BUFFER_COLOR );

				if ( g_VBAllocTracker )
					g_VBAllocTracker->TrackMeshAllocations( NULL );
			}

			Assert( data->m_pMeshInfos[i].m_pMesh );
			if ( !data->m_pMeshInfos[i].m_pMesh )
			{
				data->DestroyResource();
				data = NULL;
				break;
			}
		}
		return data;
	}

	static unsigned int EstimatedSize( const colormeshparams_t &params )
	{
		// each vertex is a 4 byte color
		return params.m_nMeshes * sizeof( IMesh* ) + params.m_nTotalVertexes * 4;
	}

	int					m_nMeshes;
	ColorMeshInfo_t		*m_pMeshInfos;
	unsigned char		**m_ppTargets;
	unsigned int		m_nTotalSize;
	FSAsyncControl_t	m_hAsyncControlVertex;
	FSAsyncControl_t	m_hAsyncControlTexel;
	unsigned int		m_bHasInvalidVB : 1;
	unsigned int		m_bColorMeshValid : 1;
	unsigned int		m_bColorTextureValid : 1;		// Whether the texture data is valid, but not necessarily created
	unsigned int		m_bColorTextureCreated : 1;	// Whether the texture data has actually been created.
	unsigned int		m_bNeedsRetry : 1;

	FileNameHandle_t	m_fnHandle;
};

//-----------------------------------------------------------------------------
//
// Implementation of IVModelRender
//
//-----------------------------------------------------------------------------

// UNDONE: Move this to hud export code, subsume previous functions
class CModelRender : public IVModelRender,
					 public CManagedDataCacheClient< CColorMeshData, colormeshparams_t >
{
public:
	// members of the IVModelRender interface
	virtual void ForcedMaterialOverride( IMaterial *newMaterial, OverrideType_t nOverrideType = OVERRIDE_NORMAL );
	virtual int DrawModel( 	
					int flags, IClientRenderable *cliententity,
					ModelInstanceHandle_t instance, int entity_index, const model_t *model, 
					const Vector& origin, QAngle const& angles,
					int skin, int body, int hitboxset, 
					const matrix3x4_t* pModelToWorld,
					const matrix3x4_t *pLightingOffset );

	virtual void  SetViewTarget( const CStudioHdr *pStudioHdr, int nBodyIndex, const Vector& target );

	// Creates, destroys instance data to be associated with the model
	virtual ModelInstanceHandle_t CreateInstance( IClientRenderable *pRenderable, LightCacheHandle_t* pHandle );
	virtual void SetStaticLighting( ModelInstanceHandle_t handle, LightCacheHandle_t* pCache );
	virtual LightCacheHandle_t GetStaticLighting( ModelInstanceHandle_t handle );
	virtual void DestroyInstance( ModelInstanceHandle_t handle );
	virtual bool ChangeInstance( ModelInstanceHandle_t handle, IClientRenderable *pRenderable );

	// Creates a decal on a model instance by doing a planar projection
	// along the ray. The material is the decal material, the radius is the
	// radius of the decal to create.
	virtual void AddDecal( ModelInstanceHandle_t handle, Ray_t const& ray, 
		const Vector& decalUp, int decalIndex, int body, bool noPokethru = false, int maxLODToDecal = ADDDECAL_TO_ALL_LODS );
	virtual void AddColoredDecal( ModelInstanceHandle_t handle, Ray_t const& ray, 
		const Vector& decalUp, int decalIndex, int body, Color cColor, bool noPokethru = false, int maxLODToDecal = ADDDECAL_TO_ALL_LODS );
	
	virtual void GetMaterialOverride( IMaterial** ppOutForcedMaterial, OverrideType_t* pOutOverrideType );

	// Removes all the decals on a model instance
	virtual void RemoveAllDecals( ModelInstanceHandle_t handle );

	// Remove all decals from all models
	virtual void RemoveAllDecalsFromAllModels();

	// Shadow rendering (render-to-texture)
	virtual matrix3x4_t* DrawModelShadowSetup( IClientRenderable *pRenderable, int body, int skin, DrawModelInfo_t *pInfo, matrix3x4_t *pBoneToWorld );
	virtual void DrawModelShadow( IClientRenderable *pRenderable, const DrawModelInfo_t &info, matrix3x4_t *pBoneToWorld );

	// Used to allow the shadow mgr to manage a list of shadows per model
	unsigned short& FirstShadowOnModelInstance( ModelInstanceHandle_t handle ) { return m_ModelInstances[handle].m_FirstShadow; }

	// This gets called when overbright, etc gets changed to recompute static prop lighting.
	virtual bool RecomputeStaticLighting( ModelInstanceHandle_t handle );

	// Handlers for alt-tab
	virtual void ReleaseAllStaticPropColorData( void );
	virtual void RestoreAllStaticPropColorData( void );

	// Extended version of drawmodel
	virtual bool DrawModelSetup( ModelRenderInfo_t &pInfo, DrawModelState_t *pState, matrix3x4_t *pBoneToWorld, matrix3x4_t** ppBoneToWorldOut );
	virtual int	DrawModelEx( ModelRenderInfo_t &pInfo );
	virtual int	DrawModelExStaticProp( ModelRenderInfo_t &pInfo );
	virtual int DrawStaticPropArrayFast( StaticPropRenderInfo_t *pProps, int count, bool bShadowDepth );

	// Sets up lighting context for a point in space
	virtual void SetupLighting( const Vector &vecCenter );
	virtual void SuppressEngineLighting( bool bSuppress );

	inline vertexFileHeader_t *CacheVertexData() { return g_pMDLCache->GetVertexData( (MDLHandle_t)(int)m_pStudioHdr->virtualModel&0xffff ); }

	bool Init();
	void Shutdown();

	bool GetItemName( DataCacheClientID_t clientId, const void *pItem, char *pDest, unsigned nMaxLen );

	struct staticPropAsyncContext_t
	{
		DataCacheHandle_t	m_ColorMeshHandle;
		CColorMeshData		*m_pColorMeshData;
		int					m_nMeshes;
		unsigned int		m_nRootLOD;
		char				m_szFilenameVertex[MAX_PATH];
		char				m_szFilenameTexel[MAX_PATH];
	};


	void StaticPropColorMeshCallback( void *pContext, const void *pData, int numReadBytes, FSAsyncStatus_t asyncStatus );
	void StaticPropColorTexelCallback(void *pContext, const void *pData, int numReadBytes, FSAsyncStatus_t asyncStatus);


	// 360 holds onto static prop color meshes during same map transitions
	void PurgeCachedStaticPropColorData();
	bool IsStaticPropColorDataCached( const char *pName );
	DataCacheHandle_t GetCachedStaticPropColorData( const char *pName );

	virtual void SetupColorMeshes( int nTotalVerts );

private:
	enum
	{
		CURRENT_LIGHTING_UNINITIALIZED = -999999
	};

	enum ModelInstanceFlags_t
	{
		MODEL_INSTANCE_HAS_STATIC_LIGHTING    = 0x1,
		MODEL_INSTANCE_HAS_DISKCOMPILED_COLOR = 0x2,
		MODEL_INSTANCE_DISKCOMPILED_COLOR_BAD = 0x4,
		MODEL_INSTANCE_HAS_COLOR_DATA		  = 0x8
	};

	struct ModelInstance_t
	{
		IClientRenderable* m_pRenderable;

		// Need to store off the model. When it changes, we lose all instance data..
		model_t* m_pModel;
		StudioDecalHandle_t	m_DecalHandle;

		// Stores off the current lighting state
		LightingState_t m_CurrentLightingState;
		LightingState_t	m_AmbientLightingState;
		Vector m_flLightIntensity[MAXLOCALLIGHTS];
		float m_flLightingTime;

		// First shadow projected onto the model
		unsigned short	m_FirstShadow;
		unsigned short  m_nFlags;

		// Static lighting
		LightCacheHandle_t m_LightCacheHandle;

		// Color mesh managed by cache
		DataCacheHandle_t m_ColorMeshHandle;
	};

	// Sets up the render state for a model
	matrix3x4_t* SetupModelState( IClientRenderable *pRenderable );

	int ComputeLOD( const ModelRenderInfo_t &info, studiohwdata_t *pStudioHWData );

	void DrawModelExecute( const DrawModelState_t &state, const ModelRenderInfo_t &pInfo, matrix3x4_t *pCustomBoneToWorld = NULL );

	void InitColormeshParams( ModelInstance_t &instance, studiohwdata_t *pStudioHWData, colormeshparams_t *pColorMeshParams );
	CColorMeshData *FindOrCreateStaticPropColorData( ModelInstanceHandle_t handle );
	void DestroyStaticPropColorData( ModelInstanceHandle_t handle );
	bool UpdateStaticPropColorData( IHandleEntity *pEnt, ModelInstanceHandle_t handle );
	void ProtectColorDataIfQueued( DataCacheHandle_t );

	void ValidateStaticPropColorData( ModelInstanceHandle_t handle );
	bool LoadStaticPropColorData( IHandleEntity *pProp, DataCacheHandle_t colorMeshHandle, studiohwdata_t *pStudioHWData );

	// Returns true if the model instance is valid
	bool IsModelInstanceValid( ModelInstanceHandle_t handle );
	
	void DebugDrawLightingOrigin( const DrawModelState_t& state, const ModelRenderInfo_t &pInfo );

	LightingState_t *TimeAverageLightingState( ModelInstanceHandle_t handle,
		LightingState_t *pLightingState, int nEntIndex, const Vector *pLightingOrigin );

	// Cause the current lighting state to match the given one
	void SnapCurrentLightingState( ModelInstance_t &inst, LightingState_t *pLightingState );

	// Sets up lighting state for rendering
	void StudioSetupLighting( const DrawModelState_t &state, const Vector& absEntCenter, 
		LightCacheHandle_t* pLightcache, bool bVertexLit, bool bNeedsEnvCubemap, bool &bStaticLighting, 
		DrawModelInfo_t &drawInfo, const ModelRenderInfo_t &pInfo, int drawFlags );

	// Time average the ambient term
	void TimeAverageAmbientLight( LightingState_t &actualLightingState, ModelInstance_t &inst, 
		float flAttenFactor, LightingState_t *pLightingState, const Vector *pLightingOrigin );

	// Old-style computation of vertex lighting
	void ComputeModelVertexLightingOld( mstudiomodel_t *pModel, 
		matrix3x4_t& matrix, const LightingState_t &lightingState, color24 *pLighting,
		bool bUseConstDirLighting, float flConstDirLightAmount );

	// New-style computation of vertex lighting
	void ComputeModelVertexLighting( IHandleEntity *pProp, 
		mstudiomodel_t *pModel, OptimizedModel::ModelLODHeader_t *pVtxLOD,
		matrix3x4_t& matrix, Vector4D *pTempMem, color24 *pLighting );

	// Internal Decal
	void AddDecalInternal( ModelInstanceHandle_t handle, Ray_t const& ray, const Vector& decalUp, int decalIndex, int body, bool bUseColor, Color cColor, bool noPokeThru, int maxLODToDecal);

	// Model instance data
	CUtlLinkedList< ModelInstance_t, ModelInstanceHandle_t > m_ModelInstances; 

	// current active model
	studiohdr_t *m_pStudioHdr;

	bool m_bSuppressEngineLighting;

	CUtlDict< DataCacheHandle_t, int > m_CachedStaticPropColorData;
	CThreadFastMutex m_CachedStaticPropMutex;

	// Allocator for static prop color mesh vertex buffers (all are pooled into one VB)
	CPooledVBAllocator_ColorMesh	m_colorMeshVBAllocator;
};


static CModelRender s_ModelRender;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CModelRender, IVModelRender, VENGINE_HUDMODEL_INTERFACE_VERSION, s_ModelRender );
IVModelRender* modelrender = &s_ModelRender;

//-----------------------------------------------------------------------------
// Resource loading for static prop lighting
//-----------------------------------------------------------------------------
class CResourcePreloadPropLighting : public CResourcePreload
{
	virtual bool CreateResource( const char *pName )
	{
		if ( !r_proplightingfromdisk.GetBool() )
		{
			// do nothing, not an error
			return true;
		}

		char szBasename[MAX_PATH];
		char szFilename[MAX_PATH];
		V_FileBase( pName, szBasename, sizeof( szBasename ) );
		V_snprintf( szFilename, sizeof( szFilename ), "%s%s.vhv", szBasename, GetPlatformExt() );

		// static props have the same name across maps
		// can check if loading the same map and early out if data present
		if ( g_pQueuedLoader->IsSameMapLoading() && s_ModelRender.IsStaticPropColorDataCached( szFilename ) )
		{
			// same map is loading, all disk prop lighting was left in the cache
			// otherwise the pre-purge operation below will do the cleanup
			return true;
		}

		// create an anonymous job to get the lighting data in memory, claim during static prop instancing
		LoaderJob_t loaderJob;
		loaderJob.m_pFilename = szFilename;
		loaderJob.m_pPathID = "GAME";
		loaderJob.m_Priority = LOADERPRIORITY_DURINGPRELOAD;
		g_pQueuedLoader->AddJob( &loaderJob );
		return true;
	}

	//-----------------------------------------------------------------------------
	// Pre purge operation before i/o commences
	//-----------------------------------------------------------------------------
	virtual void PurgeUnreferencedResources()
	{
		if ( g_pQueuedLoader->IsSameMapLoading() )
		{
			// do nothing, same map is loading, correct disk prop lighting will still be in data cache
			return;
		}

		// Map is different, need to purge any existing disk prop lighting
		// before anonymous i/o commences, otherwise 2x memory usage
		s_ModelRender.PurgeCachedStaticPropColorData();
	}

	virtual void PurgeAll()
	{
		s_ModelRender.PurgeCachedStaticPropColorData();
	}
};
static CResourcePreloadPropLighting s_ResourcePreloadPropLighting;

//-----------------------------------------------------------------------------
// Init, shutdown studiorender
//-----------------------------------------------------------------------------
void InitStudioRender( void )
{
	UpdateStudioRenderConfig();
	s_ModelRender.Init();
}

void ShutdownStudioRender( void )
{
	s_ModelRender.Shutdown();
}

//-----------------------------------------------------------------------------
// Hook needed for shadows to work
//-----------------------------------------------------------------------------
unsigned short& FirstShadowOnModelInstance( ModelInstanceHandle_t handle )
{
	return s_ModelRender.FirstShadowOnModelInstance( handle );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void R_RemoveAllDecalsFromAllModels()
{
	s_ModelRender.RemoveAllDecalsFromAllModels();
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CModelRender::Init()
{
	// start a managed section in the cache
	CCacheClientBaseClass::Init( g_pDataCache, "ColorMesh" );

	if ( IsX360() )
	{
		g_pQueuedLoader->InstallLoader( RESOURCEPRELOAD_STATICPROPLIGHTING, &s_ResourcePreloadPropLighting );
	}

	return true;
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CModelRender::Shutdown()
{
	// end the managed section
	CCacheClientBaseClass::Shutdown();
}


//-----------------------------------------------------------------------------
// Used by the client to allow it to set lighting state instead of this code
//-----------------------------------------------------------------------------
void CModelRender::SuppressEngineLighting( bool bSuppress )
{
	m_bSuppressEngineLighting = bSuppress;
}


//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CModelRender::GetItemName( DataCacheClientID_t clientId, const void *pItem, char *pDest, unsigned nMaxLen )
{
	CColorMeshData *pColorMeshData = (CColorMeshData *)pItem;
	g_pFileSystem->String( pColorMeshData->m_fnHandle, pDest, nMaxLen );
	return true;
}


//-----------------------------------------------------------------------------
// Cause the current lighting state to match the given one
//-----------------------------------------------------------------------------
void CModelRender::SnapCurrentLightingState( ModelInstance_t &inst, LightingState_t *pLightingState )
{
	inst.m_CurrentLightingState = *pLightingState;
	for ( int i = 0; i < MAXLOCALLIGHTS; ++i )
	{
		if ( i < pLightingState->numlights )
		{
			inst.m_flLightIntensity[i] = pLightingState->locallight[i]->intensity; 
		}
		else
		{
			inst.m_flLightIntensity[i].Init( 0.0f, 0.0f, 0.0f );
		}
	}

#ifndef SWDS
	inst.m_flLightingTime = cl.GetTime();
#endif
}


#define AMBIENT_MAX 8.0f

//-----------------------------------------------------------------------------
// Time average the ambient term
//-----------------------------------------------------------------------------
void CModelRender::TimeAverageAmbientLight( LightingState_t &actualLightingState, 
										   ModelInstance_t &inst, float flAttenFactor, LightingState_t *pLightingState, const Vector *pLightingOrigin )
{
	flAttenFactor = clamp( flAttenFactor, 0.f, 1.f );   // don't need this but alex is a coward
	Vector vecDelta;
	for ( int i = 0; i < 6; ++i )
	{
		VectorSubtract( pLightingState->r_boxcolor[i], inst.m_CurrentLightingState.r_boxcolor[i], vecDelta );
		vecDelta *= flAttenFactor;
		inst.m_CurrentLightingState.r_boxcolor[i] = pLightingState->r_boxcolor[i] - vecDelta;

#if defined( VISUALIZE_TIME_AVERAGE ) && !defined( SWDS )
		if ( pLightingOrigin )
		{
			Vector vecDir = vec3_origin;
			vecDir[ i >> 1 ] = (i & 0x1) ? -1.0f : 1.0f;
			CDebugOverlay::AddLineOverlay( *pLightingOrigin, *pLightingOrigin + vecDir * 20, 
				255 * inst.m_CurrentLightingState.r_boxcolor[i].x, 
				255 * inst.m_CurrentLightingState.r_boxcolor[i].y,
				255 * inst.m_CurrentLightingState.r_boxcolor[i].z, 255, false, 5.0f );

			CDebugOverlay::AddLineOverlay( *pLightingOrigin + Vector(5, 5, 5), *pLightingOrigin + vecDir * 50, 
				255 * pLightingState->r_boxcolor[i].x, 
				255 * pLightingState->r_boxcolor[i].y,
				255 * pLightingState->r_boxcolor[i].z, 255, true, 5.0f );
		}
#endif
		// haven't been able to find this rare bug which results in ambient light getting "stuck"
		// on the viewmodel extremely rarely , presumably with infinities. So, mask the bug
		// (hopefully) and warn by clamping.
#ifndef NDEBUG
		Assert( inst.m_CurrentLightingState.r_boxcolor[i].IsValid() );
		for( int nComp = 0 ; nComp < 3; nComp++ )
		{
			Assert( inst.m_CurrentLightingState.r_boxcolor[i][nComp] >= 0.0 );
			Assert( inst.m_CurrentLightingState.r_boxcolor[i][nComp] <= AMBIENT_MAX );
		}
#endif
		inst.m_CurrentLightingState.r_boxcolor[i].x = clamp( inst.m_CurrentLightingState.r_boxcolor[i].x, 0.f, AMBIENT_MAX );
		inst.m_CurrentLightingState.r_boxcolor[i].y = clamp( inst.m_CurrentLightingState.r_boxcolor[i].y, 0.f, AMBIENT_MAX );
		inst.m_CurrentLightingState.r_boxcolor[i].z = clamp( inst.m_CurrentLightingState.r_boxcolor[i].z, 0.f, AMBIENT_MAX );
	}
	memcpy( &actualLightingState.r_boxcolor, &inst.m_CurrentLightingState.r_boxcolor, sizeof(inst.m_CurrentLightingState.r_boxcolor) );
}




//-----------------------------------------------------------------------------
// Do time averaging of the lighting state to avoid popping...
//-----------------------------------------------------------------------------
LightingState_t *CModelRender::TimeAverageLightingState( ModelInstanceHandle_t handle, LightingState_t *pLightingState, int nEntIndex, const Vector *pLightingOrigin )
{
	if ( r_lightaverage.GetInt() == 0 )
		return pLightingState;

#ifndef SWDS

	float flInterpFactor = r_lightinterp.GetFloat();
	if ( flInterpFactor == 0 )
		return pLightingState;

	if ( handle == MODEL_INSTANCE_INVALID)
		return pLightingState;

	ModelInstance_t &inst = m_ModelInstances[handle];
	if ( inst.m_flLightingTime == CURRENT_LIGHTING_UNINITIALIZED )
	{
		SnapCurrentLightingState( inst, pLightingState );
		return pLightingState;
	}

	float dt = (cl.GetTime() - inst.m_flLightingTime);
	if ( dt <= 0.0f )
	{
		dt = 0.0f;
	}
	else
	{
		inst.m_flLightingTime = cl.GetTime();
	}

	static LightingState_t actualLightingState;
	static dworldlight_t s_WorldLights[MAXLOCALLIGHTS];
	
	// I'm creating the equation v = vf - (vf-vi)e^-at 
	// where vf = this frame's lighting value, vi = current time averaged lighting value
	int i;
	Vector vecDelta;
	float flAttenFactor = exp( -flInterpFactor * dt );
	TimeAverageAmbientLight( actualLightingState, inst, flAttenFactor, pLightingState, pLightingOrigin );

	// Max # of lights...
	int nWorldLights;
	if ( !g_pMaterialSystemConfig->bSoftwareLighting )
	{
		nWorldLights = min( g_pMaterialSystemHardwareConfig->MaxNumLights(), r_worldlights.GetInt() );
	}
	else
	{
		nWorldLights = r_worldlights.GetInt();
	}

	// Create a mapping of identical lights
	int nMatchCount = 0;
	bool pMatch[MAXLOCALLIGHTS];
	Vector pLight[MAXLOCALLIGHTS];
	dworldlight_t *pSourceLight[MAXLOCALLIGHTS];

	memset( pMatch, 0, sizeof(pMatch) );
	for ( i = 0; i < pLightingState->numlights; ++i )
	{
		// By default, assume the light doesn't match an existing light, so blend up from 0
		pLight[i].Init( 0.0f, 0.0f, 0.0f );
		int j;
		for ( j = 0; j < inst.m_CurrentLightingState.numlights; ++j )
		{
			if ( pLightingState->locallight[i] == inst.m_CurrentLightingState.locallight[j] )
			{
				// Ok, we found a matching light, so use the intensity of that light at the moment
				++nMatchCount;
				pMatch[j] = true;
				pLight[i] = inst.m_flLightIntensity[j];
				break;
			}
		}
	}

	// For the lights in the current lighting state, attenuate them toward their actual value
	for ( i = 0; i < pLightingState->numlights; ++i )
	{
		actualLightingState.locallight[i] = &s_WorldLights[i];
		memcpy( &s_WorldLights[i], pLightingState->locallight[i], sizeof(dworldlight_t) );

		// Light already exists? Attenuate to it...
		VectorSubtract( pLightingState->locallight[i]->intensity, pLight[i], vecDelta );
		vecDelta *= flAttenFactor;

		s_WorldLights[i].intensity = pLightingState->locallight[i]->intensity - vecDelta;
		pSourceLight[i] = pLightingState->locallight[i];
	}

	// Ramp down any light we can; we may not be able to ramp them all down
	int nCurrLight = pLightingState->numlights;
	for ( i = 0; i < inst.m_CurrentLightingState.numlights; ++i )
	{
		if ( pMatch[i] )
			continue;

		// Has it faded out to black? Then remove it.
		if ( inst.m_flLightIntensity[i].LengthSqr() < 1 )
			continue;

		if ( nCurrLight >= MAXLOCALLIGHTS )
			break;

		actualLightingState.locallight[nCurrLight] = &s_WorldLights[nCurrLight];
		memcpy( &s_WorldLights[nCurrLight], inst.m_CurrentLightingState.locallight[i], sizeof(dworldlight_t) );

		// Attenuate to black (fade out)
		VectorMultiply( inst.m_flLightIntensity[i], flAttenFactor, vecDelta );

		s_WorldLights[nCurrLight].intensity = vecDelta;
		pSourceLight[nCurrLight] = inst.m_CurrentLightingState.locallight[i];

		if (( nCurrLight >= nWorldLights ) && pLightingOrigin)
		{
			AddWorldLightToAmbientCube( &s_WorldLights[nCurrLight], *pLightingOrigin, actualLightingState.r_boxcolor ); 
		}

		++nCurrLight;
	}

	actualLightingState.numlights = min( nCurrLight, nWorldLights );
	inst.m_CurrentLightingState.numlights = nCurrLight;

	for ( i = 0; i < nCurrLight; ++i )
	{
		inst.m_CurrentLightingState.locallight[i] = pSourceLight[i];
		inst.m_flLightIntensity[i] = s_WorldLights[i].intensity;

#if defined( VISUALIZE_TIME_AVERAGE ) && !defined( SWDS )
		Vector vecColor = pSourceLight[i]->intensity;
		float flMax = max( vecColor.x, vecColor.y );
		flMax = max( flMax, vecColor.z );
		if ( flMax == 0.0f )
		{
			flMax = 1.0f;
		}
		vecColor *= 255.0f / flMax;
		float flRatio = inst.m_flLightIntensity[i].Length() / pSourceLight[i]->intensity.Length();
		vecColor *= flRatio;
		CDebugOverlay::AddLineOverlay( *pLightingOrigin, pSourceLight[i]->origin, 
			vecColor.x, vecColor.y, vecColor.z, 255, false, 5.0f );
#endif
	}

	return &actualLightingState;
#else
	return pLightingState;
#endif
}

// Ambient boost settings
static ConVar r_ambientboost( "r_ambientboost", "1", FCVAR_ARCHIVE, "Set to boost ambient term if it is totally swamped by local lights" );
static ConVar r_ambientmin( "r_ambientmin", "0.3", FCVAR_ARCHIVE, "Threshold above which ambient cube will not boost (i.e. it's already sufficiently bright" );
static ConVar r_ambientfraction( "r_ambientfraction", "0.1", FCVAR_CHEAT, "Fraction of direct lighting that ambient cube must be below to trigger boosting" );
static ConVar r_ambientfactor( "r_ambientfactor", "5", FCVAR_ARCHIVE, "Boost ambient cube by no more than this factor" );
static ConVar r_lightcachemodel ( "r_lightcachemodel", "-1", FCVAR_CHEAT, "" );
static ConVar r_drawlightcache ("r_drawlightcache", "0", FCVAR_CHEAT, "0: off\n1: draw light cache entries\n2: draw rays\n");


//-----------------------------------------------------------------------------
// Sets up lighting state for rendering
//-----------------------------------------------------------------------------
void CModelRender::StudioSetupLighting( const DrawModelState_t &state, const Vector& absEntCenter, 
	LightCacheHandle_t* pLightcache, bool bVertexLit, bool bNeedsEnvCubemap, bool &bStaticLighting, 
	DrawModelInfo_t &drawInfo, const ModelRenderInfo_t &pInfo, int drawFlags )
{
	if ( m_bSuppressEngineLighting )
		return;

#ifndef SWDS
	ITexture *pEnvCubemapTexture = NULL;
	LightingState_t lightingState;

	Vector pSaveLightPos[MAXLOCALLIGHTS];

	Vector *pDebugLightingOrigin = NULL;
	Vector vecDebugLightingOrigin = vec3_origin;

	// Cache off lighting data for rendering decals - only on dx8/dx9.
	LightingState_t lightingDecalState;

	drawInfo.m_bStaticLighting = bStaticLighting && g_pMaterialSystemHardwareConfig->SupportsStaticPlusDynamicLighting();
	drawInfo.m_nLocalLightCount = 0;

	// Compute lighting origin from input
	Vector vLightingOrigin( 0.0f, 0.0f, 0.0f );
	CMatRenderContextPtr pRenderContext( materials );
	if ( pInfo.pLightingOrigin )
	{
		vLightingOrigin = *pInfo.pLightingOrigin;
	}
	else
	{
		vLightingOrigin = absEntCenter;
		if ( pInfo.pLightingOffset )
		{
			VectorTransform( absEntCenter, *pInfo.pLightingOffset, vLightingOrigin );
		}
	}

	// Set the lighting origin state
	pRenderContext->SetLightingOrigin( vLightingOrigin );

	ModelInstance_t *pModelInst = NULL;
	bool bHasDecals = false;
	if ( pInfo.instance != m_ModelInstances.InvalidIndex() )
	{
		pModelInst = &m_ModelInstances[pInfo.instance];
		if ( pModelInst )
		{
			bHasDecals = ( pModelInst->m_DecalHandle != STUDIORENDER_DECAL_INVALID );
		}
	}

	if ( pLightcache )
	{
		// static prop case.
		if ( bStaticLighting )
		{
			if ( g_pMaterialSystemHardwareConfig->SupportsStaticPlusDynamicLighting() )
			{
				LightingState_t *pLightingState = NULL;
				// dx8 and dx9 case. . .hardware can do baked lighting plus other dynamic lighting
				// We already have the static part baked into a color mesh, so just get the dynamic stuff.
				if ( StaticLightCacheAffectedByDynamicLight( *pLightcache ) )
				{
					pLightingState = LightcacheGetStatic( *pLightcache, &pEnvCubemapTexture );
					Assert( lightingState.numlights >= 0 && lightingState.numlights <= MAXLOCALLIGHTS );
				}
				else
				{
					pLightingState = LightcacheGetStatic( *pLightcache, &pEnvCubemapTexture, LIGHTCACHEFLAGS_DYNAMIC | LIGHTCACHEFLAGS_LIGHTSTYLE );
					Assert( lightingState.numlights >= 0 && lightingState.numlights <= MAXLOCALLIGHTS );
				}
				lightingState = *pLightingState;
			}
			else
			{
				// dx6 and dx7 case. . .hardware can either do software lighting or baked lighting only.
				if ( StaticLightCacheAffectedByDynamicLight( *pLightcache ) || 
					StaticLightCacheAffectedByAnimatedLightStyle( *pLightcache ) )
				{
					bStaticLighting = false;
				}
				else if ( StaticLightCacheNeedsSwitchableLightUpdate( *pLightcache ) )
				{
					// Need to rebake lighting since a switch has turned off/on.
					UpdateStaticPropColorData( state.m_pRenderable->GetIClientUnknown(), pInfo.instance );
				}
			}
		}

		if ( !bStaticLighting )
		{
			lightingState = *(LightcacheGetStatic( *pLightcache, &pEnvCubemapTexture ));
			Assert( lightingState.numlights >= 0 && lightingState.numlights <= MAXLOCALLIGHTS );
		}

		if ( r_decalstaticprops.GetBool() && pModelInst && drawInfo.m_bStaticLighting && bHasDecals )
		{
			for ( int iCube = 0; iCube < 6; ++iCube )
			{
				drawInfo.m_vecAmbientCube[iCube] = pModelInst->m_AmbientLightingState.r_boxcolor[iCube] + lightingState.r_boxcolor[iCube];
			}

			lightingDecalState.CopyLocalLights( pModelInst->m_AmbientLightingState );
			lightingDecalState.AddAllLocalLights( lightingState );

			Assert( lightingDecalState.numlights >= 0 && lightingDecalState.numlights <= MAXLOCALLIGHTS );
		}
	}
	else	// !pLightcache
	{
		vecDebugLightingOrigin = vLightingOrigin;
		pDebugLightingOrigin = &vecDebugLightingOrigin;

		// If we don't have a lightcache entry, but we have bStaticLighting, that means
		// that we are a prop_physics that has fallen asleep.
		if ( bStaticLighting )
		{
			LightcacheGetDynamic_Stats stats;
			pEnvCubemapTexture = LightcacheGetDynamic( vLightingOrigin, lightingState, 
				stats, LIGHTCACHEFLAGS_DYNAMIC | LIGHTCACHEFLAGS_LIGHTSTYLE );
			Assert( lightingState.numlights >= 0 && lightingState.numlights <= MAXLOCALLIGHTS );

			// Deal with all the dx6/dx7 issues (ie. can't do anything besides either baked lighting
			// or software dynamic lighting.
			if ( !g_pMaterialSystemHardwareConfig->SupportsStaticPlusDynamicLighting() )
			{
				if ( ( stats.m_bHasDLights || stats.m_bHasNonSwitchableLightStyles ) )
				{
					// We either have a light switch, or a dynamic light. . do it in software.
					// We'll reget the cache entry with different flags below.
					bStaticLighting = false;
				}
				else if ( stats.m_bNeedsSwitchableLightStyleUpdate )
				{
					// Need to rebake lighting since a switch has turned off/on.
					UpdateStaticPropColorData( state.m_pRenderable->GetIClientUnknown(), pInfo.instance );
				}
			}
		}

		if ( !bStaticLighting )
		{
			LightcacheGetDynamic_Stats stats;

			// For special r_drawlightcache mode, we only draw models containing the substring set in r_lightcachemodel
			bool bDebugModel = false;
			if( r_drawlightcache.GetInt() == 5 )
			{
				if ( pModelInst && pModelInst->m_pModel && !pModelInst->m_pModel->strName.IsEmpty() )
				{
					const char *szModelName = r_lightcachemodel.GetString();
					bDebugModel = V_stristr( pModelInst->m_pModel->strName, szModelName ) != NULL;
				}
			}
	
			pEnvCubemapTexture = LightcacheGetDynamic( vLightingOrigin, lightingState, stats, 
				LIGHTCACHEFLAGS_STATIC|LIGHTCACHEFLAGS_DYNAMIC|LIGHTCACHEFLAGS_LIGHTSTYLE|LIGHTCACHEFLAGS_ALLOWFAST, bDebugModel );

			Assert( lightingState.numlights >= 0 && lightingState.numlights <= MAXLOCALLIGHTS );
		}
		
		if ( pInfo.pLightingOffset && !pInfo.pLightingOrigin )
		{
			for ( int i = 0; i < lightingState.numlights; ++i )
			{
				pSaveLightPos[i] = lightingState.locallight[i]->origin; 
				VectorITransform( pSaveLightPos[i], *pInfo.pLightingOffset, lightingState.locallight[i]->origin );
			}
		}

		// Cache lighting for decals.
		if ( pModelInst && drawInfo.m_bStaticLighting && bHasDecals )
		{
			// Only do this on dx8/dx9.
			LightcacheGetDynamic_Stats stats;
			LightcacheGetDynamic( vLightingOrigin, lightingDecalState, stats,
				LIGHTCACHEFLAGS_STATIC|LIGHTCACHEFLAGS_DYNAMIC|LIGHTCACHEFLAGS_LIGHTSTYLE|LIGHTCACHEFLAGS_ALLOWFAST );

			Assert( lightingDecalState.numlights >= 0 && lightingDecalState.numlights <= MAXLOCALLIGHTS);
			
			for ( int iCube = 0; iCube < 6; ++iCube )
			{
				VectorCopy( lightingDecalState.r_boxcolor[iCube], drawInfo.m_vecAmbientCube[iCube] );
			}

			if ( pInfo.pLightingOffset && !pInfo.pLightingOrigin )
			{
				for ( int i = 0; i < lightingDecalState.numlights; ++i )
				{
					pSaveLightPos[i] = lightingDecalState.locallight[i]->origin; 
					VectorITransform( pSaveLightPos[i], *pInfo.pLightingOffset, lightingDecalState.locallight[i]->origin );
				}
			}
		}
	}

	Assert( lightingState.numlights >= 0 && lightingState.numlights <= MAXLOCALLIGHTS );
	
	// Do time averaging of the lighting state to avoid popping...
	LightingState_t *pState;
	if ( !bStaticLighting && !pLightcache )
	{
		pState = TimeAverageLightingState( pInfo.instance, &lightingState, pInfo.entity_index, pDebugLightingOrigin );
	}
	else
	{
		pState = &lightingState;
	}

	if ( bNeedsEnvCubemap && pEnvCubemapTexture )
	{
		pRenderContext->BindLocalCubemap( pEnvCubemapTexture );
	}

	if ( g_pMaterialSystemConfig->nFullbright == 1 )
	{
		pRenderContext->SetAmbientLight( 1.0, 1.0, 1.0 );

		static Vector white[6] = 
		{
			Vector( 1.0, 1.0, 1.0 ),
			Vector( 1.0, 1.0, 1.0 ),
			Vector( 1.0, 1.0, 1.0 ),
			Vector( 1.0, 1.0, 1.0 ),
			Vector( 1.0, 1.0, 1.0 ),
			Vector( 1.0, 1.0, 1.0 ),
		};

		g_pStudioRender->SetAmbientLightColors( white );

		// Disable all the lights..
		pRenderContext->DisableAllLocalLights();
	}
	else if ( bVertexLit )
	{
		if( drawFlags & STUDIORENDER_DRAW_ITEM_BLINK )
		{
			float add = r_itemblinkmax.GetFloat() * ( FastCos( r_itemblinkrate.GetFloat() * Sys_FloatTime() ) + 1.0f );
			Vector additiveColor( add, add, add );
			static Vector temp[6];
			int i;
			for( i = 0; i < 6; i++ )
			{
				temp[i] = pState->r_boxcolor[i] + additiveColor;
			}
			g_pStudioRender->SetAmbientLightColors( temp );
		}
		else
		{
			// If we have any lights and want to do ambient boost on this model
			if ( (pState->numlights > 0) && (pInfo.pModel->flags & MODELFLAG_STUDIOHDR_AMBIENT_BOOST) && r_ambientboost.GetBool() )
			{
				Vector lumCoeff( 0.3f, 0.59f, 0.11f );
				float avgCubeLuminance = 0.0f;
				float minCubeLuminance = FLT_MAX;
				float maxCubeLuminance = 0.0f;

				// Compute average luminance of ambient cube
				for( int i = 0; i < 6; i++ )
				{
					float luminance = DotProduct( pState->r_boxcolor[i], lumCoeff );	// compute luminance
					minCubeLuminance = fpmin(minCubeLuminance, luminance);				// min luminance
					maxCubeLuminance = fpmax(maxCubeLuminance, luminance);				// max luminance
					avgCubeLuminance += luminance;										// accumulate luminance
				}
				avgCubeLuminance /= 6.0f;												// average luminance

				// Compute the amount of direct light reaching the center of the model (attenuated by distance)
				float fDirectLight = 0.0f;
				for( int i = 0; i < pState->numlights; i++ )
				{
					Vector vLight = pState->locallight[i]->origin - vLightingOrigin;
					float d2 = DotProduct( vLight, vLight );
					float d = sqrtf( d2 );
					float fAtten = 1.0f;

					float denom = pState->locallight[i]->constant_attn +
								pState->locallight[i]->linear_attn * d +
								pState->locallight[i]->quadratic_attn * d2;

					if ( denom > 0.00001f )
					{
						fAtten = 1.0f / denom;
					}

					Vector vLit = pState->locallight[i]->intensity * fAtten;
					fDirectLight += DotProduct( vLit, lumCoeff );
				}

				// If ambient cube is sufficiently dim in absolute terms and ambient cube is swamped by direct lights
				if ( avgCubeLuminance < r_ambientmin.GetFloat() && (avgCubeLuminance < (fDirectLight * r_ambientfraction.GetFloat())) )	
				{
					Vector vFinalAmbientCube[6];
					float fBoostFactor =  min( (fDirectLight * r_ambientfraction.GetFloat()) / maxCubeLuminance, 5.f ); // boost no more than a certain factor
					for( int i = 0; i < 6; i++ )
					{
						vFinalAmbientCube[i] = pState->r_boxcolor[i] * fBoostFactor;
					}
					g_pStudioRender->SetAmbientLightColors( vFinalAmbientCube );		// Boost
				}
				else
				{
					g_pStudioRender->SetAmbientLightColors( pState->r_boxcolor );		// No Boost
				}
			}
			else // Don't bother with ambient boost, just use the ambient cube as is
			{
				g_pStudioRender->SetAmbientLightColors( pState->r_boxcolor );			// No Boost
			}
		}

		pRenderContext->SetAmbientLight( 0.0, 0.0, 0.0 );
		R_SetNonAmbientLightingState( pState->numlights, pState->locallight,
			                          &drawInfo.m_nLocalLightCount, &drawInfo.m_LocalLightDescs[0], true );

		// Cache lighting for decals.
		if( pModelInst && drawInfo.m_bStaticLighting && bHasDecals )
		{
			R_SetNonAmbientLightingState( lightingDecalState.numlights, lightingDecalState.locallight,
				                          &drawInfo.m_nLocalLightCount, &drawInfo.m_LocalLightDescs[0], false );
		}
	}

	if ( pInfo.pLightingOffset && !pInfo.pLightingOrigin )
	{
		for ( int i = 0; i < lightingState.numlights; ++i )
		{
			lightingState.locallight[i]->origin = pSaveLightPos[i];
		}
	}
#endif
}


//-----------------------------------------------------------------------------
// Uses this material instead of the one the model was compiled with
//-----------------------------------------------------------------------------

// FIXME: a duplicate of what's in CEngineTool::GetLightingConditions
int GetLightingConditions( const Vector &vecLightingOrigin, Vector *pColors, int nMaxLocalLights, LightDesc_t *pLocalLights, ITexture *&pEnvCubemapTexture )
{
#ifndef SWDS
	LightcacheGetDynamic_Stats stats;
	LightingState_t state;
	pEnvCubemapTexture = NULL;
	pEnvCubemapTexture = LightcacheGetDynamic( vecLightingOrigin, state, stats );
	Assert( state.numlights >= 0 && state.numlights <= MAXLOCALLIGHTS );
	memcpy( pColors, state.r_boxcolor, sizeof(state.r_boxcolor) );

	int nLightCount = 0;
	for ( int i = 0; i < state.numlights; ++i )
	{
		LightDesc_t *pLightDesc = &pLocalLights[nLightCount];
		if (!WorldLightToMaterialLight( state.locallight[i], *pLightDesc ))
			continue;

		// Apply lightstyle
		float bias = LightStyleValue( state.locallight[i]->style );

		// Deal with overbrighting + bias
		pLightDesc->m_Color[0] *= bias;
		pLightDesc->m_Color[1] *= bias;
		pLightDesc->m_Color[2] *= bias;

		if ( ++nLightCount >= nMaxLocalLights )
			break;
	}
	return nLightCount;
#endif
	return 0;
}

// FIXME: a duplicate of what's in CCDmeMdlRenderable<T>::SetUpLighting and CDmeEmitter::SetUpLighting
void CModelRender::SetupLighting( const Vector &vecCenter )
{
#ifndef SWDS
	// Set up lighting conditions
	Vector vecAmbient[6];
	Vector4D vecAmbient4D[6];
	LightDesc_t desc[2];
	ITexture *pEnvCubemapTexture = NULL;
	int nLightCount = GetLightingConditions( vecCenter, vecAmbient, 2, desc, pEnvCubemapTexture );
	int nMaxLights = g_pMaterialSystemHardwareConfig->MaxNumLights();
	if( nLightCount > nMaxLights )
	{
		nLightCount = nMaxLights;
	}

	int i;
	for( i = 0; i < 6; i++ )
	{
		VectorCopy( vecAmbient[i], vecAmbient4D[i].AsVector3D() );
		vecAmbient4D[i][3] = 1.0f;
	}
	CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
	pRenderContext->SetAmbientLightCube( vecAmbient4D );

	if ( pEnvCubemapTexture )
	{
		pRenderContext->BindLocalCubemap( pEnvCubemapTexture );
	}

	for( i = 0; i < nLightCount; i++ )
	{
		LightDesc_t *pLight = &desc[i];
		pLight->m_Flags = 0;
		if( pLight->m_Attenuation0 != 0.0f )
		{
			pLight->m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0;
		}
		if( pLight->m_Attenuation1 != 0.0f )
		{
			pLight->m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION1;
		}
		if( pLight->m_Attenuation2 != 0.0f )
		{
			pLight->m_Flags |= LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION2;
		}

		pRenderContext->SetLight( i, desc[i] );
	}

	for( ; i < nMaxLights; i++ )
	{
		LightDesc_t disableDesc;
		disableDesc.m_Type = MATERIAL_LIGHT_DISABLE;
		pRenderContext->SetLight( i, disableDesc );
	}
#endif
}



//-----------------------------------------------------------------------------
// Uses this material instead of the one the model was compiled with
//-----------------------------------------------------------------------------
void CModelRender::ForcedMaterialOverride( IMaterial *newMaterial, OverrideType_t nOverrideType )
{
	tmZone( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );

	g_pStudioRender->ForcedMaterialOverride( newMaterial, nOverrideType );
}


//-----------------------------------------------------------------------------
// Sets up the render state for a model
//-----------------------------------------------------------------------------
matrix3x4_t* CModelRender::SetupModelState( IClientRenderable *pRenderable )
{
	const model_t *pModel = pRenderable->GetModel();
	if ( !pModel )
		return NULL;

	studiohdr_t *pStudioHdr = modelinfo->GetStudiomodel( const_cast<model_t*>(pModel) );
	if ( pStudioHdr->numbodyparts == 0 )
		return NULL;

	matrix3x4_t *pBoneMatrices = NULL;
#ifndef SWDS
	// Set up skinning state
	Assert ( pRenderable );
	{
		int nBoneCount = pStudioHdr->numbones;
		pBoneMatrices = g_pStudioRender->LockBoneMatrices( pStudioHdr->numbones );
		pRenderable->SetupBones( pBoneMatrices, nBoneCount, BONE_USED_BY_ANYTHING, cl.GetTime() ); // hack hack
		g_pStudioRender->UnlockBoneMatrices();
	}
#endif

	return pBoneMatrices;
}


struct ModelDebugOverlayData_t
{
	DrawModelInfo_t m_ModelInfo;
	DrawModelResults_t m_ModelResults;
	Vector m_Origin;

	ModelDebugOverlayData_t() {}

private:
	ModelDebugOverlayData_t( const ModelDebugOverlayData_t &vOther );
};

static CUtlVector<ModelDebugOverlayData_t> s_SavedModelInfo;

void DrawModelDebugOverlay( const DrawModelInfo_t& info, const DrawModelResults_t &results, const Vector &origin, float r = 1.0f, float g = 1.0f, float b = 1.0f )
{
#ifndef SWDS
	float alpha = 1;
	if( r_drawmodelstatsoverlaydistance.GetFloat() == 1 )
	{
		alpha = 1.f - clamp( CurrentViewOrigin().DistTo( origin ) / r_drawmodelstatsoverlaydistance.GetFloat(), 0.f, 1.f );
	}
	else
	{
		float flDistance = CurrentViewOrigin().DistTo( origin );

		// The view model keeps throwing up its data and it looks like garbage, so I am trying to get rid of it.
		if ( flDistance < 36.0f )
			return;

		if ( flDistance > r_drawmodelstatsoverlaydistance.GetFloat() )
			return;
	}

	Assert( info.m_pStudioHdr );
	Assert( info.m_pStudioHdr->pszName() );
	Assert( info.m_pHardwareData );
	float duration = 0.0f;
	int lineOffset = 0;
	if( !info.m_pStudioHdr || !info.m_pStudioHdr->pszName() || !info.m_pHardwareData )
	{
		CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, "This model has problems. . see a programmer." );
		return;
	}

	char buf[1024];
	CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, info.m_pStudioHdr->pszName() );
	Q_snprintf( buf, sizeof( buf ), "lod: %d/%d\n", results.m_nLODUsed+1, ( int )info.m_pHardwareData->m_NumLODs );
	CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, buf );
	Q_snprintf( buf, sizeof( buf ), "tris: %d\n",  results.m_ActualTriCount );
	CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, buf );
	Q_snprintf( buf, sizeof( buf ), "hardware bones: %d\n",  results.m_NumHardwareBones );
	CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, buf );		
	Q_snprintf( buf, sizeof( buf ), "num batches: %d\n",  results.m_NumBatches );
	CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, buf );		
	Q_snprintf( buf, sizeof( buf ), "has shadow lod: %s\n", ( info.m_pStudioHdr->flags & STUDIOHDR_FLAGS_HASSHADOWLOD ) ? "true" : "false" );
	CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, buf );		
	Q_snprintf( buf, sizeof( buf ), "num materials: %d\n", results.m_NumMaterials );
	CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, buf );		

	int i;
	for( i = 0; i < results.m_Materials.Count(); i++ )
	{
		IMaterial *pMaterial = results.m_Materials[i];
		if( pMaterial )
		{
			int numPasses = pMaterial->GetNumPasses();
			Q_snprintf( buf, sizeof( buf ), "\t%s (%d %s)\n", results.m_Materials[i]->GetName(), numPasses, numPasses > 1 ? "passes" : "pass" );
			CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, buf );		
		}
	}
	if( results.m_Materials.Count() > results.m_NumMaterials )
	{
		CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, "(Remaining materials not shown)\n" );		
	}
	if( r_drawmodelstatsoverlay.GetInt() == 2 )
	{
		Q_snprintf( buf, sizeof( buf ), "Render Time: %0.1f ms\n", results.m_RenderTime.GetDuration().GetMillisecondsF());
		CDebugOverlay::AddTextOverlay( origin, lineOffset++, duration, r, g, b, alpha, buf );
	}

	//Q_snprintf( buf, sizeof( buf ), "Render Time: %0.1f ms\n", info.m_pClientEntity 
#endif
}

void AddModelDebugOverlay( const DrawModelInfo_t& info, const DrawModelResults_t &results, const Vector& origin )
{
	ModelDebugOverlayData_t &tmp = s_SavedModelInfo[s_SavedModelInfo.AddToTail()];
	tmp.m_ModelInfo = info;
	tmp.m_ModelResults = results;
	tmp.m_Origin = origin;
}

void ClearSaveModelDebugOverlays( void )
{
	s_SavedModelInfo.RemoveAll();
}

int SavedModelInfo_Compare_f( const void *l, const void *r )
{
	ModelDebugOverlayData_t *left = ( ModelDebugOverlayData_t * )l;
	ModelDebugOverlayData_t *right = ( ModelDebugOverlayData_t * )r;
	return left->m_ModelResults.m_RenderTime.GetDuration().GetSeconds() < right->m_ModelResults.m_RenderTime.GetDuration().GetSeconds();
}

static ConVar r_drawmodelstatsoverlaymin( "r_drawmodelstatsoverlaymin", "0.1", FCVAR_ARCHIVE, "time in milliseconds that a model must take to render before showing an overlay in r_drawmodelstatsoverlay 2" );
static ConVar r_drawmodelstatsoverlaymax( "r_drawmodelstatsoverlaymax", "1.5", FCVAR_ARCHIVE, "time in milliseconds beyond which a model overlay is fully red in r_drawmodelstatsoverlay 2" );

void DrawSavedModelDebugOverlays( void )
{
	if( s_SavedModelInfo.Count() == 0 )
	{
		return;
	}
	float min = r_drawmodelstatsoverlaymin.GetFloat();
	float max = r_drawmodelstatsoverlaymax.GetFloat();
	float ooRange = 1.0f / ( max - min );

	int i;
	for( i = 0; i < s_SavedModelInfo.Count(); i++ )
	{
		float r, g, b;
		float t = s_SavedModelInfo[i].m_ModelResults.m_RenderTime.GetDuration().GetMillisecondsF();
		if( t > min )
		{
			if( t >= max )
			{
				r = 1.0f; g = 0.0f; b = 0.0f;
			}
			else
			{
				r = ( t - min ) * ooRange;
				g = 1.0f - r;
				b = 0.0f;
			}
			DrawModelDebugOverlay( s_SavedModelInfo[i].m_ModelInfo, s_SavedModelInfo[i].m_ModelResults, s_SavedModelInfo[i].m_Origin, r, g, b );
		}
	}
	ClearSaveModelDebugOverlays();
}

void CModelRender::DebugDrawLightingOrigin( const DrawModelState_t& state, const ModelRenderInfo_t &pInfo )
{
#ifndef SWDS
	// determine light origin in world space
	Vector illumPosition;
	Vector lightOrigin;
	if ( pInfo.pLightingOrigin )
	{
		illumPosition = *pInfo.pLightingOrigin;
		lightOrigin = illumPosition;
	}
	else
	{
		R_ComputeLightingOrigin( state.m_pRenderable, state.m_pStudioHdr, *state.m_pModelToWorld, illumPosition );
		lightOrigin = illumPosition;
		if ( pInfo.pLightingOffset )
		{
			VectorTransform( illumPosition, *pInfo.pLightingOffset, lightOrigin );
		}
	}

	// draw z planar cross at lighting origin
	Vector pt0;
	Vector pt1;
	pt0    = lightOrigin;
	pt1    = lightOrigin;
	pt0.x -= 4;
	pt1.x += 4;
	CDebugOverlay::AddLineOverlay( pt0, pt1, 0, 255, 0, 255, true, 0.0f );
	pt0    = lightOrigin;
	pt1    = lightOrigin;
	pt0.y -= 4;
	pt1.y += 4;
	CDebugOverlay::AddLineOverlay( pt0, pt1, 0, 255, 0, 255, true, 0.0f );

	// draw lines from the light origin to the hull boundaries to identify model
	Vector pt;
	pt0.x = state.m_pStudioHdr->hull_min.x;
	pt0.y = state.m_pStudioHdr->hull_min.y;
	pt0.z = state.m_pStudioHdr->hull_min.z;
	VectorTransform( pt0, *state.m_pModelToWorld, pt1 );
	CDebugOverlay::AddLineOverlay( lightOrigin, pt1, 100, 100, 150, 255, true, 0.0f  );
	pt0.x = state.m_pStudioHdr->hull_min.x;
	pt0.y = state.m_pStudioHdr->hull_max.y;
	pt0.z = state.m_pStudioHdr->hull_min.z;
	VectorTransform( pt0, *state.m_pModelToWorld, pt1 );
	CDebugOverlay::AddLineOverlay( lightOrigin, pt1, 100, 100, 150, 255, true, 0.0f  );
	pt0.x = state.m_pStudioHdr->hull_max.x;
	pt0.y = state.m_pStudioHdr->hull_max.y;
	pt0.z = state.m_pStudioHdr->hull_min.z;
	VectorTransform( pt0, *state.m_pModelToWorld, pt1 );
	CDebugOverlay::AddLineOverlay( lightOrigin, pt1, 100, 100, 150, 255, true, 0.0f  );
	pt0.x = state.m_pStudioHdr->hull_max.x;
	pt0.y = state.m_pStudioHdr->hull_min.y;
	pt0.z = state.m_pStudioHdr->hull_min.z;
	VectorTransform( pt0, *state.m_pModelToWorld, pt1 );
	CDebugOverlay::AddLineOverlay( lightOrigin, pt1, 100, 100, 150, 255, true, 0.0f  );

	pt0.x = state.m_pStudioHdr->hull_min.x;
	pt0.y = state.m_pStudioHdr->hull_min.y;
	pt0.z = state.m_pStudioHdr->hull_max.z;
	VectorTransform( pt0, *state.m_pModelToWorld, pt1 );
	CDebugOverlay::AddLineOverlay( lightOrigin, pt1, 100, 100, 150, 255, true, 0.0f  );
	pt0.x = state.m_pStudioHdr->hull_min.x;
	pt0.y = state.m_pStudioHdr->hull_max.y;
	pt0.z = state.m_pStudioHdr->hull_max.z;
	VectorTransform( pt0, *state.m_pModelToWorld, pt1 );
	CDebugOverlay::AddLineOverlay( lightOrigin, pt1, 100, 100, 150, 255, true, 0.0f  );
	pt0.x = state.m_pStudioHdr->hull_max.x;
	pt0.y = state.m_pStudioHdr->hull_max.y;
	pt0.z = state.m_pStudioHdr->hull_max.z;
	VectorTransform( pt0, *state.m_pModelToWorld, pt1 );
	CDebugOverlay::AddLineOverlay( lightOrigin, pt1, 100, 100, 150, 255, true, 0.0f  );
	pt0.x = state.m_pStudioHdr->hull_max.x;
	pt0.y = state.m_pStudioHdr->hull_min.y;
	pt0.z = state.m_pStudioHdr->hull_max.z;
	VectorTransform( pt0, *state.m_pModelToWorld, pt1 );
	CDebugOverlay::AddLineOverlay( lightOrigin, pt1, 100, 100, 150, 255, true, 0.0f  );	
#endif
}
//-----------------------------------------------------------------------------
// Actually renders the model
//-----------------------------------------------------------------------------
void CModelRender::DrawModelExecute( const DrawModelState_t &state, const ModelRenderInfo_t &pInfo, matrix3x4_t *pBoneToWorld )
{
#ifndef SWDS
	bool bShadowDepth = (pInfo.flags & STUDIO_SHADOWDEPTHTEXTURE) != 0;
	bool bSSAODepth = ( pInfo.flags & STUDIO_SSAODEPTHTEXTURE ) != 0;

	// Bail if we're rendering into shadow depth map and this model doesn't cast shadows
	if ( bShadowDepth && ( ( pInfo.pModel->flags & MODELFLAG_STUDIOHDR_DO_NOT_CAST_SHADOWS ) != 0 ) )
		return;

	// Shadow state...
	g_pShadowMgr->SetModelShadowState( pInfo.instance );

	if ( g_bTextMode )
		return;

	// Sets up flexes
	float *pFlexWeights = NULL;
	float *pFlexDelayedWeights = NULL;
	int nFlexCount = state.m_pStudioHdr->numflexdesc;
	if ( nFlexCount > 0 )
	{
		// Does setup for flexes
		Assert( pBoneToWorld );
		bool bUsesDelayedWeights = state.m_pRenderable->UsesFlexDelayedWeights();
		g_pStudioRender->LockFlexWeights( nFlexCount, &pFlexWeights, bUsesDelayedWeights ? &pFlexDelayedWeights : NULL );
		state.m_pRenderable->SetupWeights( pBoneToWorld, nFlexCount, pFlexWeights, pFlexDelayedWeights );
		g_pStudioRender->UnlockFlexWeights();
	}

	// OPTIMIZE: Try to precompute part of this mess once a frame at the very least.
	bool bUsesBumpmapping = ( g_pMaterialSystemHardwareConfig->GetDXSupportLevel() >= 80 ) && ( pInfo.pModel->flags & MODELFLAG_STUDIOHDR_USES_BUMPMAPPING );

	bool bStaticLighting = ( state.m_drawFlags & STUDIORENDER_DRAW_STATIC_LIGHTING ) &&
								( state.m_pStudioHdr->flags & STUDIOHDR_FLAGS_STATIC_PROP ) && 
								( !bUsesBumpmapping ) && 
								( pInfo.instance != MODEL_INSTANCE_INVALID ) &&
								g_pMaterialSystemHardwareConfig->SupportsColorOnSecondStream();

	bool bVertexLit = ( pInfo.pModel->flags & MODELFLAG_VERTEXLIT ) != 0;

	bool bNeedsEnvCubemap = r_showenvcubemap.GetInt() || ( pInfo.pModel->flags & MODELFLAG_STUDIOHDR_USES_ENV_CUBEMAP );
	
	if ( r_drawmodellightorigin.GetBool() && !bShadowDepth && !bSSAODepth )
	{
		DebugDrawLightingOrigin( state, pInfo );
	}

	ColorMeshInfo_t *pColorMeshes = NULL;
	DataCacheHandle_t hColorMeshData = DC_INVALID_HANDLE;
	if ( bStaticLighting )
	{
		// have static lighting, get from cache
		hColorMeshData = m_ModelInstances[pInfo.instance].m_ColorMeshHandle;
		CColorMeshData *pColorMeshData = CacheGet( hColorMeshData );
		if ( !pColorMeshData || pColorMeshData->m_bNeedsRetry )
		{
			// color meshes are not present, try to re-establish
			if ( RecomputeStaticLighting( pInfo.instance ) )
			{
				pColorMeshData = CacheGet( hColorMeshData );
			}
			else if ( !pColorMeshData || !pColorMeshData->m_bNeedsRetry )
			{
				// can't draw
				return;
			}
		}

		if ( pColorMeshData && ( pColorMeshData->m_bColorMeshValid || pColorMeshData->m_bColorTextureValid ) )
		{
			pColorMeshes = pColorMeshData->m_pMeshInfos;
			if (pColorMeshData->m_bColorTextureValid && !pColorMeshData->m_bColorTextureCreated)
			{
				CreateLightmapsFromData(pColorMeshData);
			}
		}
		else
		{
			// failed, draw without static lighting
			bStaticLighting = false;
		}
	}

	DrawModelInfo_t info;
	info.m_bStaticLighting = false;

	// get lighting from ambient light sources and radiosity bounces
	// also set up the env_cubemap from the light cache if necessary.
	if ( ( bVertexLit || bNeedsEnvCubemap ) && !bShadowDepth && !bSSAODepth )
	{
		// See if we're using static lighting
		LightCacheHandle_t* pLightCache = NULL;
		if ( pInfo.instance != MODEL_INSTANCE_INVALID )
		{
			if ( ( m_ModelInstances[pInfo.instance].m_nFlags & MODEL_INSTANCE_HAS_STATIC_LIGHTING ) && m_ModelInstances[pInfo.instance].m_LightCacheHandle )
			{
				pLightCache = &m_ModelInstances[pInfo.instance].m_LightCacheHandle;
			}
		}

		// Choose the lighting origin
		Vector entOrigin;
		R_ComputeLightingOrigin( state.m_pRenderable, state.m_pStudioHdr, *state.m_pModelToWorld, entOrigin );

		// Set up lighting based on the lighting origin
		StudioSetupLighting( state, entOrigin, pLightCache, bVertexLit, bNeedsEnvCubemap, bStaticLighting, info, pInfo, state.m_drawFlags );
	}

	// Set up the camera state
	g_pStudioRender->SetViewState( CurrentViewOrigin(), CurrentViewRight(), CurrentViewUp(), CurrentViewForward() );

	// Color + alpha modulation
	g_pStudioRender->SetColorModulation( r_colormod );
	g_pStudioRender->SetAlphaModulation( r_blend );

	Assert( modelloader->IsLoaded( pInfo.pModel ) );
	info.m_pStudioHdr = state.m_pStudioHdr;
	info.m_pHardwareData = state.m_pStudioHWData;
	info.m_Skin = pInfo.skin;
	info.m_Body = pInfo.body;
	info.m_HitboxSet = pInfo.hitboxset;
	info.m_pClientEntity = (void*)state.m_pRenderable;
	info.m_Lod = state.m_lod;
	info.m_pColorMeshes = pColorMeshes;

	// Don't do decals if shadow depth mapping...
	info.m_Decals = ( bShadowDepth || bSSAODepth ) ? STUDIORENDER_DECAL_INVALID : state.m_decals;

	// Get perf stats if we are going to use them.
	int overlayVal = r_drawmodelstatsoverlay.GetInt();
	int drawFlags = state.m_drawFlags;

	if ( bShadowDepth )
	{
		drawFlags |= STUDIORENDER_DRAW_OPAQUE_ONLY;
		drawFlags |= STUDIORENDER_SHADOWDEPTHTEXTURE;
	}

	if ( bSSAODepth == true )
	{
		drawFlags |= STUDIORENDER_DRAW_OPAQUE_ONLY;
		drawFlags |= STUDIORENDER_SSAODEPTHTEXTURE;
	}

	if ( overlayVal && !bShadowDepth && !bSSAODepth )
	{
		drawFlags |= STUDIORENDER_DRAW_GET_PERF_STATS;
	}

	if ( ( pInfo.flags & STUDIO_GENERATE_STATS ) != 0 )
	{
		drawFlags |= STUDIORENDER_GENERATE_STATS;
	}

	DrawModelResults_t results;
	g_pStudioRender->DrawModel( &results, info, pBoneToWorld, pFlexWeights, 
		pFlexDelayedWeights, pInfo.origin, drawFlags );
	info.m_Lod = results.m_nLODUsed;

	if ( overlayVal && !bShadowDepth && !bSSAODepth )
	{
		if ( overlayVal != 2 )
		{
			DrawModelDebugOverlay( info, results, pInfo.origin );
		}
		else
		{
			AddModelDebugOverlay( info, results, pInfo.origin );
		}
	}

	if ( pColorMeshes)
	{
		ProtectColorDataIfQueued( hColorMeshData );
	}

#endif
}

//-----------------------------------------------------------------------------
// Main entry point for model rendering in the engine
//-----------------------------------------------------------------------------
int CModelRender::DrawModel( 	
	int flags,
	IClientRenderable *pRenderable,
	ModelInstanceHandle_t instance,
	int entity_index, 
	const model_t *pModel, 
	const Vector &origin,
	const QAngle &angles,
	int skin,
	int body,
	int hitboxset,
	const matrix3x4_t* pModelToWorld,
	const matrix3x4_t *pLightingOffset )
{
	ModelRenderInfo_t sInfo;
	sInfo.flags = flags;
	sInfo.pRenderable = pRenderable;
	sInfo.instance = instance;
	sInfo.entity_index = entity_index;
	sInfo.pModel = pModel;
	sInfo.origin = origin;
	sInfo.angles = angles;
	sInfo.skin = skin;
	sInfo.body = body;
	sInfo.hitboxset = hitboxset;
	sInfo.pModelToWorld = pModelToWorld;
	sInfo.pLightingOffset = pLightingOffset;

	if ( (r_entity.GetInt() == -1) || (r_entity.GetInt() == entity_index) )
	{
		return DrawModelEx( sInfo );
	}

	return 0;
}

int	CModelRender::ComputeLOD( const ModelRenderInfo_t &info, studiohwdata_t *pStudioHWData )
{
	int lod = r_lod.GetInt();
	// FIXME!!!  This calc should be in studiorender, not here!!!!!  But since the bone setup
	// is done here, and we need the bone mask, we'll do it here for now.
	if ( lod == -1 )
	{
		CMatRenderContextPtr pRenderContext( materials );
		float screenSize = pRenderContext->ComputePixelWidthOfSphere(info.pRenderable->GetRenderOrigin(), 0.5f );
		float metric = pStudioHWData->LODMetric(screenSize);
		lod = pStudioHWData->GetLODForMetric(metric);
	}
	else
	{
		if ( ( info.flags & STUDIOHDR_FLAGS_HASSHADOWLOD ) && ( lod > pStudioHWData->m_NumLODs - 2 ) )
		{
			lod = pStudioHWData->m_NumLODs - 2;
		}
		else if ( lod > pStudioHWData->m_NumLODs - 1 )
		{
			lod = pStudioHWData->m_NumLODs - 1;
		}
		else if( lod < 0 )
		{
			lod = 0;
		}
	}

	if ( lod < 0 )
	{
		lod = 0;
	}
	else if ( lod >= pStudioHWData->m_NumLODs )
	{
		lod = pStudioHWData->m_NumLODs - 1;
	}

	// clamp to root lod
	if (lod < pStudioHWData->m_RootLOD)
	{
		lod = pStudioHWData->m_RootLOD;
	}

	Assert( lod >= 0 && lod < pStudioHWData->m_NumLODs );
	return lod;
}

//-----------------------------------------------------------------------------
// Purpose: 
// Input  : &pInfo - 
//-----------------------------------------------------------------------------
bool CModelRender::DrawModelSetup( ModelRenderInfo_t &pInfo, DrawModelState_t *pState, matrix3x4_t *pCustomBoneToWorld, matrix3x4_t** ppBoneToWorldOut )
{
	*ppBoneToWorldOut = NULL;

#ifdef SWDS
	return false;
#endif

#if _DEBUG
	if ( (char*)pInfo.pRenderable < (char*)1024 )
	{
		Error( "CModelRender::DrawModel: pRenderable == 0x%p", pInfo.pRenderable );
	}
#endif

	// Can only deal with studio models
	Assert( pInfo.pModel->type == mod_studio );
	Assert( modelloader->IsLoaded( pInfo.pModel ) );

	DrawModelState_t &state = *pState;
	state.m_pStudioHdr = g_pMDLCache->GetStudioHdr( pInfo.pModel->studio );
	state.m_pRenderable = pInfo.pRenderable;

	// Quick exit if we're just supposed to draw a specific model...
	if ( (r_entity.GetInt() != -1) && (r_entity.GetInt() != pInfo.entity_index) )
		return false;

	// quick exit
	if (state.m_pStudioHdr->numbodyparts == 0)
		return false;

	if ( !pInfo.pModelToWorld )
	{
		Assert( 0 );
		return false;
	}

	state.m_pModelToWorld = pInfo.pModelToWorld;

	Assert ( pInfo.pRenderable );

	state.m_pStudioHWData = g_pMDLCache->GetHardwareData( pInfo.pModel->studio );
	if ( !state.m_pStudioHWData )
		return false;

	state.m_lod = ComputeLOD( pInfo, state.m_pStudioHWData );
	
	int boneMask = BONE_USED_BY_VERTEX_AT_LOD( state.m_lod );
	// Why isn't this always set?!?

	if ( ( pInfo.flags & STUDIO_RENDER ) == 0 )
	{
		// no rendering, just force a bone setup.  Don't copy the bones
		bool bOk = pInfo.pRenderable->SetupBones( NULL, MAXSTUDIOBONES, boneMask, cl.GetTime() );
		return bOk;
	}

	int nBoneCount = state.m_pStudioHdr->numbones;
	matrix3x4_t *pBoneToWorld = pCustomBoneToWorld;
	if ( !pCustomBoneToWorld )
	{
		pBoneToWorld = g_pStudioRender->LockBoneMatrices( nBoneCount );
	}
	const bool bOk = pInfo.pRenderable->SetupBones( pBoneToWorld, nBoneCount, boneMask, cl.GetTime() );
	if ( !pCustomBoneToWorld )
	{
		g_pStudioRender->UnlockBoneMatrices();
	}
	if ( !bOk )
		return false;

	*ppBoneToWorldOut = pBoneToWorld;

	// Convert the instance to a decal handle.
	state.m_decals = STUDIORENDER_DECAL_INVALID;
	if (pInfo.instance != MODEL_INSTANCE_INVALID)
	{
		state.m_decals = m_ModelInstances[pInfo.instance].m_DecalHandle;
	}

	state.m_drawFlags = STUDIORENDER_DRAW_ENTIRE_MODEL;
	if ( pInfo.flags & STUDIO_TWOPASS )
	{
		if (pInfo.flags & STUDIO_TRANSPARENCY)
		{
			state.m_drawFlags = STUDIORENDER_DRAW_TRANSLUCENT_ONLY; 
		}
		else
		{
			state.m_drawFlags = STUDIORENDER_DRAW_OPAQUE_ONLY; 
		}
	}
	if ( pInfo.flags & STUDIO_STATIC_LIGHTING )
	{
		state.m_drawFlags |= STUDIORENDER_DRAW_STATIC_LIGHTING;
	}
	
	if( pInfo.flags & STUDIO_ITEM_BLINK )
	{
		state.m_drawFlags |= STUDIORENDER_DRAW_ITEM_BLINK;
	}

	if ( pInfo.flags & STUDIO_WIREFRAME )
	{
		state.m_drawFlags |= STUDIORENDER_DRAW_WIREFRAME;
	}

	if ( pInfo.flags & STUDIO_NOSHADOWS )
	{
		state.m_drawFlags |= STUDIORENDER_DRAW_NO_SHADOWS;
	}

	if ( r_drawmodelstatsoverlay.GetInt() == 2)
	{
		state.m_drawFlags |= STUDIORENDER_DRAW_ACCURATETIME;
	}

	if ( pInfo.flags & STUDIO_SHADOWDEPTHTEXTURE )
	{
		state.m_drawFlags |= STUDIORENDER_SHADOWDEPTHTEXTURE;
	}

	return true;
}

int	CModelRender::DrawModelEx( ModelRenderInfo_t &pInfo )
{
#ifndef SWDS
	DrawModelState_t state;

	matrix3x4_t tmpmat;
	if ( !pInfo.pModelToWorld )
	{
		pInfo.pModelToWorld = &tmpmat;

		// Turns the origin + angles into a matrix
		AngleMatrix( pInfo.angles, pInfo.origin, tmpmat );
	}

	matrix3x4_t *pBoneToWorld;
	if ( !DrawModelSetup( pInfo, &state, NULL, &pBoneToWorld ) )
		return 0;

	if ( pInfo.flags & STUDIO_RENDER )
	{
		DrawModelExecute( state, pInfo, pBoneToWorld );
	}

	return 1;
#else
	return 0;
#endif
}

int	CModelRender::DrawModelExStaticProp( ModelRenderInfo_t &pInfo )
{
#ifndef SWDS
	bool bShadowDepth = ( pInfo.flags & STUDIO_SHADOWDEPTHTEXTURE ) != 0;

#if _DEBUG
	if ( (char*)pInfo.pRenderable < (char*)1024 )
	{
		Error( "CModelRender::DrawModel: pRenderable == %p", pInfo.pRenderable );
	}	

	// Can only deal with studio models
	if ( pInfo.pModel->type != mod_studio )
		return 0;
#endif
	Assert( modelloader->IsLoaded( pInfo.pModel ) );

	DrawModelState_t state;
	state.m_pStudioHdr = g_pMDLCache->GetStudioHdr( pInfo.pModel->studio );
	state.m_pRenderable = pInfo.pRenderable;

	// quick exit
	if ( state.m_pStudioHdr->numbodyparts == 0 || g_bTextMode )
		return 1;

	state.m_pStudioHWData = g_pMDLCache->GetHardwareData( pInfo.pModel->studio );
	if ( !state.m_pStudioHWData )
		return 0;

	Assert( pInfo.pModelToWorld );
	state.m_pModelToWorld = pInfo.pModelToWorld;
	Assert ( pInfo.pRenderable );

	int lod = ComputeLOD( pInfo, state.m_pStudioHWData );
	// int boneMask = BONE_USED_BY_VERTEX_AT_LOD( lod );
	// Why isn't this always set?!?
	if ( !(pInfo.flags & STUDIO_RENDER) )
		return 0;

	// Convert the instance to a decal handle.
	StudioDecalHandle_t decalHandle = STUDIORENDER_DECAL_INVALID;
	if ( (pInfo.instance != MODEL_INSTANCE_INVALID) && !(pInfo.flags & STUDIO_SHADOWDEPTHTEXTURE) )
	{
		decalHandle = m_ModelInstances[pInfo.instance].m_DecalHandle;
	}

	int drawFlags = STUDIORENDER_DRAW_ENTIRE_MODEL;
	if ( pInfo.flags & STUDIO_TWOPASS )
	{
		if ( pInfo.flags & STUDIO_TRANSPARENCY )
		{
			drawFlags = STUDIORENDER_DRAW_TRANSLUCENT_ONLY; 
		}
		else
		{
			drawFlags = STUDIORENDER_DRAW_OPAQUE_ONLY; 
		}
	}

	if ( pInfo.flags & STUDIO_STATIC_LIGHTING )
	{
		drawFlags |= STUDIORENDER_DRAW_STATIC_LIGHTING;
	}

	if ( pInfo.flags & STUDIO_WIREFRAME )
	{
		drawFlags |= STUDIORENDER_DRAW_WIREFRAME;
	}

	if ( pInfo.flags & STUDIO_GENERATE_STATS )
	{
		drawFlags |= STUDIORENDER_GENERATE_STATS;
	}

	// Shadow state...
	g_pShadowMgr->SetModelShadowState( pInfo.instance );

	// OPTIMIZE: Try to precompute part of this mess once a frame at the very least.
	bool bUsesBumpmapping = ( g_pMaterialSystemHardwareConfig->GetDXSupportLevel() >= 80 ) && ( pInfo.pModel->flags & MODELFLAG_STUDIOHDR_USES_BUMPMAPPING );

	bool bStaticLighting = (( drawFlags & STUDIORENDER_DRAW_STATIC_LIGHTING ) &&
		( state.m_pStudioHdr->flags & STUDIOHDR_FLAGS_STATIC_PROP ) && 
		( !bUsesBumpmapping ) && 
		( pInfo.instance != MODEL_INSTANCE_INVALID ) &&
		g_pMaterialSystemHardwareConfig->SupportsColorOnSecondStream() );

	bool bVertexLit = ( pInfo.pModel->flags & MODELFLAG_VERTEXLIT ) != 0;
	bool bNeedsEnvCubemap = r_showenvcubemap.GetInt() || ( pInfo.pModel->flags & MODELFLAG_STUDIOHDR_USES_ENV_CUBEMAP );

	if ( r_drawmodellightorigin.GetBool() )
	{
		DebugDrawLightingOrigin( state, pInfo );
	}

	ColorMeshInfo_t *pColorMeshes = NULL;
	DataCacheHandle_t hColorMeshData = DC_INVALID_HANDLE;
	if ( bStaticLighting )
	{
		// have static lighting, get from cache
		hColorMeshData = m_ModelInstances[pInfo.instance].m_ColorMeshHandle;
		CColorMeshData *pColorMeshData = CacheGet( hColorMeshData );
		if ( !pColorMeshData || pColorMeshData->m_bNeedsRetry )
		{
			// color meshes are not present, try to re-establish
			if ( RecomputeStaticLighting( pInfo.instance ) )
			{
				pColorMeshData = CacheGet( hColorMeshData );
			}
			else if ( !pColorMeshData || !pColorMeshData->m_bNeedsRetry )
			{
				// can't draw
				return 0;
			}
		}

		if ( pColorMeshData && ( pColorMeshData->m_bColorMeshValid || pColorMeshData->m_bColorTextureValid ) )
		{
			pColorMeshes = pColorMeshData->m_pMeshInfos;
			if (pColorMeshData->m_bColorTextureValid && !pColorMeshData->m_bColorTextureCreated)
			{
				CreateLightmapsFromData(pColorMeshData);
			}
		}
		else
		{
			// failed, draw without static lighting
			bStaticLighting = false;
		}
	}

	DrawModelInfo_t info;
	info.m_bStaticLighting = false;

	// Get lighting from ambient light sources and radiosity bounces
	// also set up the env_cubemap from the light cache if necessary.
	// Don't bother if we're rendering to shadow depth texture
	if ( ( bVertexLit || bNeedsEnvCubemap ) && !bShadowDepth )
	{
		// See if we're using static lighting
		LightCacheHandle_t* pLightCache = NULL;
		if ( pInfo.instance != MODEL_INSTANCE_INVALID )
		{
			if ( ( m_ModelInstances[pInfo.instance].m_nFlags & MODEL_INSTANCE_HAS_STATIC_LIGHTING ) && m_ModelInstances[pInfo.instance].m_LightCacheHandle )
			{
				pLightCache = &m_ModelInstances[pInfo.instance].m_LightCacheHandle;
			}
		}

		// Choose the lighting origin
		Vector entOrigin;
		if ( !pLightCache )
		{
			R_ComputeLightingOrigin( state.m_pRenderable, state.m_pStudioHdr, *state.m_pModelToWorld, entOrigin );
		}

		// Set up lighting based on the lighting origin
		StudioSetupLighting( state, entOrigin, pLightCache, bVertexLit, bNeedsEnvCubemap, bStaticLighting, info, pInfo, drawFlags );
	}

	Assert( modelloader->IsLoaded( pInfo.pModel ) );
	info.m_pStudioHdr = state.m_pStudioHdr;
	info.m_pHardwareData = state.m_pStudioHWData;
	info.m_Decals = decalHandle;
	info.m_Skin = pInfo.skin;
	info.m_Body = pInfo.body;
	info.m_HitboxSet = pInfo.hitboxset;
	info.m_pClientEntity = (void*)state.m_pRenderable;
	info.m_Lod = lod;
	info.m_pColorMeshes = pColorMeshes;

	if ( bShadowDepth )
	{
		drawFlags |= STUDIORENDER_SHADOWDEPTHTEXTURE;
	}

#ifdef _DEBUG
	Vector tmp;
	MatrixGetColumn( *pInfo.pModelToWorld, 3, &tmp );
	Assert( VectorsAreEqual( pInfo.origin, tmp, 1e-3 ) );
#endif

	g_pStudioRender->DrawModelStaticProp( info, *pInfo.pModelToWorld, drawFlags );

	if ( pColorMeshes)
	{
		ProtectColorDataIfQueued( hColorMeshData );
	}

	return 1;
#else
	return 0;
#endif
}

struct robject_t
{
	const matrix3x4_t	*pMatrix;
	IClientRenderable	*pRenderable;
	ColorMeshInfo_t		*pColorMeshes;
	ITexture			*pEnvCubeMap;
	Vector				*pLightingOrigin;
	short				modelIndex;
	short				lod;
	ModelInstanceHandle_t instance;
	short				skin;
	short				lightIndex;
	short				pad0;
};

struct rmodel_t
{
	const model_t *			pModel;
	studiohdr_t*			pStudioHdr;
	studiohwdata_t*			pStudioHWData;
	float					maxArea;
	short					lodStart;
	byte					lodCount;
	byte					bVertexLit : 1;
	byte					bNeedsCubemap : 1;
	byte					bStaticLighting : 1;
};

class CRobjectLess
{
public:
	bool Less( const robject_t& lhs, const robject_t& rhs, void *pContext )
	{
		rmodel_t *pModels = static_cast<rmodel_t *>(pContext);
		if ( lhs.modelIndex == rhs.modelIndex )
		{
			if ( lhs.skin != rhs.skin )
				return lhs.skin < rhs.skin;
			return lhs.lod < rhs.lod;
		}
		if ( pModels[lhs.modelIndex].maxArea == pModels[rhs.modelIndex].maxArea )
			return lhs.modelIndex < rhs.modelIndex;
		return pModels[lhs.modelIndex].maxArea > pModels[rhs.modelIndex].maxArea;
	}
};

struct rdecalmodel_t
{
	short			objectIndex;
	short			lightIndex;
};
/*
// ----------------------------------------
// not yet implemented

struct rlod_t
{
	short groupCount;
	short groupStart;
};

struct rgroup_t
{
	IMesh	*pMesh;
	short	batchCount;
	short	batchStart;
	short	colorMeshIndex;
	short	pad0;
};

struct rbatch_t
{
	IMaterial		*pMaterial;
	short			primitiveType;
	short			pad0;
	unsigned short	indexOffset;
	unsigned short	indexCount;
};
// ----------------------------------------
*/

inline int FindModel( const CUtlVector<rmodel_t> &list, const model_t *pModel )
{
	for ( int j = list.Count(); --j >= 0 ; )
	{
		if ( list[j].pModel == pModel )
			return j;
	}
	return -1;
}


// NOTE: UNDONE: This is a work in progress of a new static prop rendering pipeline
// UNDONE: Expose drawing commands from studiorender and draw here
// UNDONE: Build a similar pipeline for non-static prop models
// UNDONE: Split this into several functions in a sub-object
ConVar r_staticprop_lod("r_staticprop_lod", "-1");
int CModelRender::DrawStaticPropArrayFast( StaticPropRenderInfo_t *pProps, int count, bool bShadowDepth )
{
#ifndef SWDS
	MDLCACHE_CRITICAL_SECTION_( g_pMDLCache );
	CMatRenderContextPtr pRenderContext( materials );
	const int MAX_OBJECTS = 1024;
	CUtlSortVector<robject_t, CRobjectLess> objectList(0, MAX_OBJECTS);
	CUtlVector<rmodel_t> modelList(0,256);
	CUtlVector<short> lightObjects(0,256);
	CUtlVector<short> shadowObjects(0,64);
	CUtlVector<rdecalmodel_t> decalObjects(0,64);
	CUtlVector<LightingState_t> lightStates(0,256);
	bool bForceCubemap = r_showenvcubemap.GetBool();
	int drawnCount = 0;
	int forcedLodSetting = r_lod.GetInt();
	if ( r_staticprop_lod.GetInt() >= 0 )
	{
		forcedLodSetting = r_staticprop_lod.GetInt();
	}

	// build list of objects and unique models
	for ( int i = 0; i < count; i++ )
	{
		drawnCount++;
		// UNDONE: This is a perf hit in some scenes!  Use a hash?
		int modelIndex = FindModel( modelList, pProps[i].pModel );
		if ( modelIndex < 0 )
		{
			modelIndex = modelList.AddToTail();
			modelList[modelIndex].pModel = pProps[i].pModel;
			modelList[modelIndex].pStudioHWData = g_pMDLCache->GetHardwareData( modelList[modelIndex].pModel->studio );
		}
		if ( modelList[modelIndex].pStudioHWData )
		{
			robject_t obj;
			obj.pMatrix = pProps[i].pModelToWorld;
			obj.pRenderable = pProps[i].pRenderable;
			obj.modelIndex = modelIndex;
			obj.instance = pProps[i].instance;
			obj.skin = pProps[i].skin;
			obj.lod = 0;
			obj.pColorMeshes = NULL;
			obj.pEnvCubeMap = NULL;
			obj.lightIndex = -1;
			obj.pLightingOrigin = pProps[i].pLightingOrigin;
			objectList.InsertNoSort(obj);
		}
	}

	// process list of unique models
	int lodStart = 0;
	for ( int i = 0; i < modelList.Count(); i++ )
	{
		const model_t *pModel = modelList[i].pModel;
		Assert( modelloader->IsLoaded( pModel ) );
		unsigned int flags = pModel->flags;
		modelList[i].pStudioHdr = g_pMDLCache->GetStudioHdr( pModel->studio );
		modelList[i].maxArea = 1.0f;
		modelList[i].lodStart = lodStart;
		modelList[i].lodCount = modelList[i].pStudioHWData ? modelList[i].pStudioHWData->m_NumLODs : 0;
		bool bBumpMapped = (flags & MODELFLAG_STUDIOHDR_USES_BUMPMAPPING) != 0;
		modelList[i].bStaticLighting = (( modelList[i].pStudioHdr->flags & STUDIOHDR_FLAGS_STATIC_PROP ) != 0) && !bBumpMapped;
		modelList[i].bVertexLit = ( flags & MODELFLAG_VERTEXLIT ) != 0;
		modelList[i].bNeedsCubemap = ( flags & MODELFLAG_STUDIOHDR_USES_ENV_CUBEMAP ) != 0;

		lodStart += modelList[i].lodCount;
	}

	// -1 is automatic lod
	if ( forcedLodSetting < 0 )
	{
		// compute the lod of each object
		for ( int i = 0; i < objectList.Count(); i++ )
		{
			Vector org;
			MatrixGetColumn( *objectList[i].pMatrix, 3, org );
			float screenSize = pRenderContext->ComputePixelWidthOfSphere(org, 0.5f );
			const rmodel_t &model = modelList[objectList[i].modelIndex];
			float metric = model.pStudioHWData->LODMetric(screenSize);
			objectList[i].lod = model.pStudioHWData->GetLODForMetric(metric);
			if ( objectList[i].lod < model.pStudioHWData->m_RootLOD )
			{
				objectList[i].lod = model.pStudioHWData->m_RootLOD;
			}
			modelList[objectList[i].modelIndex].maxArea = max(modelList[objectList[i].modelIndex].maxArea, screenSize);
		}
	}
	else
	{
		// force the lod of each object
		for ( int i = 0; i < objectList.Count(); i++ )
		{
			const rmodel_t &model = modelList[objectList[i].modelIndex];
			objectList[i].lod = clamp(forcedLodSetting, model.pStudioHWData->m_RootLOD, model.lodCount-1);
		}
	}
	// UNDONE: Don't sort if rendering transparent objects - for now this isn't called in the transparent case
	// sort by model, then by lod
	objectList.SetLessContext( static_cast<void *>(modelList.Base()) );
	objectList.RedoSort(true);

	ICallQueue *pCallQueue = pRenderContext->GetCallQueue();
	
	// now build out the lighting states
	if ( !bShadowDepth )
	{
		for ( int i = 0; i < objectList.Count(); i++ )
		{
			robject_t &obj = objectList[i];
			rmodel_t &model = modelList[obj.modelIndex];
			bool bStaticLighting = (model.bStaticLighting && obj.instance != MODEL_INSTANCE_INVALID);
			bool bVertexLit = model.bVertexLit;
			bool bNeedsEnvCubemap = bForceCubemap || model.bNeedsCubemap;
			bool bHasDecals = ( m_ModelInstances[obj.instance].m_DecalHandle != STUDIORENDER_DECAL_INVALID ) ? true : false;
			LightingState_t *pDecalLightState = NULL;
			if ( bHasDecals )
			{
				rdecalmodel_t decalModel;
				decalModel.lightIndex = lightStates.AddToTail();
				pDecalLightState = &lightStates[decalModel.lightIndex];
				decalModel.objectIndex = i;
				decalObjects.AddToTail( decalModel );
			}
			// for now we skip models that have shadows - will update later to include them in a post-pass
			if ( g_pShadowMgr->ModelHasShadows( obj.instance ) )
			{
				shadowObjects.AddToTail(i);
			}

			// get the static lighting from the cache
			DataCacheHandle_t hColorMeshData = DC_INVALID_HANDLE;
			if ( bStaticLighting )
			{
				// have static lighting, get from cache
				hColorMeshData = m_ModelInstances[obj.instance].m_ColorMeshHandle;
				CColorMeshData *pColorMeshData = CacheGet( hColorMeshData );
				if ( !pColorMeshData || pColorMeshData->m_bNeedsRetry )
				{
					// color meshes are not present, try to re-establish
					
					if ( UpdateStaticPropColorData( obj.pRenderable->GetIClientUnknown(), obj.instance ) )
					{
						pColorMeshData = CacheGet( hColorMeshData );
					}
					else if ( !pColorMeshData || !pColorMeshData->m_bNeedsRetry )
					{
						// can't draw
						continue;
					}
				}

				if ( pColorMeshData && ( pColorMeshData->m_bColorMeshValid || pColorMeshData->m_bColorTextureValid ) )
				{
					obj.pColorMeshes = pColorMeshData->m_pMeshInfos;
					if (pColorMeshData->m_bColorTextureValid && !pColorMeshData->m_bColorTextureCreated)
					{
						CreateLightmapsFromData(pColorMeshData);
					}

					if ( pCallQueue )
					{
						if ( CacheLock( hColorMeshData ) ) // CacheCreate above will call functions that won't take place until later. If color mesh isn't used right away, it could get dumped
						{
							pCallQueue->QueueCall( this, &CModelRender::CacheUnlock, hColorMeshData );
						}
					}
				}
				else
				{
					// failed, draw without static lighting
					bStaticLighting = false;
				}
			}

			// Get lighting from ambient light sources and radiosity bounces
			// also set up the env_cubemap from the light cache if necessary.
			if ( ( bVertexLit || bNeedsEnvCubemap ) )
			{
				// See if we're using static lighting
				LightCacheHandle_t* pLightCache = NULL;
				ITexture *pEnvCubemapTexture = NULL;
				if ( obj.instance != MODEL_INSTANCE_INVALID )
				{
					if ( ( m_ModelInstances[obj.instance].m_nFlags & MODEL_INSTANCE_HAS_STATIC_LIGHTING ) && m_ModelInstances[obj.instance].m_LightCacheHandle )
					{
						pLightCache = &m_ModelInstances[obj.instance].m_LightCacheHandle;
					}
				}

				Assert(pLightCache);
				LightingState_t lightingState;
				LightingState_t *pState = &lightingState;
				if ( pLightCache )
				{
					// dx8 and dx9 case. . .hardware can do baked lighting plus other dynamic lighting
					// We already have the static part baked into a color mesh, so just get the dynamic stuff.
					if ( !bStaticLighting || StaticLightCacheAffectedByDynamicLight( *pLightCache ) )
					{
						pState = LightcacheGetStatic( *pLightCache, &pEnvCubemapTexture, LIGHTCACHEFLAGS_STATIC | LIGHTCACHEFLAGS_DYNAMIC | LIGHTCACHEFLAGS_LIGHTSTYLE );
						Assert( pState->numlights >= 0 && pState->numlights <= MAXLOCALLIGHTS );
					}
					else
					{
						pState = LightcacheGetStatic( *pLightCache, &pEnvCubemapTexture, LIGHTCACHEFLAGS_DYNAMIC | LIGHTCACHEFLAGS_LIGHTSTYLE );
						Assert( pState->numlights >= 0 && pState->numlights <= MAXLOCALLIGHTS );
					}
					if ( bHasDecals )
					{
						for ( int iCube = 0; iCube < 6; ++iCube )
						{
							pDecalLightState->r_boxcolor[iCube] = m_ModelInstances[obj.instance].m_AmbientLightingState.r_boxcolor[iCube] + pState->r_boxcolor[iCube];
						}
						pDecalLightState->CopyLocalLights( m_ModelInstances[obj.instance].m_AmbientLightingState );
						pDecalLightState->AddAllLocalLights( *pState );
					}
				}
				else	// !pLightcache
				{
					// UNDONE: is it possible to end up here in the static prop case?
					Vector vLightingOrigin = *obj.pLightingOrigin;
					int lightCacheFlags = bStaticLighting ? (LIGHTCACHEFLAGS_DYNAMIC | LIGHTCACHEFLAGS_LIGHTSTYLE)
						: (LIGHTCACHEFLAGS_STATIC|LIGHTCACHEFLAGS_DYNAMIC|LIGHTCACHEFLAGS_LIGHTSTYLE|LIGHTCACHEFLAGS_ALLOWFAST);
					LightcacheGetDynamic_Stats stats;
					pEnvCubemapTexture = LightcacheGetDynamic( vLightingOrigin, lightingState, 
						stats, lightCacheFlags, false );
					Assert( lightingState.numlights >= 0 && lightingState.numlights <= MAXLOCALLIGHTS );
					pState = &lightingState;

					if ( bHasDecals )
					{
						LightcacheGetDynamic_Stats tempStats;
						LightcacheGetDynamic( vLightingOrigin, *pDecalLightState, tempStats,
							LIGHTCACHEFLAGS_STATIC|LIGHTCACHEFLAGS_DYNAMIC|LIGHTCACHEFLAGS_LIGHTSTYLE|LIGHTCACHEFLAGS_ALLOWFAST );
					}
				}

				if ( bNeedsEnvCubemap && pEnvCubemapTexture )
				{
					obj.pEnvCubeMap = pEnvCubemapTexture;
				}

				if ( bVertexLit )
				{
					// if we have any real lighting state we need to save it for this object
					if ( pState->numlights || pState->HasAmbientColors() )
					{
						obj.lightIndex = lightStates.AddToTail(*pState);
						lightObjects.AddToTail( i );
					}
				}
			}
		}
	}
	// now render the baked lighting props with no lighting state
	float color[3];
	color[0] = color[1] = color[2] = 1.0f;
	g_pStudioRender->SetColorModulation(color);
	g_pStudioRender->SetAlphaModulation(1.0f);
	g_pStudioRender->SetViewState( CurrentViewOrigin(), CurrentViewRight(), CurrentViewUp(), CurrentViewForward() );

	pRenderContext->MatrixMode( MATERIAL_MODEL );
	pRenderContext->PushMatrix();
	pRenderContext->LoadIdentity();
	g_pStudioRender->ClearAllShadows();
	pRenderContext->DisableAllLocalLights();
	DrawModelInfo_t info;
	for ( int i = 0; i < 6; i++ )
		info.m_vecAmbientCube[i].Init();
	g_pStudioRender->SetAmbientLightColors( info.m_vecAmbientCube );
	pRenderContext->SetAmbientLight( 0.0, 0.0, 0.0 );
	info.m_nLocalLightCount = 0;
	info.m_bStaticLighting = false;

	int drawFlags = STUDIORENDER_DRAW_ENTIRE_MODEL | STUDIORENDER_DRAW_STATIC_LIGHTING;
	if (bShadowDepth)
		drawFlags |= STUDIO_SHADOWDEPTHTEXTURE;
	info.m_Decals = STUDIORENDER_DECAL_INVALID;
	info.m_Body = 0;
	info.m_HitboxSet = 0;
	for ( int i = 0; i < objectList.Count(); i++ )
	{
		robject_t &obj = objectList[i];
		if ( obj.lightIndex >= 0 )
			continue;
		rmodel_t &model = modelList[obj.modelIndex];
		if ( obj.pEnvCubeMap )
		{
			pRenderContext->BindLocalCubemap( obj.pEnvCubeMap );
		}

		info.m_pStudioHdr = model.pStudioHdr;
		info.m_pHardwareData = model.pStudioHWData;
		info.m_Skin = obj.skin;
		info.m_pClientEntity = static_cast<void*>(obj.pRenderable);
		info.m_Lod = obj.lod;
		info.m_pColorMeshes = obj.pColorMeshes;
		g_pStudioRender->DrawModelStaticProp( info, *obj.pMatrix, drawFlags );
	}

	// now render the vertex lit props
	int				nLocalLightCount = 0;
	LightDesc_t		localLightDescs[4];
	drawFlags = STUDIORENDER_DRAW_ENTIRE_MODEL | STUDIORENDER_DRAW_STATIC_LIGHTING;
	if ( lightObjects.Count() )
	{
		for ( int i = 0; i < lightObjects.Count(); i++ )
		{
			robject_t &obj = objectList[lightObjects[i]];
			rmodel_t &model = modelList[obj.modelIndex];

			if ( obj.pEnvCubeMap )
			{
				pRenderContext->BindLocalCubemap( obj.pEnvCubeMap );
			}

			LightingState_t *pState = &lightStates[obj.lightIndex];
			g_pStudioRender->SetAmbientLightColors( pState->r_boxcolor );
			pRenderContext->SetLightingOrigin( *obj.pLightingOrigin );
			R_SetNonAmbientLightingState( pState->numlights, pState->locallight, &nLocalLightCount, localLightDescs, true );
			info.m_pStudioHdr = model.pStudioHdr;
			info.m_pHardwareData = model.pStudioHWData;
			info.m_Skin = obj.skin;
			info.m_pClientEntity = static_cast<void*>(obj.pRenderable);
			info.m_Lod = obj.lod;
			info.m_pColorMeshes = obj.pColorMeshes;
			g_pStudioRender->DrawModelStaticProp( info, *obj.pMatrix, drawFlags );
		}
	}

	if ( !IsX360() && ( r_flashlight_version2.GetInt() == 0 ) && shadowObjects.Count() )
	{
		drawFlags = STUDIORENDER_DRAW_ENTIRE_MODEL;
		for ( int i = 0; i < shadowObjects.Count(); i++ )
		{
			// draw just the shadows!
			robject_t &obj = objectList[shadowObjects[i]];
			rmodel_t &model = modelList[obj.modelIndex];
			g_pShadowMgr->SetModelShadowState( obj.instance );

			info.m_pStudioHdr = model.pStudioHdr;
			info.m_pHardwareData = model.pStudioHWData;
			info.m_Skin = obj.skin;
			info.m_pClientEntity = static_cast<void*>(obj.pRenderable);
			info.m_Lod = obj.lod;
			info.m_pColorMeshes = obj.pColorMeshes;
			g_pStudioRender->DrawStaticPropShadows( info, *obj.pMatrix, drawFlags );
		}
		g_pStudioRender->ClearAllShadows();
	}

	for ( int i = 0; i < decalObjects.Count(); i++ )
	{
		// draw just the decals!
		robject_t &obj = objectList[decalObjects[i].objectIndex];
		rmodel_t &model = modelList[obj.modelIndex];
		LightingState_t *pState = &lightStates[decalObjects[i].lightIndex];
		g_pStudioRender->SetAmbientLightColors( pState->r_boxcolor );
		pRenderContext->SetLightingOrigin( *obj.pLightingOrigin );
		R_SetNonAmbientLightingState( pState->numlights, pState->locallight, &nLocalLightCount, localLightDescs, true );
		info.m_pStudioHdr = model.pStudioHdr;
		info.m_pHardwareData = model.pStudioHWData;
		info.m_Decals = m_ModelInstances[obj.instance].m_DecalHandle;
		info.m_Skin = obj.skin;
		info.m_pClientEntity = static_cast<void*>(obj.pRenderable);
		info.m_Lod = obj.lod;
		info.m_pColorMeshes = obj.pColorMeshes;
		g_pStudioRender->DrawStaticPropDecals( info, *obj.pMatrix );
	}

	// Restore the matrices if we're skinning
	pRenderContext->MatrixMode( MATERIAL_MODEL );
	pRenderContext->PopMatrix();
	return drawnCount;
#else // SWDS
	return 0;
#endif // SWDS
}

//-----------------------------------------------------------------------------
// Shadow rendering
//-----------------------------------------------------------------------------
matrix3x4_t* CModelRender::DrawModelShadowSetup( IClientRenderable *pRenderable, int body, int skin, DrawModelInfo_t *pInfo, matrix3x4_t *pCustomBoneToWorld )
{
#ifndef SWDS
	DrawModelInfo_t &info = *pInfo;
	static ConVar r_shadowlod("r_shadowlod", "-1");
	static ConVar r_shadowlodbias("r_shadowlodbias", "2");

	model_t const* pModel = pRenderable->GetModel();
	if ( !pModel )
		return NULL;

	// FIXME: Make brush shadows work
	if ( pModel->type != mod_studio )
		return NULL;

	Assert( modelloader->IsLoaded( pModel ) && ( pModel->type == mod_studio ) );

	info.m_pStudioHdr = g_pMDLCache->GetStudioHdr( pModel->studio );
	info.m_pColorMeshes = NULL;

	// quick exit
	if (info.m_pStudioHdr->numbodyparts == 0)
		return NULL;

	Assert ( pRenderable );
	info.m_pHardwareData = g_pMDLCache->GetHardwareData( pModel->studio );
	if ( !info.m_pHardwareData )
		return NULL;

	info.m_Decals = STUDIORENDER_DECAL_INVALID;
	info.m_Skin = skin;
	info.m_Body = body;
	info.m_pClientEntity = (void*)pRenderable;
	info.m_HitboxSet = 0;

	info.m_Lod = r_shadowlod.GetInt();
	// If the .mdl has a shadowlod, force the use of that one instead
	if ( info.m_pStudioHdr->flags & STUDIOHDR_FLAGS_HASSHADOWLOD )
	{
		info.m_Lod = info.m_pHardwareData->m_NumLODs-1;
	}
	else if ( info.m_Lod == USESHADOWLOD )
	{
		int lastlod = info.m_pHardwareData->m_NumLODs - 1;
		info.m_Lod = lastlod;
	}
	else if ( info.m_Lod < 0 )
	{
		CMatRenderContextPtr pRenderContext( materials );
		// Compute the shadow LOD...
		float factor = r_shadowlodbias.GetFloat() > 0.0f ? 1.0f / r_shadowlodbias.GetFloat() : 1.0f;
		float screenSize = factor * pRenderContext->ComputePixelWidthOfSphere( pRenderable->GetRenderOrigin(), 0.5f );
		info.m_Lod = g_pStudioRender->ComputeModelLod( info.m_pHardwareData, screenSize ); 
		info.m_Lod = info.m_pHardwareData->m_NumLODs-2;
		if ( info.m_Lod < 0 )
		{
			info.m_Lod = 0;
		}
	}

	// clamp to root lod
	if (info.m_Lod < info.m_pHardwareData->m_RootLOD)
	{
		info.m_Lod = info.m_pHardwareData->m_RootLOD;
	}

	matrix3x4_t *pBoneToWorld = pCustomBoneToWorld;
	if ( !pBoneToWorld )
	{
		pBoneToWorld = g_pStudioRender->LockBoneMatrices( info.m_pStudioHdr->numbones );
	}
	const bool bOk = pRenderable->SetupBones( pBoneToWorld, info.m_pStudioHdr->numbones, BONE_USED_BY_VERTEX_AT_LOD(info.m_Lod), cl.GetTime() );
	g_pStudioRender->UnlockBoneMatrices();
	if ( !bOk )
		return NULL;
	return pBoneToWorld;
#else
	return NULL;
#endif
}

void CModelRender::DrawModelShadow( IClientRenderable *pRenderable, const DrawModelInfo_t &info, matrix3x4_t *pBoneToWorld )
{
#ifndef SWDS
	// Needed because we don't call SetupWeights
	g_pStudioRender->SetEyeViewTarget( info.m_pStudioHdr, info.m_Body, vec3_origin );

	// Color + alpha modulation
	Vector white( 1, 1, 1 );
	g_pStudioRender->SetColorModulation( white.Base() );
	g_pStudioRender->SetAlphaModulation( 1.0f );

	if ((info.m_pStudioHdr->flags & STUDIOHDR_FLAGS_USE_SHADOWLOD_MATERIALS) == 0)
	{
		g_pStudioRender->ForcedMaterialOverride( g_pMaterialShadowBuild, OVERRIDE_BUILD_SHADOWS );
	}

	g_pStudioRender->DrawModel( NULL, info, pBoneToWorld, NULL, NULL, pRenderable->GetRenderOrigin(),
		STUDIORENDER_DRAW_NO_SHADOWS | STUDIORENDER_DRAW_ENTIRE_MODEL | STUDIORENDER_DRAW_NO_FLEXES );
	g_pStudioRender->ForcedMaterialOverride( 0 );
#endif
}

void  CModelRender::SetViewTarget( const CStudioHdr *pStudioHdr, int nBodyIndex, const Vector& target )
{
	g_pStudioRender->SetEyeViewTarget( pStudioHdr->GetRenderHdr(), nBodyIndex, target );
}

void CModelRender::InitColormeshParams( ModelInstance_t &instance, studiohwdata_t *pStudioHWData, colormeshparams_t *pColorMeshParams )
{
	pColorMeshParams->m_nMeshes = 0;
	pColorMeshParams->m_nTotalVertexes = 0;
	pColorMeshParams->m_pPooledVBAllocator = NULL;

	if ( ( instance.m_nFlags & MODEL_INSTANCE_HAS_DISKCOMPILED_COLOR ) &&
		g_pMaterialSystemHardwareConfig->SupportsStreamOffset() &&
		 ( r_proplightingpooling.GetInt() == 1 ) )
	{
		// Color meshes can be allocated in a shared pool for static props
		// (saves memory on X360 due to 4-KB VB alignment)
		pColorMeshParams->m_pPooledVBAllocator = (IPooledVBAllocator *)&m_colorMeshVBAllocator;
	}

	for ( int lodID = pStudioHWData->m_RootLOD; lodID < pStudioHWData->m_NumLODs; lodID++ )
	{
		studioloddata_t *pLOD = &pStudioHWData->m_pLODs[lodID];
		for ( int meshID = 0; meshID < pStudioHWData->m_NumStudioMeshes; meshID++ )
		{
			studiomeshdata_t *pMesh = &pLOD->m_pMeshData[meshID];
			for ( int groupID = 0; groupID < pMesh->m_NumGroup; groupID++ )
			{
				pColorMeshParams->m_nVertexes[pColorMeshParams->m_nMeshes++] = pMesh->m_pMeshGroup[groupID].m_NumVertices;
				Assert( pColorMeshParams->m_nMeshes <= ARRAYSIZE( pColorMeshParams->m_nVertexes ) );

				pColorMeshParams->m_nTotalVertexes += pMesh->m_pMeshGroup[groupID].m_NumVertices;
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Allocates the static prop color data meshes
//-----------------------------------------------------------------------------
// FIXME? : Move this to StudioRender?
CColorMeshData *CModelRender::FindOrCreateStaticPropColorData( ModelInstanceHandle_t handle )
{
	if ( handle == MODEL_INSTANCE_INVALID || !g_pMaterialSystemHardwareConfig->SupportsColorOnSecondStream() )
	{
		// the card can't support it
		return NULL;
	}

	ModelInstance_t& instance = m_ModelInstances[handle];
	CColorMeshData *pColorMeshData = CacheGet( instance.m_ColorMeshHandle );
	if ( pColorMeshData )
	{
		// found in cache
		return pColorMeshData;
	}

	if ( !instance.m_pModel )
	{
		return NULL;
	}

	Assert( modelloader->IsLoaded( instance.m_pModel ) && ( instance.m_pModel->type == mod_studio ) );
	studiohwdata_t *pStudioHWData = g_pMDLCache->GetHardwareData( instance.m_pModel->studio );
	Assert( pStudioHWData );
	if ( !pStudioHWData )
		return NULL;

	colormeshparams_t params;
	InitColormeshParams( instance, pStudioHWData, &params );
	if ( params.m_nMeshes <= 0 )
	{
		// nothing to create
		return NULL;
	}

	// create the meshes
	params.m_fnHandle = instance.m_pModel->fnHandle;
	instance.m_ColorMeshHandle = CacheCreate( params );
	ProtectColorDataIfQueued( instance.m_ColorMeshHandle );
	pColorMeshData = CacheGet( instance.m_ColorMeshHandle );

	return pColorMeshData;
}

//-----------------------------------------------------------------------------
// Allocates the static prop color data meshes
//-----------------------------------------------------------------------------
// FIXME? : Move this to StudioRender?
void CModelRender::ProtectColorDataIfQueued( DataCacheHandle_t hColorMesh )
{
	if ( hColorMesh != DC_INVALID_HANDLE)
	{
		CMatRenderContextPtr pRenderContext( materials );
		ICallQueue *pCallQueue = pRenderContext->GetCallQueue();
		if ( pCallQueue )
		{
			if ( CacheLock( hColorMesh ) ) // CacheCreate above will call functions that won't take place until later. If color mesh isn't used right away, it could get dumped
			{
				pCallQueue->QueueCall( this, &CModelRender::CacheUnlock, hColorMesh );
			}
		}
	}
}


//-----------------------------------------------------------------------------
// Old-style computation of vertex lighting ( Currently In Use )
//-----------------------------------------------------------------------------
void CModelRender::ComputeModelVertexLightingOld( mstudiomodel_t *pModel, 
	matrix3x4_t& matrix, const LightingState_t &lightingState, color24 *pLighting,
	bool bUseConstDirLighting, float flConstDirLightAmount )
{
	Vector			worldPos, worldNormal, destColor;
	int				nNumLightDesc;
	LightDesc_t		lightDesc[MAXLOCALLIGHTS];
	LightingState_t *pLightingState;

	pLightingState = (LightingState_t*)&lightingState;

	// build the lighting descriptors
	R_SetNonAmbientLightingState( pLightingState->numlights, pLightingState->locallight, &nNumLightDesc, lightDesc, false );

	const thinModelVertices_t		*thinVertData	= NULL;
	const mstudio_modelvertexdata_t	*vertData		= pModel->GetVertexData();
	mstudiovertex_t					*pFatVerts		= NULL;
	if ( vertData )
	{
		pFatVerts = vertData->Vertex( 0 );
	}
	else
	{
		thinVertData = pModel->GetThinVertexData();
		if ( !thinVertData )
			return;
	}

	bool bHasSSE = MathLib_SSEEnabled();

	// light all vertexes
	for ( int i = 0; i < pModel->numvertices; ++i )
	{
		if ( vertData )
		{
#ifdef _WIN32
			if (bHasSSE)
			{
				// hint the next vertex
				// data is loaded with one extra vertex for read past
#if !defined( _X360 ) // X360TBD
				_mm_prefetch( (char*)&pFatVerts[i+1], _MM_HINT_T0 );
#endif
		}
#endif

			VectorTransform( pFatVerts[i].m_vecPosition, matrix, worldPos );
			VectorRotate( pFatVerts[i].m_vecNormal, matrix, worldNormal );
		}
		else
		{
			Vector position;
			Vector normal;
			thinVertData->GetModelPosition(	pModel, i, &position );
			thinVertData->GetModelNormal( pModel, i, &normal );
			VectorTransform( position, matrix, worldPos );
			VectorRotate( normal, matrix, worldNormal );
		}

		if ( bUseConstDirLighting )
		{
			g_pStudioRender->ComputeLightingConstDirectional( pLightingState->r_boxcolor,
				nNumLightDesc, lightDesc, worldPos, worldNormal, destColor, flConstDirLightAmount );
		}
		else
		{
            g_pStudioRender->ComputeLighting( pLightingState->r_boxcolor,
				nNumLightDesc, lightDesc, worldPos, worldNormal, destColor );
		}
		
		// to gamma space
		destColor[0] = LinearToVertexLight( destColor[0] );
		destColor[1] = LinearToVertexLight( destColor[1] );
		destColor[2] = LinearToVertexLight( destColor[2] );

		Assert( (destColor[0] >= 0.0f) && (destColor[0] <= 1.0f) );
		Assert( (destColor[1] >= 0.0f) && (destColor[1] <= 1.0f) );
		Assert( (destColor[2] >= 0.0f) && (destColor[2] <= 1.0f) );

		pLighting[i].r = FastFToC(destColor[0]);
		pLighting[i].g = FastFToC(destColor[1]);
		pLighting[i].b = FastFToC(destColor[2]);
	}
}


//-----------------------------------------------------------------------------
// New-style computation of vertex lighting ( Not Used Yet )
//-----------------------------------------------------------------------------
void CModelRender::ComputeModelVertexLighting( IHandleEntity *pProp, 
	mstudiomodel_t *pModel, OptimizedModel::ModelLODHeader_t *pVtxLOD,
	matrix3x4_t& matrix, Vector4D *pTempMem, color24 *pLighting )
{
#ifndef SWDS
	if ( IsX360() )
		return;

	int i;
	unsigned char *pInSolid = (unsigned char*)stackalloc( ((pModel->numvertices + 7) >> 3) * sizeof(unsigned char) );
	Vector worldPos, worldNormal;

	const mstudio_modelvertexdata_t *vertData = pModel->GetVertexData();
	Assert( vertData );
	if ( !vertData )
		return;

	for ( i = 0; i < pModel->numvertices; ++i )
	{
		const Vector &pos = *vertData->Position( i );
		const Vector &normal = *vertData->Normal( i );
		VectorTransform( pos, matrix, worldPos );
		VectorRotate( normal, matrix, worldNormal );
		bool bNonSolid = ComputeVertexLightingFromSphericalSamples( worldPos, worldNormal, pProp, &(pTempMem[i].AsVector3D()) );
		
		int nByte = i >> 3;
		int nBit = i & 0x7;

		if ( bNonSolid )
		{
			pTempMem[i].w = 1.0f;
			pInSolid[ nByte ] &= ~(1 << nBit);
		}
		else
		{
			pTempMem[i].Init( );
			pInSolid[ nByte ] |= (1 << nBit);
		}
	}

	// Must iterate over each triangle to average out the colors for those
	// vertices in solid.
	// Iterate over all the meshes....
	for (int meshID = 0; meshID < pModel->nummeshes; ++meshID)
	{
		Assert( pModel->nummeshes == pVtxLOD->numMeshes );
		mstudiomesh_t* pMesh = pModel->pMesh(meshID);
		OptimizedModel::MeshHeader_t* pVtxMesh = pVtxLOD->pMesh(meshID);

		// Iterate over all strip groups.
		for( int stripGroupID = 0; stripGroupID < pVtxMesh->numStripGroups; ++stripGroupID )
		{
			OptimizedModel::StripGroupHeader_t* pStripGroup = pVtxMesh->pStripGroup(stripGroupID);
			
			// Iterate over all indices
			Assert( pStripGroup->numIndices % 3 == 0 );
			for (i = 0; i < pStripGroup->numIndices; i += 3)
			{
				unsigned short nIndex1 = *pStripGroup->pIndex( i );
				unsigned short nIndex2 = *pStripGroup->pIndex( i + 1 );
				unsigned short nIndex3 = *pStripGroup->pIndex( i + 2 );

				int v[3];
				v[0] = pStripGroup->pVertex( nIndex1 )->origMeshVertID + pMesh->vertexoffset;
				v[1] = pStripGroup->pVertex( nIndex2 )->origMeshVertID + pMesh->vertexoffset;
				v[2] = pStripGroup->pVertex( nIndex3 )->origMeshVertID + pMesh->vertexoffset;

				Assert( v[0] < pModel->numvertices );
				Assert( v[1] < pModel->numvertices );
				Assert( v[2] < pModel->numvertices );

				bool bSolid[3];
				bSolid[0] = ( pInSolid[ v[0] >> 3 ] & ( 1 << ( v[0] & 0x7 ) ) ) != 0;
				bSolid[1] = ( pInSolid[ v[1] >> 3 ] & ( 1 << ( v[1] & 0x7 ) ) ) != 0;
				bSolid[2] = ( pInSolid[ v[2] >> 3 ] & ( 1 << ( v[2] & 0x7 ) ) ) != 0;

				int nValidCount = 0;
				int nAverage[3];
				if ( !bSolid[0] ) { nAverage[nValidCount++] = v[0]; }
				if ( !bSolid[1] ) { nAverage[nValidCount++] = v[1]; }
				if ( !bSolid[2] ) { nAverage[nValidCount++] = v[2]; }

				if ( nValidCount == 3 )
					continue;

				Vector vecAverage( 0, 0, 0 );
				for ( int j = 0; j < nValidCount; ++j )
				{
					vecAverage += pTempMem[nAverage[j]].AsVector3D();
				}

				if (nValidCount != 0)
				{
					vecAverage /= nValidCount;
				}

				if ( bSolid[0] ) { pTempMem[ v[0] ].AsVector3D() += vecAverage; pTempMem[ v[0] ].w += 1.0f; }
				if ( bSolid[1] ) { pTempMem[ v[1] ].AsVector3D() += vecAverage; pTempMem[ v[1] ].w += 1.0f; }
				if ( bSolid[2] ) { pTempMem[ v[2] ].AsVector3D() += vecAverage; pTempMem[ v[2] ].w += 1.0f; }
			}
		}
	}

	Vector destColor;
	for ( i = 0; i < pModel->numvertices; ++i )
	{
		if ( pTempMem[i].w != 0.0f )
		{
			pTempMem[i] /= pTempMem[i].w;
		}

		destColor[0] = LinearToVertexLight( pTempMem[i][0] );
		destColor[1] = LinearToVertexLight( pTempMem[i][1] );
		destColor[2] = LinearToVertexLight( pTempMem[i][2] );

		ColorClampTruncate( destColor );

		pLighting[i].r = FastFToC(destColor[0]);
		pLighting[i].g = FastFToC(destColor[1]);
		pLighting[i].b = FastFToC(destColor[2]);
	}
#endif
}

//-----------------------------------------------------------------------------
// Sanity check and setup the compiled color mesh for an optimal async load
// during runtime.
//-----------------------------------------------------------------------------
void CModelRender::ValidateStaticPropColorData( ModelInstanceHandle_t handle )
{
	if ( !r_proplightingfromdisk.GetBool() )
	{
		return;
	}

	ModelInstance_t *pInstance = &m_ModelInstances[handle];
	IHandleEntity* pProp = pInstance->m_pRenderable->GetIClientUnknown();

	if ( !g_pMaterialSystemHardwareConfig->SupportsColorOnSecondStream() || !StaticPropMgr()->IsStaticProp( pProp ) )
	{
		// can't support it or not a static prop
		return;
	}

	if ( !g_bLoadedMapHasBakedPropLighting || StaticPropMgr()->PropHasBakedLightingDisabled( pProp ) )
	{
		return;
	}

	MEM_ALLOC_CREDIT();

	// fetch the header
	CUtlBuffer utlBuf;
	char fileName[MAX_PATH];
	if ( g_pMaterialSystemHardwareConfig->GetHDRType() == HDR_TYPE_NONE || g_bBakedPropLightingNoSeparateHDR )
	{
		Q_snprintf( fileName, sizeof( fileName ), "sp_%d%s.vhv", StaticPropMgr()->GetStaticPropIndex( pProp ), GetPlatformExt() );
	}
	else
	{	
		Q_snprintf( fileName, sizeof( fileName ), "sp_hdr_%d%s.vhv", StaticPropMgr()->GetStaticPropIndex( pProp ), GetPlatformExt() );
	}

	if ( IsX360()  )
	{
		DataCacheHandle_t hColorMesh = GetCachedStaticPropColorData( fileName );
		if ( hColorMesh != DC_INVALID_HANDLE )
		{
			// already have it
			pInstance->m_ColorMeshHandle = hColorMesh;
			pInstance->m_nFlags &= ~MODEL_INSTANCE_DISKCOMPILED_COLOR_BAD;
			pInstance->m_nFlags |= MODEL_INSTANCE_HAS_DISKCOMPILED_COLOR;
			return;
		}
	}

	if ( !g_pFileSystem->ReadFile( fileName, "GAME", utlBuf, sizeof( HardwareVerts::FileHeader_t ), 0 ) )
	{
		// not available
		return;
	}

	studiohdr_t *pStudioHdr = g_pMDLCache->GetStudioHdr( pInstance->m_pModel->studio );

	HardwareVerts::FileHeader_t *pVhvHdr = (HardwareVerts::FileHeader_t *)utlBuf.Base();
	if ( pVhvHdr->m_nVersion != VHV_VERSION || 
		pVhvHdr->m_nChecksum != (unsigned int)pStudioHdr->checksum || 
		pVhvHdr->m_nVertexSize != 4 )
	{
		// out of sync
		// mark for debug visualization
		pInstance->m_nFlags |= MODEL_INSTANCE_DISKCOMPILED_COLOR_BAD;
		return;
	}

	// async callback can safely stream data into targets
	pInstance->m_nFlags &= ~MODEL_INSTANCE_DISKCOMPILED_COLOR_BAD;
	pInstance->m_nFlags |= MODEL_INSTANCE_HAS_DISKCOMPILED_COLOR;
}

//-----------------------------------------------------------------------------
// Async loader callback
// Called from async i/o thread - must spend minimal cycles in this context
//-----------------------------------------------------------------------------
void CModelRender::StaticPropColorMeshCallback( void *pContext, const void *pData, int numReadBytes, FSAsyncStatus_t asyncStatus )
{
	// get our preserved data
	Assert( pContext );
	staticPropAsyncContext_t *pStaticPropContext = (staticPropAsyncContext_t *)pContext;

	HardwareVerts::FileHeader_t *pVhvHdr;
	byte *pOriginalData = NULL;
	int numLightingComponents = 1;

	if ( asyncStatus != FSASYNC_OK )
	{
		// any i/o error
		goto cleanUp;
	}

	if ( IsX360() )
	{
		// only the 360 has compressed VHV data
		// the compressed data is after the header
		byte *pCompressedData = (byte *)pData + sizeof( HardwareVerts::FileHeader_t );
		if ( CLZMA::IsCompressed( pCompressedData ) )
		{
			// create a buffer that matches the original
			int actualSize = CLZMA::GetActualSize( pCompressedData );
			pOriginalData = (byte *)malloc( sizeof( HardwareVerts::FileHeader_t ) + actualSize );

			// place the header, then uncompress directly after it
			V_memcpy( pOriginalData, pData, sizeof( HardwareVerts::FileHeader_t ) );
			int outputLength = CLZMA::Uncompress( pCompressedData, pOriginalData + sizeof( HardwareVerts::FileHeader_t ) );
			if ( outputLength != actualSize )
			{
				goto cleanUp;
			}
			pData = pOriginalData;
		}
	}

	pVhvHdr = (HardwareVerts::FileHeader_t *)pData;

	int startMesh;
	for ( startMesh=0; startMesh<pVhvHdr->m_nMeshes; startMesh++ )
	{
		// skip past higher detail lod meshes that must be ignored
		// find first mesh that matches desired lod
		if ( pVhvHdr->pMesh( startMesh )->m_nLod == pStaticPropContext->m_nRootLOD )
		{
			break;
		}
	}

	int meshID;
	for ( meshID = startMesh; meshID<pVhvHdr->m_nMeshes; meshID++ )
	{
		int numVertexes = pVhvHdr->pMesh( meshID )->m_nVertexes;
		if ( numVertexes != pStaticPropContext->m_pColorMeshData->m_pMeshInfos[meshID-startMesh].m_nNumVerts )
		{
			// meshes are out of sync, discard data
			break;
		}

		int nID = meshID-startMesh;

		unsigned char *pIn = (unsigned char *) pVhvHdr->pVertexBase( meshID );
		unsigned char *pOut = NULL;
			
		CMeshBuilder meshBuilder;
		meshBuilder.Begin( pStaticPropContext->m_pColorMeshData->m_pMeshInfos[ nID ].m_pMesh, MATERIAL_HETEROGENOUS, numVertexes, 0 );
		if ( numLightingComponents > 1 )
		{
			pOut = reinterpret_cast< unsigned char * >( const_cast< float * >( meshBuilder.Normal() ) );
		}
		else
		{
			pOut = meshBuilder.Specular();
		}

#ifdef DX_TO_GL_ABSTRACTION
		// OPENGL_SWAP_COLORS
		for ( int i=0; i < (numVertexes * numLightingComponents ); i++ )
		{
			unsigned char red = *pIn++;
			unsigned char green = *pIn++;
			unsigned char blue = *pIn++;
			*pOut++ = blue;
			*pOut++ = green;
			*pOut++ = red;
			*pOut++ = *pIn++; // Alpha goes straight across
		}
#else
		V_memcpy( pOut, pIn, numVertexes * 4 * numLightingComponents );
#endif
		meshBuilder.End();
	}
cleanUp:
	if ( IsX360() )
	{
		AUTO_LOCK( m_CachedStaticPropMutex );
		// track the color mesh's datacache handle so that we can find it long after the model instance's are gone
		// the static prop filenames are guaranteed uniquely decorated
		m_CachedStaticPropColorData.Insert( pStaticPropContext->m_szFilenameVertex, pStaticPropContext->m_ColorMeshHandle );

		// No support for lightmap textures on X360. 
	}

	// mark as completed in single atomic operation
	pStaticPropContext->m_pColorMeshData->m_bColorMeshValid = true;
	CacheUnlock( pStaticPropContext->m_ColorMeshHandle );
	delete pStaticPropContext;

	if ( pOriginalData )
	{
		free( pOriginalData );
	}
}

//-----------------------------------------------------------------------------
// Async loader callback
// Called from async i/o thread - must spend minimal cycles in this context
//-----------------------------------------------------------------------------
void CModelRender::StaticPropColorTexelCallback(void *pContext, const void *pData, int numReadBytes, FSAsyncStatus_t asyncStatus)
{
	// get our preserved data
	Assert(pContext);
	staticPropAsyncContext_t *pStaticPropContext = (staticPropAsyncContext_t *)pContext;

	HardwareTexels::FileHeader_t *pVhtHdr;

	// This needs to be above the goto or clang complains "goto into protected scope."
	bool anyTextures = false;

	if (asyncStatus != FSASYNC_OK)
	{
		// any i/o error
		goto cleanUp;
	}

	pVhtHdr = (HardwareTexels::FileHeader_t *)pData;

	int startMesh;
	for (startMesh = 0; startMesh < pVhtHdr->m_nMeshes; startMesh++)
	{
		// skip past higher detail lod meshes that must be ignored
		// find first mesh that matches desired lod
		if (pVhtHdr->pMesh(startMesh)->m_nLod == pStaticPropContext->m_nRootLOD)
		{
			break;
		}
	}



	int meshID;
	for ( meshID = startMesh; meshID < pVhtHdr->m_nMeshes; meshID++ )
	{
		const HardwareTexels::MeshHeader_t* pMeshData = pVhtHdr->pMesh( meshID );

		// We can't create the real texture here because that's just how the material system works.
		// So instead, squirrel away what we need for later.
		ColorTexelsInfo_t* newCTI = new ColorTexelsInfo_t;
		newCTI->m_nWidth = pMeshData->m_nWidth;
		newCTI->m_nHeight = pMeshData->m_nHeight;
		newCTI->m_nMipmapCount = ImageLoader::GetNumMipMapLevels( newCTI->m_nWidth, newCTI->m_nHeight );
		newCTI->m_ImageFormat = ( ImageFormat ) pVhtHdr->m_nTexelFormat;
		newCTI->m_nByteCount = pVhtHdr->pMesh( meshID )->m_nBytes;
		newCTI->m_pTexelData = new byte[ newCTI->m_nByteCount ];
		Q_memcpy( newCTI->m_pTexelData, pVhtHdr->pTexelBase( meshID ), newCTI->m_nByteCount );

		pStaticPropContext->m_pColorMeshData->m_pMeshInfos[ meshID - startMesh ].m_pLightmapData = newCTI;
		Assert( pStaticPropContext->m_pColorMeshData->m_pMeshInfos[ meshID - startMesh ].m_pLightmap == NULL );
		anyTextures = true;
	}

	// This only gets set if we actually have texel data. Otherwise, it remains false.
	pStaticPropContext->m_pColorMeshData->m_bColorTextureValid = anyTextures;

cleanUp:
	// mark as completed in single atomic operation
	CacheUnlock( pStaticPropContext->m_ColorMeshHandle );
	delete pStaticPropContext;
}

//-----------------------------------------------------------------------------
// Async loader callback
// Called from async i/o thread - must spend minimal cycles in this context
//-----------------------------------------------------------------------------
static void StaticPropColorMeshCallback( const FileAsyncRequest_t &request, int numReadBytes, FSAsyncStatus_t asyncStatus )
{
	s_ModelRender.StaticPropColorMeshCallback( request.pContext, request.pData, numReadBytes, asyncStatus );
}

//-----------------------------------------------------------------------------
// Async loader callback
// Called from async i/o thread - must spend minimal cycles in this context
//-----------------------------------------------------------------------------
static void StaticPropColorTexelCallback( const FileAsyncRequest_t &request, int numReadBytes, FSAsyncStatus_t asyncStatus )
{
	s_ModelRender.StaticPropColorTexelCallback( request.pContext, request.pData, numReadBytes, asyncStatus );
}


//-----------------------------------------------------------------------------
// Queued loader callback
// Called from async i/o thread - must spend minimal cycles in this context
//-----------------------------------------------------------------------------
static void QueuedLoaderCallback_PropLighting( void *pContext, void *pContext2, const void *pData, int nSize, LoaderError_t loaderError )
{
	// translate error
	FSAsyncStatus_t asyncStatus = ( loaderError == LOADERERROR_NONE ? FSASYNC_OK : FSASYNC_ERR_READING );

	// mimic async i/o completion
	s_ModelRender.StaticPropColorMeshCallback( pContext, pData, nSize, asyncStatus );
}

//-----------------------------------------------------------------------------
// Loads the serialized static prop color data.
// Returns false if legacy path should be used.
//-----------------------------------------------------------------------------
bool CModelRender::LoadStaticPropColorData( IHandleEntity *pProp, DataCacheHandle_t colorMeshHandle, studiohwdata_t *pStudioHWData )
{
	if ( !g_bLoadedMapHasBakedPropLighting || !r_proplightingfromdisk.GetBool() )
	{
		return false;
	}

	// lock the mesh memory during async transfer
	// the color meshes should already have low quality data to be used during rendering
	CColorMeshData *pColorMeshData = CacheLock( colorMeshHandle );
	if ( !pColorMeshData )
	{
		return false;
	}

	if ( pColorMeshData->m_hAsyncControlVertex || pColorMeshData->m_hAsyncControlTexel )
	{
		// load in progress, ignore additional request 
		// or already loaded, ignore until discarded from cache
		CacheUnlock( colorMeshHandle );
		return true;
	}

	// each static prop has its own compiled color mesh
	char fileName[MAX_PATH];
	if ( g_pMaterialSystemHardwareConfig->GetHDRType() == HDR_TYPE_NONE || g_bBakedPropLightingNoSeparateHDR )
	{
        Q_snprintf( fileName, sizeof( fileName ), "sp_%d%s.vhv", StaticPropMgr()->GetStaticPropIndex( pProp ), GetPlatformExt() );
	}
	else
	{
        Q_snprintf( fileName, sizeof( fileName ), "sp_hdr_%d%s.vhv", StaticPropMgr()->GetStaticPropIndex( pProp ), GetPlatformExt() );
	}

	// mark as invalid, async callback will set upon completion
	// prevents rendering during async transfer into locked mesh, otherwise d3drip
	pColorMeshData->m_bColorMeshValid = false;
	pColorMeshData->m_bColorTextureValid = false;
	pColorMeshData->m_bColorTextureCreated = false;


	// async load high quality lighting from file
	// can't optimal async yet, because need flat ppColorMesh[], so use callback to distribute
	// create our private context of data for the callback
	staticPropAsyncContext_t *pContextVertex = new staticPropAsyncContext_t;
	pContextVertex->m_nRootLOD = pStudioHWData->m_RootLOD;
	pContextVertex->m_nMeshes = pColorMeshData->m_nMeshes;
	pContextVertex->m_ColorMeshHandle = colorMeshHandle;
	pContextVertex->m_pColorMeshData = pColorMeshData;
	V_strncpy( pContextVertex->m_szFilenameVertex, fileName, sizeof( pContextVertex->m_szFilenameVertex ) );

	if ( IsX360() && g_pQueuedLoader->IsMapLoading() )
	{
		if ( !g_pQueuedLoader->ClaimAnonymousJob( fileName, QueuedLoaderCallback_PropLighting, (void *)pContextVertex ) )
		{
			// not there as expected
			// as a less optimal fallback during loading, issue as a standard queued loader job
			LoaderJob_t loaderJob;
			loaderJob.m_pFilename = fileName;
			loaderJob.m_pPathID = "GAME";
			loaderJob.m_pCallback = QueuedLoaderCallback_PropLighting;
			loaderJob.m_pContext = (void *)pContextVertex;
			loaderJob.m_Priority = LOADERPRIORITY_BEFOREPLAY;
			g_pQueuedLoader->AddJob( &loaderJob );
		}
		return true;
	}

	// async load the file
	FileAsyncRequest_t fileRequest;
	fileRequest.pContext = (void *)pContextVertex;
	fileRequest.pfnCallback = ::StaticPropColorMeshCallback;
	fileRequest.pData = NULL;
	fileRequest.pszFilename = fileName;
	fileRequest.nOffset = 0;
	fileRequest.flags = 0; // FSASYNC_FLAGS_SYNC;
	fileRequest.nBytes = 0;
	fileRequest.priority = -1;
	fileRequest.pszPathID = "GAME";

	// This must be done before sending pContextVertex down
	staticPropAsyncContext_t* pContextTexel = new staticPropAsyncContext_t( *pContextVertex );
	
	// queue vertex data for async load
	{
		MEM_ALLOC_CREDIT();
		g_pFileSystem->AsyncRead( fileRequest, &pColorMeshData->m_hAsyncControlVertex );
	}

	Q_snprintf( fileName, sizeof( fileName ), "texelslighting_%d.ppl", StaticPropMgr()->GetStaticPropIndex( pProp ) );
	V_strncpy( pContextTexel->m_szFilenameTexel, fileName, sizeof( pContextTexel->m_szFilenameTexel ) );

	
	// We are already locked, but we will unlock twice--so lock once more for the texel processing. 
	CacheLock( colorMeshHandle );

	// queue texel data for async load
	fileRequest.pContext = pContextTexel;
	fileRequest.pfnCallback = ::StaticPropColorTexelCallback;
	fileRequest.pData = NULL;
	fileRequest.pszFilename = fileName; // This doesn't need to happen, but included for clarity.

	{
		MEM_ALLOC_CREDIT();
		g_pFileSystem->AsyncRead( fileRequest, &pColorMeshData->m_hAsyncControlTexel );
	}

	return true;
}

//-----------------------------------------------------------------------------
// Computes the static prop color data.
// Data calculation may be delayed if data is disk based.
// Returns FALSE if data not available or error. For retry polling pattern.
// Resturns TRUE if operation succesful or in progress (succeeds later).
//-----------------------------------------------------------------------------
bool CModelRender::UpdateStaticPropColorData( IHandleEntity *pProp, ModelInstanceHandle_t handle )
{
	MDLCACHE_CRITICAL_SECTION_( g_pMDLCache );

#ifndef SWDS
	// find or allocate color meshes
	CColorMeshData *pColorMeshData = FindOrCreateStaticPropColorData( handle );
	if ( !pColorMeshData )
	{
		return false;
	}

	// HACK: on PC, VB creation can fail due to device loss
	if ( IsPC() && pColorMeshData->m_bHasInvalidVB )
	{
		// Don't retry until color data is flushed by device restore
		pColorMeshData->m_bColorMeshValid = false;
		pColorMeshData->m_bNeedsRetry = false;
		return false;
	}

	unsigned char debugColor[3] = {0};
	bool bDebugColor = false;
	if ( r_debugrandomstaticlighting.GetBool() )
	{
		// randomize with bright colors, skip black and white
		// purposely not deterministic to catch bugs with excessive re-baking (i.e. disco)
		Vector fRandomColor;
		int nColor = RandomInt(1,6);
		fRandomColor.x = (nColor>>2) & 1;
		fRandomColor.y = (nColor>>1) & 1;
		fRandomColor.z = nColor & 1;
		VectorNormalize( fRandomColor );
		debugColor[0] = fRandomColor[0] * 255.0f;
		debugColor[1] = fRandomColor[1] * 255.0f;
		debugColor[2] = fRandomColor[2] * 255.0f;
		bDebugColor = true;
	}

	// FIXME? : Move this to StudioRender?
	ModelInstance_t &inst = m_ModelInstances[handle];
	Assert( inst.m_pModel );
	Assert( modelloader->IsLoaded( inst.m_pModel ) && ( inst.m_pModel->type == mod_studio ) );

	if ( r_proplightingfromdisk.GetInt() == 2 )
	{
		// This visualization debug mode is strictly to debug which static prop models have valid disk
		// based lighting. There should be no red models, only green or yellow. Yellow models denote the legacy
		// lower quality runtime baked lighting.
		if ( inst.m_nFlags & MODEL_INSTANCE_DISKCOMPILED_COLOR_BAD )
		{
			// prop was compiled for static prop lighting, but out of sync
			// bad disk data for model, show as red
			debugColor[0] = 255.0f;
			debugColor[1] = 0;
			debugColor[2] = 0;
		}
		else if ( inst.m_nFlags & MODEL_INSTANCE_HAS_DISKCOMPILED_COLOR )
		{
			// valid disk data, show as green
			debugColor[0] = 0;
			debugColor[1] = 255.0f;
			debugColor[2] = 0;
		}
		else
		{
			// no disk based data, using runtime method, show as yellow
			// identifies a prop that wasn't compiled for static prop lighting
			debugColor[0] = 255.0f;
			debugColor[1] = 255.0f;
			debugColor[2] = 0;
		}
		bDebugColor = true;
	}

	studiohdr_t *pStudioHdr = g_pMDLCache->GetStudioHdr( inst.m_pModel->studio );
	studiohwdata_t *pStudioHWData = g_pMDLCache->GetHardwareData( inst.m_pModel->studio );
	Assert( pStudioHdr && pStudioHWData );

	if ( !bDebugColor && ( inst.m_nFlags & MODEL_INSTANCE_HAS_DISKCOMPILED_COLOR ) )
	{
		// start an async load on available higher quality disc based data
		if ( LoadStaticPropColorData( pProp, inst.m_ColorMeshHandle, pStudioHWData ) )
		{
			// async in progress, operation expected to succeed
			// async callback handles finalization
			return true;
		}
	}
	
	// lighting calculation path
	// calculation may abort due to lack of async requested data, caller should retry 
	pColorMeshData->m_bColorMeshValid = false;
	pColorMeshData->m_bColorTextureValid = false;
	pColorMeshData->m_bColorTextureCreated = false;
	pColorMeshData->m_bNeedsRetry = true;

	if ( !bDebugColor )
	{
		// vertexes must be available for lighting calculation
		vertexFileHeader_t *pVertexHdr = g_pMDLCache->GetVertexData( (MDLHandle_t)(int)pStudioHdr->virtualModel&0xffff );
		if ( !pVertexHdr )
		{
			// data not available yet
			return false;
		}
	}

	inst.m_nFlags |= MODEL_INSTANCE_HAS_COLOR_DATA;

	// calculate lighting, set for access to verts
	m_pStudioHdr = pStudioHdr;

	// Sets the model transform state in g_pStudioRender
	matrix3x4_t matrix;
	AngleMatrix( inst.m_pRenderable->GetRenderAngles(), inst.m_pRenderable->GetRenderOrigin(), matrix );
	
	// Get static lighting only!!  We'll add dynamic and lightstyles in in the vertex shader. . .
	unsigned int lightCacheFlags = LIGHTCACHEFLAGS_STATIC;
	if ( !g_pMaterialSystemHardwareConfig->SupportsStaticPlusDynamicLighting() )
	{
		// . . . unless we can't do anything but static or dynamic simulaneously. . then
		// we'll bake the lightstyle info here.
		lightCacheFlags |= LIGHTCACHEFLAGS_LIGHTSTYLE;
	}

	LightingState_t lightingState;
	if ( (inst.m_nFlags & MODEL_INSTANCE_HAS_STATIC_LIGHTING) && inst.m_LightCacheHandle )
	{
		lightingState = *(LightcacheGetStatic( inst.m_LightCacheHandle, NULL, lightCacheFlags ));
	}
	else
	{
		// Choose the lighting origin
		Vector entOrigin;
		R_ComputeLightingOrigin( inst.m_pRenderable, pStudioHdr, matrix, entOrigin );
		LightcacheGetDynamic_Stats stats;
		LightcacheGetDynamic( entOrigin, lightingState, stats, lightCacheFlags );
	}

	// See if the studiohdr wants to use constant directional light, ie
	// the surface normal plays no part in determining light intensity
	bool bUseConstDirLighting = false;
	float flConstDirLightingAmount = 0.0;
	if ( pStudioHdr->flags & STUDIOHDR_FLAGS_CONSTANT_DIRECTIONAL_LIGHT_DOT )
	{
		bUseConstDirLighting = true;
		flConstDirLightingAmount =  (float)( pStudioHdr->constdirectionallightdot ) / 255.0;
	}

	CUtlMemory< color24 > tmpLightingMem; 
	
	// Iterate over every body part...
	for ( int bodyPartID = 0; bodyPartID < pStudioHdr->numbodyparts; ++bodyPartID )
	{
		mstudiobodyparts_t* pBodyPart = pStudioHdr->pBodypart( bodyPartID );

		// Iterate over every submodel...
		for ( int modelID = 0; modelID < pBodyPart->nummodels; ++modelID )
		{
			mstudiomodel_t* pModel = pBodyPart->pModel(modelID);

			if ( pModel->numvertices == 0 )
				continue;

			// Make sure we've got enough space allocated
			tmpLightingMem.EnsureCapacity( pModel->numvertices );

			if ( !bDebugColor )
			{
				// Compute lighting for each unique vertex in the model exactly once
				ComputeModelVertexLightingOld( pModel, matrix, lightingState, tmpLightingMem.Base(), bUseConstDirLighting, flConstDirLightingAmount );
			}
			else
			{
				for ( int i=0; i<pModel->numvertices; i++ )
				{
					tmpLightingMem[i].r = debugColor[0];
					tmpLightingMem[i].g = debugColor[1];
					tmpLightingMem[i].b = debugColor[2];
				}
			}

			// distribute the lighting results to the mesh's vertexes
			for ( int lodID = pStudioHWData->m_RootLOD; lodID < pStudioHWData->m_NumLODs; ++lodID )
			{
				studioloddata_t *pStudioLODData = &pStudioHWData->m_pLODs[lodID];
				studiomeshdata_t *pStudioMeshData = pStudioLODData->m_pMeshData;

				// Iterate over all the meshes....
				for ( int meshID = 0; meshID < pModel->nummeshes; ++meshID)
				{
					mstudiomesh_t* pMesh = pModel->pMesh( meshID );

					// Iterate over all strip groups.
					for ( int stripGroupID = 0; stripGroupID < pStudioMeshData[pMesh->meshid].m_NumGroup; ++stripGroupID )
					{
						studiomeshgroup_t* pMeshGroup = &pStudioMeshData[pMesh->meshid].m_pMeshGroup[stripGroupID];
						ColorMeshInfo_t* pColorMeshInfo = &pColorMeshData->m_pMeshInfos[pMeshGroup->m_ColorMeshID];

						CMeshBuilder meshBuilder;
						meshBuilder.Begin( pColorMeshInfo->m_pMesh, MATERIAL_HETEROGENOUS, pMeshGroup->m_NumVertices, 0 );
						
						if ( !meshBuilder.VertexSize() )
						{
							meshBuilder.End();
							return false;		// Aborting processing, since something was wrong with D3D
						}

						// We need to account for the stream offset used by pool-allocated (static-lit) color meshes:
						int streamOffset = pColorMeshInfo->m_nVertOffsetInBytes / meshBuilder.VertexSize();
						meshBuilder.AdvanceVertices( streamOffset );

						// Iterate over all vertices
						for ( int i = 0; i < pMeshGroup->m_NumVertices; ++i)
						{
							int nVertIndex = pMesh->vertexoffset + pMeshGroup->m_pGroupIndexToMeshIndex[i];
							Assert( nVertIndex < pModel->numvertices );
							meshBuilder.Specular3ub( tmpLightingMem[nVertIndex].r, tmpLightingMem[nVertIndex].g, tmpLightingMem[nVertIndex].b );
							meshBuilder.AdvanceVertex();
						}

						meshBuilder.End();
					}
				}
			}
		}
	}
	
	pColorMeshData->m_bColorMeshValid = true;
	pColorMeshData->m_bNeedsRetry = false;
#endif
	
	return true;
}


//-----------------------------------------------------------------------------
// FIXME? : Move this to StudioRender?
//-----------------------------------------------------------------------------
void CModelRender::DestroyStaticPropColorData( ModelInstanceHandle_t handle )
{
#ifndef SWDS
	if ( handle == MODEL_INSTANCE_INVALID )
		return;

	if ( m_ModelInstances[handle].m_ColorMeshHandle != DC_INVALID_HANDLE )
	{
		CacheRemove( m_ModelInstances[handle].m_ColorMeshHandle );
		m_ModelInstances[handle].m_ColorMeshHandle = DC_INVALID_HANDLE;
	}
#endif
}


void CModelRender::ReleaseAllStaticPropColorData( void )
{
	FOR_EACH_LL( m_ModelInstances, i )
	{
		DestroyStaticPropColorData( i );
	}
	if ( IsX360() )
	{
		PurgeCachedStaticPropColorData();
	}
}


void CModelRender::RestoreAllStaticPropColorData( void )
{
#if !defined( SWDS )
	if ( !host_state.worldmodel )
		return;

	// invalidate all static lighting cache data
	InvalidateStaticLightingCache();

	// rebake
	FOR_EACH_LL( m_ModelInstances, i )
	{
		UpdateStaticPropColorData( m_ModelInstances[i].m_pRenderable->GetIClientUnknown(), i );
	}
#endif
}

void RestoreAllStaticPropColorData( void )
{
	s_ModelRender.RestoreAllStaticPropColorData();
}


//-----------------------------------------------------------------------------
// Creates, destroys instance data to be associated with the model
//-----------------------------------------------------------------------------
ModelInstanceHandle_t CModelRender::CreateInstance( IClientRenderable *pRenderable, LightCacheHandle_t *pCache )
{
	Assert( pRenderable );

	// ensure all components are available
	model_t *pModel = (model_t*)pRenderable->GetModel();

	// We're ok, allocate a new instance handle
	ModelInstanceHandle_t handle = m_ModelInstances.AddToTail();
	ModelInstance_t& instance = m_ModelInstances[handle];

	instance.m_pRenderable = pRenderable;
	instance.m_DecalHandle = STUDIORENDER_DECAL_INVALID;
	instance.m_pModel = (model_t*)pModel;
	instance.m_ColorMeshHandle = DC_INVALID_HANDLE;
	instance.m_flLightingTime = CURRENT_LIGHTING_UNINITIALIZED;
	instance.m_nFlags = 0;
	instance.m_LightCacheHandle = 0;

	instance.m_AmbientLightingState.ZeroLightingState();
	for ( int i = 0; i < 6; ++i )
	{
		// To catch errors with uninitialized m_AmbientLightingState...
		// force to pure red
		instance.m_AmbientLightingState.r_boxcolor[i].x = 1.0;
	}

#ifndef SWDS
	instance.m_FirstShadow = g_pShadowMgr->InvalidShadowIndex();
#endif

	// Static props use baked lighting for performance reasons
	if ( pCache )
	{
		SetStaticLighting( handle, pCache );

		// validate static color meshes once, now at load/create time
		ValidateStaticPropColorData( handle );
	
		// 360 persists the color meshes across same map loads
		if ( !IsX360() || instance.m_ColorMeshHandle == DC_INVALID_HANDLE )
		{
			// builds out color meshes or loads disk colors, now at load/create time
			RecomputeStaticLighting( handle );
		}
		else
			if ( r_decalstaticprops.GetBool() && instance.m_LightCacheHandle )
			{
				instance.m_AmbientLightingState = *(LightcacheGetStatic( *pCache, NULL, LIGHTCACHEFLAGS_STATIC ));
			}
	}
	
	return handle;
}


//-----------------------------------------------------------------------------
// Assigns static lighting to the model instance
//-----------------------------------------------------------------------------
void CModelRender::SetStaticLighting( ModelInstanceHandle_t handle, LightCacheHandle_t *pCache )
{
	// FIXME: If we make static lighting available for client-side props,
	// we must clean up the lightcache handles as the model instances are removed.
	// At the moment, since only the static prop manager uses this, it cleans up all LightCacheHandles 
	// at level shutdown.

	// The reason I moved the lightcache handles into here is because this place needs
	// to know about lighting overrides when restoring meshes for alt-tab reasons
	// It was a real pain to do this from within the static prop mgr, where the
	// lightcache handle used to reside
	if (handle != MODEL_INSTANCE_INVALID)
	{
		ModelInstance_t& instance = m_ModelInstances[handle];
		if ( pCache )
		{
			instance.m_LightCacheHandle = *pCache;
			instance.m_nFlags |= MODEL_INSTANCE_HAS_STATIC_LIGHTING;
		}
		else
		{
			instance.m_LightCacheHandle = 0;
			instance.m_nFlags &= ~MODEL_INSTANCE_HAS_STATIC_LIGHTING;
		}
	}
}

LightCacheHandle_t CModelRender::GetStaticLighting( ModelInstanceHandle_t handle )
{
	if (handle != MODEL_INSTANCE_INVALID)
	{
		ModelInstance_t& instance = m_ModelInstances[handle];
		if ( instance.m_nFlags & MODEL_INSTANCE_HAS_STATIC_LIGHTING )
			return instance.m_LightCacheHandle;
		return 0;
	}

	return NULL;
}


//-----------------------------------------------------------------------------
// This gets called when overbright, etc gets changed to recompute static prop lighting.
// Returns FALSE if needed async data not available to complete computation or an error (don't draw).
// Returns TRUE if operation succeeded or computation skipped (ok to draw).
// Callers use this to track state in a retry pattern, so the expensive computation
// only happens once as needed or can continue to be polled until success.
//-----------------------------------------------------------------------------
bool CModelRender::RecomputeStaticLighting( ModelInstanceHandle_t handle )
{
#ifndef SWDS
	if ( handle == MODEL_INSTANCE_INVALID )
	{
		return false;
	}

	if ( !g_pMaterialSystemHardwareConfig->SupportsColorOnSecondStream() )
	{
		// static lighting not supported, but callers can proceed
		return true;
	}

	ModelInstance_t& instance = m_ModelInstances[handle];
	Assert( modelloader->IsLoaded( instance.m_pModel ) && ( instance.m_pModel->type == mod_studio ) );

	// get data, possibly delayed due to async
	studiohdr_t *pStudioHdr = g_pMDLCache->GetStudioHdr( instance.m_pModel->studio );
	if ( !pStudioHdr )
	{
		// data not available
		return false;
	}

	if ( pStudioHdr->flags & STUDIOHDR_FLAGS_STATIC_PROP )
	{
		// get data, possibly delayed due to async
		studiohwdata_t *pStudioHWData = g_pMDLCache->GetHardwareData( instance.m_pModel->studio );
		if ( !pStudioHWData )
		{
			// data not available
			return false;
		}

		if ( r_decalstaticprops.GetBool() && instance.m_LightCacheHandle )
		{
			instance.m_AmbientLightingState = *(LightcacheGetStatic( instance.m_LightCacheHandle, NULL, LIGHTCACHEFLAGS_STATIC ));
		}

		return UpdateStaticPropColorData( instance.m_pRenderable->GetIClientUnknown(), handle );
	}

#endif
	// success
	return true;
}

void CModelRender::PurgeCachedStaticPropColorData( void )
{
	// valid for 360 only
	Assert( IsX360() );
	if ( IsPC() )
	{
		return;
	}

	// flush all the color mesh data
	GetCacheSection()->Flush( true, true );
	DataCacheStatus_t status;
	GetCacheSection()->GetStatus( &status );
	if ( status.nBytes )
	{
		DevWarning( "CModelRender: ColorMesh %d bytes failed to flush!\n", status.nBytes );
	}

	m_colorMeshVBAllocator.Clear();
	m_CachedStaticPropColorData.Purge();
}

bool CModelRender::IsStaticPropColorDataCached( const char *pName )
{
	// valid for 360 only
	Assert( IsX360() );
	if ( IsPC() )
	{
		return false;
	}

	DataCacheHandle_t hColorMesh = DC_INVALID_HANDLE;
	{
		AUTO_LOCK( m_CachedStaticPropMutex );
		int iIndex = m_CachedStaticPropColorData.Find( pName );
		if ( m_CachedStaticPropColorData.IsValidIndex( iIndex ) )
		{
			hColorMesh = m_CachedStaticPropColorData[iIndex];
		}
	}

	CColorMeshData *pColorMeshData = CacheGetNoTouch( hColorMesh );
	if ( pColorMeshData )
	{
		// color mesh data is in cache
		return true;
	}

	return false;
}

DataCacheHandle_t CModelRender::GetCachedStaticPropColorData( const char *pName )
{
	// valid for 360 only
	Assert( IsX360() );
	if ( IsPC() )
	{
		return DC_INVALID_HANDLE;
	}

	DataCacheHandle_t hColorMesh = DC_INVALID_HANDLE;
	{
		AUTO_LOCK( m_CachedStaticPropMutex );
		int iIndex = m_CachedStaticPropColorData.Find( pName );
		if ( m_CachedStaticPropColorData.IsValidIndex( iIndex ) )
		{
			hColorMesh = m_CachedStaticPropColorData[iIndex];
		}
	}

	return hColorMesh;
}

void CModelRender::SetupColorMeshes( int nTotalVerts )
{
	Assert( IsX360() );
	if ( IsPC() )
	{
		return;
	}

	if ( !g_pQueuedLoader->IsMapLoading() )
	{
		// oops, the queued loader didn't run which does the pre-purge cleanup
		// do the cleanup now
		PurgeCachedStaticPropColorData();
	}

	// Set up the appropriate default value for color mesh pooling
	if ( r_proplightingpooling.GetInt() == -1 )
	{
		// This is useful on X360 because VBs are 4-KB aligned, so using a shared VB saves tons of memory
		r_proplightingpooling.SetValue( true );
	}

	if ( r_proplightingpooling.GetInt() == 1 )
	{
		if ( m_colorMeshVBAllocator.GetNumVertsAllocated() == 0 )
		{
			if ( nTotalVerts )
			{
				// Allocate a mesh (vertex buffer) big enough to accommodate all static prop color meshes
				// (which are allocated inside CModelRender::FindOrCreateStaticPropColorData() ):
				m_colorMeshVBAllocator.Init( VERTEX_SPECULAR, nTotalVerts );
			}
		}
		else
		{
			// already allocated
			// 360 keeps the color meshes during same map loads
			// vb allocator already allocated, needs to match
			Assert( m_colorMeshVBAllocator.GetNumVertsAllocated() == nTotalVerts );
		}
	}
}

void CModelRender::DestroyInstance( ModelInstanceHandle_t handle )
{
	if ( handle == MODEL_INSTANCE_INVALID )
		return;

	g_pStudioRender->DestroyDecalList( m_ModelInstances[handle].m_DecalHandle );
#ifndef SWDS
	g_pShadowMgr->RemoveAllShadowsFromModel( handle );
#endif

	// 360 holds onto static prop disk color data only, to avoid redundant work during same map load
	// can only persist props with disk based lighting
	// check for dvd mode as a reasonable assurance that the queued loader will be responsible for a possible purge
	// if the queued loader doesn't run, the purge will get caught later than intended
	bool bPersistLighting = IsX360() && 
		( m_ModelInstances[handle].m_nFlags & MODEL_INSTANCE_HAS_DISKCOMPILED_COLOR ) && 
		( g_pFullFileSystem->GetDVDMode() == DVDMODE_STRICT );
	if ( !bPersistLighting )
	{
		DestroyStaticPropColorData( handle );
	}

	m_ModelInstances.Remove( handle );
}

bool CModelRender::ChangeInstance( ModelInstanceHandle_t handle, IClientRenderable *pRenderable )
{
	if ( handle == MODEL_INSTANCE_INVALID || !pRenderable )
		return false;

	ModelInstance_t& instance = m_ModelInstances[handle];

	if ( instance.m_pModel != pRenderable->GetModel() )
	{
		DevMsg("MoveInstanceHandle: models are different!\n");
		return false;
	}

	// ok, models are the same, change renderable pointer
	instance.m_pRenderable = pRenderable;

	return true;
}


//-----------------------------------------------------------------------------
// It's not valid if the model index changed + we have non-zero instance data
//-----------------------------------------------------------------------------
bool CModelRender::IsModelInstanceValid( ModelInstanceHandle_t handle )
{
	if ( handle == MODEL_INSTANCE_INVALID )
		return false;

	ModelInstance_t& inst = m_ModelInstances[handle];
	if ( inst.m_DecalHandle == STUDIORENDER_DECAL_INVALID )
		return false;

	model_t const* pModel = inst.m_pRenderable->GetModel();
	return inst.m_pModel == pModel;
}


//-----------------------------------------------------------------------------
// Creates a decal on a model instance by doing a planar projection
//-----------------------------------------------------------------------------
void CModelRender::AddDecal( ModelInstanceHandle_t handle, Ray_t const& ray,
	const Vector& decalUp, int decalIndex, int body, bool noPokeThru, int maxLODToDecal )
{
	Color cColorTemp;
	AddDecalInternal( handle, ray, decalUp, decalIndex, body, false, cColorTemp, noPokeThru, maxLODToDecal );
}

//-----------------------------------------------------------------------------
void CModelRender::AddColoredDecal( ModelInstanceHandle_t handle, Ray_t const& ray,
	const Vector& decalUp, int decalIndex, int body, Color cColor, bool noPokeThru, int maxLODToDecal )
{
	AddDecalInternal( handle, ray, decalUp, decalIndex, body, true, cColor, noPokeThru, maxLODToDecal );
}

//-----------------------------------------------------------------------------
void CModelRender::GetMaterialOverride( IMaterial** ppOutForcedMaterial, OverrideType_t* pOutOverrideType )
{
	g_pStudioRender->GetMaterialOverride( ppOutForcedMaterial, pOutOverrideType );
}

//-----------------------------------------------------------------------------
void CModelRender::AddDecalInternal( ModelInstanceHandle_t handle, Ray_t const& ray, 
	const Vector& decalUp, int decalIndex, int body, bool bUseColor, Color cColor, bool noPokeThru, int maxLODToDecal)
{
	if (handle == MODEL_INSTANCE_INVALID)
		return;

	// Get the decal material + radius
	IMaterial* pDecalMaterial;
	float w, h;
	R_DecalGetMaterialAndSize( decalIndex, pDecalMaterial, w, h );
	if ( !pDecalMaterial )
	{
		DevWarning("Bad decal index %d\n", decalIndex );
		return;
	}
	w *= 0.5f;
	h *= 0.5f;

	// FIXME: For now, don't render fading decals on props...
	bool found = false;
	pDecalMaterial->FindVar( "$decalFadeDuration", &found, false );
	if ( found )
		return;

	if ( bUseColor )
	{
		IMaterialVar *pColor = pDecalMaterial->FindVar( "$color2", &found, false );
		if ( found )
		{
			// expects a 0..1 value.  Input is 0 to 255
			pColor->SetVecValue( cColor.r() / 255.0f, cColor.g() / 255.0f, cColor.b() / 255.0f );
		}
	}
	
	// FIXME: Pass w and h into AddDecal
	float radius = (w > h) ? w : h;

	ModelInstance_t& inst = m_ModelInstances[handle];
	if (!IsModelInstanceValid(handle))
	{
		g_pStudioRender->DestroyDecalList(inst.m_DecalHandle);
		inst.m_DecalHandle = STUDIORENDER_DECAL_INVALID;
	}

	Assert( modelloader->IsLoaded( inst.m_pModel ) && ( inst.m_pModel->type == mod_studio ) );
	if ( inst.m_DecalHandle == STUDIORENDER_DECAL_INVALID )
	{
		studiohwdata_t *pStudioHWData = g_pMDLCache->GetHardwareData( inst.m_pModel->studio );
		inst.m_DecalHandle = g_pStudioRender->CreateDecalList( pStudioHWData );
	}

	matrix3x4_t *pBoneToWorld = SetupModelState( inst.m_pRenderable );
	g_pStudioRender->AddDecal( inst.m_DecalHandle, g_pMDLCache->GetStudioHdr( inst.m_pModel->studio ),
		pBoneToWorld, ray, decalUp, pDecalMaterial, radius, body, noPokeThru, maxLODToDecal );
}

//-----------------------------------------------------------------------------
// Purpose: Removes all the decals on a model instance
//-----------------------------------------------------------------------------
void CModelRender::RemoveAllDecals( ModelInstanceHandle_t handle )
{
	if (handle == MODEL_INSTANCE_INVALID)
		return;

	ModelInstance_t& inst = m_ModelInstances[handle];
	if (!IsModelInstanceValid(handle))
		return;

	g_pStudioRender->DestroyDecalList( inst.m_DecalHandle );
	inst.m_DecalHandle = STUDIORENDER_DECAL_INVALID;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CModelRender::RemoveAllDecalsFromAllModels()
{
	for ( ModelInstanceHandle_t i = m_ModelInstances.Head(); 
		i != m_ModelInstances.InvalidIndex(); 
		i = m_ModelInstances.Next( i ) )
	{
		RemoveAllDecals( i );
	}
}

const vertexFileHeader_t * mstudiomodel_t::CacheVertexData( void *pModelData )
{
	// make requested data resident
	Assert( pModelData == NULL );
	return s_ModelRender.CacheVertexData();
}

bool CheckVarRange_r_rootlod()
{
	return CheckVarRange_Generic( &r_rootlod, 0, 2 );
}

bool CheckVarRange_r_lod()
{
	return CheckVarRange_Generic( &r_lod, -1, 2 );
}


// Convar callback to change lod 
//-----------------------------------------------------------------------------
void r_lod_f( IConVar *var, const char *pOldValue, float flOldValue )
{
	CheckVarRange_r_lod();
}

//-----------------------------------------------------------------------------
// Convar callback to change root lod 
//-----------------------------------------------------------------------------
void SetRootLOD_f( IConVar *pConVar, const char *pOldString, float flOldValue )
{
	// Make sure the variable is in range.
	if ( CheckVarRange_r_rootlod() )
		return;	// was called recursively.

	ConVarRef var( pConVar );
	UpdateStudioRenderConfig();
	if ( !g_LostVideoMemory && Q_strcmp( var.GetString(), pOldString ) )
	{
		// reload only the necessary models to desired lod
		modelloader->Studio_ReloadModels( IModelLoader::RELOAD_LOD_CHANGED );
	}
}

//-----------------------------------------------------------------------------
// Discard and reload (rebuild, rebake, etc) models to the current lod
//-----------------------------------------------------------------------------
void FlushLOD_f()
{
	UpdateStudioRenderConfig();
	if ( !g_LostVideoMemory )
	{
		// force a full discard and rebuild of all loaded models
		modelloader->Studio_ReloadModels( IModelLoader::RELOAD_EVERYTHING );
	}
}

//-----------------------------------------------------------------------------
//
// CPooledVBAllocator_ColorMesh implementation
//
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// CPooledVBAllocator_ColorMesh constructor
//-----------------------------------------------------------------------------
CPooledVBAllocator_ColorMesh::CPooledVBAllocator_ColorMesh()
: m_pMesh( NULL )
{
	Clear();
}

//-----------------------------------------------------------------------------
// CPooledVBAllocator_ColorMesh destructor
//  - Clear should have been called
//-----------------------------------------------------------------------------
CPooledVBAllocator_ColorMesh::~CPooledVBAllocator_ColorMesh()
{
	CheckIsClear();

	// Clean up, if it hadn't been done already
	Clear();
}

//-----------------------------------------------------------------------------
// Init
//  - Allocate the internal shared mesh (vertex buffer)
//-----------------------------------------------------------------------------
bool CPooledVBAllocator_ColorMesh::Init( VertexFormat_t format, int numVerts )
{
	if ( !CheckIsClear() )
		return false;

	if ( g_VBAllocTracker )
		g_VBAllocTracker->TrackMeshAllocations( "CPooledVBAllocator_ColorMesh::Init" );

	CMatRenderContextPtr pRenderContext( materials );
	m_pMesh = pRenderContext->CreateStaticMesh( format, TEXTURE_GROUP_STATIC_VERTEX_BUFFER_COLOR );
	if ( m_pMesh )
	{
		// Build out the underlying vertex buffer
		CMeshBuilder meshBuilder;
		int numIndices = 0;
		meshBuilder.Begin( m_pMesh, MATERIAL_HETEROGENOUS, numVerts, numIndices );
		{
			m_pVertexBufferBase	= meshBuilder.Specular();
			m_totalVerts		= numVerts;
			m_vertexSize		= meshBuilder.VertexSize();
			// Probably good to catch any change to vertex size... there may be assumptions based on it:
			Assert( m_vertexSize == 4 );
			// Start at the bottom of the VB and work your way up like a simple stack
			m_nextFreeOffset	= 0;
		}
		meshBuilder.End();
	}

	if ( g_VBAllocTracker )
		g_VBAllocTracker->TrackMeshAllocations( NULL );

	return ( m_pMesh != NULL );
}

//-----------------------------------------------------------------------------
// Clear
//  - frees the shared mesh (vertex buffer), resets member variables
//-----------------------------------------------------------------------------
void CPooledVBAllocator_ColorMesh::Clear( void )
{
	if ( m_pMesh != NULL )
	{
		if ( m_numAllocations > 0 )
		{
			Warning( "ERROR: CPooledVBAllocator_ColorMesh::Clear should not be called until all allocations released!" );
			Assert( m_numAllocations == 0 );
		}
		CMatRenderContextPtr pRenderContext( materials );
		pRenderContext->DestroyStaticMesh( m_pMesh );
		m_pMesh = NULL;
	}

	m_pVertexBufferBase		= NULL;
	m_totalVerts			= 0;
	m_vertexSize			= 0;

	m_numAllocations		= 0;
	m_numVertsAllocated		= 0;
	m_nextFreeOffset		= -1;
	m_bStartedDeallocation	= false;
}

//-----------------------------------------------------------------------------
// CheckIsClear
//  - assert/warn if the allocator isn't in a clear state
//    (no extant allocations, no internal mesh)
//-----------------------------------------------------------------------------
bool CPooledVBAllocator_ColorMesh::CheckIsClear( void )
{
	if ( m_pMesh )
	{
		Warning( "ERROR: CPooledVBAllocator_ColorMesh's internal mesh (vertex buffer) should have been freed!" );
		Assert( m_pMesh == NULL );
		return false;
	}

	if ( m_numAllocations > 0 )
	{
		Warning( "ERROR: CPooledVBAllocator_ColorMesh has unfreed allocations!" );
		Assert( m_numAllocations == 0 );
		return false;
	}

	return true;
}

//-----------------------------------------------------------------------------
// Allocate
//  - Allocate a sub-range of 'numVerts' from free space in the shared vertex buffer
//    (returns the byte offset from the start of the VB to the new allocation)
//  - returns -1 on failure
//-----------------------------------------------------------------------------
int CPooledVBAllocator_ColorMesh::Allocate( int numVerts )
{
	if ( m_pMesh == NULL )
	{
		Warning( "ERROR: CPooledVBAllocator_ColorMesh::Allocate cannot be called before Init (expect a crash)" );
		Assert( m_pMesh );
		return -1;
	}

	// Once we start deallocating, we have to keep going until everything has been freed
	if ( m_bStartedDeallocation )
	{
		Warning( "ERROR: CPooledVBAllocator_ColorMesh::Allocate being called after some (but not all) calls to Deallocate have been called - invalid! (expect visual artifacts)" );
		Assert( !m_bStartedDeallocation );
		return -1;
	}

	if ( numVerts > ( m_totalVerts - m_numVertsAllocated ) )
	{
		Warning( "ERROR: CPooledVBAllocator_ColorMesh::Allocate failing - not enough space left in the vertex buffer!" );
		Assert( numVerts <= ( m_totalVerts - m_numVertsAllocated ) );
		return -1;
	}

	int result = m_nextFreeOffset;

	m_numAllocations	+= 1;
	m_numVertsAllocated	+= numVerts;
	m_nextFreeOffset	+= numVerts*m_vertexSize;

	return result;
}

//-----------------------------------------------------------------------------
// Deallocate
//  - Deallocate an existing allocation
//-----------------------------------------------------------------------------
void CPooledVBAllocator_ColorMesh::Deallocate( int offset, int numVerts )
{
	if ( m_pMesh == NULL )
	{
		Warning( "ERROR: CPooledVBAllocator_ColorMesh::Deallocate cannot be called before Init" );
		Assert( m_pMesh != NULL );
		return;
	}

	if ( m_numAllocations == 0 )
	{
		Warning( "ERROR: CPooledVBAllocator_ColorMesh::Deallocate called too many times! (bug in calling code)" );
		Assert( m_numAllocations > 0 );
		return;
	}

	if ( numVerts > m_numVertsAllocated )
	{
		Warning( "ERROR: CPooledVBAllocator_ColorMesh::Deallocate called with too many verts, trying to free more than were allocated (bug in calling code)" );
		Assert( numVerts <= m_numVertsAllocated );
		numVerts = m_numVertsAllocated; // Hack (avoid counters ever going below zero)
	}

	// Now all extant allocations must be freed before we make any new allocations
	m_bStartedDeallocation = true;

	m_numAllocations	-= 1;
	m_numVertsAllocated	-= numVerts;
	m_nextFreeOffset	 = 0; // (we shouldn't be returning this until everything's free, at which point 0 is valid)

	// Are we empty?
	if ( m_numAllocations == 0 )
	{
		if ( m_numVertsAllocated != 0 )
		{
			Warning( "ERROR: CPooledVBAllocator_ColorMesh::Deallocate, after all allocations have been freed too few verts total have been deallocated (bug in calling code)" );
			Assert( m_numVertsAllocated == 0 );
		}

		// We can start allocating again, now
		m_bStartedDeallocation = false;
	}
}

//-----------------------------------------------------------------------------
// CreateLightmapsFromData
//  - Creates Lightmap Textures from data that was squirreled away during ASYNC load.
//  This is necessary because the material system doesn't like us creating things from ASYNC loaders.
//-----------------------------------------------------------------------------
static void CreateLightmapsFromData(CColorMeshData* _colorMeshData)
{
	Assert(_colorMeshData->m_bColorTextureValid);
	Assert(!_colorMeshData->m_bColorTextureCreated);

	for (int mesh = 0; mesh < _colorMeshData->m_nMeshes; ++mesh)
	{
		ColorMeshInfo_t* meshInfo = &_colorMeshData->m_pMeshInfos[mesh];

		// Ensure that we haven't somehow already messed with these.
		Assert(meshInfo->m_pLightmapData);
		Assert(!meshInfo->m_pLightmap);

		ColorTexelsInfo_t* cti = meshInfo->m_pLightmapData;

		Assert(cti->m_pTexelData);
		
		meshInfo->m_pLightmap = g_pMaterialSystem->CreateTextureFromBits(cti->m_nWidth, cti->m_nHeight, cti->m_nMipmapCount, cti->m_ImageFormat, cti->m_nByteCount, cti->m_pTexelData);

		// If this triggers, we need to figure out if it's reasonable to fail. If it is, then we should figure out how to signal back
		// that we shouldn't try to create this again (probably by clearing _colorMeshData->m_bColoTextureValid)
		Assert(meshInfo->m_pLightmap);

		// Cleanup after ourselves.
		delete [] cti->m_pTexelData;
		delete cti;

		meshInfo->m_pLightmapData = NULL;
	}

	_colorMeshData->m_bColorTextureCreated = true;
}