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
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Spawn and use functions for editor-placed triggers.
//
//===========================================================================//
#include "cbase.h"
#include "ai_basenpc.h"
#include "player.h"
#include "saverestore.h"
#include "gamerules.h"
#include "entityapi.h"
#include "entitylist.h"
#include "ndebugoverlay.h"
#include "globalstate.h"
#include "filters.h"
#include "vstdlib/random.h"
#include "triggers.h"
#include "saverestoretypes.h"
#include "hierarchy.h"
#include "bspfile.h"
#include "saverestore_utlvector.h"
#include "physics_saverestore.h"
#include "te_effect_dispatch.h"
#include "ammodef.h"
#include "iservervehicle.h"
#include "movevars_shared.h"
#include "physics_prop_ragdoll.h"
#include "props.h"
#include "RagdollBoogie.h"
#include "EntityParticleTrail.h"
#include "in_buttons.h"
#include "ai_behavior_follow.h"
#include "ai_behavior_lead.h"
#include "gameinterface.h"
#include "ilagcompensationmanager.h"
#ifdef HL2_DLL
#include "hl2_player.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define DEBUG_TRANSITIONS_VERBOSE 2
ConVar g_debug_transitions( "g_debug_transitions", "0", FCVAR_NONE, "Set to 1 and restart the map to be warned if the map has no trigger_transition volumes. Set to 2 to see a dump of all entities & associated results during a transition." );
// Global list of triggers that care about weapon fire
// Doesn't need saving, the triggers re-add themselves on restore.
CUtlVector< CHandle<CTriggerMultiple> > g_hWeaponFireTriggers;
extern CServerGameDLL g_ServerGameDLL;
extern bool g_fGameOver;
ConVar showtriggers( "showtriggers", "0", FCVAR_CHEAT, "Shows trigger brushes" );
bool IsTriggerClass( CBaseEntity *pEntity );
// Command to dynamically toggle trigger visibility
void Cmd_ShowtriggersToggle_f( const CCommand &args )
{
// Loop through the entities in the game and make visible anything derived from CBaseTrigger
CBaseEntity *pEntity = gEntList.FirstEnt();
while ( pEntity )
{
if ( IsTriggerClass(pEntity) )
{
// If a classname is specified, only show triggles of that type
if ( args.ArgC() > 1 )
{
const char *sClassname = args[1];
if ( sClassname && sClassname[0] )
{
if ( !FClassnameIs( pEntity, sClassname ) )
{
pEntity = gEntList.NextEnt( pEntity );
continue;
}
}
}
if ( pEntity->IsEffectActive( EF_NODRAW ) )
{
pEntity->RemoveEffects( EF_NODRAW );
}
else
{
pEntity->AddEffects( EF_NODRAW );
}
}
pEntity = gEntList.NextEnt( pEntity );
}
}
static ConCommand showtriggers_toggle( "showtriggers_toggle", Cmd_ShowtriggersToggle_f, "Toggle show triggers", FCVAR_CHEAT );
// Global Savedata for base trigger
BEGIN_DATADESC( CBaseTrigger )
// Keyfields
DEFINE_KEYFIELD( m_iFilterName, FIELD_STRING, "filtername" ),
DEFINE_FIELD( m_hFilter, FIELD_EHANDLE ),
DEFINE_KEYFIELD( m_bDisabled, FIELD_BOOLEAN, "StartDisabled" ),
DEFINE_UTLVECTOR( m_hTouchingEntities, FIELD_EHANDLE ),
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ),
DEFINE_INPUTFUNC( FIELD_VOID, "TouchTest", InputTouchTest ),
DEFINE_INPUTFUNC( FIELD_VOID, "StartTouch", InputStartTouch ),
DEFINE_INPUTFUNC( FIELD_VOID, "EndTouch", InputEndTouch ),
// Outputs
DEFINE_OUTPUT( m_OnStartTouch, "OnStartTouch"),
DEFINE_OUTPUT( m_OnStartTouchAll, "OnStartTouchAll"),
DEFINE_OUTPUT( m_OnEndTouch, "OnEndTouch"),
DEFINE_OUTPUT( m_OnEndTouchAll, "OnEndTouchAll"),
DEFINE_OUTPUT( m_OnTouching, "OnTouching" ),
DEFINE_OUTPUT( m_OnNotTouching, "OnNotTouching" ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger, CBaseTrigger );
CBaseTrigger::CBaseTrigger()
{
AddEFlags( EFL_USE_PARTITION_WHEN_NOT_SOLID );
}
//------------------------------------------------------------------------------
// Purpose: Input handler to turn on this trigger.
//------------------------------------------------------------------------------
void CBaseTrigger::InputEnable( inputdata_t &inputdata )
{
Enable();
}
//------------------------------------------------------------------------------
// Purpose: Input handler to turn off this trigger.
//------------------------------------------------------------------------------
void CBaseTrigger::InputDisable( inputdata_t &inputdata )
{
Disable();
}
void CBaseTrigger::InputTouchTest( inputdata_t &inputdata )
{
TouchTest();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CBaseTrigger::Spawn()
{
if ( HasSpawnFlags( SF_TRIGGER_ONLY_PLAYER_ALLY_NPCS ) || HasSpawnFlags( SF_TRIGGER_ONLY_NPCS_IN_VEHICLES ) )
{
// Automatically set this trigger to work with NPC's.
AddSpawnFlags( SF_TRIGGER_ALLOW_NPCS );
}
if ( HasSpawnFlags( SF_TRIGGER_ONLY_CLIENTS_IN_VEHICLES ) )
{
AddSpawnFlags( SF_TRIGGER_ALLOW_CLIENTS );
}
if ( HasSpawnFlags( SF_TRIGGER_ONLY_CLIENTS_OUT_OF_VEHICLES ) )
{
AddSpawnFlags( SF_TRIGGER_ALLOW_CLIENTS );
}
BaseClass::Spawn();
}
//------------------------------------------------------------------------------
// Cleanup
//------------------------------------------------------------------------------
void CBaseTrigger::UpdateOnRemove( void )
{
if ( VPhysicsGetObject())
{
VPhysicsGetObject()->RemoveTrigger();
}
BaseClass::UpdateOnRemove();
}
//------------------------------------------------------------------------------
// Purpose: Turns on this trigger.
//------------------------------------------------------------------------------
void CBaseTrigger::Enable( void )
{
m_bDisabled = false;
if ( VPhysicsGetObject())
{
VPhysicsGetObject()->EnableCollisions( true );
}
if (!IsSolidFlagSet( FSOLID_TRIGGER ))
{
AddSolidFlags( FSOLID_TRIGGER );
PhysicsTouchTriggers();
}
}
//------------------------------------------------------------------------------
// Purpose :
//------------------------------------------------------------------------------
void CBaseTrigger::Activate( void )
{
// Get a handle to my filter entity if there is one
if (m_iFilterName != NULL_STRING)
{
m_hFilter = dynamic_cast<CBaseFilter *>(gEntList.FindEntityByName( NULL, m_iFilterName ));
}
BaseClass::Activate();
}
//-----------------------------------------------------------------------------
// Purpose: Called after player becomes active in the game
//-----------------------------------------------------------------------------
void CBaseTrigger::PostClientActive( void )
{
BaseClass::PostClientActive();
if ( !m_bDisabled )
{
PhysicsTouchTriggers();
}
}
//------------------------------------------------------------------------------
// Purpose: Turns off this trigger.
//------------------------------------------------------------------------------
void CBaseTrigger::Disable( void )
{
m_bDisabled = true;
if ( VPhysicsGetObject())
{
VPhysicsGetObject()->EnableCollisions( false );
}
if (IsSolidFlagSet(FSOLID_TRIGGER))
{
RemoveSolidFlags( FSOLID_TRIGGER );
PhysicsTouchTriggers();
}
}
//------------------------------------------------------------------------------
// Purpose: Tests to see if anything is touching this trigger.
//------------------------------------------------------------------------------
void CBaseTrigger::TouchTest( void )
{
// If the trigger is disabled don't test to see if anything is touching it.
if ( !m_bDisabled )
{
if ( m_hTouchingEntities.Count() !=0 )
{
m_OnTouching.FireOutput( this, this );
}
else
{
m_OnNotTouching.FireOutput( this, this );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Draw any debug text overlays
// Output : Current text offset from the top
//-----------------------------------------------------------------------------
int CBaseTrigger::DrawDebugTextOverlays(void)
{
int text_offset = BaseClass::DrawDebugTextOverlays();
if (m_debugOverlays & OVERLAY_TEXT_BIT)
{
// --------------
// Print Target
// --------------
char tempstr[255];
if (IsSolidFlagSet(FSOLID_TRIGGER))
{
Q_strncpy(tempstr,"State: Enabled",sizeof(tempstr));
}
else
{
Q_strncpy(tempstr,"State: Disabled",sizeof(tempstr));
}
EntityText(text_offset,tempstr,0);
text_offset++;
}
return text_offset;
}
//-----------------------------------------------------------------------------
// Purpose: Return true if the specified point is within this zone
//-----------------------------------------------------------------------------
bool CBaseTrigger::PointIsWithin( const Vector &vecPoint )
{
Ray_t ray;
trace_t tr;
ICollideable *pCollide = CollisionProp();
ray.Init( vecPoint, vecPoint );
enginetrace->ClipRayToCollideable( ray, MASK_ALL, pCollide, &tr );
return ( tr.startsolid );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseTrigger::InitTrigger( )
{
SetSolid( GetParent() ? SOLID_VPHYSICS : SOLID_BSP );
AddSolidFlags( FSOLID_NOT_SOLID );
if (m_bDisabled)
{
RemoveSolidFlags( FSOLID_TRIGGER );
}
else
{
AddSolidFlags( FSOLID_TRIGGER );
}
SetMoveType( MOVETYPE_NONE );
SetModel( STRING( GetModelName() ) ); // set size and link into world
if ( showtriggers.GetInt() == 0 )
{
AddEffects( EF_NODRAW );
}
m_hTouchingEntities.Purge();
if ( HasSpawnFlags( SF_TRIG_TOUCH_DEBRIS ) )
{
CollisionProp()->AddSolidFlags( FSOLID_TRIGGER_TOUCH_DEBRIS );
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns true if this entity passes the filter criteria, false if not.
// Input : pOther - The entity to be filtered.
//-----------------------------------------------------------------------------
bool CBaseTrigger::PassesTriggerFilters(CBaseEntity *pOther)
{
// First test spawn flag filters
if ( HasSpawnFlags(SF_TRIGGER_ALLOW_ALL) ||
(HasSpawnFlags(SF_TRIGGER_ALLOW_CLIENTS) && (pOther->GetFlags() & FL_CLIENT)) ||
(HasSpawnFlags(SF_TRIGGER_ALLOW_NPCS) && (pOther->GetFlags() & FL_NPC)) ||
(HasSpawnFlags(SF_TRIGGER_ALLOW_PUSHABLES) && FClassnameIs(pOther, "func_pushable")) ||
(HasSpawnFlags(SF_TRIGGER_ALLOW_PHYSICS) && pOther->GetMoveType() == MOVETYPE_VPHYSICS)
#if defined( HL2_EPISODIC ) || defined( TF_DLL )
||
( HasSpawnFlags(SF_TRIG_TOUCH_DEBRIS) &&
(pOther->GetCollisionGroup() == COLLISION_GROUP_DEBRIS ||
pOther->GetCollisionGroup() == COLLISION_GROUP_DEBRIS_TRIGGER ||
pOther->GetCollisionGroup() == COLLISION_GROUP_INTERACTIVE_DEBRIS)
)
#endif
)
{
if ( pOther->GetFlags() & FL_NPC )
{
CAI_BaseNPC *pNPC = pOther->MyNPCPointer();
if ( HasSpawnFlags( SF_TRIGGER_ONLY_PLAYER_ALLY_NPCS ) )
{
if ( !pNPC || !pNPC->IsPlayerAlly() )
{
return false;
}
}
if ( HasSpawnFlags( SF_TRIGGER_ONLY_NPCS_IN_VEHICLES ) )
{
if ( !pNPC || !pNPC->IsInAVehicle() )
return false;
}
}
bool bOtherIsPlayer = pOther->IsPlayer();
if ( bOtherIsPlayer )
{
CBasePlayer *pPlayer = (CBasePlayer*)pOther;
if ( !pPlayer->IsAlive() )
return false;
if ( HasSpawnFlags(SF_TRIGGER_ONLY_CLIENTS_IN_VEHICLES) )
{
if ( !pPlayer->IsInAVehicle() )
return false;
// Make sure we're also not exiting the vehicle at the moment
IServerVehicle *pVehicleServer = pPlayer->GetVehicle();
if ( pVehicleServer == NULL )
return false;
if ( pVehicleServer->IsPassengerExiting() )
return false;
}
if ( HasSpawnFlags(SF_TRIGGER_ONLY_CLIENTS_OUT_OF_VEHICLES) )
{
if ( pPlayer->IsInAVehicle() )
return false;
}
if ( HasSpawnFlags( SF_TRIGGER_DISALLOW_BOTS ) )
{
if ( pPlayer->IsFakeClient() )
return false;
}
}
CBaseFilter *pFilter = m_hFilter.Get();
return (!pFilter) ? true : pFilter->PassesFilter( this, pOther );
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Called to simulate what happens when an entity touches the trigger.
// Input : pOther - The entity that is touching us.
//-----------------------------------------------------------------------------
void CBaseTrigger::InputStartTouch( inputdata_t &inputdata )
{
//Pretend we just touched the trigger.
StartTouch( inputdata.pCaller );
}
//-----------------------------------------------------------------------------
// Purpose: Called to simulate what happens when an entity leaves the trigger.
// Input : pOther - The entity that is touching us.
//-----------------------------------------------------------------------------
void CBaseTrigger::InputEndTouch( inputdata_t &inputdata )
{
//And... pretend we left the trigger.
EndTouch( inputdata.pCaller );
}
//-----------------------------------------------------------------------------
// Purpose: Called when an entity starts touching us.
// Input : pOther - The entity that is touching us.
//-----------------------------------------------------------------------------
void CBaseTrigger::StartTouch(CBaseEntity *pOther)
{
if (PassesTriggerFilters(pOther) )
{
EHANDLE hOther;
hOther = pOther;
bool bAdded = false;
if ( m_hTouchingEntities.Find( hOther ) == m_hTouchingEntities.InvalidIndex() )
{
m_hTouchingEntities.AddToTail( hOther );
bAdded = true;
}
m_OnStartTouch.FireOutput(pOther, this);
if ( bAdded && ( m_hTouchingEntities.Count() == 1 ) )
{
// First entity to touch us that passes our filters
m_OnStartTouchAll.FireOutput( pOther, this );
StartTouchAll();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Called when an entity stops touching us.
// Input : pOther - The entity that was touching us.
//-----------------------------------------------------------------------------
void CBaseTrigger::EndTouch(CBaseEntity *pOther)
{
if ( IsTouching( pOther ) )
{
EHANDLE hOther;
hOther = pOther;
m_hTouchingEntities.FindAndRemove( hOther );
//FIXME: Without this, triggers fire their EndTouch outputs when they are disabled!
//if ( !m_bDisabled )
//{
m_OnEndTouch.FireOutput(pOther, this);
//}
// If there are no more entities touching this trigger, fire the lost all touches
// Loop through the touching entities backwards. Clean out old ones, and look for existing
bool bFoundOtherTouchee = false;
int iSize = m_hTouchingEntities.Count();
for ( int i = iSize-1; i >= 0; i-- )
{
EHANDLE hOther;
hOther = m_hTouchingEntities[i];
if ( !hOther )
{
m_hTouchingEntities.Remove( i );
}
else if ( hOther->IsPlayer() && !hOther->IsAlive() )
{
#ifdef STAGING_ONLY
if ( !HushAsserts() )
{
AssertMsg( false, "Dead player [%s] is still touching this trigger at [%f %f %f]", hOther->GetEntityName().ToCStr(), XYZ( hOther->GetAbsOrigin() ) );
}
Warning( "Dead player [%s] is still touching this trigger at [%f %f %f]", hOther->GetEntityName().ToCStr(), XYZ( hOther->GetAbsOrigin() ) );
#endif
m_hTouchingEntities.Remove( i );
}
else
{
bFoundOtherTouchee = true;
}
}
//FIXME: Without this, triggers fire their EndTouch outputs when they are disabled!
// Didn't find one?
if ( !bFoundOtherTouchee /*&& !m_bDisabled*/ )
{
m_OnEndTouchAll.FireOutput(pOther, this);
EndTouchAll();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Return true if the specified entity is touching us
//-----------------------------------------------------------------------------
bool CBaseTrigger::IsTouching( CBaseEntity *pOther )
{
EHANDLE hOther;
hOther = pOther;
return ( m_hTouchingEntities.Find( hOther ) != m_hTouchingEntities.InvalidIndex() );
}
//-----------------------------------------------------------------------------
// Purpose: Return a pointer to the first entity of the specified type being touched by this trigger
//-----------------------------------------------------------------------------
CBaseEntity *CBaseTrigger::GetTouchedEntityOfType( const char *sClassName )
{
int iCount = m_hTouchingEntities.Count();
for ( int i = 0; i < iCount; i++ )
{
CBaseEntity *pEntity = m_hTouchingEntities[i];
if ( FClassnameIs( pEntity, sClassName ) )
return pEntity;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Toggles this trigger between enabled and disabled.
//-----------------------------------------------------------------------------
void CBaseTrigger::InputToggle( inputdata_t &inputdata )
{
if (IsSolidFlagSet( FSOLID_TRIGGER ))
{
RemoveSolidFlags(FSOLID_TRIGGER);
}
else
{
AddSolidFlags(FSOLID_TRIGGER);
}
PhysicsTouchTriggers();
}
//-----------------------------------------------------------------------------
// Purpose: Removes anything that touches it. If the trigger has a targetname,
// firing it will toggle state.
//-----------------------------------------------------------------------------
class CTriggerRemove : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerRemove, CBaseTrigger );
void Spawn( void );
void Touch( CBaseEntity *pOther );
DECLARE_DATADESC();
// Outputs
COutputEvent m_OnRemove;
};
BEGIN_DATADESC( CTriggerRemove )
// Outputs
DEFINE_OUTPUT( m_OnRemove, "OnRemove" ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger_remove, CTriggerRemove );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerRemove::Spawn( void )
{
BaseClass::Spawn();
InitTrigger();
}
//-----------------------------------------------------------------------------
// Purpose: Trigger hurt that causes radiation will do a radius check and set
// the player's geiger counter level according to distance from center
// of trigger.
//-----------------------------------------------------------------------------
void CTriggerRemove::Touch( CBaseEntity *pOther )
{
if (!PassesTriggerFilters(pOther))
return;
UTIL_Remove( pOther );
}
BEGIN_DATADESC( CTriggerHurt )
// Function Pointers
DEFINE_FUNCTION( CTriggerHurtShim::RadiationThinkShim ),
DEFINE_FUNCTION( CTriggerHurtShim::HurtThinkShim ),
// Fields
DEFINE_FIELD( m_flOriginalDamage, FIELD_FLOAT ),
DEFINE_KEYFIELD( m_flDamage, FIELD_FLOAT, "damage" ),
DEFINE_KEYFIELD( m_flDamageCap, FIELD_FLOAT, "damagecap" ),
DEFINE_KEYFIELD( m_bitsDamageInflict, FIELD_INTEGER, "damagetype" ),
DEFINE_KEYFIELD( m_damageModel, FIELD_INTEGER, "damagemodel" ),
DEFINE_KEYFIELD( m_bNoDmgForce, FIELD_BOOLEAN, "nodmgforce" ),
DEFINE_FIELD( m_flLastDmgTime, FIELD_TIME ),
DEFINE_FIELD( m_flDmgResetTime, FIELD_TIME ),
DEFINE_UTLVECTOR( m_hurtEntities, FIELD_EHANDLE ),
// Inputs
DEFINE_INPUT( m_flDamage, FIELD_FLOAT, "SetDamage" ),
// Outputs
DEFINE_OUTPUT( m_OnHurt, "OnHurt" ),
DEFINE_OUTPUT( m_OnHurtPlayer, "OnHurtPlayer" ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger_hurt, CTriggerHurt );
IMPLEMENT_AUTO_LIST( ITriggerHurtAutoList );
//-----------------------------------------------------------------------------
// Purpose: Called when spawning, after keyvalues have been handled.
//-----------------------------------------------------------------------------
void CTriggerHurt::Spawn( void )
{
BaseClass::Spawn();
InitTrigger();
m_flOriginalDamage = m_flDamage;
SetNextThink( TICK_NEVER_THINK );
SetThink( NULL );
if (m_bitsDamageInflict & DMG_RADIATION)
{
SetThink ( &CTriggerHurtShim::RadiationThinkShim );
SetNextThink( gpGlobals->curtime + random->RandomFloat(0.0, 0.5) );
}
}
//-----------------------------------------------------------------------------
// Purpose: Trigger hurt that causes radiation will do a radius check and set
// the player's geiger counter level according to distance from center
// of trigger.
//-----------------------------------------------------------------------------
void CTriggerHurt::RadiationThink( void )
{
// check to see if a player is in pvs
// if not, continue
Vector vecSurroundMins, vecSurroundMaxs;
CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs );
CBasePlayer *pPlayer = static_cast<CBasePlayer *>(UTIL_FindClientInPVS( vecSurroundMins, vecSurroundMaxs ));
if (pPlayer)
{
// get range to player;
float flRange = CollisionProp()->CalcDistanceFromPoint( pPlayer->WorldSpaceCenter() );
flRange *= 3.0f;
pPlayer->NotifyNearbyRadiationSource(flRange);
}
float dt = gpGlobals->curtime - m_flLastDmgTime;
if ( dt >= 0.5 )
{
HurtAllTouchers( dt );
}
SetNextThink( gpGlobals->curtime + 0.25 );
}
//-----------------------------------------------------------------------------
// Purpose: When touched, a hurt trigger does m_flDamage points of damage each half-second.
// Input : pOther - The entity that is touching us.
//-----------------------------------------------------------------------------
bool CTriggerHurt::HurtEntity( CBaseEntity *pOther, float damage )
{
if ( !pOther->m_takedamage || !PassesTriggerFilters(pOther) )
return false;
// If player is disconnected, we're probably in this routine via the
// PhysicsRemoveTouchedList() function to make sure all Untouch()'s are called for the
// player. Calling TakeDamage() in this case can get into the speaking criteria, which
// will then loop through the control points and the touched list again. We shouldn't
// need to hurt players that are disconnected, so skip all of this...
bool bPlayerDisconnected = pOther->IsPlayer() && ( ((CBasePlayer *)pOther)->IsConnected() == false );
if ( bPlayerDisconnected )
return false;
if ( damage < 0 )
{
pOther->TakeHealth( -damage, m_bitsDamageInflict );
}
else
{
// The damage position is the nearest point on the damaged entity
// to the trigger's center. Not perfect, but better than nothing.
Vector vecCenter = CollisionProp()->WorldSpaceCenter();
Vector vecDamagePos;
pOther->CollisionProp()->CalcNearestPoint( vecCenter, &vecDamagePos );
CTakeDamageInfo info( this, this, damage, m_bitsDamageInflict );
info.SetDamagePosition( vecDamagePos );
if ( !m_bNoDmgForce )
{
GuessDamageForce( &info, ( vecDamagePos - vecCenter ), vecDamagePos );
}
else
{
info.SetDamageForce( vec3_origin );
}
pOther->TakeDamage( info );
}
if (pOther->IsPlayer())
{
m_OnHurtPlayer.FireOutput(pOther, this);
}
else
{
m_OnHurt.FireOutput(pOther, this);
}
m_hurtEntities.AddToTail( EHANDLE(pOther) );
//NDebugOverlay::Box( pOther->GetAbsOrigin(), pOther->WorldAlignMins(), pOther->WorldAlignMaxs(), 255,0,0,0,0.5 );
return true;
}
void CTriggerHurt::HurtThink()
{
// if I hurt anyone, think again
if ( HurtAllTouchers( 0.5 ) <= 0 )
{
SetThink(NULL);
}
else
{
SetNextThink( gpGlobals->curtime + 0.5f );
}
}
void CTriggerHurt::EndTouch( CBaseEntity *pOther )
{
if (PassesTriggerFilters(pOther))
{
EHANDLE hOther;
hOther = pOther;
// if this guy has never taken damage, hurt him now
if ( !m_hurtEntities.HasElement( hOther ) )
{
HurtEntity( pOther, m_flDamage * 0.5 );
}
}
BaseClass::EndTouch( pOther );
}
//-----------------------------------------------------------------------------
// Purpose: called from RadiationThink() as well as HurtThink()
// This function applies damage to any entities currently touching the
// trigger
// Input : dt - time since last call
// Output : int - number of entities actually hurt
//-----------------------------------------------------------------------------
#define TRIGGER_HURT_FORGIVE_TIME 3.0f // time in seconds
int CTriggerHurt::HurtAllTouchers( float dt )
{
int hurtCount = 0;
// half second worth of damage
float fldmg = m_flDamage * dt;
m_flLastDmgTime = gpGlobals->curtime;
m_hurtEntities.RemoveAll();
touchlink_t *root = ( touchlink_t * )GetDataObject( TOUCHLINK );
if ( root )
{
for ( touchlink_t *link = root->nextLink; link != root; link = link->nextLink )
{
CBaseEntity *pTouch = link->entityTouched;
if ( pTouch )
{
if ( HurtEntity( pTouch, fldmg ) )
{
hurtCount++;
}
}
}
}
if( m_damageModel == DAMAGEMODEL_DOUBLE_FORGIVENESS )
{
if( hurtCount == 0 )
{
if( gpGlobals->curtime > m_flDmgResetTime )
{
// Didn't hurt anyone. Reset the damage if it's time. (hence, the forgiveness)
m_flDamage = m_flOriginalDamage;
}
}
else
{
// Hurt someone! double the damage
m_flDamage *= 2.0f;
if( m_flDamage > m_flDamageCap )
{
// Clamp
m_flDamage = m_flDamageCap;
}
// Now, put the damage reset time into the future. The forgive time is how long the trigger
// must go without harming anyone in order that its accumulated damage be reset to the amount
// set by the level designer. This is a stop-gap for an exploit where players could hop through
// slime and barely take any damage because the trigger would reset damage anytime there was no
// one in the trigger when this function was called. (sjb)
m_flDmgResetTime = gpGlobals->curtime + TRIGGER_HURT_FORGIVE_TIME;
}
}
return hurtCount;
}
void CTriggerHurt::Touch( CBaseEntity *pOther )
{
if ( m_pfnThink == NULL )
{
SetThink( &CTriggerHurtShim::HurtThinkShim );
SetNextThink( gpGlobals->curtime );
}
}
//-----------------------------------------------------------------------------
// Purpose: Checks if this point is in any trigger_hurt zones with positive damage
//-----------------------------------------------------------------------------
bool IsTakingTriggerHurtDamageAtPoint( const Vector &vecPoint )
{
for ( int i = 0; i < ITriggerHurtAutoList::AutoList().Count(); i++ )
{
// Some maps use trigger_hurt with negative values as healing triggers; don't consider those
CTriggerHurt *pTrigger = static_cast<CTriggerHurt*>( ITriggerHurtAutoList::AutoList()[i] );
if ( !pTrigger->m_bDisabled && pTrigger->PointIsWithin( vecPoint ) && pTrigger->m_flDamage > 0.f )
{
return true;
}
}
return false;
}
// ##################################################################################
// >> TriggerMultiple
// ##################################################################################
LINK_ENTITY_TO_CLASS( trigger_multiple, CTriggerMultiple );
BEGIN_DATADESC( CTriggerMultiple )
// Function Pointers
DEFINE_FUNCTION(MultiTouch),
DEFINE_FUNCTION(MultiWaitOver ),
// Outputs
DEFINE_OUTPUT(m_OnTrigger, "OnTrigger")
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose: Called when spawning, after keyvalues have been handled.
//-----------------------------------------------------------------------------
void CTriggerMultiple::Spawn( void )
{
BaseClass::Spawn();
InitTrigger();
if (m_flWait == 0)
{
m_flWait = 0.2;
}
ASSERTSZ(m_iHealth == 0, "trigger_multiple with health");
SetTouch( &CTriggerMultiple::MultiTouch );
}
//-----------------------------------------------------------------------------
// Purpose: Touch function. Activates the trigger.
// Input : pOther - The thing that touched us.
//-----------------------------------------------------------------------------
void CTriggerMultiple::MultiTouch(CBaseEntity *pOther)
{
if (PassesTriggerFilters(pOther))
{
ActivateMultiTrigger( pOther );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pActivator -
//-----------------------------------------------------------------------------
void CTriggerMultiple::ActivateMultiTrigger(CBaseEntity *pActivator)
{
if (GetNextThink() > gpGlobals->curtime)
return; // still waiting for reset time
m_hActivator = pActivator;
m_OnTrigger.FireOutput(m_hActivator, this);
if (m_flWait > 0)
{
SetThink( &CTriggerMultiple::MultiWaitOver );
SetNextThink( gpGlobals->curtime + m_flWait );
}
else
{
// we can't just remove (self) here, because this is a touch function
// called while C code is looping through area links...
SetTouch( NULL );
SetNextThink( gpGlobals->curtime + 0.1f );
SetThink( &CTriggerMultiple::SUB_Remove );
}
}
//-----------------------------------------------------------------------------
// Purpose: The wait time has passed, so set back up for another activation
//-----------------------------------------------------------------------------
void CTriggerMultiple::MultiWaitOver( void )
{
SetThink( NULL );
}
// ##################################################################################
// >> TriggerOnce
// ##################################################################################
class CTriggerOnce : public CTriggerMultiple
{
DECLARE_CLASS( CTriggerOnce, CTriggerMultiple );
public:
void Spawn( void );
};
LINK_ENTITY_TO_CLASS( trigger_once, CTriggerOnce );
void CTriggerOnce::Spawn( void )
{
BaseClass::Spawn();
m_flWait = -1;
}
// ##################################################################################
// >> TriggerLook
//
// Triggers once when player is looking at m_target
//
// ##################################################################################
#define SF_TRIGGERLOOK_FIREONCE 128
#define SF_TRIGGERLOOK_USEVELOCITY 256
class CTriggerLook : public CTriggerOnce
{
DECLARE_CLASS( CTriggerLook, CTriggerOnce );
public:
EHANDLE m_hLookTarget;
float m_flFieldOfView;
float m_flLookTime; // How long must I look for
float m_flLookTimeTotal; // How long have I looked
float m_flLookTimeLast; // When did I last look
float m_flTimeoutDuration; // Number of seconds after start touch to fire anyway
bool m_bTimeoutFired; // True if the OnTimeout output fired since the last StartTouch.
EHANDLE m_hActivator; // The entity that triggered us.
void Spawn( void );
void Touch( CBaseEntity *pOther );
void StartTouch(CBaseEntity *pOther);
void EndTouch( CBaseEntity *pOther );
int DrawDebugTextOverlays(void);
DECLARE_DATADESC();
private:
void Trigger(CBaseEntity *pActivator, bool bTimeout);
void TimeoutThink();
COutputEvent m_OnTimeout;
};
LINK_ENTITY_TO_CLASS( trigger_look, CTriggerLook );
BEGIN_DATADESC( CTriggerLook )
DEFINE_FIELD( m_hLookTarget, FIELD_EHANDLE ),
DEFINE_FIELD( m_flLookTimeTotal, FIELD_FLOAT ),
DEFINE_FIELD( m_flLookTimeLast, FIELD_TIME ),
DEFINE_KEYFIELD( m_flTimeoutDuration, FIELD_FLOAT, "timeout" ),
DEFINE_FIELD( m_bTimeoutFired, FIELD_BOOLEAN ),
DEFINE_FIELD( m_hActivator, FIELD_EHANDLE ),
DEFINE_OUTPUT( m_OnTimeout, "OnTimeout" ),
DEFINE_FUNCTION( TimeoutThink ),
// Inputs
DEFINE_INPUT( m_flFieldOfView, FIELD_FLOAT, "FieldOfView" ),
DEFINE_INPUT( m_flLookTime, FIELD_FLOAT, "LookTime" ),
END_DATADESC()
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerLook::Spawn( void )
{
m_hLookTarget = NULL;
m_flLookTimeTotal = -1;
m_bTimeoutFired = false;
BaseClass::Spawn();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pOther -
//-----------------------------------------------------------------------------
void CTriggerLook::StartTouch(CBaseEntity *pOther)
{
BaseClass::StartTouch(pOther);
if (pOther->IsPlayer() && m_flTimeoutDuration)
{
m_bTimeoutFired = false;
m_hActivator = pOther;
SetThink(&CTriggerLook::TimeoutThink);
SetNextThink(gpGlobals->curtime + m_flTimeoutDuration);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerLook::TimeoutThink(void)
{
Trigger(m_hActivator, true);
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerLook::EndTouch(CBaseEntity *pOther)
{
BaseClass::EndTouch(pOther);
if (pOther->IsPlayer())
{
SetThink(NULL);
SetNextThink( TICK_NEVER_THINK );
m_flLookTimeTotal = -1;
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerLook::Touch(CBaseEntity *pOther)
{
// Don't fire the OnTrigger if we've already fired the OnTimeout. This will be
// reset in OnEndTouch.
if (m_bTimeoutFired)
return;
// --------------------------------
// Make sure we have a look target
// --------------------------------
if (m_hLookTarget == NULL)
{
m_hLookTarget = GetNextTarget();
if (m_hLookTarget == NULL)
{
return;
}
}
// This is designed for single player only
// so we'll always have the same player
if (pOther->IsPlayer())
{
// ----------------------------------------
// Check that toucher is facing the target
// ----------------------------------------
Vector vLookDir;
if ( HasSpawnFlags( SF_TRIGGERLOOK_USEVELOCITY ) )
{
vLookDir = pOther->GetAbsVelocity();
if ( vLookDir == vec3_origin )
{
// See if they're in a vehicle
CBasePlayer *pPlayer = (CBasePlayer *)pOther;
if ( pPlayer->IsInAVehicle() )
{
vLookDir = pPlayer->GetVehicle()->GetVehicleEnt()->GetSmoothedVelocity();
}
}
VectorNormalize( vLookDir );
}
else
{
vLookDir = ((CBaseCombatCharacter*)pOther)->EyeDirection3D( );
}
Vector vTargetDir = m_hLookTarget->GetAbsOrigin() - pOther->EyePosition();
VectorNormalize(vTargetDir);
float fDotPr = DotProduct(vLookDir,vTargetDir);
if (fDotPr > m_flFieldOfView)
{
// Is it the first time I'm looking?
if (m_flLookTimeTotal == -1)
{
m_flLookTimeLast = gpGlobals->curtime;
m_flLookTimeTotal = 0;
}
else
{
m_flLookTimeTotal += gpGlobals->curtime - m_flLookTimeLast;
m_flLookTimeLast = gpGlobals->curtime;
}
if (m_flLookTimeTotal >= m_flLookTime)
{
Trigger(pOther, false);
}
}
else
{
m_flLookTimeTotal = -1;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Called when the trigger is fired by look logic or timeout.
//-----------------------------------------------------------------------------
void CTriggerLook::Trigger(CBaseEntity *pActivator, bool bTimeout)
{
if (bTimeout)
{
// Fired due to timeout (player never looked at the target).
m_OnTimeout.FireOutput(pActivator, this);
// Don't fire the OnTrigger for this toucher.
m_bTimeoutFired = true;
}
else
{
// Fire because the player looked at the target.
m_OnTrigger.FireOutput(pActivator, this);
m_flLookTimeTotal = -1;
// Cancel the timeout think.
SetThink(NULL);
SetNextThink( TICK_NEVER_THINK );
}
if (HasSpawnFlags(SF_TRIGGERLOOK_FIREONCE))
{
SetThink(&CTriggerLook::SUB_Remove);
SetNextThink(gpGlobals->curtime);
}
}
//-----------------------------------------------------------------------------
// Purpose: Draw any debug text overlays
// Output : Current text offset from the top
//-----------------------------------------------------------------------------
int CTriggerLook::DrawDebugTextOverlays(void)
{
int text_offset = BaseClass::DrawDebugTextOverlays();
if (m_debugOverlays & OVERLAY_TEXT_BIT)
{
// ----------------
// Print Look time
// ----------------
char tempstr[255];
Q_snprintf(tempstr,sizeof(tempstr),"Time: %3.2f",m_flLookTime - MAX(0,m_flLookTimeTotal));
EntityText(text_offset,tempstr,0);
text_offset++;
}
return text_offset;
}
// ##################################################################################
// >> TriggerVolume
// ##################################################################################
class CTriggerVolume : public CPointEntity // Derive from point entity so this doesn't move across levels
{
public:
DECLARE_CLASS( CTriggerVolume, CPointEntity );
void Spawn( void );
};
LINK_ENTITY_TO_CLASS( trigger_transition, CTriggerVolume );
// Define space that travels across a level transition
void CTriggerVolume::Spawn( void )
{
SetSolid( SOLID_BSP );
AddSolidFlags( FSOLID_NOT_SOLID );
SetMoveType( MOVETYPE_NONE );
SetModel( STRING( GetModelName() ) ); // set size and link into world
if ( showtriggers.GetInt() == 0 )
{
AddEffects( EF_NODRAW );
}
}
#define SF_CHANGELEVEL_NOTOUCH 0x0002
#define SF_CHANGELEVEL_CHAPTER 0x0004
#define cchMapNameMost 32
enum
{
TRANSITION_VOLUME_SCREENED_OUT = 0,
TRANSITION_VOLUME_NOT_FOUND = 1,
TRANSITION_VOLUME_PASSED = 2,
};
//------------------------------------------------------------------------------
// Reesponsible for changing levels when the player touches it
//------------------------------------------------------------------------------
class CChangeLevel : public CBaseTrigger
{
DECLARE_DATADESC();
public:
DECLARE_CLASS( CChangeLevel, CBaseTrigger );
void Spawn( void );
void Activate( void );
bool KeyValue( const char *szKeyName, const char *szValue );
static int ChangeList( levellist_t *pLevelList, int maxList );
private:
void TouchChangeLevel( CBaseEntity *pOther );
void ChangeLevelNow( CBaseEntity *pActivator );
void InputChangeLevel( inputdata_t &inputdata );
bool IsEntityInTransition( CBaseEntity *pEntity );
void NotifyEntitiesOutOfTransition();
void WarnAboutActiveLead( void );
static CBaseEntity *FindLandmark( const char *pLandmarkName );
static int AddTransitionToList( levellist_t *pLevelList, int listCount, const char *pMapName, const char *pLandmarkName, edict_t *pentLandmark );
static int InTransitionVolume( CBaseEntity *pEntity, const char *pVolumeName );
// Builds the list of entities to save when moving across a transition
static int BuildChangeLevelList( levellist_t *pLevelList, int maxList );
// Builds the list of entities to bring across a particular transition
static int BuildEntityTransitionList( CBaseEntity *pLandmarkEntity, const char *pLandmarkName, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList );
// Adds a single entity to the transition list, if appropriate. Returns the new count
static int AddEntityToTransitionList( CBaseEntity *pEntity, int flags, int nCount, CBaseEntity **ppEntList, int *pEntityFlags );
// Adds in all entities depended on by entities near the transition
static int AddDependentEntities( int nCount, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList );
// Figures out save flags for the entity
static int ComputeEntitySaveFlags( CBaseEntity *pEntity );
private:
char m_szMapName[cchMapNameMost]; // trigger_changelevel only: next map
char m_szLandmarkName[cchMapNameMost]; // trigger_changelevel only: landmark on next map
bool m_bTouched;
// Outputs
COutputEvent m_OnChangeLevel;
};
LINK_ENTITY_TO_CLASS( trigger_changelevel, CChangeLevel );
// Global Savedata for changelevel trigger
BEGIN_DATADESC( CChangeLevel )
DEFINE_AUTO_ARRAY( m_szMapName, FIELD_CHARACTER ),
DEFINE_AUTO_ARRAY( m_szLandmarkName, FIELD_CHARACTER ),
// DEFINE_FIELD( m_touchTime, FIELD_TIME ), // don't save
// DEFINE_FIELD( m_bTouched, FIELD_BOOLEAN ),
// Function Pointers
DEFINE_FUNCTION( TouchChangeLevel ),
DEFINE_INPUTFUNC( FIELD_VOID, "ChangeLevel", InputChangeLevel ),
// Outputs
DEFINE_OUTPUT( m_OnChangeLevel, "OnChangeLevel"),
END_DATADESC()
//
// Cache user-entity-field values until spawn is called.
//
bool CChangeLevel::KeyValue( const char *szKeyName, const char *szValue )
{
if (FStrEq(szKeyName, "map"))
{
if (strlen(szValue) >= cchMapNameMost)
{
Warning( "Map name '%s' too long (32 chars)\n", szValue );
Assert(0);
}
Q_strncpy(m_szMapName, szValue, sizeof(m_szMapName));
}
else if (FStrEq(szKeyName, "landmark"))
{
if (strlen(szValue) >= cchMapNameMost)
{
Warning( "Landmark name '%s' too long (32 chars)\n", szValue );
Assert(0);
}
Q_strncpy(m_szLandmarkName, szValue, sizeof( m_szLandmarkName ));
}
else
return BaseClass::KeyValue( szKeyName, szValue );
return true;
}
void CChangeLevel::Spawn( void )
{
if ( FStrEq( m_szMapName, "" ) )
{
Msg( "a trigger_changelevel doesn't have a map" );
}
if ( FStrEq( m_szLandmarkName, "" ) )
{
Msg( "trigger_changelevel to %s doesn't have a landmark", m_szMapName );
}
InitTrigger();
if ( !HasSpawnFlags(SF_CHANGELEVEL_NOTOUCH) )
{
SetTouch( &CChangeLevel::TouchChangeLevel );
}
// Msg( "TRANSITION: %s (%s)\n", m_szMapName, m_szLandmarkName );
}
void CChangeLevel::Activate( void )
{
BaseClass::Activate();
if ( gpGlobals->eLoadType == MapLoad_NewGame )
{
if ( HasSpawnFlags( SF_CHANGELEVEL_CHAPTER ) )
{
VPhysicsInitStatic();
RemoveSolidFlags( FSOLID_NOT_SOLID | FSOLID_TRIGGER );
SetTouch( NULL );
return;
}
}
// Level transitions will bust if they are in solid
CBaseEntity *pLandmark = FindLandmark( m_szLandmarkName );
if ( pLandmark )
{
int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() );
if ( clusterIndex < 0 )
{
Warning( "trigger_changelevel to map %s has a landmark embedded in solid!\n"
"This will break level transitions!\n", m_szMapName );
}
if ( g_debug_transitions.GetInt() )
{
if ( !gEntList.FindEntityByClassname( NULL, "trigger_transition" ) )
{
Warning( "Map has no trigger_transition volumes for landmark %s\n", m_szLandmarkName );
}
}
}
m_bTouched = false;
}
static char st_szNextMap[cchMapNameMost];
static char st_szNextSpot[cchMapNameMost];
// Used to show debug for only the transition volume we're currently in
static int g_iDebuggingTransition = 0;
CBaseEntity *CChangeLevel::FindLandmark( const char *pLandmarkName )
{
CBaseEntity *pentLandmark;
pentLandmark = gEntList.FindEntityByName( NULL, pLandmarkName );
while ( pentLandmark )
{
// Found the landmark
if ( FClassnameIs( pentLandmark, "info_landmark" ) )
return pentLandmark;
else
pentLandmark = gEntList.FindEntityByName( pentLandmark, pLandmarkName );
}
Warning( "Can't find landmark %s\n", pLandmarkName );
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Allows level transitions to be triggered by buttons, etc.
//-----------------------------------------------------------------------------
void CChangeLevel::InputChangeLevel( inputdata_t &inputdata )
{
// Ignore changelevel transitions if the player's dead or attempting a challenge
if ( gpGlobals->maxClients == 1 )
{
CBasePlayer *pPlayer = UTIL_GetLocalPlayer();
if ( pPlayer && ( !pPlayer->IsAlive() || pPlayer->GetBonusChallenge() > 0 ) )
return;
}
ChangeLevelNow( inputdata.pActivator );
}
//-----------------------------------------------------------------------------
// Purpose: Performs the level change and fires targets.
// Input : pActivator -
//-----------------------------------------------------------------------------
bool CChangeLevel::IsEntityInTransition( CBaseEntity *pEntity )
{
int transitionState = InTransitionVolume(pEntity, m_szLandmarkName);
if ( transitionState == TRANSITION_VOLUME_SCREENED_OUT )
{
return false;
}
// look for a landmark entity
CBaseEntity *pLandmark = FindLandmark( m_szLandmarkName );
if ( !pLandmark )
return false;
// Check to make sure it's also in the PVS of landmark
byte pvs[MAX_MAP_CLUSTERS/8];
int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() );
engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs );
Vector vecSurroundMins, vecSurroundMaxs;
pEntity->CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs );
return engine->CheckBoxInPVS( vecSurroundMins, vecSurroundMaxs, pvs, sizeof( pvs ) );
}
void CChangeLevel::NotifyEntitiesOutOfTransition()
{
CBaseEntity *pEnt = gEntList.FirstEnt();
while ( pEnt )
{
// Found the landmark
if ( pEnt->ObjectCaps() & FCAP_NOTIFY_ON_TRANSITION )
{
variant_t emptyVariant;
if ( !(pEnt->ObjectCaps() & (FCAP_ACROSS_TRANSITION|FCAP_FORCE_TRANSITION)) || !IsEntityInTransition( pEnt ) )
{
pEnt->AcceptInput( "OutsideTransition", this, this, emptyVariant, 0 );
}
else
{
pEnt->AcceptInput( "InsideTransition", this, this, emptyVariant, 0 );
}
}
pEnt = gEntList.NextEnt( pEnt );
}
}
//------------------------------------------------------------------------------
// Purpose : Checks all spawned AIs and prints a warning if any are actively leading
// Input :
// Output :
//------------------------------------------------------------------------------
void CChangeLevel::WarnAboutActiveLead( void )
{
int i;
CAI_BaseNPC * ai;
CAI_BehaviorBase * behavior;
for ( i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
ai = g_AI_Manager.AccessAIs()[i];
behavior = ai->GetRunningBehavior();
if ( behavior )
{
if ( dynamic_cast<CAI_LeadBehavior *>( behavior ) )
{
Warning( "Entity '%s' is still actively leading\n", STRING( ai->GetEntityName() ) );
}
}
}
}
void CChangeLevel::ChangeLevelNow( CBaseEntity *pActivator )
{
CBaseEntity *pLandmark;
levellist_t levels[16];
Assert(!FStrEq(m_szMapName, ""));
// Don't work in deathmatch
if ( g_pGameRules->IsDeathmatch() )
return;
// Some people are firing these multiple times in a frame, disable
if ( m_bTouched )
return;
m_bTouched = true;
CBaseEntity *pPlayer = (pActivator && pActivator->IsPlayer()) ? pActivator : UTIL_GetLocalPlayer();
int transitionState = InTransitionVolume(pPlayer, m_szLandmarkName);
if ( transitionState == TRANSITION_VOLUME_SCREENED_OUT )
{
DevMsg( 2, "Player isn't in the transition volume %s, aborting\n", m_szLandmarkName );
return;
}
// look for a landmark entity
pLandmark = FindLandmark( m_szLandmarkName );
if ( !pLandmark )
return;
// no transition volumes, check PVS of landmark
if ( transitionState == TRANSITION_VOLUME_NOT_FOUND )
{
byte pvs[MAX_MAP_CLUSTERS/8];
int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() );
engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs );
if ( pPlayer )
{
Vector vecSurroundMins, vecSurroundMaxs;
pPlayer->CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs );
bool playerInPVS = engine->CheckBoxInPVS( vecSurroundMins, vecSurroundMaxs, pvs, sizeof( pvs ) );
//Assert( playerInPVS );
if ( !playerInPVS )
{
Warning( "Player isn't in the landmark's (%s) PVS, aborting\n", m_szLandmarkName );
#ifndef HL1_DLL
// HL1 works even with these errors!
return;
#endif
}
}
}
WarnAboutActiveLead();
g_iDebuggingTransition = 0;
st_szNextSpot[0] = 0; // Init landmark to NULL
Q_strncpy(st_szNextSpot, m_szLandmarkName,sizeof(st_szNextSpot));
// This object will get removed in the call to engine->ChangeLevel, copy the params into "safe" memory
Q_strncpy(st_szNextMap, m_szMapName, sizeof(st_szNextMap));
m_hActivator = pActivator;
m_OnChangeLevel.FireOutput(pActivator, this);
NotifyEntitiesOutOfTransition();
//// Msg( "Level touches %d levels\n", ChangeList( levels, 16 ) );
if ( g_debug_transitions.GetInt() )
{
Msg( "CHANGE LEVEL: %s %s\n", st_szNextMap, st_szNextSpot );
}
// If we're debugging, don't actually change level
if ( g_debug_transitions.GetInt() == 0 )
{
engine->ChangeLevel( st_szNextMap, st_szNextSpot );
}
else
{
// Build a change list so we can see what would be transitioning
CSaveRestoreData *pSaveData = SaveInit( 0 );
if ( pSaveData )
{
g_pGameSaveRestoreBlockSet->PreSave( pSaveData );
pSaveData->levelInfo.connectionCount = BuildChangeList( pSaveData->levelInfo.levelList, MAX_LEVEL_CONNECTIONS );
g_pGameSaveRestoreBlockSet->PostSave();
}
SetTouch( NULL );
}
}
//
// GLOBALS ASSUMED SET: st_szNextMap
//
void CChangeLevel::TouchChangeLevel( CBaseEntity *pOther )
{
CBasePlayer *pPlayer = ToBasePlayer(pOther);
if ( !pPlayer )
return;
if( pPlayer->IsSinglePlayerGameEnding() )
{
// Some semblance of deceleration, but allow player to fall normally.
// Also, disable controls.
Vector vecVelocity = pPlayer->GetAbsVelocity();
vecVelocity.x *= 0.5f;
vecVelocity.y *= 0.5f;
pPlayer->SetAbsVelocity( vecVelocity );
pPlayer->AddFlag( FL_FROZEN );
return;
}
if ( !pPlayer->IsInAVehicle() && pPlayer->GetMoveType() == MOVETYPE_NOCLIP )
{
DevMsg("In level transition: %s %s\n", st_szNextMap, st_szNextSpot );
return;
}
ChangeLevelNow( pOther );
}
// Add a transition to the list, but ignore duplicates
// (a designer may have placed multiple trigger_changelevels with the same landmark)
int CChangeLevel::AddTransitionToList( levellist_t *pLevelList, int listCount, const char *pMapName, const char *pLandmarkName, edict_t *pentLandmark )
{
int i;
if ( !pLevelList || !pMapName || !pLandmarkName || !pentLandmark )
return 0;
// Ignore changelevels to the level we're ready in. Mapmakers love to do this!
if ( stricmp( pMapName, STRING(gpGlobals->mapname) ) == 0 )
return 0;
for ( i = 0; i < listCount; i++ )
{
if ( pLevelList[i].pentLandmark == pentLandmark && stricmp( pLevelList[i].mapName, pMapName ) == 0 )
return 0;
}
Q_strncpy( pLevelList[listCount].mapName, pMapName, sizeof(pLevelList[listCount].mapName) );
Q_strncpy( pLevelList[listCount].landmarkName, pLandmarkName, sizeof(pLevelList[listCount].landmarkName) );
pLevelList[listCount].pentLandmark = pentLandmark;
CBaseEntity *ent = CBaseEntity::Instance( pentLandmark );
Assert( ent );
pLevelList[listCount].vecLandmarkOrigin = ent->GetAbsOrigin();
return 1;
}
int BuildChangeList( levellist_t *pLevelList, int maxList )
{
return CChangeLevel::ChangeList( pLevelList, maxList );
}
struct collidelist_t
{
const CPhysCollide *pCollide;
Vector origin;
QAngle angles;
};
// NOTE: This routine is relatively slow. If you need to use it for per-frame work, consider that fact.
// UNDONE: Expand this to the full matrix of solid types on each side and move into enginetrace
static bool TestEntityTriggerIntersection_Accurate( CBaseEntity *pTrigger, CBaseEntity *pEntity )
{
Assert( pTrigger->GetSolid() == SOLID_BSP );
if ( pTrigger->Intersects( pEntity ) ) // It touches one, it's in the volume
{
switch ( pEntity->GetSolid() )
{
case SOLID_BBOX:
{
ICollideable *pCollide = pTrigger->CollisionProp();
Ray_t ray;
trace_t tr;
ray.Init( pEntity->GetAbsOrigin(), pEntity->GetAbsOrigin(), pEntity->WorldAlignMins(), pEntity->WorldAlignMaxs() );
enginetrace->ClipRayToCollideable( ray, MASK_ALL, pCollide, &tr );
if ( tr.startsolid )
return true;
}
break;
case SOLID_BSP:
case SOLID_VPHYSICS:
{
CPhysCollide *pTriggerCollide = modelinfo->GetVCollide( pTrigger->GetModelIndex() )->solids[0];
Assert( pTriggerCollide );
CUtlVector<collidelist_t> collideList;
IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT];
int physicsCount = pEntity->VPhysicsGetObjectList( pList, ARRAYSIZE(pList) );
if ( physicsCount )
{
for ( int i = 0; i < physicsCount; i++ )
{
const CPhysCollide *pCollide = pList[i]->GetCollide();
if ( pCollide )
{
collidelist_t element;
element.pCollide = pCollide;
pList[i]->GetPosition( &element.origin, &element.angles );
collideList.AddToTail( element );
}
}
}
else
{
vcollide_t *pVCollide = modelinfo->GetVCollide( pEntity->GetModelIndex() );
if ( pVCollide && pVCollide->solidCount )
{
collidelist_t element;
element.pCollide = pVCollide->solids[0];
element.origin = pEntity->GetAbsOrigin();
element.angles = pEntity->GetAbsAngles();
collideList.AddToTail( element );
}
}
for ( int i = collideList.Count()-1; i >= 0; --i )
{
const collidelist_t &element = collideList[i];
trace_t tr;
physcollision->TraceCollide( element.origin, element.origin, element.pCollide, element.angles, pTriggerCollide, pTrigger->GetAbsOrigin(), pTrigger->GetAbsAngles(), &tr );
if ( tr.startsolid )
return true;
}
}
break;
default:
return true;
}
}
return false;
}
int CChangeLevel::InTransitionVolume( CBaseEntity *pEntity, const char *pVolumeName )
{
CBaseEntity *pVolume;
if ( pEntity->ObjectCaps() & FCAP_FORCE_TRANSITION )
return TRANSITION_VOLUME_PASSED;
// If you're following another entity, follow it through the transition (weapons follow the player)
pEntity = pEntity->GetRootMoveParent();
int inVolume = TRANSITION_VOLUME_NOT_FOUND; // Unless we find a trigger_transition, everything is in the volume
pVolume = gEntList.FindEntityByName( NULL, pVolumeName );
while ( pVolume )
{
if ( pVolume && FClassnameIs( pVolume, "trigger_transition" ) )
{
if ( TestEntityTriggerIntersection_Accurate(pVolume, pEntity ) ) // It touches one, it's in the volume
return TRANSITION_VOLUME_PASSED;
inVolume = TRANSITION_VOLUME_SCREENED_OUT; // Found a trigger_transition, but I don't intersect it -- if I don't find another, don't go!
}
pVolume = gEntList.FindEntityByName( pVolume, pVolumeName );
}
return inVolume;
}
//------------------------------------------------------------------------------
// Builds the list of entities to save when moving across a transition
//------------------------------------------------------------------------------
int CChangeLevel::BuildChangeLevelList( levellist_t *pLevelList, int maxList )
{
int nCount = 0;
CBaseEntity *pentChangelevel = gEntList.FindEntityByClassname( NULL, "trigger_changelevel" );
while ( pentChangelevel )
{
CChangeLevel *pTrigger = dynamic_cast<CChangeLevel *>(pentChangelevel);
if ( pTrigger )
{
// Find the corresponding landmark
CBaseEntity *pentLandmark = FindLandmark( pTrigger->m_szLandmarkName );
if ( pentLandmark )
{
// Build a list of unique transitions
if ( AddTransitionToList( pLevelList, nCount, pTrigger->m_szMapName, pTrigger->m_szLandmarkName, pentLandmark->edict() ) )
{
++nCount;
if ( nCount >= maxList ) // FULL!!
break;
}
}
}
pentChangelevel = gEntList.FindEntityByClassname( pentChangelevel, "trigger_changelevel" );
}
return nCount;
}
//------------------------------------------------------------------------------
// Adds a single entity to the transition list, if appropriate. Returns the new count
//------------------------------------------------------------------------------
int CChangeLevel::ComputeEntitySaveFlags( CBaseEntity *pEntity )
{
if ( g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE )
{
Msg( "Trying %s (%s): ", pEntity->GetClassname(), pEntity->GetDebugName() );
}
int caps = pEntity->ObjectCaps();
if ( caps & FCAP_DONT_SAVE )
{
if ( g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE )
{
Msg( "IGNORED due to being marked \"Don't save\".\n" );
}
return 0;
}
// If this entity can be moved or is global, mark it
int flags = 0;
if ( caps & FCAP_ACROSS_TRANSITION )
{
flags |= FENTTABLE_MOVEABLE;
}
if ( pEntity->m_iGlobalname != NULL_STRING && !pEntity->IsDormant() )
{
flags |= FENTTABLE_GLOBAL;
}
if ( g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE && !flags )
{
Msg( "IGNORED, no across_transition flag & no globalname\n" );
}
return flags;
}
//------------------------------------------------------------------------------
// Adds a single entity to the transition list, if appropriate. Returns the new count
//------------------------------------------------------------------------------
inline int CChangeLevel::AddEntityToTransitionList( CBaseEntity *pEntity, int flags, int nCount, CBaseEntity **ppEntList, int *pEntityFlags )
{
ppEntList[ nCount ] = pEntity;
pEntityFlags[ nCount ] = flags;
++nCount;
// If we're debugging, make it visible
if ( g_iDebuggingTransition )
{
if ( g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE )
{
// In verbose mode we've already printed out what the entity is
Msg("ADDED.\n");
}
else
{
// In non-verbose mode, we just print this line
Msg( "ADDED %s (%s) to transition.\n", pEntity->GetClassname(), pEntity->GetDebugName() );
}
pEntity->m_debugOverlays |= (OVERLAY_BBOX_BIT | OVERLAY_NAME_BIT);
}
return nCount;
}
//------------------------------------------------------------------------------
// Builds the list of entities to bring across a particular transition
//------------------------------------------------------------------------------
int CChangeLevel::BuildEntityTransitionList( CBaseEntity *pLandmarkEntity, const char *pLandmarkName,
CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList )
{
int iEntity = 0;
// Only show debug for the transition to the level we're going to
if ( g_debug_transitions.GetInt() && pLandmarkEntity->NameMatches(st_szNextSpot) )
{
g_iDebuggingTransition = g_debug_transitions.GetInt();
// Show us where the landmark entity is
pLandmarkEntity->m_debugOverlays |= (OVERLAY_PIVOT_BIT | OVERLAY_BBOX_BIT | OVERLAY_NAME_BIT);
}
else
{
g_iDebuggingTransition = 0;
}
// Follow the linked list of entities in the PVS of the transition landmark
CBaseEntity *pEntity = NULL;
while ( (pEntity = UTIL_EntitiesInPVS( pLandmarkEntity, pEntity)) != NULL )
{
int flags = ComputeEntitySaveFlags( pEntity );
if ( !flags )
continue;
// Check to make sure the entity isn't screened out by a trigger_transition
if ( !InTransitionVolume( pEntity, pLandmarkName ) )
{
if ( g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE )
{
Msg( "IGNORED, outside transition volume.\n" );
}
continue;
}
if ( iEntity >= nMaxList )
{
Warning( "Too many entities across a transition!\n" );
Assert( 0 );
return iEntity;
}
iEntity = AddEntityToTransitionList( pEntity, flags, iEntity, ppEntList, pEntityFlags );
}
return iEntity;
}
//------------------------------------------------------------------------------
// Tests bits in a bitfield
//------------------------------------------------------------------------------
static inline bool IsBitSet( char *pBuf, int nBit )
{
return (pBuf[ nBit >> 3 ] & ( 1 << (nBit & 0x7) )) != 0;
}
static inline void Set( char *pBuf, int nBit )
{
pBuf[ nBit >> 3 ] |= 1 << (nBit & 0x7);
}
//------------------------------------------------------------------------------
// Adds in all entities depended on by entities near the transition
//------------------------------------------------------------------------------
#define MAX_ENTITY_BYTE_COUNT (NUM_ENT_ENTRIES >> 3)
int CChangeLevel::AddDependentEntities( int nCount, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList )
{
char pEntitiesSaved[MAX_ENTITY_BYTE_COUNT];
memset( pEntitiesSaved, 0, MAX_ENTITY_BYTE_COUNT * sizeof(char) );
// Populate the initial bitfield
int i;
for ( i = 0; i < nCount; ++i )
{
// NOTE: Must use GetEntryIndex because we're saving non-networked entities
int nEntIndex = ppEntList[i]->GetRefEHandle().GetEntryIndex();
// We shouldn't already have this entity in the list!
Assert( !IsBitSet( pEntitiesSaved, nEntIndex ) );
// Mark the entity as being in the list
Set( pEntitiesSaved, nEntIndex );
}
IEntitySaveUtils *pSaveUtils = GetEntitySaveUtils();
// Iterate over entities whose dependencies we've not yet processed
// NOTE: nCount will change value during this loop in AddEntityToTransitionList
for ( i = 0; i < nCount; ++i )
{
CBaseEntity *pEntity = ppEntList[i];
// Find dependencies in the hash.
int nDepCount = pSaveUtils->GetEntityDependencyCount( pEntity );
if ( !nDepCount )
continue;
CBaseEntity **ppDependentEntities = (CBaseEntity**)stackalloc( nDepCount * sizeof(CBaseEntity*) );
pSaveUtils->GetEntityDependencies( pEntity, nDepCount, ppDependentEntities );
for ( int j = 0; j < nDepCount; ++j )
{
CBaseEntity *pDependent = ppDependentEntities[j];
if ( !pDependent )
continue;
// NOTE: Must use GetEntryIndex because we're saving non-networked entities
int nEntIndex = pDependent->GetRefEHandle().GetEntryIndex();
// Don't re-add it if it's already in the list
if ( IsBitSet( pEntitiesSaved, nEntIndex ) )
continue;
// Mark the entity as being in the list
Set( pEntitiesSaved, nEntIndex );
int flags = ComputeEntitySaveFlags( pEntity );
if ( flags )
{
if ( nCount >= nMaxList )
{
Warning( "Too many entities across a transition!\n" );
Assert( 0 );
return false;
}
if ( g_debug_transitions.GetInt() )
{
Msg( "ADDED DEPENDANCY: %s (%s)\n", pEntity->GetClassname(), pEntity->GetDebugName() );
}
nCount = AddEntityToTransitionList( pEntity, flags, nCount, ppEntList, pEntityFlags );
}
else
{
Warning("Warning!! Save dependency is linked to an entity that doesn't want to be saved!\n");
}
}
}
return nCount;
}
//------------------------------------------------------------------------------
// This builds the list of all transitions on this level and which entities
// are in their PVS's and can / should be moved across.
//------------------------------------------------------------------------------
// We can only ever move 512 entities across a transition
#define MAX_ENTITY 512
// FIXME: This has grown into a complicated beast. Can we make this more elegant?
int CChangeLevel::ChangeList( levellist_t *pLevelList, int maxList )
{
// Find all of the possible level changes on this BSP
int count = BuildChangeLevelList( pLevelList, maxList );
if ( !gpGlobals->pSaveData || ( static_cast<CSaveRestoreData *>(gpGlobals->pSaveData)->NumEntities() == 0 ) )
return count;
CSave saveHelper( static_cast<CSaveRestoreData *>(gpGlobals->pSaveData) );
// For each level change, find nearby entities and save them
int i;
for ( i = 0; i < count; i++ )
{
CBaseEntity *pEntList[ MAX_ENTITY ];
int entityFlags[ MAX_ENTITY ];
// First, figure out which entities are near the transition
CBaseEntity *pLandmarkEntity = CBaseEntity::Instance( pLevelList[i].pentLandmark );
int iEntity = BuildEntityTransitionList( pLandmarkEntity, pLevelList[i].landmarkName, pEntList, entityFlags, MAX_ENTITY );
// FIXME: Activate if we have a dependency problem on level transition
// Next, add in all entities depended on by entities near the transition
// iEntity = AddDependentEntities( iEntity, pEntList, entityFlags, MAX_ENTITY );
int j;
for ( j = 0; j < iEntity; j++ )
{
// Mark entity table with 1<<i
int index = saveHelper.EntityIndex( pEntList[j] );
// Flag it with the level number
saveHelper.EntityFlagsSet( index, entityFlags[j] | (1<<i) );
}
}
return count;
}
//-----------------------------------------------------------------------------
// Purpose: A trigger that pushes the player, NPCs, or objects.
//-----------------------------------------------------------------------------
class CTriggerPush : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerPush, CBaseTrigger );
void Spawn( void );
void Activate( void );
void Touch( CBaseEntity *pOther );
void Untouch( CBaseEntity *pOther );
Vector m_vecPushDir;
DECLARE_DATADESC();
float m_flAlternateTicksFix; // Scale factor to apply to the push speed when running with alternate ticks
float m_flPushSpeed;
};
BEGIN_DATADESC( CTriggerPush )
DEFINE_KEYFIELD( m_vecPushDir, FIELD_VECTOR, "pushdir" ),
DEFINE_KEYFIELD( m_flAlternateTicksFix, FIELD_FLOAT, "alternateticksfix" ),
//DEFINE_FIELD( m_flPushSpeed, FIELD_FLOAT ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger_push, CTriggerPush );
//-----------------------------------------------------------------------------
// Purpose: Called when spawning, after keyvalues have been handled.
//-----------------------------------------------------------------------------
void CTriggerPush::Spawn()
{
// Convert pushdir from angles to a vector
Vector vecAbsDir;
QAngle angPushDir = QAngle(m_vecPushDir.x, m_vecPushDir.y, m_vecPushDir.z);
AngleVectors(angPushDir, &vecAbsDir);
// Transform the vector into entity space
VectorIRotate( vecAbsDir, EntityToWorldTransform(), m_vecPushDir );
BaseClass::Spawn();
InitTrigger();
if (m_flSpeed == 0)
{
m_flSpeed = 100;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CTriggerPush::Activate()
{
// Fix problems with triggers pushing too hard under sv_alternateticks.
// This is somewhat hacky, but it's simple and we're really close to shipping.
ConVarRef sv_alternateticks( "sv_alternateticks" );
if ( ( m_flAlternateTicksFix != 0 ) && sv_alternateticks.GetBool() )
{
m_flPushSpeed = m_flSpeed * m_flAlternateTicksFix;
}
else
{
m_flPushSpeed = m_flSpeed;
}
BaseClass::Activate();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pOther -
//-----------------------------------------------------------------------------
void CTriggerPush::Touch( CBaseEntity *pOther )
{
if ( !pOther->IsSolid() || (pOther->GetMoveType() == MOVETYPE_PUSH || pOther->GetMoveType() == MOVETYPE_NONE ) )
return;
if (!PassesTriggerFilters(pOther))
return;
// FIXME: If something is hierarchically attached, should we try to push the parent?
if (pOther->GetMoveParent())
return;
// Transform the push dir into global space
Vector vecAbsDir;
VectorRotate( m_vecPushDir, EntityToWorldTransform(), vecAbsDir );
// Instant trigger, just transfer velocity and remove
if (HasSpawnFlags(SF_TRIG_PUSH_ONCE))
{
pOther->ApplyAbsVelocityImpulse( m_flPushSpeed * vecAbsDir );
if ( vecAbsDir.z > 0 )
{
pOther->SetGroundEntity( NULL );
}
UTIL_Remove( this );
return;
}
switch( pOther->GetMoveType() )
{
case MOVETYPE_NONE:
case MOVETYPE_PUSH:
case MOVETYPE_NOCLIP:
break;
case MOVETYPE_VPHYSICS:
{
IPhysicsObject *pPhys = pOther->VPhysicsGetObject();
if ( pPhys )
{
// UNDONE: Assume the velocity is for a 100kg object, scale with mass
pPhys->ApplyForceCenter( m_flPushSpeed * vecAbsDir * 100.0f * gpGlobals->frametime );
return;
}
}
break;
default:
{
#if defined( HL2_DLL )
// HACK HACK HL2 players on ladders will only be disengaged if the sf is set, otherwise no push occurs.
if ( pOther->IsPlayer() &&
pOther->GetMoveType() == MOVETYPE_LADDER )
{
if ( !HasSpawnFlags(SF_TRIG_PUSH_AFFECT_PLAYER_ON_LADDER) )
{
// Ignore the push
return;
}
}
#endif
Vector vecPush = (m_flPushSpeed * vecAbsDir);
if ( ( pOther->GetFlags() & FL_BASEVELOCITY ) && !lagcompensation->IsCurrentlyDoingLagCompensation() )
{
vecPush = vecPush + pOther->GetBaseVelocity();
}
if ( vecPush.z > 0 && (pOther->GetFlags() & FL_ONGROUND) )
{
pOther->SetGroundEntity( NULL );
Vector origin = pOther->GetAbsOrigin();
origin.z += 1.0f;
pOther->SetAbsOrigin( origin );
}
#ifdef HL1_DLL
// Apply the z velocity as a force so it counteracts gravity properly
Vector vecImpulse( 0, 0, vecPush.z * 0.025 );//magic hack number
pOther->ApplyAbsVelocityImpulse( vecImpulse );
// apply x, y as a base velocity so we travel at constant speed on conveyors
vecPush.z = 0;
#endif
pOther->SetBaseVelocity( vecPush );
pOther->AddFlag( FL_BASEVELOCITY );
}
break;
}
}
//-----------------------------------------------------------------------------
// Teleport trigger
//-----------------------------------------------------------------------------
const int SF_TELEPORT_PRESERVE_ANGLES = 0x20; // Preserve angles even when a local landmark is not specified
class CTriggerTeleport : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerTeleport, CBaseTrigger );
virtual void Spawn( void ) OVERRIDE;
virtual void Touch( CBaseEntity *pOther ) OVERRIDE;
string_t m_iLandmark;
DECLARE_DATADESC();
};
LINK_ENTITY_TO_CLASS( trigger_teleport, CTriggerTeleport );
BEGIN_DATADESC( CTriggerTeleport )
DEFINE_KEYFIELD( m_iLandmark, FIELD_STRING, "landmark" ),
END_DATADESC()
void CTriggerTeleport::Spawn( void )
{
InitTrigger();
}
//-----------------------------------------------------------------------------
// Purpose: Teleports the entity that touched us to the location of our target,
// setting the toucher's angles to our target's angles if they are a
// player.
//
// If a landmark was specified, the toucher is offset from the target
// by their initial offset from the landmark and their angles are
// left alone.
//
// Input : pOther - The entity that touched us.
//-----------------------------------------------------------------------------
void CTriggerTeleport::Touch( CBaseEntity *pOther )
{
CBaseEntity *pentTarget = NULL;
if (!PassesTriggerFilters(pOther))
{
return;
}
// The activator and caller are the same
pentTarget = gEntList.FindEntityByName( pentTarget, m_target, NULL, pOther, pOther );
if (!pentTarget)
{
return;
}
//
// If a landmark was specified, offset the player relative to the landmark.
//
CBaseEntity *pentLandmark = NULL;
Vector vecLandmarkOffset(0, 0, 0);
if (m_iLandmark != NULL_STRING)
{
// The activator and caller are the same
pentLandmark = gEntList.FindEntityByName(pentLandmark, m_iLandmark, NULL, pOther, pOther );
if (pentLandmark)
{
vecLandmarkOffset = pOther->GetAbsOrigin() - pentLandmark->GetAbsOrigin();
}
}
pOther->SetGroundEntity( NULL );
Vector tmp = pentTarget->GetAbsOrigin();
if (!pentLandmark && pOther->IsPlayer())
{
// make origin adjustments in case the teleportee is a player. (origin in center, not at feet)
tmp.z -= pOther->WorldAlignMins().z;
}
//
// Only modify the toucher's angles and zero their velocity if no landmark was specified.
//
const QAngle *pAngles = NULL;
Vector *pVelocity = NULL;
#ifdef HL1_DLL
Vector vecZero(0,0,0);
#endif
if (!pentLandmark && !HasSpawnFlags(SF_TELEPORT_PRESERVE_ANGLES) )
{
pAngles = &pentTarget->GetAbsAngles();
#ifdef HL1_DLL
pVelocity = &vecZero;
#else
pVelocity = NULL; //BUGBUG - This does not set the player's velocity to zero!!!
#endif
}
tmp += vecLandmarkOffset;
pOther->Teleport( &tmp, pAngles, pVelocity );
}
LINK_ENTITY_TO_CLASS( info_teleport_destination, CPointEntity );
//-----------------------------------------------------------------------------
// Teleport Relative trigger
//-----------------------------------------------------------------------------
class CTriggerTeleportRelative : public CBaseTrigger
{
public:
DECLARE_CLASS(CTriggerTeleportRelative, CBaseTrigger);
virtual void Spawn( void ) OVERRIDE;
virtual void Touch( CBaseEntity *pOther ) OVERRIDE;
Vector m_TeleportOffset;
DECLARE_DATADESC();
};
LINK_ENTITY_TO_CLASS( trigger_teleport_relative, CTriggerTeleportRelative );
BEGIN_DATADESC( CTriggerTeleportRelative )
DEFINE_KEYFIELD( m_TeleportOffset, FIELD_VECTOR, "teleportoffset" )
END_DATADESC()
void CTriggerTeleportRelative::Spawn( void )
{
InitTrigger();
}
void CTriggerTeleportRelative::Touch( CBaseEntity *pOther )
{
if ( !PassesTriggerFilters(pOther) )
{
return;
}
const Vector finalPos = m_TeleportOffset + WorldSpaceCenter();
const Vector *momentum = &vec3_origin;
pOther->Teleport( &finalPos, NULL, momentum );
}
//-----------------------------------------------------------------------------
// Purpose: Saves the game when the player touches the trigger. Can be enabled or disabled
//-----------------------------------------------------------------------------
class CTriggerToggleSave : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerToggleSave, CBaseTrigger );
void Spawn( void );
void Touch( CBaseEntity *pOther );
void InputEnable( inputdata_t &inputdata )
{
m_bDisabled = false;
}
void InputDisable( inputdata_t &inputdata )
{
m_bDisabled = true;
}
bool m_bDisabled; // Initial state
DECLARE_DATADESC();
};
BEGIN_DATADESC( CTriggerToggleSave )
DEFINE_KEYFIELD( m_bDisabled, FIELD_BOOLEAN, "StartDisabled" ),
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger_togglesave, CTriggerToggleSave );
//-----------------------------------------------------------------------------
// Purpose: Called when spawning, after keyvalues have been set.
//-----------------------------------------------------------------------------
void CTriggerToggleSave::Spawn( void )
{
if ( g_pGameRules->IsDeathmatch() )
{
UTIL_Remove( this );
return;
}
InitTrigger();
}
//-----------------------------------------------------------------------------
// Purpose: Performs the autosave when the player touches us.
// Input : pOther -
//-----------------------------------------------------------------------------
void CTriggerToggleSave::Touch( CBaseEntity *pOther )
{
if( m_bDisabled )
return;
// Only save on clients
if ( !pOther->IsPlayer() )
return;
// Can be re-enabled
m_bDisabled = true;
engine->ServerCommand( "autosave\n" );
}
//-----------------------------------------------------------------------------
// Purpose: Saves the game when the player touches the trigger.
//-----------------------------------------------------------------------------
class CTriggerSave : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerSave, CBaseTrigger );
void Spawn( void );
void Touch( CBaseEntity *pOther );
DECLARE_DATADESC();
bool m_bForceNewLevelUnit;
float m_fDangerousTimer;
int m_minHitPoints;
};
BEGIN_DATADESC( CTriggerSave )
DEFINE_KEYFIELD( m_bForceNewLevelUnit, FIELD_BOOLEAN, "NewLevelUnit" ),
DEFINE_KEYFIELD( m_minHitPoints, FIELD_INTEGER, "MinimumHitPoints" ),
DEFINE_KEYFIELD( m_fDangerousTimer, FIELD_FLOAT, "DangerousTimer" ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger_autosave, CTriggerSave );
//-----------------------------------------------------------------------------
// Purpose: Called when spawning, after keyvalues have been set.
//-----------------------------------------------------------------------------
void CTriggerSave::Spawn( void )
{
if ( g_pGameRules->IsDeathmatch() )
{
UTIL_Remove( this );
return;
}
InitTrigger();
}
//-----------------------------------------------------------------------------
// Purpose: Performs the autosave when the player touches us.
// Input : pOther -
//-----------------------------------------------------------------------------
void CTriggerSave::Touch( CBaseEntity *pOther )
{
// Only save on clients
if ( !pOther->IsPlayer() )
return;
if ( m_fDangerousTimer != 0.0f )
{
if ( g_ServerGameDLL.m_fAutoSaveDangerousTime != 0.0f && g_ServerGameDLL.m_fAutoSaveDangerousTime >= gpGlobals->curtime )
{
// A previous dangerous auto save was waiting to become safe
CBasePlayer *pPlayer = UTIL_PlayerByIndex( 1 );
if ( pPlayer->GetDeathTime() == 0.0f || pPlayer->GetDeathTime() > gpGlobals->curtime )
{
// The player isn't dead, so make the dangerous auto save safe
engine->ServerCommand( "autosavedangerousissafe\n" );
}
}
}
// this is a one-way transition - there is no way to return to the previous map.
if ( m_bForceNewLevelUnit )
{
engine->ClearSaveDir();
}
UTIL_Remove( this );
if ( m_fDangerousTimer != 0.0f )
{
// There's a dangerous timer. Save if we have enough hitpoints.
CBasePlayer *pPlayer = UTIL_PlayerByIndex( 1 );
if (pPlayer && pPlayer->GetHealth() >= m_minHitPoints)
{
engine->ServerCommand( "autosavedangerous\n" );
g_ServerGameDLL.m_fAutoSaveDangerousTime = gpGlobals->curtime + m_fDangerousTimer;
}
}
else
{
engine->ServerCommand( "autosave\n" );
}
}
class CTriggerGravity : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerGravity, CBaseTrigger );
DECLARE_DATADESC();
void Spawn( void );
void GravityTouch( CBaseEntity *pOther );
};
LINK_ENTITY_TO_CLASS( trigger_gravity, CTriggerGravity );
BEGIN_DATADESC( CTriggerGravity )
// Function Pointers
DEFINE_FUNCTION(GravityTouch),
END_DATADESC()
void CTriggerGravity::Spawn( void )
{
BaseClass::Spawn();
InitTrigger();
SetTouch( &CTriggerGravity::GravityTouch );
}
void CTriggerGravity::GravityTouch( CBaseEntity *pOther )
{
// Only save on clients
if ( !pOther->IsPlayer() )
return;
pOther->SetGravity( GetGravity() );
}
// this is a really bad idea.
class CAI_ChangeTarget : public CBaseEntity
{
public:
DECLARE_CLASS( CAI_ChangeTarget, CBaseEntity );
// Input handlers.
void InputActivate( inputdata_t &inputdata );
int ObjectCaps( void ) { return BaseClass::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; }
DECLARE_DATADESC();
private:
string_t m_iszNewTarget;
};
LINK_ENTITY_TO_CLASS( ai_changetarget, CAI_ChangeTarget );
BEGIN_DATADESC( CAI_ChangeTarget )
DEFINE_KEYFIELD( m_iszNewTarget, FIELD_STRING, "m_iszNewTarget" ),
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "Activate", InputActivate ),
END_DATADESC()
void CAI_ChangeTarget::InputActivate( inputdata_t &inputdata )
{
CBaseEntity *pTarget = NULL;
while ((pTarget = gEntList.FindEntityByName( pTarget, m_target, NULL, inputdata.pActivator, inputdata.pCaller )) != NULL)
{
pTarget->m_target = m_iszNewTarget;
CAI_BaseNPC *pNPC = pTarget->MyNPCPointer( );
if (pNPC)
{
pNPC->SetGoalEnt( NULL );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Change an NPC's hint group to something new
//-----------------------------------------------------------------------------
class CAI_ChangeHintGroup : public CBaseEntity
{
public:
DECLARE_CLASS( CAI_ChangeHintGroup, CBaseEntity );
int ObjectCaps( void ) { return BaseClass::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; }
// Input handlers.
void InputActivate( inputdata_t &inputdata );
DECLARE_DATADESC();
private:
CAI_BaseNPC *FindQualifiedNPC( CAI_BaseNPC *pPrev, CBaseEntity *pActivator, CBaseEntity *pCaller );
int m_iSearchType;
string_t m_strSearchName;
string_t m_strNewHintGroup;
float m_flRadius;
bool m_bHintGroupNavLimiting;
};
LINK_ENTITY_TO_CLASS( ai_changehintgroup, CAI_ChangeHintGroup );
BEGIN_DATADESC( CAI_ChangeHintGroup )
DEFINE_KEYFIELD( m_iSearchType, FIELD_INTEGER, "SearchType" ),
DEFINE_KEYFIELD( m_strSearchName, FIELD_STRING, "SearchName" ),
DEFINE_KEYFIELD( m_strNewHintGroup, FIELD_STRING, "NewHintGroup" ),
DEFINE_KEYFIELD( m_flRadius, FIELD_FLOAT, "Radius" ),
DEFINE_KEYFIELD( m_bHintGroupNavLimiting, FIELD_BOOLEAN, "hintlimiting" ),
DEFINE_INPUTFUNC( FIELD_VOID, "Activate", InputActivate ),
END_DATADESC()
CAI_BaseNPC *CAI_ChangeHintGroup::FindQualifiedNPC( CAI_BaseNPC *pPrev, CBaseEntity *pActivator, CBaseEntity *pCaller )
{
CBaseEntity *pEntity = pPrev;
CAI_BaseNPC *pResult = NULL;
const char *pszSearchName = STRING(m_strSearchName);
while ( !pResult )
{
// Find a candidate
switch ( m_iSearchType )
{
case 0:
{
pEntity = gEntList.FindEntityByNameWithin( pEntity, pszSearchName, GetLocalOrigin(), m_flRadius, NULL, pActivator, pCaller );
break;
}
case 1:
{
pEntity = gEntList.FindEntityByClassnameWithin( pEntity, pszSearchName, GetLocalOrigin(), m_flRadius );
break;
}
case 2:
{
pEntity = gEntList.FindEntityInSphere( pEntity, GetLocalOrigin(), ( m_flRadius != 0.0 ) ? m_flRadius : FLT_MAX );
break;
}
}
if ( !pEntity )
return NULL;
// Qualify
pResult = pEntity->MyNPCPointer();
if ( pResult && m_iSearchType == 2 && (!FStrEq( STRING(pResult->GetHintGroup()), pszSearchName ) ) )
{
pResult = NULL;
}
}
return pResult;
}
void CAI_ChangeHintGroup::InputActivate( inputdata_t &inputdata )
{
CAI_BaseNPC *pTarget = NULL;
while((pTarget = FindQualifiedNPC( pTarget, inputdata.pActivator, inputdata.pCaller )) != NULL)
{
pTarget->SetHintGroup( m_strNewHintGroup, m_bHintGroupNavLimiting );
}
}
#define SF_CAMERA_PLAYER_POSITION 1
#define SF_CAMERA_PLAYER_TARGET 2
#define SF_CAMERA_PLAYER_TAKECONTROL 4
#define SF_CAMERA_PLAYER_INFINITE_WAIT 8
#define SF_CAMERA_PLAYER_SNAP_TO 16
#define SF_CAMERA_PLAYER_NOT_SOLID 32
#define SF_CAMERA_PLAYER_INTERRUPT 64
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CTriggerCamera : public CBaseEntity
{
public:
DECLARE_CLASS( CTriggerCamera, CBaseEntity );
void Spawn( void );
bool KeyValue( const char *szKeyName, const char *szValue );
void Enable( void );
void Disable( void );
void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
void FollowTarget( void );
void Move(void);
// Always transmit to clients so they know where to move the view to
virtual int UpdateTransmitState();
DECLARE_DATADESC();
// Input handlers
void InputEnable( inputdata_t &inputdata );
void InputDisable( inputdata_t &inputdata );
private:
EHANDLE m_hPlayer;
EHANDLE m_hTarget;
// used for moving the camera along a path (rail rides)
CBaseEntity *m_pPath;
string_t m_sPath;
float m_flWait;
float m_flReturnTime;
float m_flStopTime;
float m_moveDistance;
float m_targetSpeed;
float m_initialSpeed;
float m_acceleration;
float m_deceleration;
int m_state;
Vector m_vecMoveDir;
string_t m_iszTargetAttachment;
int m_iAttachmentIndex;
bool m_bSnapToGoal;
#if HL2_EPISODIC
bool m_bInterpolatePosition;
// these are interpolation vars used for interpolating the camera over time
Vector m_vStartPos, m_vEndPos;
float m_flInterpStartTime;
const static float kflPosInterpTime; // seconds
#endif
int m_nPlayerButtons;
int m_nOldTakeDamage;
private:
COutputEvent m_OnEndFollow;
};
#if HL2_EPISODIC
const float CTriggerCamera::kflPosInterpTime = 2.0f;
#endif
LINK_ENTITY_TO_CLASS( point_viewcontrol, CTriggerCamera );
BEGIN_DATADESC( CTriggerCamera )
DEFINE_FIELD( m_hPlayer, FIELD_EHANDLE ),
DEFINE_FIELD( m_hTarget, FIELD_EHANDLE ),
DEFINE_FIELD( m_pPath, FIELD_CLASSPTR ),
DEFINE_FIELD( m_sPath, FIELD_STRING ),
DEFINE_FIELD( m_flWait, FIELD_FLOAT ),
DEFINE_FIELD( m_flReturnTime, FIELD_TIME ),
DEFINE_FIELD( m_flStopTime, FIELD_TIME ),
DEFINE_FIELD( m_moveDistance, FIELD_FLOAT ),
DEFINE_FIELD( m_targetSpeed, FIELD_FLOAT ),
DEFINE_FIELD( m_initialSpeed, FIELD_FLOAT ),
DEFINE_FIELD( m_acceleration, FIELD_FLOAT ),
DEFINE_FIELD( m_deceleration, FIELD_FLOAT ),
DEFINE_FIELD( m_state, FIELD_INTEGER ),
DEFINE_FIELD( m_vecMoveDir, FIELD_VECTOR ),
DEFINE_KEYFIELD( m_iszTargetAttachment, FIELD_STRING, "targetattachment" ),
DEFINE_FIELD( m_iAttachmentIndex, FIELD_INTEGER ),
DEFINE_FIELD( m_bSnapToGoal, FIELD_BOOLEAN ),
#if HL2_EPISODIC
DEFINE_KEYFIELD( m_bInterpolatePosition, FIELD_BOOLEAN, "interpolatepositiontoplayer" ),
DEFINE_FIELD( m_vStartPos, FIELD_VECTOR ),
DEFINE_FIELD( m_vEndPos, FIELD_VECTOR ),
DEFINE_FIELD( m_flInterpStartTime, FIELD_TIME ),
#endif
DEFINE_FIELD( m_nPlayerButtons, FIELD_INTEGER ),
DEFINE_FIELD( m_nOldTakeDamage, FIELD_INTEGER ),
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
// Function Pointers
DEFINE_FUNCTION( FollowTarget ),
DEFINE_OUTPUT( m_OnEndFollow, "OnEndFollow" ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerCamera::Spawn( void )
{
BaseClass::Spawn();
SetMoveType( MOVETYPE_NOCLIP );
SetSolid( SOLID_NONE ); // Remove model & collisions
SetRenderColorA( 0 ); // The engine won't draw this model if this is set to 0 and blending is on
m_nRenderMode = kRenderTransTexture;
m_state = USE_OFF;
m_initialSpeed = m_flSpeed;
if ( m_acceleration == 0 )
m_acceleration = 500;
if ( m_deceleration == 0 )
m_deceleration = 500;
DispatchUpdateTransmitState();
}
int CTriggerCamera::UpdateTransmitState()
{
// always tranmit if currently used by a monitor
if ( m_state == USE_ON )
{
return SetTransmitState( FL_EDICT_ALWAYS );
}
else
{
return SetTransmitState( FL_EDICT_DONTSEND );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTriggerCamera::KeyValue( const char *szKeyName, const char *szValue )
{
if (FStrEq(szKeyName, "wait"))
{
m_flWait = atof(szValue);
}
else if (FStrEq(szKeyName, "moveto"))
{
m_sPath = AllocPooledString( szValue );
}
else if (FStrEq(szKeyName, "acceleration"))
{
m_acceleration = atof( szValue );
}
else if (FStrEq(szKeyName, "deceleration"))
{
m_deceleration = atof( szValue );
}
else
return BaseClass::KeyValue( szKeyName, szValue );
return true;
}
//------------------------------------------------------------------------------
// Purpose: Input handler to turn on this trigger.
//------------------------------------------------------------------------------
void CTriggerCamera::InputEnable( inputdata_t &inputdata )
{
m_hPlayer = inputdata.pActivator;
Enable();
}
//------------------------------------------------------------------------------
// Purpose: Input handler to turn off this trigger.
//------------------------------------------------------------------------------
void CTriggerCamera::InputDisable( inputdata_t &inputdata )
{
Disable();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerCamera::Enable( void )
{
m_state = USE_ON;
if ( !m_hPlayer || !m_hPlayer->IsPlayer() )
{
m_hPlayer = UTIL_GetLocalPlayer();
}
if ( !m_hPlayer )
{
DispatchUpdateTransmitState();
return;
}
Assert( m_hPlayer->IsPlayer() );
CBasePlayer *pPlayer = NULL;
if ( m_hPlayer->IsPlayer() )
{
pPlayer = ((CBasePlayer*)m_hPlayer.Get());
}
else
{
Warning("CTriggerCamera could not find a player!\n");
return;
}
// if the player was already under control of a similar trigger, disable the previous trigger.
{
CBaseEntity *pPrevViewControl = pPlayer->GetViewEntity();
if (pPrevViewControl && pPrevViewControl != pPlayer)
{
CTriggerCamera *pOtherCamera = dynamic_cast<CTriggerCamera *>(pPrevViewControl);
if ( pOtherCamera )
{
if ( pOtherCamera == this )
{
// what the hell do you think you are doing?
Warning("Viewcontrol %s was enabled twice in a row!\n", GetDebugName());
return;
}
else
{
pOtherCamera->Disable();
}
}
}
}
m_nPlayerButtons = pPlayer->m_nButtons;
// Make the player invulnerable while under control of the camera. This will prevent situations where the player dies while under camera control but cannot restart their game due to disabled player inputs.
m_nOldTakeDamage = m_hPlayer->m_takedamage;
m_hPlayer->m_takedamage = DAMAGE_NO;
if ( HasSpawnFlags( SF_CAMERA_PLAYER_NOT_SOLID ) )
{
m_hPlayer->AddSolidFlags( FSOLID_NOT_SOLID );
}
m_flReturnTime = gpGlobals->curtime + m_flWait;
m_flSpeed = m_initialSpeed;
m_targetSpeed = m_initialSpeed;
// this pertains to view angles, not translation.
if ( HasSpawnFlags( SF_CAMERA_PLAYER_SNAP_TO ) )
{
m_bSnapToGoal = true;
}
if ( HasSpawnFlags(SF_CAMERA_PLAYER_TARGET ) )
{
m_hTarget = m_hPlayer;
}
else
{
m_hTarget = GetNextTarget();
}
// If we don't have a target, ignore the attachment / etc
if ( m_hTarget )
{
m_iAttachmentIndex = 0;
if ( m_iszTargetAttachment != NULL_STRING )
{
if ( !m_hTarget->GetBaseAnimating() )
{
Warning("%s tried to target an attachment (%s) on target %s, which has no model.\n", GetClassname(), STRING(m_iszTargetAttachment), STRING(m_hTarget->GetEntityName()) );
}
else
{
m_iAttachmentIndex = m_hTarget->GetBaseAnimating()->LookupAttachment( STRING(m_iszTargetAttachment) );
if ( m_iAttachmentIndex <= 0 )
{
Warning("%s could not find attachment %s on target %s.\n", GetClassname(), STRING(m_iszTargetAttachment), STRING(m_hTarget->GetEntityName()) );
}
}
}
}
if (HasSpawnFlags(SF_CAMERA_PLAYER_TAKECONTROL ) )
{
((CBasePlayer*)m_hPlayer.Get())->EnableControl(FALSE);
}
if ( m_sPath != NULL_STRING )
{
m_pPath = gEntList.FindEntityByName( NULL, m_sPath, NULL, m_hPlayer );
}
else
{
m_pPath = NULL;
}
m_flStopTime = gpGlobals->curtime;
if ( m_pPath )
{
if ( m_pPath->m_flSpeed != 0 )
m_targetSpeed = m_pPath->m_flSpeed;
m_flStopTime += m_pPath->GetDelay();
}
// copy over player information. If we're interpolating from
// the player position, do something more elaborate.
#if HL2_EPISODIC
if (m_bInterpolatePosition)
{
// initialize the values we'll spline between
m_vStartPos = m_hPlayer->EyePosition();
m_vEndPos = GetAbsOrigin();
m_flInterpStartTime = gpGlobals->curtime;
UTIL_SetOrigin( this, m_hPlayer->EyePosition() );
SetLocalAngles( QAngle( m_hPlayer->GetLocalAngles().x, m_hPlayer->GetLocalAngles().y, 0 ) );
SetAbsVelocity( vec3_origin );
}
else
#endif
if (HasSpawnFlags(SF_CAMERA_PLAYER_POSITION ) )
{
UTIL_SetOrigin( this, m_hPlayer->EyePosition() );
SetLocalAngles( QAngle( m_hPlayer->GetLocalAngles().x, m_hPlayer->GetLocalAngles().y, 0 ) );
SetAbsVelocity( m_hPlayer->GetAbsVelocity() );
}
else
{
SetAbsVelocity( vec3_origin );
}
pPlayer->SetViewEntity( this );
// Hide the player's viewmodel
if ( pPlayer->GetActiveWeapon() )
{
pPlayer->GetActiveWeapon()->AddEffects( EF_NODRAW );
}
// Only track if we have a target
if ( m_hTarget )
{
// follow the player down
SetThink( &CTriggerCamera::FollowTarget );
SetNextThink( gpGlobals->curtime );
}
m_moveDistance = 0;
Move();
DispatchUpdateTransmitState();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerCamera::Disable( void )
{
if ( m_hPlayer && m_hPlayer->IsAlive() )
{
if ( HasSpawnFlags( SF_CAMERA_PLAYER_NOT_SOLID ) )
{
m_hPlayer->RemoveSolidFlags( FSOLID_NOT_SOLID );
}
((CBasePlayer*)m_hPlayer.Get())->SetViewEntity( m_hPlayer );
((CBasePlayer*)m_hPlayer.Get())->EnableControl(TRUE);
// Restore the player's viewmodel
if ( ((CBasePlayer*)m_hPlayer.Get())->GetActiveWeapon() )
{
((CBasePlayer*)m_hPlayer.Get())->GetActiveWeapon()->RemoveEffects( EF_NODRAW );
}
//return the player to previous takedamage state
m_hPlayer->m_takedamage = m_nOldTakeDamage;
}
m_state = USE_OFF;
m_flReturnTime = gpGlobals->curtime;
SetThink( NULL );
m_OnEndFollow.FireOutput(this, this); // dvsents2: what is the best name for this output?
SetLocalAngularVelocity( vec3_angle );
DispatchUpdateTransmitState();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerCamera::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
if ( !ShouldToggle( useType, m_state ) )
return;
// Toggle state
if ( m_state != USE_OFF )
{
Disable();
}
else
{
m_hPlayer = pActivator;
Enable();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerCamera::FollowTarget( )
{
if (m_hPlayer == NULL)
return;
if ( m_hTarget == NULL )
{
Disable();
return;
}
if ( !HasSpawnFlags(SF_CAMERA_PLAYER_INFINITE_WAIT) && (!m_hTarget || m_flReturnTime < gpGlobals->curtime) )
{
Disable();
return;
}
QAngle vecGoal;
if ( m_iAttachmentIndex )
{
Vector vecOrigin;
m_hTarget->GetBaseAnimating()->GetAttachment( m_iAttachmentIndex, vecOrigin );
VectorAngles( vecOrigin - GetAbsOrigin(), vecGoal );
}
else
{
if ( m_hTarget )
{
VectorAngles( m_hTarget->GetAbsOrigin() - GetAbsOrigin(), vecGoal );
}
else
{
// Use the viewcontroller's angles
vecGoal = GetAbsAngles();
}
}
// Should we just snap to the goal angles?
if ( m_bSnapToGoal )
{
SetAbsAngles( vecGoal );
m_bSnapToGoal = false;
}
else
{
// UNDONE: Can't we just use UTIL_AngleDiff here?
QAngle angles = GetLocalAngles();
if (angles.y > 360)
angles.y -= 360;
if (angles.y < 0)
angles.y += 360;
SetLocalAngles( angles );
float dx = vecGoal.x - GetLocalAngles().x;
float dy = vecGoal.y - GetLocalAngles().y;
if (dx < -180)
dx += 360;
if (dx > 180)
dx = dx - 360;
if (dy < -180)
dy += 360;
if (dy > 180)
dy = dy - 360;
QAngle vecAngVel;
vecAngVel.Init( dx * 40 * gpGlobals->frametime, dy * 40 * gpGlobals->frametime, GetLocalAngularVelocity().z );
SetLocalAngularVelocity(vecAngVel);
}
if (!HasSpawnFlags(SF_CAMERA_PLAYER_TAKECONTROL))
{
SetAbsVelocity( GetAbsVelocity() * 0.8 );
if (GetAbsVelocity().Length( ) < 10.0)
{
SetAbsVelocity( vec3_origin );
}
}
SetNextThink( gpGlobals->curtime );
Move();
}
void CTriggerCamera::Move()
{
if ( HasSpawnFlags( SF_CAMERA_PLAYER_INTERRUPT ) )
{
if ( m_hPlayer )
{
CBasePlayer *pPlayer = ToBasePlayer( m_hPlayer );
if ( pPlayer )
{
int buttonsChanged = m_nPlayerButtons ^ pPlayer->m_nButtons;
if ( buttonsChanged && pPlayer->m_nButtons )
{
Disable();
return;
}
m_nPlayerButtons = pPlayer->m_nButtons;
}
}
}
// In vanilla HL2, the camera is either on a path, or doesn't move. In episodic
// we add the capacity for interpolation to the start point.
#if HL2_EPISODIC
if (m_pPath)
#else
// Not moving on a path, return
if (!m_pPath)
return;
#endif
{
// Subtract movement from the previous frame
m_moveDistance -= m_flSpeed * gpGlobals->frametime;
// Have we moved enough to reach the target?
if ( m_moveDistance <= 0 )
{
variant_t emptyVariant;
m_pPath->AcceptInput( "InPass", this, this, emptyVariant, 0 );
// Time to go to the next target
m_pPath = m_pPath->GetNextTarget();
// Set up next corner
if ( !m_pPath )
{
SetAbsVelocity( vec3_origin );
}
else
{
if ( m_pPath->m_flSpeed != 0 )
m_targetSpeed = m_pPath->m_flSpeed;
m_vecMoveDir = m_pPath->GetLocalOrigin() - GetLocalOrigin();
m_moveDistance = VectorNormalize( m_vecMoveDir );
m_flStopTime = gpGlobals->curtime + m_pPath->GetDelay();
}
}
if ( m_flStopTime > gpGlobals->curtime )
m_flSpeed = UTIL_Approach( 0, m_flSpeed, m_deceleration * gpGlobals->frametime );
else
m_flSpeed = UTIL_Approach( m_targetSpeed, m_flSpeed, m_acceleration * gpGlobals->frametime );
float fraction = 2 * gpGlobals->frametime;
SetAbsVelocity( ((m_vecMoveDir * m_flSpeed) * fraction) + (GetAbsVelocity() * (1-fraction)) );
}
#if HL2_EPISODIC
else if (m_bInterpolatePosition)
{
// get the interpolation parameter [0..1]
float tt = (gpGlobals->curtime - m_flInterpStartTime) / kflPosInterpTime;
if (tt >= 1.0f)
{
// we're there, we're done
UTIL_SetOrigin( this, m_vEndPos );
SetAbsVelocity( vec3_origin );
m_bInterpolatePosition = false;
}
else
{
Assert(tt >= 0);
Vector nextPos = ( (m_vEndPos - m_vStartPos) * SimpleSpline(tt) ) + m_vStartPos;
// rather than stomping origin, set the velocity so that we get there in the proper time
Vector desiredVel = (nextPos - GetAbsOrigin()) * (1.0f / gpGlobals->frametime);
SetAbsVelocity( desiredVel );
}
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: Starts/stops cd audio tracks
//-----------------------------------------------------------------------------
class CTriggerCDAudio : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerCDAudio, CBaseTrigger );
void Spawn( void );
virtual void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
void PlayTrack( void );
void Touch ( CBaseEntity *pOther );
};
LINK_ENTITY_TO_CLASS( trigger_cdaudio, CTriggerCDAudio );
//-----------------------------------------------------------------------------
// Purpose: Changes tracks or stops CD when player touches
// Input : pOther - The entity that touched us.
//-----------------------------------------------------------------------------
void CTriggerCDAudio::Touch ( CBaseEntity *pOther )
{
if ( !pOther->IsPlayer() )
{
return;
}
PlayTrack();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerCDAudio::Spawn( void )
{
BaseClass::Spawn();
InitTrigger();
}
void CTriggerCDAudio::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
PlayTrack();
}
//-----------------------------------------------------------------------------
// Purpose: Issues a client command to play a given CD track. Called from
// trigger_cdaudio and target_cdaudio.
// Input : iTrack - Track number to play.
//-----------------------------------------------------------------------------
static void PlayCDTrack( int iTrack )
{
edict_t *pClient;
// manually find the single player.
pClient = engine->PEntityOfEntIndex( 1 );
Assert(gpGlobals->maxClients == 1);
// Can't play if the client is not connected!
if ( !pClient )
return;
// UNDONE: Move this to engine sound
if ( iTrack < -1 || iTrack > 30 )
{
Warning( "TriggerCDAudio - Track %d out of range\n", iTrack );
return;
}
if ( iTrack == -1 )
{
engine->ClientCommand ( pClient, "cd pause\n");
}
else
{
engine->ClientCommand ( pClient, "cd play %3d\n", iTrack);
}
}
// only plays for ONE client, so only use in single play!
void CTriggerCDAudio::PlayTrack( void )
{
PlayCDTrack( (int)m_iHealth );
SetTouch( NULL );
UTIL_Remove( this );
}
//-----------------------------------------------------------------------------
// Purpose: Measures the proximity to a specified entity of any entities within
// the trigger, provided they are within a given radius of the specified
// entity. The nearest entity distance is output as a number from [0 - 1].
//-----------------------------------------------------------------------------
class CTriggerProximity : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerProximity, CBaseTrigger );
virtual void Spawn(void);
virtual void Activate(void);
virtual void StartTouch(CBaseEntity *pOther);
virtual void EndTouch(CBaseEntity *pOther);
void MeasureThink(void);
protected:
EHANDLE m_hMeasureTarget;
string_t m_iszMeasureTarget; // The entity from which we measure proximities.
float m_fRadius; // The radius around the measure target that we measure within.
int m_nTouchers; // Number of entities touching us.
// Outputs
COutputFloat m_NearestEntityDistance;
DECLARE_DATADESC();
};
BEGIN_DATADESC( CTriggerProximity )
// Functions
DEFINE_FUNCTION(MeasureThink),
// Keys
DEFINE_KEYFIELD(m_iszMeasureTarget, FIELD_STRING, "measuretarget"),
DEFINE_FIELD( m_hMeasureTarget, FIELD_EHANDLE ),
DEFINE_KEYFIELD(m_fRadius, FIELD_FLOAT, "radius"),
DEFINE_FIELD( m_nTouchers, FIELD_INTEGER ),
// Outputs
DEFINE_OUTPUT(m_NearestEntityDistance, "NearestEntityDistance"),
END_DATADESC()
LINK_ENTITY_TO_CLASS(trigger_proximity, CTriggerProximity);
LINK_ENTITY_TO_CLASS(logic_proximity, CPointEntity);
//-----------------------------------------------------------------------------
// Purpose: Called when spawning, after keyvalues have been handled.
//-----------------------------------------------------------------------------
void CTriggerProximity::Spawn(void)
{
// Avoid divide by zero in MeasureThink!
if (m_fRadius == 0)
{
m_fRadius = 32;
}
InitTrigger();
}
//-----------------------------------------------------------------------------
// Purpose: Called after all entities have spawned and after a load game.
// Finds the reference point from which to measure.
//-----------------------------------------------------------------------------
void CTriggerProximity::Activate(void)
{
BaseClass::Activate();
m_hMeasureTarget = gEntList.FindEntityByName(NULL, m_iszMeasureTarget );
//
// Disable our Touch function if we were given a bad measure target.
//
if ((m_hMeasureTarget == NULL) || (m_hMeasureTarget->edict() == NULL))
{
Warning( "TriggerProximity - Missing measure target or measure target with no origin!\n");
}
}
//-----------------------------------------------------------------------------
// Purpose: Decrements the touch count and cancels the think if the count reaches
// zero.
// Input : pOther -
//-----------------------------------------------------------------------------
void CTriggerProximity::StartTouch(CBaseEntity *pOther)
{
BaseClass::StartTouch( pOther );
if ( PassesTriggerFilters( pOther ) )
{
m_nTouchers++;
SetThink( &CTriggerProximity::MeasureThink );
SetNextThink( gpGlobals->curtime );
}
}
//-----------------------------------------------------------------------------
// Purpose: Decrements the touch count and cancels the think if the count reaches
// zero.
// Input : pOther -
//-----------------------------------------------------------------------------
void CTriggerProximity::EndTouch(CBaseEntity *pOther)
{
BaseClass::EndTouch( pOther );
if ( PassesTriggerFilters( pOther ) )
{
m_nTouchers--;
if ( m_nTouchers == 0 )
{
SetThink( NULL );
SetNextThink( TICK_NEVER_THINK );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Think function called every frame as long as we have entities touching
// us that we care about. Finds the closest entity to the measure
// target and outputs the distance as a normalized value from [0..1].
//-----------------------------------------------------------------------------
void CTriggerProximity::MeasureThink( void )
{
if ( ( m_hMeasureTarget == NULL ) || ( m_hMeasureTarget->edict() == NULL ) )
{
SetThink(NULL);
SetNextThink( TICK_NEVER_THINK );
return;
}
//
// Traverse our list of touchers and find the entity that is closest to the
// measure target.
//
float fMinDistance = m_fRadius + 100;
CBaseEntity *pNearestEntity = NULL;
touchlink_t *root = ( touchlink_t * )GetDataObject( TOUCHLINK );
if ( root )
{
touchlink_t *pLink = root->nextLink;
while ( pLink != root )
{
CBaseEntity *pEntity = pLink->entityTouched;
// If this is an entity that we care about, check its distance.
if ( ( pEntity != NULL ) && PassesTriggerFilters( pEntity ) )
{
float flDistance = (pEntity->GetLocalOrigin() - m_hMeasureTarget->GetLocalOrigin()).Length();
if (flDistance < fMinDistance)
{
fMinDistance = flDistance;
pNearestEntity = pEntity;
}
}
pLink = pLink->nextLink;
}
}
// Update our output with the nearest entity distance, normalized to [0..1].
if ( fMinDistance <= m_fRadius )
{
fMinDistance /= m_fRadius;
if ( fMinDistance != m_NearestEntityDistance.Get() )
{
m_NearestEntityDistance.Set( fMinDistance, pNearestEntity, this );
}
}
SetNextThink( gpGlobals->curtime );
}
// ##################################################################################
// >> TriggerWind
//
// Blows physics objects in the trigger
//
// ##################################################################################
#define MAX_WIND_CHANGE 5.0f
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
class CPhysicsWind : public IMotionEvent
{
DECLARE_SIMPLE_DATADESC();
public:
simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular )
{
// If we have no windspeed, we're not doing anything
if ( !m_flWindSpeed )
return IMotionEvent::SIM_NOTHING;
// Get a cosine modulated noise between 5 and 20 that is object specific
int nNoiseMod = 5+(int)pObject%15; //
// Turn wind yaw direction into a vector and add noise
QAngle vWindAngle = vec3_angle;
vWindAngle[1] = m_nWindYaw+(30*cos(nNoiseMod * gpGlobals->curtime + nNoiseMod));
Vector vWind;
AngleVectors(vWindAngle,&vWind);
// Add lift with noise
vWind.z = 1.1 + (1.0 * sin(nNoiseMod * gpGlobals->curtime + nNoiseMod));
linear = 3*vWind*m_flWindSpeed;
angular = vec3_origin;
return IMotionEvent::SIM_GLOBAL_FORCE;
}
int m_nWindYaw;
float m_flWindSpeed;
};
BEGIN_SIMPLE_DATADESC( CPhysicsWind )
DEFINE_FIELD( m_nWindYaw, FIELD_INTEGER ),
DEFINE_FIELD( m_flWindSpeed, FIELD_FLOAT ),
END_DATADESC()
extern short g_sModelIndexSmoke;
extern float GetFloorZ(const Vector &origin);
#define WIND_THINK_CONTEXT "WindThinkContext"
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CTriggerWind : public CBaseVPhysicsTrigger
{
DECLARE_CLASS( CTriggerWind, CBaseVPhysicsTrigger );
public:
DECLARE_DATADESC();
void Spawn( void );
bool KeyValue( const char *szKeyName, const char *szValue );
void OnRestore();
void UpdateOnRemove();
bool CreateVPhysics();
void StartTouch( CBaseEntity *pOther );
void EndTouch( CBaseEntity *pOther );
void WindThink( void );
int DrawDebugTextOverlays( void );
// Input handlers
void InputEnable( inputdata_t &inputdata );
void InputSetSpeed( inputdata_t &inputdata );
private:
int m_nSpeedBase; // base line for how hard the wind blows
int m_nSpeedNoise; // noise added to wind speed +/-
int m_nSpeedCurrent;// current wind speed
int m_nSpeedTarget; // wind speed I'm approaching
int m_nDirBase; // base line for direction the wind blows (yaw)
int m_nDirNoise; // noise added to wind direction
int m_nDirCurrent; // the current wind direction
int m_nDirTarget; // wind direction I'm approaching
int m_nHoldBase; // base line for how long to wait before changing wind
int m_nHoldNoise; // noise added to how long to wait before changing wind
bool m_bSwitch; // when does wind change
IPhysicsMotionController* m_pWindController;
CPhysicsWind m_WindCallback;
};
LINK_ENTITY_TO_CLASS( trigger_wind, CTriggerWind );
BEGIN_DATADESC( CTriggerWind )
DEFINE_FIELD( m_nSpeedCurrent, FIELD_INTEGER),
DEFINE_FIELD( m_nSpeedTarget, FIELD_INTEGER),
DEFINE_FIELD( m_nDirBase, FIELD_INTEGER),
DEFINE_FIELD( m_nDirCurrent, FIELD_INTEGER),
DEFINE_FIELD( m_nDirTarget, FIELD_INTEGER),
DEFINE_FIELD( m_bSwitch, FIELD_BOOLEAN),
DEFINE_FIELD( m_nSpeedBase, FIELD_INTEGER ),
DEFINE_KEYFIELD( m_nSpeedNoise, FIELD_INTEGER, "SpeedNoise"),
DEFINE_KEYFIELD( m_nDirNoise, FIELD_INTEGER, "DirectionNoise"),
DEFINE_KEYFIELD( m_nHoldBase, FIELD_INTEGER, "HoldTime"),
DEFINE_KEYFIELD( m_nHoldNoise, FIELD_INTEGER, "HoldNoise"),
DEFINE_PHYSPTR( m_pWindController ),
DEFINE_EMBEDDED( m_WindCallback ),
DEFINE_FUNCTION( WindThink ),
DEFINE_INPUTFUNC( FIELD_INTEGER, "SetSpeed", InputSetSpeed ),
END_DATADESC()
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerWind::Spawn( void )
{
m_bSwitch = true;
m_nDirBase = GetLocalAngles().y;
BaseClass::Spawn();
m_nSpeedCurrent = m_nSpeedBase;
m_nDirCurrent = m_nDirBase;
SetContextThink( &CTriggerWind::WindThink, gpGlobals->curtime, WIND_THINK_CONTEXT );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTriggerWind::KeyValue( const char *szKeyName, const char *szValue )
{
// Done here to avoid collision with CBaseEntity's speed key
if ( FStrEq(szKeyName, "Speed") )
{
m_nSpeedBase = atoi( szValue );
}
else
return BaseClass::KeyValue( szKeyName, szValue );
return true;
}
//------------------------------------------------------------------------------
// Create VPhysics
//------------------------------------------------------------------------------
bool CTriggerWind::CreateVPhysics()
{
BaseClass::CreateVPhysics();
m_pWindController = physenv->CreateMotionController( &m_WindCallback );
return true;
}
//------------------------------------------------------------------------------
// Cleanup
//------------------------------------------------------------------------------
void CTriggerWind::UpdateOnRemove()
{
if ( m_pWindController )
{
physenv->DestroyMotionController( m_pWindController );
m_pWindController = NULL;
}
BaseClass::UpdateOnRemove();
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerWind::OnRestore()
{
BaseClass::OnRestore();
if ( m_pWindController )
{
m_pWindController->SetEventHandler( &m_WindCallback );
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerWind::StartTouch(CBaseEntity *pOther)
{
if ( !PassesTriggerFilters(pOther) )
return;
if ( pOther->IsPlayer() )
return;
IPhysicsObject *pPhys = pOther->VPhysicsGetObject();
if ( pPhys)
{
m_pWindController->AttachObject( pPhys, false );
pPhys->Wake();
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerWind::EndTouch(CBaseEntity *pOther)
{
if ( !PassesTriggerFilters(pOther) )
return;
if ( pOther->IsPlayer() )
return;
IPhysicsObject *pPhys = pOther->VPhysicsGetObject();
if ( pPhys && m_pWindController )
{
m_pWindController->DetachObject( pPhys );
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerWind::InputEnable( inputdata_t &inputdata )
{
BaseClass::InputEnable( inputdata );
SetContextThink( &CTriggerWind::WindThink, gpGlobals->curtime + 0.1f, WIND_THINK_CONTEXT );
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerWind::WindThink( void )
{
// By default...
SetContextThink( &CTriggerWind::WindThink, gpGlobals->curtime + 0.1, WIND_THINK_CONTEXT );
// Is it time to change the wind?
if (m_bSwitch)
{
m_bSwitch = false;
// Set new target direction and speed
m_nSpeedTarget = m_nSpeedBase + random->RandomInt( -m_nSpeedNoise, m_nSpeedNoise );
m_nDirTarget = UTIL_AngleMod( m_nDirBase + random->RandomInt(-m_nDirNoise, m_nDirNoise) );
}
else
{
bool bDone = true;
// either ramp up, or sleep till change
if (abs(m_nSpeedTarget - m_nSpeedCurrent) > MAX_WIND_CHANGE)
{
m_nSpeedCurrent += (m_nSpeedTarget > m_nSpeedCurrent) ? MAX_WIND_CHANGE : -MAX_WIND_CHANGE;
bDone = false;
}
if (abs(m_nDirTarget - m_nDirCurrent) > MAX_WIND_CHANGE)
{
m_nDirCurrent = UTIL_ApproachAngle( m_nDirTarget, m_nDirCurrent, MAX_WIND_CHANGE );
bDone = false;
}
if (bDone)
{
m_nSpeedCurrent = m_nSpeedTarget;
SetContextThink( &CTriggerWind::WindThink, m_nHoldBase + random->RandomFloat(-m_nHoldNoise,m_nHoldNoise), WIND_THINK_CONTEXT );
m_bSwitch = true;
}
}
// If we're starting to blow, where we weren't before, wake up all our objects
if ( m_nSpeedCurrent )
{
m_pWindController->WakeObjects();
}
// store the wind data in the controller callback
m_WindCallback.m_nWindYaw = m_nDirCurrent;
if ( m_bDisabled )
{
m_WindCallback.m_flWindSpeed = 0;
}
else
{
m_WindCallback.m_flWindSpeed = m_nSpeedCurrent;
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerWind::InputSetSpeed( inputdata_t &inputdata )
{
// Set new speed and mark to switch
m_nSpeedBase = inputdata.value.Int();
m_bSwitch = true;
}
//-----------------------------------------------------------------------------
// Purpose: Draw any debug text overlays
// Output : Current text offset from the top
//-----------------------------------------------------------------------------
int CTriggerWind::DrawDebugTextOverlays(void)
{
int text_offset = BaseClass::DrawDebugTextOverlays();
if (m_debugOverlays & OVERLAY_TEXT_BIT)
{
// --------------
// Print Target
// --------------
char tempstr[255];
Q_snprintf(tempstr,sizeof(tempstr),"Dir: %i (%i)",m_nDirCurrent,m_nDirTarget);
EntityText(text_offset,tempstr,0);
text_offset++;
Q_snprintf(tempstr,sizeof(tempstr),"Speed: %i (%i)",m_nSpeedCurrent,m_nSpeedTarget);
EntityText(text_offset,tempstr,0);
text_offset++;
}
return text_offset;
}
// ##################################################################################
// >> TriggerImpact
//
// Blows physics objects in the trigger
//
// ##################################################################################
#define TRIGGERIMPACT_VIEWKICK_SCALE 0.1
class CTriggerImpact : public CTriggerMultiple
{
DECLARE_CLASS( CTriggerImpact, CTriggerMultiple );
public:
DECLARE_DATADESC();
float m_flMagnitude;
float m_flNoise;
float m_flViewkick;
void Spawn( void );
void StartTouch( CBaseEntity *pOther );
// Inputs
void InputSetMagnitude( inputdata_t &inputdata );
void InputImpact( inputdata_t &inputdata );
// Outputs
COutputVector m_pOutputForce; // Output force in case anyone else wants to use it
// Debug
int DrawDebugTextOverlays(void);
};
LINK_ENTITY_TO_CLASS( trigger_impact, CTriggerImpact );
BEGIN_DATADESC( CTriggerImpact )
DEFINE_KEYFIELD( m_flMagnitude, FIELD_FLOAT, "Magnitude"),
DEFINE_KEYFIELD( m_flNoise, FIELD_FLOAT, "Noise"),
DEFINE_KEYFIELD( m_flViewkick, FIELD_FLOAT, "Viewkick"),
// Inputs
DEFINE_INPUTFUNC( FIELD_VOID, "Impact", InputImpact ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "SetMagnitude", InputSetMagnitude ),
// Outputs
DEFINE_OUTPUT(m_pOutputForce, "ImpactForce"),
// Function Pointers
DEFINE_FUNCTION( Disable ),
END_DATADESC()
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerImpact::Spawn( void )
{
// Clamp date in case user made an error
m_flNoise = clamp(m_flNoise,0.f,1.f);
m_flViewkick = clamp(m_flViewkick,0.f,1.f);
// Always start disabled
m_bDisabled = true;
BaseClass::Spawn();
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerImpact::InputImpact( inputdata_t &inputdata )
{
// Output the force vector in case anyone else wants to use it
Vector vDir;
AngleVectors( GetLocalAngles(),&vDir );
m_pOutputForce.Set( m_flMagnitude * vDir, inputdata.pActivator, inputdata.pCaller);
// Enable long enough to throw objects inside me
Enable();
SetNextThink( gpGlobals->curtime + 0.1f );
SetThink(&CTriggerImpact::Disable);
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerImpact::StartTouch(CBaseEntity *pOther)
{
//If the entity is valid and has physics, hit it
if ( ( pOther != NULL ) && ( pOther->VPhysicsGetObject() != NULL ) )
{
Vector vDir;
AngleVectors( GetLocalAngles(),&vDir );
vDir += RandomVector(-m_flNoise,m_flNoise);
pOther->VPhysicsGetObject()->ApplyForceCenter( m_flMagnitude * vDir );
}
// If the player, so a view kick
if (pOther->IsPlayer() && fabs(m_flMagnitude)>0 )
{
Vector vDir;
AngleVectors( GetLocalAngles(),&vDir );
float flPunch = -m_flViewkick*m_flMagnitude*TRIGGERIMPACT_VIEWKICK_SCALE;
pOther->ViewPunch( QAngle( vDir.y * flPunch, 0, vDir.x * flPunch ) );
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTriggerImpact::InputSetMagnitude( inputdata_t &inputdata )
{
m_flMagnitude = inputdata.value.Float();
}
//-----------------------------------------------------------------------------
// Purpose: Draw any debug text overlays
// Output : Current text offset from the top
//-----------------------------------------------------------------------------
int CTriggerImpact::DrawDebugTextOverlays(void)
{
int text_offset = BaseClass::DrawDebugTextOverlays();
if (m_debugOverlays & OVERLAY_TEXT_BIT)
{
char tempstr[255];
Q_snprintf(tempstr,sizeof(tempstr),"Magnitude: %3.2f",m_flMagnitude);
EntityText(text_offset,tempstr,0);
text_offset++;
}
return text_offset;
}
//-----------------------------------------------------------------------------
// Purpose: Disables auto movement on players that touch it
//-----------------------------------------------------------------------------
const int SF_TRIGGER_MOVE_AUTODISABLE = 0x80; // disable auto movement
const int SF_TRIGGER_AUTO_DUCK = 0x800; // Duck automatically
class CTriggerPlayerMovement : public CBaseTrigger
{
DECLARE_CLASS( CTriggerPlayerMovement, CBaseTrigger );
public:
void Spawn( void );
void StartTouch( CBaseEntity *pOther );
void EndTouch( CBaseEntity *pOther );
DECLARE_DATADESC();
};
BEGIN_DATADESC( CTriggerPlayerMovement )
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger_playermovement, CTriggerPlayerMovement );
//-----------------------------------------------------------------------------
// Purpose: Called when spawning, after keyvalues have been handled.
//-----------------------------------------------------------------------------
void CTriggerPlayerMovement::Spawn( void )
{
if( HasSpawnFlags( SF_TRIGGER_ONLY_PLAYER_ALLY_NPCS ) )
{
// @Note (toml 01-07-04): fix up spawn flag collision coding error. Remove at some point once all maps fixed up please!
DevMsg("*** trigger_playermovement using obsolete spawnflag. Remove and reset with new value for \"Disable auto player movement\"\n" );
RemoveSpawnFlags(SF_TRIGGER_ONLY_PLAYER_ALLY_NPCS);
AddSpawnFlags(SF_TRIGGER_MOVE_AUTODISABLE);
}
BaseClass::Spawn();
InitTrigger();
}
// UNDONE: This will not support a player touching more than one of these
// UNDONE: Do we care? If so, ref count automovement in the player?
void CTriggerPlayerMovement::StartTouch( CBaseEntity *pOther )
{
if (!PassesTriggerFilters(pOther))
return;
CBasePlayer *pPlayer = ToBasePlayer( pOther );
if ( !pPlayer )
return;
if ( HasSpawnFlags( SF_TRIGGER_AUTO_DUCK ) )
{
pPlayer->ForceButtons( IN_DUCK );
}
// UNDONE: Currently this is the only operation this trigger can do
if ( HasSpawnFlags(SF_TRIGGER_MOVE_AUTODISABLE) )
{
pPlayer->m_Local.m_bAllowAutoMovement = false;
}
}
void CTriggerPlayerMovement::EndTouch( CBaseEntity *pOther )
{
if (!PassesTriggerFilters(pOther))
return;
CBasePlayer *pPlayer = ToBasePlayer( pOther );
if ( !pPlayer )
return;
if ( HasSpawnFlags( SF_TRIGGER_AUTO_DUCK ) )
{
pPlayer->UnforceButtons( IN_DUCK );
}
if ( HasSpawnFlags(SF_TRIGGER_MOVE_AUTODISABLE) )
{
pPlayer->m_Local.m_bAllowAutoMovement = true;
}
}
//------------------------------------------------------------------------------
// Base VPhysics trigger implementation
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Save/load
//------------------------------------------------------------------------------
BEGIN_DATADESC( CBaseVPhysicsTrigger )
DEFINE_KEYFIELD( m_bDisabled, FIELD_BOOLEAN, "StartDisabled" ),
DEFINE_KEYFIELD( m_iFilterName, FIELD_STRING, "filtername" ),
DEFINE_FIELD( m_hFilter, FIELD_EHANDLE ),
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ),
END_DATADESC()
//------------------------------------------------------------------------------
// Spawn
//------------------------------------------------------------------------------
void CBaseVPhysicsTrigger::Spawn()
{
Precache();
SetSolid( SOLID_VPHYSICS );
AddSolidFlags( FSOLID_NOT_SOLID );
// NOTE: Don't make yourself FSOLID_TRIGGER here or you'll get game
// collisions AND vphysics collisions. You don't want any game collisions
// so just use FSOLID_NOT_SOLID
SetMoveType( MOVETYPE_NONE );
SetModel( STRING( GetModelName() ) ); // set size and link into world
if ( showtriggers.GetInt() == 0 )
{
AddEffects( EF_NODRAW );
}
CreateVPhysics();
}
//------------------------------------------------------------------------------
// Create VPhysics
//------------------------------------------------------------------------------
bool CBaseVPhysicsTrigger::CreateVPhysics()
{
IPhysicsObject *pPhysics;
if ( !HasSpawnFlags( SF_VPHYSICS_MOTION_MOVEABLE ) )
{
pPhysics = VPhysicsInitStatic();
}
else
{
pPhysics = VPhysicsInitShadow( false, false );
}
pPhysics->BecomeTrigger();
return true;
}
//------------------------------------------------------------------------------
// Cleanup
//------------------------------------------------------------------------------
void CBaseVPhysicsTrigger::UpdateOnRemove()
{
if ( VPhysicsGetObject())
{
VPhysicsGetObject()->RemoveTrigger();
}
BaseClass::UpdateOnRemove();
}
//------------------------------------------------------------------------------
// Activate
//------------------------------------------------------------------------------
void CBaseVPhysicsTrigger::Activate( void )
{
// Get a handle to my filter entity if there is one
if (m_iFilterName != NULL_STRING)
{
m_hFilter = dynamic_cast<CBaseFilter *>(gEntList.FindEntityByName( NULL, m_iFilterName ));
}
BaseClass::Activate();
}
//------------------------------------------------------------------------------
// Inputs
//------------------------------------------------------------------------------
void CBaseVPhysicsTrigger::InputToggle( inputdata_t &inputdata )
{
if ( m_bDisabled )
{
InputEnable( inputdata );
}
else
{
InputDisable( inputdata );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseVPhysicsTrigger::InputEnable( inputdata_t &inputdata )
{
if ( m_bDisabled )
{
m_bDisabled = false;
if ( VPhysicsGetObject())
{
VPhysicsGetObject()->EnableCollisions( true );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseVPhysicsTrigger::InputDisable( inputdata_t &inputdata )
{
if ( !m_bDisabled )
{
m_bDisabled = true;
if ( VPhysicsGetObject())
{
VPhysicsGetObject()->EnableCollisions( false );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseVPhysicsTrigger::StartTouch( CBaseEntity *pOther )
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseVPhysicsTrigger::EndTouch( CBaseEntity *pOther )
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CBaseVPhysicsTrigger::PassesTriggerFilters( CBaseEntity *pOther )
{
if ( pOther->GetMoveType() != MOVETYPE_VPHYSICS && !pOther->IsPlayer() )
return false;
// First test spawn flag filters
if ( HasSpawnFlags(SF_TRIGGER_ALLOW_ALL) ||
(HasSpawnFlags(SF_TRIGGER_ALLOW_CLIENTS) && (pOther->GetFlags() & FL_CLIENT)) ||
(HasSpawnFlags(SF_TRIGGER_ALLOW_NPCS) && (pOther->GetFlags() & FL_NPC)) ||
(HasSpawnFlags(SF_TRIGGER_ALLOW_PUSHABLES) && FClassnameIs(pOther, "func_pushable")) ||
(HasSpawnFlags(SF_TRIGGER_ALLOW_PHYSICS) && pOther->GetMoveType() == MOVETYPE_VPHYSICS))
{
bool bOtherIsPlayer = pOther->IsPlayer();
if( HasSpawnFlags(SF_TRIGGER_ONLY_PLAYER_ALLY_NPCS) && !bOtherIsPlayer )
{
CAI_BaseNPC *pNPC = pOther->MyNPCPointer();
if( !pNPC || !pNPC->IsPlayerAlly() )
{
return false;
}
}
if ( HasSpawnFlags(SF_TRIGGER_ONLY_CLIENTS_IN_VEHICLES) && bOtherIsPlayer )
{
if ( !((CBasePlayer*)pOther)->IsInAVehicle() )
return false;
}
if ( HasSpawnFlags(SF_TRIGGER_ONLY_CLIENTS_OUT_OF_VEHICLES) && bOtherIsPlayer )
{
if ( ((CBasePlayer*)pOther)->IsInAVehicle() )
return false;
}
CBaseFilter *pFilter = m_hFilter.Get();
return (!pFilter) ? true : pFilter->PassesFilter( this, pOther );
}
return false;
}
//=====================================================================================================================
//-----------------------------------------------------------------------------
// Purpose: VPhysics trigger that changes the motion of vphysics objects that touch it
//-----------------------------------------------------------------------------
class CTriggerVPhysicsMotion : public CBaseVPhysicsTrigger, public IMotionEvent
{
DECLARE_CLASS( CTriggerVPhysicsMotion, CBaseVPhysicsTrigger );
public:
void Spawn();
void Precache();
virtual void UpdateOnRemove();
bool CreateVPhysics();
void OnRestore();
// UNDONE: Pass trigger event in or change Start/EndTouch. Add ITriggerVPhysics perhaps?
// BUGBUG: If a player touches two of these, his movement will screw up.
// BUGBUG: If a player uses crouch/uncrouch it will generate touch events and clear the motioncontroller flag
void StartTouch( CBaseEntity *pOther );
void EndTouch( CBaseEntity *pOther );
void InputSetVelocityLimitTime( inputdata_t &inputdata );
float LinearLimit();
inline bool HasGravityScale() { return m_gravityScale != 1.0 ? true : false; }
inline bool HasAirDensity() { return m_addAirDensity != 0 ? true : false; }
inline bool HasLinearLimit() { return LinearLimit() != 0.0f; }
inline bool HasLinearScale() { return m_linearScale != 1.0 ? true : false; }
inline bool HasAngularLimit() { return m_angularLimit != 0 ? true : false; }
inline bool HasAngularScale() { return m_angularScale != 1.0 ? true : false; }
inline bool HasLinearForce() { return m_linearForce != 0.0 ? true : false; }
DECLARE_DATADESC();
virtual simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular );
private:
IPhysicsMotionController *m_pController;
#ifndef _XBOX
EntityParticleTrailInfo_t m_ParticleTrail;
#endif //!_XBOX
float m_gravityScale;
float m_addAirDensity;
float m_linearLimit;
float m_linearLimitDelta;
float m_linearLimitTime;
float m_linearLimitStart;
float m_linearLimitStartTime;
float m_linearScale;
float m_angularLimit;
float m_angularScale;
float m_linearForce;
QAngle m_linearForceAngles;
};
//------------------------------------------------------------------------------
// Save/load
//------------------------------------------------------------------------------
BEGIN_DATADESC( CTriggerVPhysicsMotion )
DEFINE_PHYSPTR( m_pController ),
#ifndef _XBOX
DEFINE_EMBEDDED( m_ParticleTrail ),
#endif //!_XBOX
DEFINE_INPUT( m_gravityScale, FIELD_FLOAT, "SetGravityScale" ),
DEFINE_INPUT( m_addAirDensity, FIELD_FLOAT, "SetAdditionalAirDensity" ),
DEFINE_INPUT( m_linearLimit, FIELD_FLOAT, "SetVelocityLimit" ),
DEFINE_INPUT( m_linearLimitDelta, FIELD_FLOAT, "SetVelocityLimitDelta" ),
DEFINE_FIELD( m_linearLimitTime, FIELD_FLOAT ),
DEFINE_FIELD( m_linearLimitStart, FIELD_TIME ),
DEFINE_FIELD( m_linearLimitStartTime, FIELD_TIME ),
DEFINE_INPUT( m_linearScale, FIELD_FLOAT, "SetVelocityScale" ),
DEFINE_INPUT( m_angularLimit, FIELD_FLOAT, "SetAngVelocityLimit" ),
DEFINE_INPUT( m_angularScale, FIELD_FLOAT, "SetAngVelocityScale" ),
DEFINE_INPUT( m_linearForce, FIELD_FLOAT, "SetLinearForce" ),
DEFINE_INPUT( m_linearForceAngles, FIELD_VECTOR, "SetLinearForceAngles" ),
DEFINE_INPUTFUNC( FIELD_STRING, "SetVelocityLimitTime", InputSetVelocityLimitTime ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger_vphysics_motion, CTriggerVPhysicsMotion );
//------------------------------------------------------------------------------
// Spawn
//------------------------------------------------------------------------------
void CTriggerVPhysicsMotion::Spawn()
{
Precache();
BaseClass::Spawn();
}
//------------------------------------------------------------------------------
// Precache
//------------------------------------------------------------------------------
void CTriggerVPhysicsMotion::Precache()
{
#ifndef _XBOX
if ( m_ParticleTrail.m_strMaterialName != NULL_STRING )
{
PrecacheMaterial( STRING(m_ParticleTrail.m_strMaterialName) );
}
#endif //!_XBOX
}
//------------------------------------------------------------------------------
// Create VPhysics
//------------------------------------------------------------------------------
float CTriggerVPhysicsMotion::LinearLimit()
{
if ( m_linearLimitTime == 0.0f )
return m_linearLimit;
float dt = gpGlobals->curtime - m_linearLimitStartTime;
if ( dt >= m_linearLimitTime )
{
m_linearLimitTime = 0.0;
return m_linearLimit;
}
dt /= m_linearLimitTime;
float flLimit = RemapVal( dt, 0.0f, 1.0f, m_linearLimitStart, m_linearLimit );
return flLimit;
}
//------------------------------------------------------------------------------
// Create VPhysics
//------------------------------------------------------------------------------
bool CTriggerVPhysicsMotion::CreateVPhysics()
{
m_pController = physenv->CreateMotionController( this );
BaseClass::CreateVPhysics();
return true;
}
//------------------------------------------------------------------------------
// Cleanup
//------------------------------------------------------------------------------
void CTriggerVPhysicsMotion::UpdateOnRemove()
{
if ( m_pController )
{
physenv->DestroyMotionController( m_pController );
m_pController = NULL;
}
BaseClass::UpdateOnRemove();
}
//------------------------------------------------------------------------------
// Restore
//------------------------------------------------------------------------------
void CTriggerVPhysicsMotion::OnRestore()
{
BaseClass::OnRestore();
if ( m_pController )
{
m_pController->SetEventHandler( this );
}
}
//------------------------------------------------------------------------------
// Start/End Touch
//------------------------------------------------------------------------------
// UNDONE: Pass trigger event in or change Start/EndTouch. Add ITriggerVPhysics perhaps?
// BUGBUG: If a player touches two of these, his movement will screw up.
// BUGBUG: If a player uses crouch/uncrouch it will generate touch events and clear the motioncontroller flag
void CTriggerVPhysicsMotion::StartTouch( CBaseEntity *pOther )
{
BaseClass::StartTouch( pOther );
if ( !PassesTriggerFilters(pOther) )
return;
CBasePlayer *pPlayer = ToBasePlayer( pOther );
if ( pPlayer )
{
pPlayer->SetPhysicsFlag( PFLAG_VPHYSICS_MOTIONCONTROLLER, true );
pPlayer->m_Local.m_bSlowMovement = true;
}
triggerevent_t event;
PhysGetTriggerEvent( &event, this );
if ( event.pObject )
{
// these all get done again on save/load, so check
m_pController->AttachObject( event.pObject, true );
}
// Don't show these particles on the XBox
#ifndef _XBOX
if ( m_ParticleTrail.m_strMaterialName != NULL_STRING )
{
CEntityParticleTrail::Create( pOther, m_ParticleTrail, this );
}
#endif
if ( pOther->GetBaseAnimating() && pOther->GetBaseAnimating()->IsRagdoll() )
{
CRagdollBoogie::IncrementSuppressionCount( pOther );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerVPhysicsMotion::EndTouch( CBaseEntity *pOther )
{
BaseClass::EndTouch( pOther );
if ( !PassesTriggerFilters(pOther) )
return;
CBasePlayer *pPlayer = ToBasePlayer( pOther );
if ( pPlayer )
{
pPlayer->SetPhysicsFlag( PFLAG_VPHYSICS_MOTIONCONTROLLER, false );
pPlayer->m_Local.m_bSlowMovement = false;
}
triggerevent_t event;
PhysGetTriggerEvent( &event, this );
if ( event.pObject && m_pController )
{
m_pController->DetachObject( event.pObject );
}
#ifndef _XBOX
if ( m_ParticleTrail.m_strMaterialName != NULL_STRING )
{
CEntityParticleTrail::Destroy( pOther, m_ParticleTrail );
}
#endif //!_XBOX
if ( pOther->GetBaseAnimating() && pOther->GetBaseAnimating()->IsRagdoll() )
{
CRagdollBoogie::DecrementSuppressionCount( pOther );
}
}
//------------------------------------------------------------------------------
// Inputs
//------------------------------------------------------------------------------
void CTriggerVPhysicsMotion::InputSetVelocityLimitTime( inputdata_t &inputdata )
{
m_linearLimitStart = LinearLimit();
m_linearLimitStartTime = gpGlobals->curtime;
float args[2];
UTIL_StringToFloatArray( args, 2, inputdata.value.String() );
m_linearLimit = args[0];
m_linearLimitTime = args[1];
}
//------------------------------------------------------------------------------
// Apply the forces to the entity
//------------------------------------------------------------------------------
IMotionEvent::simresult_e CTriggerVPhysicsMotion::Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular )
{
if ( m_bDisabled )
return SIM_NOTHING;
linear.Init();
angular.Init();
if ( HasGravityScale() )
{
// assume object already has 1.0 gravities applied to it, so apply the additional amount
linear.z -= (m_gravityScale-1) * GetCurrentGravity();
}
if ( HasLinearForce() )
{
Vector vecForceDir;
AngleVectors( m_linearForceAngles, &vecForceDir );
VectorMA( linear, m_linearForce, vecForceDir, linear );
}
if ( HasAirDensity() || HasLinearLimit() || HasLinearScale() || HasAngularLimit() || HasAngularScale() )
{
Vector vel;
AngularImpulse angVel;
pObject->GetVelocity( &vel, &angVel );
vel += linear * deltaTime; // account for gravity scale
Vector unitVel = vel;
Vector unitAngVel = angVel;
float speed = VectorNormalize( unitVel );
float angSpeed = VectorNormalize( unitAngVel );
float speedScale = 0.0;
float angSpeedScale = 0.0;
if ( HasAirDensity() )
{
float linearDrag = -0.5 * m_addAirDensity * pObject->CalculateLinearDrag( unitVel ) * deltaTime;
if ( linearDrag < -1 )
{
linearDrag = -1;
}
speedScale += linearDrag / deltaTime;
float angDrag = -0.5 * m_addAirDensity * pObject->CalculateAngularDrag( unitAngVel ) * deltaTime;
if ( angDrag < -1 )
{
angDrag = -1;
}
angSpeedScale += angDrag / deltaTime;
}
if ( HasLinearLimit() && speed > m_linearLimit )
{
float flDeltaVel = (LinearLimit() - speed) / deltaTime;
if ( m_linearLimitDelta != 0.0f )
{
float flMaxDeltaVel = -m_linearLimitDelta / deltaTime;
if ( flDeltaVel < flMaxDeltaVel )
{
flDeltaVel = flMaxDeltaVel;
}
}
VectorMA( linear, flDeltaVel, unitVel, linear );
}
if ( HasAngularLimit() && angSpeed > m_angularLimit )
{
angular += ((m_angularLimit - angSpeed)/deltaTime) * unitAngVel;
}
if ( HasLinearScale() )
{
speedScale = ( (speedScale+1) * m_linearScale ) - 1;
}
if ( HasAngularScale() )
{
angSpeedScale = ( (angSpeedScale+1) * m_angularScale ) - 1;
}
linear += vel * speedScale;
angular += angVel * angSpeedScale;
}
return SIM_GLOBAL_ACCELERATION;
}
class CServerRagdollTrigger : public CBaseTrigger
{
DECLARE_CLASS( CServerRagdollTrigger, CBaseTrigger );
public:
virtual void StartTouch( CBaseEntity *pOther );
virtual void EndTouch( CBaseEntity *pOther );
virtual void Spawn( void );
};
LINK_ENTITY_TO_CLASS( trigger_serverragdoll, CServerRagdollTrigger );
void CServerRagdollTrigger::Spawn( void )
{
BaseClass::Spawn();
InitTrigger();
}
void CServerRagdollTrigger::StartTouch(CBaseEntity *pOther)
{
BaseClass::StartTouch( pOther );
if ( pOther->IsPlayer() )
return;
CBaseCombatCharacter *pCombatChar = pOther->MyCombatCharacterPointer();
if ( pCombatChar )
{
pCombatChar->m_bForceServerRagdoll = true;
}
}
void CServerRagdollTrigger::EndTouch(CBaseEntity *pOther)
{
BaseClass::EndTouch( pOther );
if ( pOther->IsPlayer() )
return;
CBaseCombatCharacter *pCombatChar = pOther->MyCombatCharacterPointer();
if ( pCombatChar )
{
pCombatChar->m_bForceServerRagdoll = false;
}
}
//-----------------------------------------------------------------------------
// Purpose: A trigger that adds impulse to touching entities
//-----------------------------------------------------------------------------
class CTriggerApplyImpulse : public CBaseTrigger
{
public:
DECLARE_CLASS( CTriggerApplyImpulse, CBaseTrigger );
DECLARE_DATADESC();
CTriggerApplyImpulse();
void Spawn( void );
void InputApplyImpulse( inputdata_t& );
private:
Vector m_vecImpulseDir;
float m_flForce;
};
BEGIN_DATADESC( CTriggerApplyImpulse )
DEFINE_KEYFIELD( m_vecImpulseDir, FIELD_VECTOR, "impulse_dir" ),
DEFINE_KEYFIELD( m_flForce, FIELD_FLOAT, "force" ),
DEFINE_INPUTFUNC( FIELD_VOID, "ApplyImpulse", InputApplyImpulse ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( trigger_apply_impulse, CTriggerApplyImpulse );
CTriggerApplyImpulse::CTriggerApplyImpulse()
{
m_flForce = 300.f;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerApplyImpulse::Spawn()
{
// Convert pushdir from angles to a vector
Vector vecAbsDir;
QAngle angPushDir = QAngle(m_vecImpulseDir.x, m_vecImpulseDir.y, m_vecImpulseDir.z);
AngleVectors(angPushDir, &vecAbsDir);
// Transform the vector into entity space
VectorIRotate( vecAbsDir, EntityToWorldTransform(), m_vecImpulseDir );
BaseClass::Spawn();
InitTrigger();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTriggerApplyImpulse::InputApplyImpulse( inputdata_t& )
{
Vector vecImpulse = m_flForce * m_vecImpulseDir;
FOR_EACH_VEC( m_hTouchingEntities, i )
{
if ( m_hTouchingEntities[i] )
{
m_hTouchingEntities[i]->ApplyAbsVelocityImpulse( vecImpulse );
}
}
}
#ifdef HL1_DLL
//----------------------------------------------------------------------------------
// func_friction
//----------------------------------------------------------------------------------
class CFrictionModifier : public CBaseTrigger
{
DECLARE_CLASS( CFrictionModifier, CBaseTrigger );
public:
void Spawn( void );
bool KeyValue( const char *szKeyName, const char *szValue );
virtual void StartTouch(CBaseEntity *pOther);
virtual void EndTouch(CBaseEntity *pOther);
virtual int ObjectCaps( void ) { return CBaseEntity::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; }
float m_frictionFraction;
DECLARE_DATADESC();
};
LINK_ENTITY_TO_CLASS( func_friction, CFrictionModifier );
BEGIN_DATADESC( CFrictionModifier )
DEFINE_FIELD( m_frictionFraction, FIELD_FLOAT ),
END_DATADESC()
// Modify an entity's friction
void CFrictionModifier::Spawn( void )
{
BaseClass::Spawn();
InitTrigger();
}
// Sets toucher's friction to m_frictionFraction (1.0 = normal friction)
bool CFrictionModifier::KeyValue( const char *szKeyName, const char *szValue )
{
if (FStrEq(szKeyName, "modifier"))
{
m_frictionFraction = atof(szValue) / 100.0;
}
else
{
BaseClass::KeyValue( szKeyName, szValue );
}
return true;
}
void CFrictionModifier::StartTouch( CBaseEntity *pOther )
{
if ( !pOther->IsPlayer() ) // ignore player
{
pOther->SetFriction( m_frictionFraction );
}
}
void CFrictionModifier::EndTouch( CBaseEntity *pOther )
{
if ( !pOther->IsPlayer() ) // ignore player
{
pOther->SetFriction( 1.0f );
}
}
#endif //HL1_DLL
bool IsTriggerClass( CBaseEntity *pEntity )
{
if ( NULL != dynamic_cast<CBaseTrigger *>(pEntity) )
return true;
if ( NULL != dynamic_cast<CTriggerVPhysicsMotion *>(pEntity) )
return true;
if ( NULL != dynamic_cast<CTriggerVolume *>(pEntity) )
return true;
return false;
}
|