File: sv_main.c

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

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
// sv_main.c -- server main program

#include "quakedef.h"
#include "sv_demo.h"
#include "libcurl.h"
#include "csprogs.h"
#include "thread.h"

static void SV_SaveEntFile_f(void);
static void SV_StartDownload_f(void);
static void SV_Download_f(void);
static void SV_VM_Setup(void);
extern cvar_t net_connecttimeout;

cvar_t sv_worldmessage = {CVAR_READONLY, "sv_worldmessage", "", "title of current level"};
cvar_t sv_worldname = {CVAR_READONLY, "sv_worldname", "", "name of current worldmodel"};
cvar_t sv_worldnamenoextension = {CVAR_READONLY, "sv_worldnamenoextension", "", "name of current worldmodel without extension"};
cvar_t sv_worldbasename = {CVAR_READONLY, "sv_worldbasename", "", "name of current worldmodel without maps/ prefix or extension"};

cvar_t sv_disablenotify = {0, "sv_disablenotify", "1", "suppress broadcast prints when certain cvars are changed (CVAR_NOTIFY flag in engine code)"};
cvar_t coop = {0, "coop","0", "coop mode, 0 = no coop, 1 = coop mode, multiple players playing through the singleplayer game (coop mode also shuts off deathmatch)"};
cvar_t deathmatch = {0, "deathmatch","0", "deathmatch mode, values depend on mod but typically 0 = no deathmatch, 1 = normal deathmatch with respawning weapons, 2 = weapons stay (players can only pick up new weapons)"};
cvar_t fraglimit = {CVAR_NOTIFY, "fraglimit","0", "ends level if this many frags is reached by any player"};
cvar_t gamecfg = {0, "gamecfg", "0", "unused cvar in quake, can be used by mods"};
cvar_t noexit = {CVAR_NOTIFY, "noexit","0", "kills anyone attempting to use an exit"};
cvar_t nomonsters = {0, "nomonsters", "0", "unused cvar in quake, can be used by mods"};
cvar_t pausable = {0, "pausable","1", "allow players to pause or not (otherwise, only the server admin can)"};
cvar_t pr_checkextension = {CVAR_READONLY, "pr_checkextension", "1", "indicates to QuakeC that the standard quakec extensions system is available (if 0, quakec should not attempt to use extensions)"};
cvar_t samelevel = {CVAR_NOTIFY, "samelevel","0", "repeats same level if level ends (due to timelimit or someone hitting an exit)"};
cvar_t skill = {0, "skill","1", "difficulty level of game, affects monster layouts in levels, 0 = easy, 1 = normal, 2 = hard, 3 = nightmare (same layout as hard but monsters fire twice)"};
cvar_t slowmo = {0, "slowmo", "1.0", "controls game speed, 0.5 is half speed, 2 is double speed"};

cvar_t sv_accelerate = {0, "sv_accelerate", "10", "rate at which a player accelerates to sv_maxspeed"};
cvar_t sv_aim = {CVAR_SAVE, "sv_aim", "2", "maximum cosine angle for quake's vertical autoaim, a value above 1 completely disables the autoaim, quake used 0.93"};
cvar_t sv_airaccel_qw = {0, "sv_airaccel_qw", "1", "ratio of QW-style air control as opposed to simple acceleration; when < 0, the speed is clamped against the maximum allowed forward speed after the move"};
cvar_t sv_airaccel_qw_stretchfactor = {0, "sv_airaccel_qw_stretchfactor", "0", "when set, the maximum acceleration increase the player may get compared to forward-acceleration when strafejumping"};
cvar_t sv_airaccel_sideways_friction = {0, "sv_airaccel_sideways_friction", "", "anti-sideways movement stabilization (reduces speed gain when zigzagging); when < 0, only so much friction is applied that braking (by accelerating backwards) cannot be stronger"};
cvar_t sv_airaccelerate = {0, "sv_airaccelerate", "-1", "rate at which a player accelerates to sv_maxairspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
cvar_t sv_airstopaccelerate = {0, "sv_airstopaccelerate", "0", "when set, replacement for sv_airaccelerate when moving backwards"};
cvar_t sv_airspeedlimit_nonqw = {0, "sv_airspeedlimit_nonqw", "0", "when set, this is a soft speed limit while in air when using airaccel_qw not equal to 1"};
cvar_t sv_airstrafeaccelerate = {0, "sv_airstrafeaccelerate", "0", "when set, replacement for sv_airaccelerate when just strafing"};
cvar_t sv_maxairstrafespeed = {0, "sv_maxairstrafespeed", "0", "when set, replacement for sv_maxairspeed when just strafing"};
cvar_t sv_airstrafeaccel_qw = {0, "sv_airstrafeaccel_qw", "0", "when set, replacement for sv_airaccel_qw when just strafing"};
cvar_t sv_aircontrol = {0, "sv_aircontrol", "0", "CPMA-style air control"};
cvar_t sv_aircontrol_power = {0, "sv_aircontrol_power", "2", "CPMA-style air control exponent"};
cvar_t sv_aircontrol_penalty = {0, "sv_aircontrol_penalty", "0", "deceleration while using CPMA-style air control"};
cvar_t sv_allowdownloads = {0, "sv_allowdownloads", "1", "whether to allow clients to download files from the server (does not affect http downloads)"};
cvar_t sv_allowdownloads_archive = {0, "sv_allowdownloads_archive", "0", "whether to allow downloads of archives (pak/pk3)"};
cvar_t sv_allowdownloads_config = {0, "sv_allowdownloads_config", "0", "whether to allow downloads of config files (cfg)"};
cvar_t sv_allowdownloads_dlcache = {0, "sv_allowdownloads_dlcache", "0", "whether to allow downloads of dlcache files (dlcache/)"};
cvar_t sv_allowdownloads_inarchive = {0, "sv_allowdownloads_inarchive", "0", "whether to allow downloads from archives (pak/pk3)"};
cvar_t sv_areagrid_mingridsize = {CVAR_NOTIFY, "sv_areagrid_mingridsize", "128", "minimum areagrid cell size, smaller values work better for lots of small objects, higher values for large objects"};
cvar_t sv_checkforpacketsduringsleep = {0, "sv_checkforpacketsduringsleep", "0", "uses select() function to wait between frames which can be interrupted by packets being received, instead of Sleep()/usleep()/SDL_Sleep() functions which do not check for packets"};
cvar_t sv_clmovement_enable = {0, "sv_clmovement_enable", "1", "whether to allow clients to use cl_movement prediction, which can cause choppy movement on the server which may annoy other players"};
cvar_t sv_clmovement_minping = {0, "sv_clmovement_minping", "0", "if client ping is below this time in milliseconds, then their ability to use cl_movement prediction is disabled for a while (as they don't need it)"};
cvar_t sv_clmovement_minping_disabletime = {0, "sv_clmovement_minping_disabletime", "1000", "when client falls below minping, disable their prediction for this many milliseconds (should be at least 1000 or else their prediction may turn on/off frequently)"};
cvar_t sv_clmovement_inputtimeout = {0, "sv_clmovement_inputtimeout", "0.2", "when a client does not send input for this many seconds, force them to move anyway (unlike QuakeWorld)"};
cvar_t sv_cullentities_nevercullbmodels = {0, "sv_cullentities_nevercullbmodels", "0", "if enabled the clients are always notified of moving doors and lifts and other submodels of world (warning: eats a lot of network bandwidth on some levels!)"};
cvar_t sv_cullentities_pvs = {0, "sv_cullentities_pvs", "1", "fast but loose culling of hidden entities"};
cvar_t sv_cullentities_stats = {0, "sv_cullentities_stats", "0", "displays stats on network entities culled by various methods for each client"};
cvar_t sv_cullentities_trace = {0, "sv_cullentities_trace", "0", "somewhat slow but very tight culling of hidden entities, minimizes network traffic and makes wallhack cheats useless"};
cvar_t sv_cullentities_trace_delay = {0, "sv_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
cvar_t sv_cullentities_trace_delay_players = {0, "sv_cullentities_trace_delay_players", "0.2", "number of seconds until the entity gets actually culled if it is a player entity"};
cvar_t sv_cullentities_trace_enlarge = {0, "sv_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
cvar_t sv_cullentities_trace_eyejitter = {0, "sv_cullentities_trace_eyejitter", "16", "jitter the eye by this much for each trace"};
cvar_t sv_cullentities_trace_prediction = {0, "sv_cullentities_trace_prediction", "1", "also trace from the predicted player position"};
cvar_t sv_cullentities_trace_prediction_time = {0, "sv_cullentities_trace_prediction_time", "0.2", "how many seconds of prediction to use"};
cvar_t sv_cullentities_trace_entityocclusion = {0, "sv_cullentities_trace_entityocclusion", "0", "also check if doors and other bsp models are in the way"};
cvar_t sv_cullentities_trace_samples = {0, "sv_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
cvar_t sv_cullentities_trace_samples_extra = {0, "sv_cullentities_trace_samples_extra", "2", "number of samples to test for entity culling when the entity affects its surroundings by e.g. dlight"};
cvar_t sv_cullentities_trace_samples_players = {0, "sv_cullentities_trace_samples_players", "8", "number of samples to test for entity culling when the entity is a player entity"};
cvar_t sv_debugmove = {CVAR_NOTIFY, "sv_debugmove", "0", "disables collision detection optimizations for debugging purposes"};
cvar_t sv_echobprint = {CVAR_SAVE, "sv_echobprint", "1", "prints gamecode bprint() calls to server console"};
cvar_t sv_edgefriction = {0, "edgefriction", "1", "how much you slow down when nearing a ledge you might fall off, multiplier of sv_friction (Quake used 2, QuakeWorld used 1 due to a bug in physics code)"};
cvar_t sv_entpatch = {0, "sv_entpatch", "1", "enables loading of .ent files to override entities in the bsp (for example Threewave CTF server pack contains .ent patch files enabling play of CTF on id1 maps)"};
cvar_t sv_fixedframeratesingleplayer = {0, "sv_fixedframeratesingleplayer", "1", "allows you to use server-style timing system in singleplayer (don't run faster than sys_ticrate)"};
cvar_t sv_freezenonclients = {CVAR_NOTIFY, "sv_freezenonclients", "0", "freezes time, except for players, allowing you to walk around and take screenshots of explosions"};
cvar_t sv_friction = {CVAR_NOTIFY, "sv_friction","4", "how fast you slow down"};
cvar_t sv_gameplayfix_blowupfallenzombies = {0, "sv_gameplayfix_blowupfallenzombies", "1", "causes findradius to detect SOLID_NOT entities such as zombies and corpses on the floor, allowing splash damage to apply to them"};
cvar_t sv_gameplayfix_consistentplayerprethink = {0, "sv_gameplayfix_consistentplayerprethink", "0", "improves fairness in multiplayer by running all PlayerPreThink functions (which fire weapons) before performing physics, then running all PlayerPostThink functions"};
cvar_t sv_gameplayfix_delayprojectiles = {0, "sv_gameplayfix_delayprojectiles", "1", "causes entities to not move on the same frame they are spawned, meaning that projectiles wait until the next frame to perform their first move, giving proper interpolation and rocket trails, but making weapons harder to use at low framerates"};
cvar_t sv_gameplayfix_droptofloorstartsolid = {0, "sv_gameplayfix_droptofloorstartsolid", "1", "prevents items and monsters that start in a solid area from falling out of the level (makes droptofloor treat trace_startsolid as an acceptable outcome)"};
cvar_t sv_gameplayfix_droptofloorstartsolid_nudgetocorrect = {0, "sv_gameplayfix_droptofloorstartsolid_nudgetocorrect", "1", "tries to nudge stuck items and monsters out of walls before droptofloor is performed"};
cvar_t sv_gameplayfix_easierwaterjump = {0, "sv_gameplayfix_easierwaterjump", "1", "changes water jumping to make it easier to get out of water (exactly like in QuakeWorld)"};
cvar_t sv_gameplayfix_findradiusdistancetobox = {0, "sv_gameplayfix_findradiusdistancetobox", "1", "causes findradius to check the distance to the corner of a box rather than the center of the box, makes findradius detect bmodels such as very large doors that would otherwise be unaffected by splash damage"};
cvar_t sv_gameplayfix_gravityunaffectedbyticrate = {0, "sv_gameplayfix_gravityunaffectedbyticrate", "0", "fix some ticrate issues in physics."};
cvar_t sv_gameplayfix_grenadebouncedownslopes = {0, "sv_gameplayfix_grenadebouncedownslopes", "1", "prevents MOVETYPE_BOUNCE (grenades) from getting stuck when fired down a downward sloping surface"};
cvar_t sv_gameplayfix_multiplethinksperframe = {0, "sv_gameplayfix_multiplethinksperframe", "1", "allows entities to think more often than the server framerate, primarily useful for very high fire rate weapons"};
cvar_t sv_gameplayfix_noairborncorpse = {0, "sv_gameplayfix_noairborncorpse", "1", "causes entities (corpses, items, etc) sitting ontop of moving entities (players) to fall when the moving entity (player) is no longer supporting them"};
cvar_t sv_gameplayfix_noairborncorpse_allowsuspendeditems = {0, "sv_gameplayfix_noairborncorpse_allowsuspendeditems", "1", "causes entities sitting ontop of objects that are instantaneously remove to float in midair (special hack to allow a common level design trick for floating items)"};
cvar_t sv_gameplayfix_nudgeoutofsolid = {0, "sv_gameplayfix_nudgeoutofsolid", "0", "attempts to fix physics errors (where an object ended up in solid for some reason)"};
cvar_t sv_gameplayfix_nudgeoutofsolid_separation = {0, "sv_gameplayfix_nudgeoutofsolid_separation", "0.03125", "keep objects this distance apart to prevent collision issues on seams"};
cvar_t sv_gameplayfix_q2airaccelerate = {0, "sv_gameplayfix_q2airaccelerate", "0", "Quake2-style air acceleration"};
cvar_t sv_gameplayfix_nogravityonground = {0, "sv_gameplayfix_nogravityonground", "0", "turn off gravity when on ground (to get rid of sliding)"};
cvar_t sv_gameplayfix_setmodelrealbox = {0, "sv_gameplayfix_setmodelrealbox", "1", "fixes a bug in Quake that made setmodel always set the entity box to ('-16 -16 -16', '16 16 16') rather than properly checking the model box, breaks some poorly coded mods"};
cvar_t sv_gameplayfix_slidemoveprojectiles = {0, "sv_gameplayfix_slidemoveprojectiles", "1", "allows MOVETYPE_FLY/FLYMISSILE/TOSS/BOUNCE/BOUNCEMISSILE entities to finish their move in a frame even if they hit something, fixes 'gravity accumulation' bug for grenades on steep slopes"};
cvar_t sv_gameplayfix_stepdown = {0, "sv_gameplayfix_stepdown", "0", "attempts to step down stairs, not just up them (prevents the familiar thud..thud..thud.. when running down stairs and slopes)"};
cvar_t sv_gameplayfix_stepmultipletimes = {0, "sv_gameplayfix_stepmultipletimes", "0", "applies step-up onto a ledge more than once in a single frame, when running quickly up stairs"};
cvar_t sv_gameplayfix_nostepmoveonsteepslopes = {0, "sv_gameplayfix_nostepmoveonsteepslopes", "0", "crude fix which prevents MOVETYPE_STEP (not swimming or flying) to move on slopes whose angle is bigger than 45 degree"};
cvar_t sv_gameplayfix_swiminbmodels = {0, "sv_gameplayfix_swiminbmodels", "1", "causes pointcontents (used to determine if you are in a liquid) to check bmodel entities as well as the world model, so you can swim around in (possibly moving) water bmodel entities"};
cvar_t sv_gameplayfix_upwardvelocityclearsongroundflag = {0, "sv_gameplayfix_upwardvelocityclearsongroundflag", "1", "prevents monsters, items, and most other objects from being stuck to the floor when pushed around by damage, and other situations in mods"};
cvar_t sv_gameplayfix_downtracesupportsongroundflag = {0, "sv_gameplayfix_downtracesupportsongroundflag", "1", "prevents very short moves from clearing onground (which may make the player stick to the floor at high netfps)"};
cvar_t sv_gameplayfix_q1bsptracelinereportstexture = {0, "sv_gameplayfix_q1bsptracelinereportstexture", "1", "enables mods to get accurate trace_texture results on q1bsp by using a surface-hitting traceline implementation rather than the standard solidbsp method, q3bsp always reports texture accurately"};
cvar_t sv_gameplayfix_unstickplayers = {0, "sv_gameplayfix_unstickplayers", "1", "big hack to try and fix the rare case of MOVETYPE_WALK entities getting stuck in the world clipping hull."};
cvar_t sv_gameplayfix_unstickentities = {0, "sv_gameplayfix_unstickentities", "1", "hack to check if entities are crossing world collision hull and try to move them to the right position"};
cvar_t sv_gameplayfix_fixedcheckwatertransition = {0, "sv_gameplayfix_fixedcheckwatertransition", "1", "fix two very stupid bugs in SV_CheckWaterTransition when watertype is CONTENTS_EMPTY (the bugs causes waterlevel to be 1 on first frame, -1 on second frame - the fix makes it 0 on both frames)"};
cvar_t sv_gravity = {CVAR_NOTIFY, "sv_gravity","800", "how fast you fall (512 = roughly earth gravity)"};
cvar_t sv_init_frame_count = {0, "sv_init_frame_count", "2", "number of frames to run to allow everything to settle before letting clients connect"};
cvar_t sv_idealpitchscale = {0, "sv_idealpitchscale","0.8", "how much to look up/down slopes and stairs when not using freelook"};
cvar_t sv_jumpstep = {CVAR_NOTIFY, "sv_jumpstep", "0", "whether you can step up while jumping"};
cvar_t sv_jumpvelocity = {0, "sv_jumpvelocity", "270", "cvar that can be used by QuakeC code for jump velocity"};
cvar_t sv_maxairspeed = {0, "sv_maxairspeed", "30", "maximum speed a player can accelerate to when airborn (note that it is possible to completely stop by moving the opposite direction)"};
cvar_t sv_maxrate = {CVAR_SAVE | CVAR_NOTIFY, "sv_maxrate", "1000000", "upper limit on client rate cvar, should reflect your network connection quality"};
cvar_t sv_maxspeed = {CVAR_NOTIFY, "sv_maxspeed", "320", "maximum speed a player can accelerate to when on ground (can be exceeded by tricks)"};
cvar_t sv_maxvelocity = {CVAR_NOTIFY, "sv_maxvelocity","2000", "universal speed limit on all entities"};
cvar_t sv_nostep = {CVAR_NOTIFY, "sv_nostep","0", "prevents MOVETYPE_STEP entities (monsters) from moving"};
cvar_t sv_playerphysicsqc = {CVAR_NOTIFY, "sv_playerphysicsqc", "1", "enables QuakeC function to override player physics"};
cvar_t sv_progs = {0, "sv_progs", "progs.dat", "selects which quakec progs.dat file to run" };
cvar_t sv_protocolname = {0, "sv_protocolname", "DP7", "selects network protocol to host for (values include QUAKE, QUAKEDP, NEHAHRAMOVIE, DP1 and up)"};
cvar_t sv_random_seed = {0, "sv_random_seed", "", "random seed; when set, on every map start this random seed is used to initialize the random number generator. Don't touch it unless for benchmarking or debugging"};
cvar_t sv_ratelimitlocalplayer = {0, "sv_ratelimitlocalplayer", "0", "whether to apply rate limiting to the local player in a listen server (only useful for testing)"};
cvar_t sv_sound_land = {0, "sv_sound_land", "demon/dland2.wav", "sound to play when MOVETYPE_STEP entity hits the ground at high speed (empty cvar disables the sound)"};
cvar_t sv_sound_watersplash = {0, "sv_sound_watersplash", "misc/h2ohit1.wav", "sound to play when MOVETYPE_FLY/TOSS/BOUNCE/STEP entity enters or leaves water (empty cvar disables the sound)"};
cvar_t sv_stepheight = {CVAR_NOTIFY, "sv_stepheight", "18", "how high you can step up (TW_SV_STEPCONTROL extension)"};
cvar_t sv_stopspeed = {CVAR_NOTIFY, "sv_stopspeed","100", "how fast you come to a complete stop"};
cvar_t sv_wallfriction = {CVAR_NOTIFY, "sv_wallfriction", "1", "how much you slow down when sliding along a wall"};
cvar_t sv_wateraccelerate = {0, "sv_wateraccelerate", "-1", "rate at which a player accelerates to sv_maxspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
cvar_t sv_waterfriction = {CVAR_NOTIFY, "sv_waterfriction","-1", "how fast you slow down, if less than 0 the sv_friction variable is used instead"};
cvar_t sv_warsowbunny_airforwardaccel = {0, "sv_warsowbunny_airforwardaccel", "1.00001", "how fast you accelerate until you reach sv_maxspeed"};
cvar_t sv_warsowbunny_accel = {0, "sv_warsowbunny_accel", "0.1585", "how fast you accelerate until after reaching sv_maxspeed (it gets harder as you near sv_warsowbunny_topspeed)"};
cvar_t sv_warsowbunny_topspeed = {0, "sv_warsowbunny_topspeed", "925", "soft speed limit (can get faster with rjs and on ramps)"};
cvar_t sv_warsowbunny_turnaccel = {0, "sv_warsowbunny_turnaccel", "0", "max sharpness of turns (also master switch for the sv_warsowbunny_* mode; set this to 9 to enable)"};
cvar_t sv_warsowbunny_backtosideratio = {0, "sv_warsowbunny_backtosideratio", "0.8", "lower values make it easier to change direction without losing speed; the drawback is \"understeering\" in sharp turns"};
cvar_t sv_onlycsqcnetworking = {0, "sv_onlycsqcnetworking", "0", "disables legacy entity networking code for higher performance (except on clients, which can still be legacy)"};
cvar_t sv_areadebug = {0, "sv_areadebug", "0", "disables physics culling for debugging purposes (only for development)"};
cvar_t sys_ticrate = {CVAR_SAVE, "sys_ticrate","0.0138889", "how long a server frame is in seconds, 0.05 is 20fps server rate, 0.1 is 10fps (can not be set higher than 0.1), 0 runs as many server frames as possible (makes games against bots a little smoother, overwhelms network players), 0.0138889 matches QuakeWorld physics"};
cvar_t teamplay = {CVAR_NOTIFY, "teamplay","0", "teamplay mode, values depend on mod but typically 0 = no teams, 1 = no team damage no self damage, 2 = team damage and self damage, some mods support 3 = no team damage but can damage self"};
cvar_t timelimit = {CVAR_NOTIFY, "timelimit","0", "ends level at this time (in minutes)"};
cvar_t sv_threaded = {0, "sv_threaded", "0", "enables a separate thread for server code, improving performance, especially when hosting a game while playing, EXPERIMENTAL, may be crashy"};

cvar_t saved1 = {CVAR_SAVE, "saved1", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
cvar_t saved2 = {CVAR_SAVE, "saved2", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
cvar_t saved3 = {CVAR_SAVE, "saved3", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
cvar_t saved4 = {CVAR_SAVE, "saved4", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
cvar_t savedgamecfg = {CVAR_SAVE, "savedgamecfg", "0", "unused cvar in quake that is saved to config.cfg on exit, can be used by mods"};
cvar_t scratch1 = {0, "scratch1", "0", "unused cvar in quake, can be used by mods"};
cvar_t scratch2 = {0,"scratch2", "0", "unused cvar in quake, can be used by mods"};
cvar_t scratch3 = {0, "scratch3", "0", "unused cvar in quake, can be used by mods"};
cvar_t scratch4 = {0, "scratch4", "0", "unused cvar in quake, can be used by mods"};
cvar_t temp1 = {0, "temp1","0", "general cvar for mods to use, in stock id1 this selects which death animation to use on players (0 = random death, other values select specific death scenes)"};

cvar_t nehx00 = {0, "nehx00", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx01 = {0, "nehx01", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx02 = {0, "nehx02", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx03 = {0, "nehx03", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx04 = {0, "nehx04", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx05 = {0, "nehx05", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx06 = {0, "nehx06", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx07 = {0, "nehx07", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx08 = {0, "nehx08", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx09 = {0, "nehx09", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx10 = {0, "nehx10", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx11 = {0, "nehx11", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx12 = {0, "nehx12", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx13 = {0, "nehx13", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx14 = {0, "nehx14", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx15 = {0, "nehx15", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx16 = {0, "nehx16", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx17 = {0, "nehx17", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx18 = {0, "nehx18", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t nehx19 = {0, "nehx19", "0", "nehahra data storage cvar (used in singleplayer)"};
cvar_t cutscene = {0, "cutscene", "1", "enables cutscenes in nehahra, can be used by other mods"};

cvar_t sv_autodemo_perclient = {CVAR_SAVE, "sv_autodemo_perclient", "0", "set to 1 to enable autorecorded per-client demos (they'll start to record at the beginning of a match); set it to 2 to also record client->server packets (for debugging)"};
cvar_t sv_autodemo_perclient_nameformat = {CVAR_SAVE, "sv_autodemo_perclient_nameformat", "sv_autodemos/%Y-%m-%d_%H-%M", "The format of the sv_autodemo_perclient filename, followed by the map name, the client number and the IP address + port number, separated by underscores (the date is encoded using strftime escapes)" };
cvar_t sv_autodemo_perclient_discardable = {CVAR_SAVE, "sv_autodemo_perclient_discardable", "0", "Allow game code to decide whether a demo should be kept or discarded."};

cvar_t halflifebsp = {0, "halflifebsp", "0", "indicates the current map is hlbsp format (useful to know because of different bounding box sizes)"};
cvar_t sv_mapformat_is_quake2 = {0, "sv_mapformat_is_quake2", "0", "indicates the current map is q2bsp format (useful to know because of different entity behaviors, .frame on submodels and other things)"};
cvar_t sv_mapformat_is_quake3 = {0, "sv_mapformat_is_quake3", "0", "indicates the current map is q2bsp format (useful to know because of different entity behaviors)"};

server_t sv;
server_static_t svs;

mempool_t *sv_mempool = NULL;

extern cvar_t slowmo;
extern float		scr_centertime_off;

// MUST match effectnameindex_t in client.h
static const char *standardeffectnames[EFFECT_TOTAL] =
{
	"",
	"TE_GUNSHOT",
	"TE_GUNSHOTQUAD",
	"TE_SPIKE",
	"TE_SPIKEQUAD",
	"TE_SUPERSPIKE",
	"TE_SUPERSPIKEQUAD",
	"TE_WIZSPIKE",
	"TE_KNIGHTSPIKE",
	"TE_EXPLOSION",
	"TE_EXPLOSIONQUAD",
	"TE_TAREXPLOSION",
	"TE_TELEPORT",
	"TE_LAVASPLASH",
	"TE_SMALLFLASH",
	"TE_FLAMEJET",
	"EF_FLAME",
	"TE_BLOOD",
	"TE_SPARK",
	"TE_PLASMABURN",
	"TE_TEI_G3",
	"TE_TEI_SMOKE",
	"TE_TEI_BIGEXPLOSION",
	"TE_TEI_PLASMAHIT",
	"EF_STARDUST",
	"TR_ROCKET",
	"TR_GRENADE",
	"TR_BLOOD",
	"TR_WIZSPIKE",
	"TR_SLIGHTBLOOD",
	"TR_KNIGHTSPIKE",
	"TR_VORESPIKE",
	"TR_NEHAHRASMOKE",
	"TR_NEXUIZPLASMA",
	"TR_GLOWTRAIL",
	"SVC_PARTICLE"
};

#define SV_REQFUNCS 0
#define sv_reqfuncs NULL

//#define SV_REQFUNCS (sizeof(sv_reqfuncs) / sizeof(const char *))
//static const char *sv_reqfuncs[] = {
//};

#define SV_REQFIELDS (sizeof(sv_reqfields) / sizeof(prvm_required_field_t))

prvm_required_field_t sv_reqfields[] =
{
#define PRVM_DECLARE_serverglobalfloat(x)
#define PRVM_DECLARE_serverglobalvector(x)
#define PRVM_DECLARE_serverglobalstring(x)
#define PRVM_DECLARE_serverglobaledict(x)
#define PRVM_DECLARE_serverglobalfunction(x)
#define PRVM_DECLARE_clientglobalfloat(x)
#define PRVM_DECLARE_clientglobalvector(x)
#define PRVM_DECLARE_clientglobalstring(x)
#define PRVM_DECLARE_clientglobaledict(x)
#define PRVM_DECLARE_clientglobalfunction(x)
#define PRVM_DECLARE_menuglobalfloat(x)
#define PRVM_DECLARE_menuglobalvector(x)
#define PRVM_DECLARE_menuglobalstring(x)
#define PRVM_DECLARE_menuglobaledict(x)
#define PRVM_DECLARE_menuglobalfunction(x)
#define PRVM_DECLARE_serverfieldfloat(x) {ev_float, #x},
#define PRVM_DECLARE_serverfieldvector(x) {ev_vector, #x},
#define PRVM_DECLARE_serverfieldstring(x) {ev_string, #x},
#define PRVM_DECLARE_serverfieldedict(x) {ev_entity, #x},
#define PRVM_DECLARE_serverfieldfunction(x) {ev_function, #x},
#define PRVM_DECLARE_clientfieldfloat(x)
#define PRVM_DECLARE_clientfieldvector(x)
#define PRVM_DECLARE_clientfieldstring(x)
#define PRVM_DECLARE_clientfieldedict(x)
#define PRVM_DECLARE_clientfieldfunction(x)
#define PRVM_DECLARE_menufieldfloat(x)
#define PRVM_DECLARE_menufieldvector(x)
#define PRVM_DECLARE_menufieldstring(x)
#define PRVM_DECLARE_menufieldedict(x)
#define PRVM_DECLARE_menufieldfunction(x)
#define PRVM_DECLARE_serverfunction(x)
#define PRVM_DECLARE_clientfunction(x)
#define PRVM_DECLARE_menufunction(x)
#define PRVM_DECLARE_field(x)
#define PRVM_DECLARE_global(x)
#define PRVM_DECLARE_function(x)
#include "prvm_offsets.h"
#undef PRVM_DECLARE_serverglobalfloat
#undef PRVM_DECLARE_serverglobalvector
#undef PRVM_DECLARE_serverglobalstring
#undef PRVM_DECLARE_serverglobaledict
#undef PRVM_DECLARE_serverglobalfunction
#undef PRVM_DECLARE_clientglobalfloat
#undef PRVM_DECLARE_clientglobalvector
#undef PRVM_DECLARE_clientglobalstring
#undef PRVM_DECLARE_clientglobaledict
#undef PRVM_DECLARE_clientglobalfunction
#undef PRVM_DECLARE_menuglobalfloat
#undef PRVM_DECLARE_menuglobalvector
#undef PRVM_DECLARE_menuglobalstring
#undef PRVM_DECLARE_menuglobaledict
#undef PRVM_DECLARE_menuglobalfunction
#undef PRVM_DECLARE_serverfieldfloat
#undef PRVM_DECLARE_serverfieldvector
#undef PRVM_DECLARE_serverfieldstring
#undef PRVM_DECLARE_serverfieldedict
#undef PRVM_DECLARE_serverfieldfunction
#undef PRVM_DECLARE_clientfieldfloat
#undef PRVM_DECLARE_clientfieldvector
#undef PRVM_DECLARE_clientfieldstring
#undef PRVM_DECLARE_clientfieldedict
#undef PRVM_DECLARE_clientfieldfunction
#undef PRVM_DECLARE_menufieldfloat
#undef PRVM_DECLARE_menufieldvector
#undef PRVM_DECLARE_menufieldstring
#undef PRVM_DECLARE_menufieldedict
#undef PRVM_DECLARE_menufieldfunction
#undef PRVM_DECLARE_serverfunction
#undef PRVM_DECLARE_clientfunction
#undef PRVM_DECLARE_menufunction
#undef PRVM_DECLARE_field
#undef PRVM_DECLARE_global
#undef PRVM_DECLARE_function
};

#define SV_REQGLOBALS (sizeof(sv_reqglobals) / sizeof(prvm_required_field_t))

prvm_required_field_t sv_reqglobals[] =
{
#define PRVM_DECLARE_serverglobalfloat(x) {ev_float, #x},
#define PRVM_DECLARE_serverglobalvector(x) {ev_vector, #x},
#define PRVM_DECLARE_serverglobalstring(x) {ev_string, #x},
#define PRVM_DECLARE_serverglobaledict(x) {ev_entity, #x},
#define PRVM_DECLARE_serverglobalfunction(x) {ev_function, #x},
#define PRVM_DECLARE_clientglobalfloat(x)
#define PRVM_DECLARE_clientglobalvector(x)
#define PRVM_DECLARE_clientglobalstring(x)
#define PRVM_DECLARE_clientglobaledict(x)
#define PRVM_DECLARE_clientglobalfunction(x)
#define PRVM_DECLARE_menuglobalfloat(x)
#define PRVM_DECLARE_menuglobalvector(x)
#define PRVM_DECLARE_menuglobalstring(x)
#define PRVM_DECLARE_menuglobaledict(x)
#define PRVM_DECLARE_menuglobalfunction(x)
#define PRVM_DECLARE_serverfieldfloat(x)
#define PRVM_DECLARE_serverfieldvector(x)
#define PRVM_DECLARE_serverfieldstring(x)
#define PRVM_DECLARE_serverfieldedict(x)
#define PRVM_DECLARE_serverfieldfunction(x)
#define PRVM_DECLARE_clientfieldfloat(x)
#define PRVM_DECLARE_clientfieldvector(x)
#define PRVM_DECLARE_clientfieldstring(x)
#define PRVM_DECLARE_clientfieldedict(x)
#define PRVM_DECLARE_clientfieldfunction(x)
#define PRVM_DECLARE_menufieldfloat(x)
#define PRVM_DECLARE_menufieldvector(x)
#define PRVM_DECLARE_menufieldstring(x)
#define PRVM_DECLARE_menufieldedict(x)
#define PRVM_DECLARE_menufieldfunction(x)
#define PRVM_DECLARE_serverfunction(x)
#define PRVM_DECLARE_clientfunction(x)
#define PRVM_DECLARE_menufunction(x)
#define PRVM_DECLARE_field(x)
#define PRVM_DECLARE_global(x)
#define PRVM_DECLARE_function(x)
#include "prvm_offsets.h"
#undef PRVM_DECLARE_serverglobalfloat
#undef PRVM_DECLARE_serverglobalvector
#undef PRVM_DECLARE_serverglobalstring
#undef PRVM_DECLARE_serverglobaledict
#undef PRVM_DECLARE_serverglobalfunction
#undef PRVM_DECLARE_clientglobalfloat
#undef PRVM_DECLARE_clientglobalvector
#undef PRVM_DECLARE_clientglobalstring
#undef PRVM_DECLARE_clientglobaledict
#undef PRVM_DECLARE_clientglobalfunction
#undef PRVM_DECLARE_menuglobalfloat
#undef PRVM_DECLARE_menuglobalvector
#undef PRVM_DECLARE_menuglobalstring
#undef PRVM_DECLARE_menuglobaledict
#undef PRVM_DECLARE_menuglobalfunction
#undef PRVM_DECLARE_serverfieldfloat
#undef PRVM_DECLARE_serverfieldvector
#undef PRVM_DECLARE_serverfieldstring
#undef PRVM_DECLARE_serverfieldedict
#undef PRVM_DECLARE_serverfieldfunction
#undef PRVM_DECLARE_clientfieldfloat
#undef PRVM_DECLARE_clientfieldvector
#undef PRVM_DECLARE_clientfieldstring
#undef PRVM_DECLARE_clientfieldedict
#undef PRVM_DECLARE_clientfieldfunction
#undef PRVM_DECLARE_menufieldfloat
#undef PRVM_DECLARE_menufieldvector
#undef PRVM_DECLARE_menufieldstring
#undef PRVM_DECLARE_menufieldedict
#undef PRVM_DECLARE_menufieldfunction
#undef PRVM_DECLARE_serverfunction
#undef PRVM_DECLARE_clientfunction
#undef PRVM_DECLARE_menufunction
#undef PRVM_DECLARE_field
#undef PRVM_DECLARE_global
#undef PRVM_DECLARE_function
};



//============================================================================

static void SV_AreaStats_f(void)
{
	World_PrintAreaStats(&sv.world, "server");
}

/*
===============
SV_Init
===============
*/
void SV_Init (void)
{
	// init the csqc progs cvars, since they are updated/used by the server code
	// TODO: fix this since this is a quick hack to make some of [515]'s broken code run ;) [9/13/2006 Black]
	extern cvar_t csqc_progname;	//[515]: csqc crc check and right csprogs name according to progs.dat
	extern cvar_t csqc_progcrc;
	extern cvar_t csqc_progsize;
	extern cvar_t csqc_usedemoprogs;

	Cvar_RegisterVariable(&sv_worldmessage);
	Cvar_RegisterVariable(&sv_worldname);
	Cvar_RegisterVariable(&sv_worldnamenoextension);
	Cvar_RegisterVariable(&sv_worldbasename);

	Cvar_RegisterVariable (&csqc_progname);
	Cvar_RegisterVariable (&csqc_progcrc);
	Cvar_RegisterVariable (&csqc_progsize);
	Cvar_RegisterVariable (&csqc_usedemoprogs);

	Cmd_AddCommand("sv_saveentfile", SV_SaveEntFile_f, "save map entities to .ent file (to allow external editing)");
	Cmd_AddCommand("sv_areastats", SV_AreaStats_f, "prints statistics on entity culling during collision traces");
	Cmd_AddCommand_WithClientCommand("sv_startdownload", NULL, SV_StartDownload_f, "begins sending a file to the client (network protocol use only)");
	Cmd_AddCommand_WithClientCommand("download", NULL, SV_Download_f, "downloads a specified file from the server");

	Cvar_RegisterVariable (&sv_disablenotify);
	Cvar_RegisterVariable (&coop);
	Cvar_RegisterVariable (&deathmatch);
	Cvar_RegisterVariable (&fraglimit);
	Cvar_RegisterVariable (&gamecfg);
	Cvar_RegisterVariable (&noexit);
	Cvar_RegisterVariable (&nomonsters);
	Cvar_RegisterVariable (&pausable);
	Cvar_RegisterVariable (&pr_checkextension);
	Cvar_RegisterVariable (&samelevel);
	Cvar_RegisterVariable (&skill);
	Cvar_RegisterVariable (&slowmo);
	Cvar_RegisterVariable (&sv_accelerate);
	Cvar_RegisterVariable (&sv_aim);
	Cvar_RegisterVariable (&sv_airaccel_qw);
	Cvar_RegisterVariable (&sv_airaccel_qw_stretchfactor);
	Cvar_RegisterVariable (&sv_airaccel_sideways_friction);
	Cvar_RegisterVariable (&sv_airaccelerate);
	Cvar_RegisterVariable (&sv_airstopaccelerate);
	Cvar_RegisterVariable (&sv_airstrafeaccelerate);
	Cvar_RegisterVariable (&sv_maxairstrafespeed);
	Cvar_RegisterVariable (&sv_airstrafeaccel_qw);
	Cvar_RegisterVariable (&sv_airspeedlimit_nonqw);
	Cvar_RegisterVariable (&sv_aircontrol);
	Cvar_RegisterVariable (&sv_aircontrol_power);
	Cvar_RegisterVariable (&sv_aircontrol_penalty);
	Cvar_RegisterVariable (&sv_allowdownloads);
	Cvar_RegisterVariable (&sv_allowdownloads_archive);
	Cvar_RegisterVariable (&sv_allowdownloads_config);
	Cvar_RegisterVariable (&sv_allowdownloads_dlcache);
	Cvar_RegisterVariable (&sv_allowdownloads_inarchive);
	Cvar_RegisterVariable (&sv_areagrid_mingridsize);
	Cvar_RegisterVariable (&sv_checkforpacketsduringsleep);
	Cvar_RegisterVariable (&sv_clmovement_enable);
	Cvar_RegisterVariable (&sv_clmovement_minping);
	Cvar_RegisterVariable (&sv_clmovement_minping_disabletime);
	Cvar_RegisterVariable (&sv_clmovement_inputtimeout);
	Cvar_RegisterVariable (&sv_cullentities_nevercullbmodels);
	Cvar_RegisterVariable (&sv_cullentities_pvs);
	Cvar_RegisterVariable (&sv_cullentities_stats);
	Cvar_RegisterVariable (&sv_cullentities_trace);
	Cvar_RegisterVariable (&sv_cullentities_trace_delay);
	Cvar_RegisterVariable (&sv_cullentities_trace_delay_players);
	Cvar_RegisterVariable (&sv_cullentities_trace_enlarge);
	Cvar_RegisterVariable (&sv_cullentities_trace_eyejitter);
	Cvar_RegisterVariable (&sv_cullentities_trace_entityocclusion);
	Cvar_RegisterVariable (&sv_cullentities_trace_prediction);
	Cvar_RegisterVariable (&sv_cullentities_trace_prediction_time);
	Cvar_RegisterVariable (&sv_cullentities_trace_samples);
	Cvar_RegisterVariable (&sv_cullentities_trace_samples_extra);
	Cvar_RegisterVariable (&sv_cullentities_trace_samples_players);
	Cvar_RegisterVariable (&sv_debugmove);
	Cvar_RegisterVariable (&sv_echobprint);
	Cvar_RegisterVariable (&sv_edgefriction);
	Cvar_RegisterVariable (&sv_entpatch);
	Cvar_RegisterVariable (&sv_fixedframeratesingleplayer);
	Cvar_RegisterVariable (&sv_freezenonclients);
	Cvar_RegisterVariable (&sv_friction);
	Cvar_RegisterVariable (&sv_gameplayfix_blowupfallenzombies);
	Cvar_RegisterVariable (&sv_gameplayfix_consistentplayerprethink);
	Cvar_RegisterVariable (&sv_gameplayfix_delayprojectiles);
	Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid);
	Cvar_RegisterVariable (&sv_gameplayfix_droptofloorstartsolid_nudgetocorrect);
	Cvar_RegisterVariable (&sv_gameplayfix_easierwaterjump);
	Cvar_RegisterVariable (&sv_gameplayfix_findradiusdistancetobox);
	Cvar_RegisterVariable (&sv_gameplayfix_gravityunaffectedbyticrate);
	Cvar_RegisterVariable (&sv_gameplayfix_grenadebouncedownslopes);
	Cvar_RegisterVariable (&sv_gameplayfix_multiplethinksperframe);
	Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse);
	Cvar_RegisterVariable (&sv_gameplayfix_noairborncorpse_allowsuspendeditems);
	Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid);
	Cvar_RegisterVariable (&sv_gameplayfix_nudgeoutofsolid_separation);
	Cvar_RegisterVariable (&sv_gameplayfix_q2airaccelerate);
	Cvar_RegisterVariable (&sv_gameplayfix_nogravityonground);
	Cvar_RegisterVariable (&sv_gameplayfix_setmodelrealbox);
	Cvar_RegisterVariable (&sv_gameplayfix_slidemoveprojectiles);
	Cvar_RegisterVariable (&sv_gameplayfix_stepdown);
	Cvar_RegisterVariable (&sv_gameplayfix_stepmultipletimes);
	Cvar_RegisterVariable (&sv_gameplayfix_nostepmoveonsteepslopes);
	Cvar_RegisterVariable (&sv_gameplayfix_swiminbmodels);
	Cvar_RegisterVariable (&sv_gameplayfix_upwardvelocityclearsongroundflag);
	Cvar_RegisterVariable (&sv_gameplayfix_downtracesupportsongroundflag);
	Cvar_RegisterVariable (&sv_gameplayfix_q1bsptracelinereportstexture);
	Cvar_RegisterVariable (&sv_gameplayfix_unstickplayers);
	Cvar_RegisterVariable (&sv_gameplayfix_unstickentities);
	Cvar_RegisterVariable (&sv_gameplayfix_fixedcheckwatertransition);
	Cvar_RegisterVariable (&sv_gravity);
	Cvar_RegisterVariable (&sv_init_frame_count);
	Cvar_RegisterVariable (&sv_idealpitchscale);
	Cvar_RegisterVariable (&sv_jumpstep);
	Cvar_RegisterVariable (&sv_jumpvelocity);
	Cvar_RegisterVariable (&sv_maxairspeed);
	Cvar_RegisterVariable (&sv_maxrate);
	Cvar_RegisterVariable (&sv_maxspeed);
	Cvar_RegisterVariable (&sv_maxvelocity);
	Cvar_RegisterVariable (&sv_nostep);
	Cvar_RegisterVariable (&sv_playerphysicsqc);
	Cvar_RegisterVariable (&sv_progs);
	Cvar_RegisterVariable (&sv_protocolname);
	Cvar_RegisterVariable (&sv_random_seed);
	Cvar_RegisterVariable (&sv_ratelimitlocalplayer);
	Cvar_RegisterVariable (&sv_sound_land);
	Cvar_RegisterVariable (&sv_sound_watersplash);
	Cvar_RegisterVariable (&sv_stepheight);
	Cvar_RegisterVariable (&sv_stopspeed);
	Cvar_RegisterVariable (&sv_wallfriction);
	Cvar_RegisterVariable (&sv_wateraccelerate);
	Cvar_RegisterVariable (&sv_waterfriction);
	Cvar_RegisterVariable (&sv_warsowbunny_airforwardaccel);
	Cvar_RegisterVariable (&sv_warsowbunny_accel);
	Cvar_RegisterVariable (&sv_warsowbunny_topspeed);
	Cvar_RegisterVariable (&sv_warsowbunny_turnaccel);
	Cvar_RegisterVariable (&sv_warsowbunny_backtosideratio);
	Cvar_RegisterVariable (&sv_onlycsqcnetworking);
	Cvar_RegisterVariable (&sv_areadebug);
	Cvar_RegisterVariable (&sys_ticrate);
	Cvar_RegisterVariable (&teamplay);
	Cvar_RegisterVariable (&timelimit);
	Cvar_RegisterVariable (&sv_threaded);

	Cvar_RegisterVariable (&saved1);
	Cvar_RegisterVariable (&saved2);
	Cvar_RegisterVariable (&saved3);
	Cvar_RegisterVariable (&saved4);
	Cvar_RegisterVariable (&savedgamecfg);
	Cvar_RegisterVariable (&scratch1);
	Cvar_RegisterVariable (&scratch2);
	Cvar_RegisterVariable (&scratch3);
	Cvar_RegisterVariable (&scratch4);
	Cvar_RegisterVariable (&temp1);

	// LordHavoc: Nehahra uses these to pass data around cutscene demos
	Cvar_RegisterVariable (&nehx00);
	Cvar_RegisterVariable (&nehx01);
	Cvar_RegisterVariable (&nehx02);
	Cvar_RegisterVariable (&nehx03);
	Cvar_RegisterVariable (&nehx04);
	Cvar_RegisterVariable (&nehx05);
	Cvar_RegisterVariable (&nehx06);
	Cvar_RegisterVariable (&nehx07);
	Cvar_RegisterVariable (&nehx08);
	Cvar_RegisterVariable (&nehx09);
	Cvar_RegisterVariable (&nehx10);
	Cvar_RegisterVariable (&nehx11);
	Cvar_RegisterVariable (&nehx12);
	Cvar_RegisterVariable (&nehx13);
	Cvar_RegisterVariable (&nehx14);
	Cvar_RegisterVariable (&nehx15);
	Cvar_RegisterVariable (&nehx16);
	Cvar_RegisterVariable (&nehx17);
	Cvar_RegisterVariable (&nehx18);
	Cvar_RegisterVariable (&nehx19);
	Cvar_RegisterVariable (&cutscene); // for Nehahra but useful to other mods as well

	Cvar_RegisterVariable (&sv_autodemo_perclient);
	Cvar_RegisterVariable (&sv_autodemo_perclient_nameformat);
	Cvar_RegisterVariable (&sv_autodemo_perclient_discardable);

	Cvar_RegisterVariable (&halflifebsp);
	Cvar_RegisterVariable (&sv_mapformat_is_quake2);
	Cvar_RegisterVariable (&sv_mapformat_is_quake3);

	sv_mempool = Mem_AllocPool("server", 0, NULL);
}

static void SV_SaveEntFile_f(void)
{
	char vabuf[1024];
	if (!sv.active || !sv.worldmodel)
	{
		Con_Print("Not running a server\n");
		return;
	}
	FS_WriteFile(va(vabuf, sizeof(vabuf), "%s.ent", sv.worldnamenoextension), sv.worldmodel->brush.entities, (fs_offset_t)strlen(sv.worldmodel->brush.entities));
}


/*
=============================================================================

EVENT MESSAGES

=============================================================================
*/

/*
==================
SV_StartParticle

Make sure the event gets sent to all clients
==================
*/
void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
{
	int i;

	if (sv.datagram.cursize > MAX_PACKETFRAGMENT-18)
		return;
	MSG_WriteByte (&sv.datagram, svc_particle);
	MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
	MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
	MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
	for (i=0 ; i<3 ; i++)
		MSG_WriteChar (&sv.datagram, (int)bound(-128, dir[i]*16, 127));
	MSG_WriteByte (&sv.datagram, count);
	MSG_WriteByte (&sv.datagram, color);
	SV_FlushBroadcastMessages();
}

/*
==================
SV_StartEffect

Make sure the event gets sent to all clients
==================
*/
void SV_StartEffect (vec3_t org, int modelindex, int startframe, int framecount, int framerate)
{
	if (modelindex >= 256 || startframe >= 256)
	{
		if (sv.datagram.cursize > MAX_PACKETFRAGMENT-19)
			return;
		MSG_WriteByte (&sv.datagram, svc_effect2);
		MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
		MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
		MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
		MSG_WriteShort (&sv.datagram, modelindex);
		MSG_WriteShort (&sv.datagram, startframe);
		MSG_WriteByte (&sv.datagram, framecount);
		MSG_WriteByte (&sv.datagram, framerate);
	}
	else
	{
		if (sv.datagram.cursize > MAX_PACKETFRAGMENT-17)
			return;
		MSG_WriteByte (&sv.datagram, svc_effect);
		MSG_WriteCoord (&sv.datagram, org[0], sv.protocol);
		MSG_WriteCoord (&sv.datagram, org[1], sv.protocol);
		MSG_WriteCoord (&sv.datagram, org[2], sv.protocol);
		MSG_WriteByte (&sv.datagram, modelindex);
		MSG_WriteByte (&sv.datagram, startframe);
		MSG_WriteByte (&sv.datagram, framecount);
		MSG_WriteByte (&sv.datagram, framerate);
	}
	SV_FlushBroadcastMessages();
}

/*
==================
SV_StartSound

Each entity can have eight independant sound sources, like voice,
weapon, feet, etc.

Channel 0 is an auto-allocate channel, the others override anything
already running on that entity/channel pair.

An attenuation of 0 will play full volume everywhere in the level.
Larger attenuations will drop off.  (max 4 attenuation)

==================
*/
void SV_StartSound (prvm_edict_t *entity, int channel, const char *sample, int nvolume, float attenuation, qboolean reliable, float speed)
{
	prvm_prog_t *prog = SVVM_prog;
	sizebuf_t *dest;
	int sound_num, field_mask, i, ent, speed4000;

	dest = (reliable ? &sv.reliable_datagram : &sv.datagram);

	if (nvolume < 0 || nvolume > 255)
	{
		Con_Printf ("SV_StartSound: volume = %i\n", nvolume);
		return;
	}

	if (attenuation < 0 || attenuation > 4)
	{
		Con_Printf ("SV_StartSound: attenuation = %f\n", attenuation);
		return;
	}

	if (!IS_CHAN(channel))
	{
		Con_Printf ("SV_StartSound: channel = %i\n", channel);
		return;
	}

	channel = CHAN_ENGINE2NET(channel);

	if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
		return;

// find precache number for sound
	sound_num = SV_SoundIndex(sample, 1);
	if (!sound_num)
		return;

	ent = PRVM_NUM_FOR_EDICT(entity);

	speed4000 = (int)floor(speed * 4000.0f + 0.5f);
	field_mask = 0;
	if (nvolume != DEFAULT_SOUND_PACKET_VOLUME)
		field_mask |= SND_VOLUME;
	if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
		field_mask |= SND_ATTENUATION;
	if (speed4000 && speed4000 != 4000)
		field_mask |= SND_SPEEDUSHORT4000;
	if (ent >= 8192 || channel < 0 || channel > 7)
		field_mask |= SND_LARGEENTITY;
	if (sound_num >= 256)
		field_mask |= SND_LARGESOUND;

// directed messages go only to the entity they are targeted on
	MSG_WriteByte (dest, svc_sound);
	MSG_WriteByte (dest, field_mask);
	if (field_mask & SND_VOLUME)
		MSG_WriteByte (dest, nvolume);
	if (field_mask & SND_ATTENUATION)
		MSG_WriteByte (dest, (int)(attenuation*64));
	if (field_mask & SND_SPEEDUSHORT4000)
		MSG_WriteShort (dest, speed4000);
	if (field_mask & SND_LARGEENTITY)
	{
		MSG_WriteShort (dest, ent);
		MSG_WriteChar (dest, channel);
	}
	else
		MSG_WriteShort (dest, (ent<<3) | channel);
	if ((field_mask & SND_LARGESOUND) || sv.protocol == PROTOCOL_NEHAHRABJP2)
		MSG_WriteShort (dest, sound_num);
	else
		MSG_WriteByte (dest, sound_num);
	for (i = 0;i < 3;i++)
		MSG_WriteCoord (dest, PRVM_serveredictvector(entity, origin)[i]+0.5*(PRVM_serveredictvector(entity, mins)[i]+PRVM_serveredictvector(entity, maxs)[i]), sv.protocol);

	// TODO do we have to do anything here when dest is &sv.reliable_datagram?
	if(!reliable)
		SV_FlushBroadcastMessages();
}

/*
==================
SV_StartPointSound

Nearly the same logic as SV_StartSound, except an origin
instead of an entity is provided and channel is omitted.

The entity sent to the client is 0 (world) and the channel
is 0 (CHAN_AUTO).  SND_LARGEENTITY will never occur in this
function, therefore the check for it is omitted.

==================
*/
void SV_StartPointSound (vec3_t origin, const char *sample, int nvolume, float attenuation, float speed)
{
	int sound_num, field_mask, i, speed4000;

	if (nvolume < 0 || nvolume > 255)
	{
		Con_Printf ("SV_StartPointSound: volume = %i\n", nvolume);
		return;
	}

	if (attenuation < 0 || attenuation > 4)
	{
		Con_Printf ("SV_StartPointSound: attenuation = %f\n", attenuation);
		return;
	}

	if (sv.datagram.cursize > MAX_PACKETFRAGMENT-21)
		return;

	// find precache number for sound
	sound_num = SV_SoundIndex(sample, 1);
	if (!sound_num)
		return;

	speed4000 = (int)(speed * 40.0f);
	field_mask = 0;
	if (nvolume != DEFAULT_SOUND_PACKET_VOLUME)
		field_mask |= SND_VOLUME;
	if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
		field_mask |= SND_ATTENUATION;
	if (sound_num >= 256)
		field_mask |= SND_LARGESOUND;
	if (speed4000 && speed4000 != 4000)
		field_mask |= SND_SPEEDUSHORT4000;

// directed messages go only to the entity they are targeted on
	MSG_WriteByte (&sv.datagram, svc_sound);
	MSG_WriteByte (&sv.datagram, field_mask);
	if (field_mask & SND_VOLUME)
		MSG_WriteByte (&sv.datagram, nvolume);
	if (field_mask & SND_ATTENUATION)
		MSG_WriteByte (&sv.datagram, (int)(attenuation*64));
	if (field_mask & SND_SPEEDUSHORT4000)
		MSG_WriteShort (&sv.datagram, speed4000);
	// Always write entnum 0 for the world entity
	MSG_WriteShort (&sv.datagram, (0<<3) | 0);
	if (field_mask & SND_LARGESOUND)
		MSG_WriteShort (&sv.datagram, sound_num);
	else
		MSG_WriteByte (&sv.datagram, sound_num);
	for (i = 0;i < 3;i++)
		MSG_WriteCoord (&sv.datagram, origin[i], sv.protocol);
	SV_FlushBroadcastMessages();
}

/*
==============================================================================

CLIENT SPAWNING

==============================================================================
*/

/*
================
SV_SendServerinfo

Sends the first message from the server to a connected client.
This will be sent on the initial connection and upon each server load.
================
*/
void SV_SendServerinfo (client_t *client)
{
	prvm_prog_t *prog = SVVM_prog;
	int i;
	char message[128];
	char vabuf[1024];

	// we know that this client has a netconnection and thus is not a bot

	// edicts get reallocated on level changes, so we need to update it here
	client->edict = PRVM_EDICT_NUM((client - svs.clients) + 1);

	// clear cached stuff that depends on the level
	client->weaponmodel[0] = 0;
	client->weaponmodelindex = 0;

	// LordHavoc: clear entityframe tracking
	client->latestframenum = 0;

	// initialize the movetime, so a speedhack can't make use of the time before this client joined
	client->cmd.time = sv.time;

	if (client->entitydatabase)
		EntityFrame_FreeDatabase(client->entitydatabase);
	if (client->entitydatabase4)
		EntityFrame4_FreeDatabase(client->entitydatabase4);
	if (client->entitydatabase5)
		EntityFrame5_FreeDatabase(client->entitydatabase5);

	memset(client->stats, 0, sizeof(client->stats));
	memset(client->statsdeltabits, 0, sizeof(client->statsdeltabits));

	if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_NEHAHRABJP && sv.protocol != PROTOCOL_NEHAHRABJP2 && sv.protocol != PROTOCOL_NEHAHRABJP3)
	{
		if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3)
			client->entitydatabase = EntityFrame_AllocDatabase(sv_mempool);
		else if (sv.protocol == PROTOCOL_DARKPLACES4)
			client->entitydatabase4 = EntityFrame4_AllocDatabase(sv_mempool);
		else
			client->entitydatabase5 = EntityFrame5_AllocDatabase(sv_mempool);
	}

	// reset csqc entity versions
	for (i = 0;i < prog->max_edicts;i++)
	{
		client->csqcentityscope[i] = 0;
		client->csqcentitysendflags[i] = 0xFFFFFF;
	}
	for (i = 0;i < NUM_CSQCENTITYDB_FRAMES;i++)
	{
		client->csqcentityframehistory[i].num = 0;
		client->csqcentityframehistory[i].framenum = -1;
	}
	client->csqcnumedicts = 0;
	client->csqcentityframehistory_next = 0;

	SZ_Clear (&client->netconnection->message);
	MSG_WriteByte (&client->netconnection->message, svc_print);
	dpsnprintf (message, sizeof (message), "\nServer: %s build %s (progs %i crc)\n", gamename, buildstring, prog->filecrc);
	MSG_WriteString (&client->netconnection->message,message);

	SV_StopDemoRecording(client); // to split up demos into different files
	if(sv_autodemo_perclient.integer)
	{
		char demofile[MAX_OSPATH];
		char ipaddress[MAX_QPATH];
		size_t j;

		// start a new demo file
		LHNETADDRESS_ToString(&(client->netconnection->peeraddress), ipaddress, sizeof(ipaddress), true);
		for(j = 0; ipaddress[j]; ++j)
			if(!isalnum(ipaddress[j]))
				ipaddress[j] = '-';
		dpsnprintf (demofile, sizeof(demofile), "%s_%s_%d_%s.dem", Sys_TimeString (sv_autodemo_perclient_nameformat.string), sv.worldbasename, PRVM_NUM_FOR_EDICT(client->edict), ipaddress);

		SV_StartDemoRecording(client, demofile, -1);
	}

	//[515]: init csprogs according to version of svprogs, check the crc, etc.
	if (sv.csqc_progname[0])
	{
		Con_DPrintf("sending csqc info to client (\"%s\" with size %i and crc %i)\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);
		MSG_WriteByte (&client->netconnection->message, svc_stufftext);
		MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progname %s\n", sv.csqc_progname));
		MSG_WriteByte (&client->netconnection->message, svc_stufftext);
		MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progsize %i\n", sv.csqc_progsize));
		MSG_WriteByte (&client->netconnection->message, svc_stufftext);
		MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "csqc_progcrc %i\n", sv.csqc_progcrc));

		if(client->sv_demo_file != NULL)
		{
			int k;
			static char buf[NET_MAXMESSAGE];
			sizebuf_t sb;

			sb.data = (unsigned char *) buf;
			sb.maxsize = sizeof(buf);
			k = 0;
			while(MakeDownloadPacket(sv.csqc_progname, svs.csqc_progdata, sv.csqc_progsize, sv.csqc_progcrc, k++, &sb, sv.protocol))
				SV_WriteDemoMessage(client, &sb, false);
		}

		//[515]: init stufftext string (it is sent before svc_serverinfo)
		if (PRVM_GetString(prog, PRVM_serverglobalstring(SV_InitCmd)))
		{
			MSG_WriteByte (&client->netconnection->message, svc_stufftext);
			MSG_WriteString (&client->netconnection->message, va(vabuf, sizeof(vabuf), "%s\n", PRVM_GetString(prog, PRVM_serverglobalstring(SV_InitCmd))));
		}
	}

	//if (sv_allowdownloads.integer)
	// always send the info that the server supports the protocol, even if downloads are forbidden
	// only because of that, the CSQC exception can work
	{
		MSG_WriteByte (&client->netconnection->message, svc_stufftext);
		MSG_WriteString (&client->netconnection->message, "cl_serverextension_download 2\n");
	}

	// send at this time so it's guaranteed to get executed at the right time
	{
		client_t *save;
		save = host_client;
		host_client = client;
		Curl_SendRequirements();
		host_client = save;
	}

	MSG_WriteByte (&client->netconnection->message, svc_serverinfo);
	MSG_WriteLong (&client->netconnection->message, Protocol_NumberForEnum(sv.protocol));
	MSG_WriteByte (&client->netconnection->message, svs.maxclients);

	if (!coop.integer && deathmatch.integer)
		MSG_WriteByte (&client->netconnection->message, GAME_DEATHMATCH);
	else
		MSG_WriteByte (&client->netconnection->message, GAME_COOP);

	MSG_WriteString (&client->netconnection->message,PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)));

	for (i = 1;i < MAX_MODELS && sv.model_precache[i][0];i++)
		MSG_WriteString (&client->netconnection->message, sv.model_precache[i]);
	MSG_WriteByte (&client->netconnection->message, 0);

	for (i = 1;i < MAX_SOUNDS && sv.sound_precache[i][0];i++)
		MSG_WriteString (&client->netconnection->message, sv.sound_precache[i]);
	MSG_WriteByte (&client->netconnection->message, 0);

// send music
	MSG_WriteByte (&client->netconnection->message, svc_cdtrack);
	MSG_WriteByte (&client->netconnection->message, (int)PRVM_serveredictfloat(prog->edicts, sounds));
	MSG_WriteByte (&client->netconnection->message, (int)PRVM_serveredictfloat(prog->edicts, sounds));

// set view
// store this in clientcamera, too
	client->clientcamera = PRVM_NUM_FOR_EDICT(client->edict);
	MSG_WriteByte (&client->netconnection->message, svc_setview);
	MSG_WriteShort (&client->netconnection->message, client->clientcamera);

	MSG_WriteByte (&client->netconnection->message, svc_signonnum);
	MSG_WriteByte (&client->netconnection->message, 1);

	client->prespawned = false;		// need prespawn, spawn, etc
	client->spawned = false;		// need prespawn, spawn, etc
	client->begun = false;			// need prespawn, spawn, etc
	client->sendsignon = 1;			// send this message, and increment to 2, 2 will be set to 0 by the prespawn command

	// clear movement info until client enters the new level properly
	memset(&client->cmd, 0, sizeof(client->cmd));
	client->movesequence = 0;
	client->movement_highestsequence_seen = 0;
	memset(&client->movement_count, 0, sizeof(client->movement_count));
#ifdef NUM_PING_TIMES
	for (i = 0;i < NUM_PING_TIMES;i++)
		client->ping_times[i] = 0;
	client->num_pings = 0;
#endif
	client->ping = 0;

	// allow the client some time to send his keepalives, even if map loading took ages
	client->netconnection->timeout = realtime + net_connecttimeout.value;
}

/*
================
SV_ConnectClient

Initializes a client_t for a new net connection.  This will only be called
once for a player each game, not once for each level change.
================
*/
void SV_ConnectClient (int clientnum, netconn_t *netconnection)
{
	prvm_prog_t *prog = SVVM_prog;
	client_t		*client;
	int				i;

	client = svs.clients + clientnum;

// set up the client_t
	if (sv.loadgame)
	{
		float backupparms[NUM_SPAWN_PARMS];
		memcpy(backupparms, client->spawn_parms, sizeof(backupparms));
		memset(client, 0, sizeof(*client));
		memcpy(client->spawn_parms, backupparms, sizeof(backupparms));
	}
	else
		memset(client, 0, sizeof(*client));
	client->active = true;
	client->netconnection = netconnection;

	Con_DPrintf("Client %s connected\n", client->netconnection ? client->netconnection->address : "botclient");

	if(client->netconnection && client->netconnection->crypto.authenticated)
	{
		Con_Printf("%s connection to %s has been established: client is %s@%s%.*s, I am %.*s@%s%.*s\n",
				client->netconnection->crypto.use_aes ? "Encrypted" : "Authenticated",
				client->netconnection->address,
				client->netconnection->crypto.client_idfp[0] ? client->netconnection->crypto.client_idfp : "-",
				(client->netconnection->crypto.client_issigned || !client->netconnection->crypto.client_keyfp[0]) ? "" : "~",
				crypto_keyfp_recommended_length, client->netconnection->crypto.client_keyfp[0] ? client->netconnection->crypto.client_keyfp : "-",
				crypto_keyfp_recommended_length, client->netconnection->crypto.server_idfp[0] ? client->netconnection->crypto.server_idfp : "-",
				(client->netconnection->crypto.server_issigned || !client->netconnection->crypto.server_keyfp[0]) ? "" : "~",
				crypto_keyfp_recommended_length, client->netconnection->crypto.server_keyfp[0] ? client->netconnection->crypto.server_keyfp : "-"
				);
	}

	strlcpy(client->name, "unconnected", sizeof(client->name));
	strlcpy(client->old_name, "unconnected", sizeof(client->old_name));
	client->prespawned = false;
	client->spawned = false;
	client->begun = false;
	client->edict = PRVM_EDICT_NUM(clientnum+1);
	if (client->netconnection)
		client->netconnection->message.allowoverflow = true;		// we can catch it
	// prepare the unreliable message buffer
	client->unreliablemsg.data = client->unreliablemsg_data;
	client->unreliablemsg.maxsize = sizeof(client->unreliablemsg_data);
	// updated by receiving "rate" command from client, this is also the default if not using a DP client
	client->rate = 1000000000;
	client->connecttime = realtime;

	if (!sv.loadgame)
	{
		// call the progs to get default spawn parms for the new client
		// set self to world to intentionally cause errors with broken SetNewParms code in some mods
		PRVM_serverglobalfloat(time) = sv.time;
		PRVM_serverglobaledict(self) = 0;
		prog->ExecuteProgram(prog, PRVM_serverfunction(SetNewParms), "QC function SetNewParms is missing");
		for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
			client->spawn_parms[i] = (&PRVM_serverglobalfloat(parm1))[i];

		// set up the entity for this client (including .colormap, .team, etc)
		PRVM_ED_ClearEdict(prog, client->edict);
	}

	// don't call SendServerinfo for a fresh botclient because its fields have
	// not been set up by the qc yet
	if (client->netconnection)
		SV_SendServerinfo (client);
	else
		client->prespawned = client->spawned = client->begun = true;
}


/*
===============================================================================

FRAME UPDATES

===============================================================================
*/

/*
=============================================================================

The PVS must include a small area around the client to allow head bobbing
or other small motion on the client side.  Otherwise, a bob might cause an
entity that should be visible to not show up, especially when the bob
crosses a waterline.

=============================================================================
*/

static qboolean SV_PrepareEntityForSending (prvm_edict_t *ent, entity_state_t *cs, int enumber)
{
	prvm_prog_t *prog = SVVM_prog;
	int i;
	unsigned int sendflags;
	unsigned int version;
	unsigned int modelindex, effects, flags, glowsize, lightstyle, lightpflags, light[4], specialvisibilityradius;
	unsigned int customizeentityforclient;
	unsigned int sendentity;
	float f;
	prvm_vec_t *v;
	vec3_t cullmins, cullmaxs;
	dp_model_t *model;

	// fast path for games that do not use legacy entity networking
	// note: still networks clients even if they are legacy
	sendentity = PRVM_serveredictfunction(ent, SendEntity);
	if (sv_onlycsqcnetworking.integer && !sendentity && enumber > svs.maxclients)
		return false;

	// this 2 billion unit check is actually to detect NAN origins
	// (we really don't want to send those)
	if (!(VectorLength2(PRVM_serveredictvector(ent, origin)) < 2000000000.0*2000000000.0))
		return false;

	// EF_NODRAW prevents sending for any reason except for your own
	// client, so we must keep all clients in this superset
	effects = (unsigned)PRVM_serveredictfloat(ent, effects);

	// we can omit invisible entities with no effects that are not clients
	// LordHavoc: this could kill tags attached to an invisible entity, I
	// just hope we never have to support that case
	i = (int)PRVM_serveredictfloat(ent, modelindex);
	modelindex = (i >= 1 && i < MAX_MODELS && PRVM_serveredictstring(ent, model) && *PRVM_GetString(prog, PRVM_serveredictstring(ent, model)) && sv.models[i]) ? i : 0;

	flags = 0;
	i = (int)(PRVM_serveredictfloat(ent, glow_size) * 0.25f);
	glowsize = (unsigned char)bound(0, i, 255);
	if (PRVM_serveredictfloat(ent, glow_trail))
		flags |= RENDER_GLOWTRAIL;
	if (PRVM_serveredictedict(ent, viewmodelforclient))
		flags |= RENDER_VIEWMODEL;

	v = PRVM_serveredictvector(ent, color);
	f = v[0]*256;
	light[0] = (unsigned short)bound(0, f, 65535);
	f = v[1]*256;
	light[1] = (unsigned short)bound(0, f, 65535);
	f = v[2]*256;
	light[2] = (unsigned short)bound(0, f, 65535);
	f = PRVM_serveredictfloat(ent, light_lev);
	light[3] = (unsigned short)bound(0, f, 65535);
	lightstyle = (unsigned char)PRVM_serveredictfloat(ent, style);
	lightpflags = (unsigned char)PRVM_serveredictfloat(ent, pflags);

	if (gamemode == GAME_TENEBRAE)
	{
		// tenebrae's EF_FULLDYNAMIC conflicts with Q2's EF_NODRAW
		if (effects & 16)
		{
			effects &= ~16;
			lightpflags |= PFLAGS_FULLDYNAMIC;
		}
		// tenebrae's EF_GREEN conflicts with DP's EF_ADDITIVE
		if (effects & 32)
		{
			effects &= ~32;
			light[0] = (int)(0.2*256);
			light[1] = (int)(1.0*256);
			light[2] = (int)(0.2*256);
			light[3] = 200;
			lightpflags |= PFLAGS_FULLDYNAMIC;
		}
	}

	specialvisibilityradius = 0;
	if (lightpflags & PFLAGS_FULLDYNAMIC)
		specialvisibilityradius = max(specialvisibilityradius, light[3]);
	if (glowsize)
		specialvisibilityradius = max(specialvisibilityradius, glowsize * 4);
	if (flags & RENDER_GLOWTRAIL)
		specialvisibilityradius = max(specialvisibilityradius, 100);
	if (effects & (EF_BRIGHTFIELD | EF_MUZZLEFLASH | EF_BRIGHTLIGHT | EF_DIMLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
	{
		if (effects & EF_BRIGHTFIELD)
			specialvisibilityradius = max(specialvisibilityradius, 80);
		if (effects & EF_MUZZLEFLASH)
			specialvisibilityradius = max(specialvisibilityradius, 100);
		if (effects & EF_BRIGHTLIGHT)
			specialvisibilityradius = max(specialvisibilityradius, 400);
		if (effects & EF_DIMLIGHT)
			specialvisibilityradius = max(specialvisibilityradius, 200);
		if (effects & EF_RED)
			specialvisibilityradius = max(specialvisibilityradius, 200);
		if (effects & EF_BLUE)
			specialvisibilityradius = max(specialvisibilityradius, 200);
		if (effects & EF_FLAME)
			specialvisibilityradius = max(specialvisibilityradius, 250);
		if (effects & EF_STARDUST)
			specialvisibilityradius = max(specialvisibilityradius, 100);
	}

	// early culling checks
	// (final culling is done by SV_MarkWriteEntityStateToClient)
	customizeentityforclient = PRVM_serveredictfunction(ent, customizeentityforclient);
	if (!customizeentityforclient && enumber > svs.maxclients && (!modelindex && !specialvisibilityradius))
		return false;

	*cs = defaultstate;
	cs->active = ACTIVE_NETWORK;
	cs->number = enumber;
	VectorCopy(PRVM_serveredictvector(ent, origin), cs->origin);
	VectorCopy(PRVM_serveredictvector(ent, angles), cs->angles);
	cs->flags = flags;
	cs->effects = effects;
	cs->colormap = (unsigned)PRVM_serveredictfloat(ent, colormap);
	cs->modelindex = modelindex;
	cs->skin = (unsigned)PRVM_serveredictfloat(ent, skin);
	cs->frame = (unsigned)PRVM_serveredictfloat(ent, frame);
	cs->viewmodelforclient = PRVM_serveredictedict(ent, viewmodelforclient);
	cs->exteriormodelforclient = PRVM_serveredictedict(ent, exteriormodeltoclient);
	cs->nodrawtoclient = PRVM_serveredictedict(ent, nodrawtoclient);
	cs->drawonlytoclient = PRVM_serveredictedict(ent, drawonlytoclient);
	cs->customizeentityforclient = customizeentityforclient;
	cs->tagentity = PRVM_serveredictedict(ent, tag_entity);
	cs->tagindex = (unsigned char)PRVM_serveredictfloat(ent, tag_index);
	cs->glowsize = glowsize;
	cs->traileffectnum = PRVM_serveredictfloat(ent, traileffectnum);

	// don't need to init cs->colormod because the defaultstate did that for us
	//cs->colormod[0] = cs->colormod[1] = cs->colormod[2] = 32;
	v = PRVM_serveredictvector(ent, colormod);
	if (VectorLength2(v))
	{
		i = (int)(v[0] * 32.0f);cs->colormod[0] = bound(0, i, 255);
		i = (int)(v[1] * 32.0f);cs->colormod[1] = bound(0, i, 255);
		i = (int)(v[2] * 32.0f);cs->colormod[2] = bound(0, i, 255);
	}

	// don't need to init cs->glowmod because the defaultstate did that for us
	//cs->glowmod[0] = cs->glowmod[1] = cs->glowmod[2] = 32;
	v = PRVM_serveredictvector(ent, glowmod);
	if (VectorLength2(v))
	{
		i = (int)(v[0] * 32.0f);cs->glowmod[0] = bound(0, i, 255);
		i = (int)(v[1] * 32.0f);cs->glowmod[1] = bound(0, i, 255);
		i = (int)(v[2] * 32.0f);cs->glowmod[2] = bound(0, i, 255);
	}

	cs->modelindex = modelindex;

	cs->alpha = 255;
	f = (PRVM_serveredictfloat(ent, alpha) * 255.0f);
	if (f)
	{
		i = (int)f;
		cs->alpha = (unsigned char)bound(0, i, 255);
	}
	// halflife
	f = (PRVM_serveredictfloat(ent, renderamt));
	if (f)
	{
		i = (int)f;
		cs->alpha = (unsigned char)bound(0, i, 255);
	}

	cs->scale = 16;
	f = (PRVM_serveredictfloat(ent, scale) * 16.0f);
	if (f)
	{
		i = (int)f;
		cs->scale = (unsigned char)bound(0, i, 255);
	}

	cs->glowcolor = 254;
	f = PRVM_serveredictfloat(ent, glow_color);
	if (f)
		cs->glowcolor = (int)f;

	if (PRVM_serveredictfloat(ent, fullbright))
		cs->effects |= EF_FULLBRIGHT;

	f = PRVM_serveredictfloat(ent, modelflags);
	if (f)
		cs->effects |= ((unsigned int)f & 0xff) << 24;

	if (PRVM_serveredictfloat(ent, movetype) == MOVETYPE_STEP)
		cs->flags |= RENDER_STEP;
	if (cs->number != sv.writeentitiestoclient_cliententitynumber && (cs->effects & EF_LOWPRECISION) && cs->origin[0] >= -32768 && cs->origin[1] >= -32768 && cs->origin[2] >= -32768 && cs->origin[0] <= 32767 && cs->origin[1] <= 32767 && cs->origin[2] <= 32767)
		cs->flags |= RENDER_LOWPRECISION;
	if (PRVM_serveredictfloat(ent, colormap) >= 1024)
		cs->flags |= RENDER_COLORMAPPED;
	if (cs->viewmodelforclient)
		cs->flags |= RENDER_VIEWMODEL; // show relative to the view

	if (PRVM_serveredictfloat(ent, sendcomplexanimation))
	{
		cs->flags |= RENDER_COMPLEXANIMATION;
		if (PRVM_serveredictfloat(ent, skeletonindex) >= 1)
			cs->skeletonobject = ent->priv.server->skeleton;
		cs->framegroupblend[0].frame = PRVM_serveredictfloat(ent, frame);
		cs->framegroupblend[1].frame = PRVM_serveredictfloat(ent, frame2);
		cs->framegroupblend[2].frame = PRVM_serveredictfloat(ent, frame3);
		cs->framegroupblend[3].frame = PRVM_serveredictfloat(ent, frame4);
		cs->framegroupblend[0].start = PRVM_serveredictfloat(ent, frame1time);
		cs->framegroupblend[1].start = PRVM_serveredictfloat(ent, frame2time);
		cs->framegroupblend[2].start = PRVM_serveredictfloat(ent, frame3time);
		cs->framegroupblend[3].start = PRVM_serveredictfloat(ent, frame4time);
		cs->framegroupblend[1].lerp = PRVM_serveredictfloat(ent, lerpfrac);
		cs->framegroupblend[2].lerp = PRVM_serveredictfloat(ent, lerpfrac3);
		cs->framegroupblend[3].lerp = PRVM_serveredictfloat(ent, lerpfrac4);
		cs->framegroupblend[0].lerp = 1.0f - cs->framegroupblend[1].lerp - cs->framegroupblend[2].lerp - cs->framegroupblend[3].lerp;
		cs->frame = 0; // don't need the legacy frame
	}

	cs->light[0] = light[0];
	cs->light[1] = light[1];
	cs->light[2] = light[2];
	cs->light[3] = light[3];
	cs->lightstyle = lightstyle;
	cs->lightpflags = lightpflags;

	cs->specialvisibilityradius = specialvisibilityradius;

	// calculate the visible box of this entity (don't use the physics box
	// as that is often smaller than a model, and would not count
	// specialvisibilityradius)
	if ((model = SV_GetModelByIndex(modelindex)) && (model->type != mod_null))
	{
		float scale = cs->scale * (1.0f / 16.0f);
		if (cs->angles[0] || cs->angles[2]) // pitch and roll
		{
			VectorMA(cs->origin, scale, model->rotatedmins, cullmins);
			VectorMA(cs->origin, scale, model->rotatedmaxs, cullmaxs);
		}
		else if (cs->angles[1] || ((effects | model->effects) & EF_ROTATE))
		{
			VectorMA(cs->origin, scale, model->yawmins, cullmins);
			VectorMA(cs->origin, scale, model->yawmaxs, cullmaxs);
		}
		else
		{
			VectorMA(cs->origin, scale, model->normalmins, cullmins);
			VectorMA(cs->origin, scale, model->normalmaxs, cullmaxs);
		}
	}
	else
	{
		// if there is no model (or it could not be loaded), use the physics box
		VectorAdd(cs->origin, PRVM_serveredictvector(ent, mins), cullmins);
		VectorAdd(cs->origin, PRVM_serveredictvector(ent, maxs), cullmaxs);
	}
	if (specialvisibilityradius)
	{
		cullmins[0] = min(cullmins[0], cs->origin[0] - specialvisibilityradius);
		cullmins[1] = min(cullmins[1], cs->origin[1] - specialvisibilityradius);
		cullmins[2] = min(cullmins[2], cs->origin[2] - specialvisibilityradius);
		cullmaxs[0] = max(cullmaxs[0], cs->origin[0] + specialvisibilityradius);
		cullmaxs[1] = max(cullmaxs[1], cs->origin[1] + specialvisibilityradius);
		cullmaxs[2] = max(cullmaxs[2], cs->origin[2] + specialvisibilityradius);
	}

	// calculate center of bbox for network prioritization purposes
	VectorMAM(0.5f, cullmins, 0.5f, cullmaxs, cs->netcenter);

	// if culling box has moved, update pvs cluster links
	if (!VectorCompare(cullmins, ent->priv.server->cullmins) || !VectorCompare(cullmaxs, ent->priv.server->cullmaxs))
	{
		VectorCopy(cullmins, ent->priv.server->cullmins);
		VectorCopy(cullmaxs, ent->priv.server->cullmaxs);
		// a value of -1 for pvs_numclusters indicates that the links are not
		// cached, and should be re-tested each time, this is the case if the
		// culling box touches too many pvs clusters to store, or if the world
		// model does not support FindBoxClusters
		ent->priv.server->pvs_numclusters = -1;
		if (sv.worldmodel && sv.worldmodel->brush.FindBoxClusters)
		{
			i = sv.worldmodel->brush.FindBoxClusters(sv.worldmodel, cullmins, cullmaxs, MAX_ENTITYCLUSTERS, ent->priv.server->pvs_clusterlist);
			if (i <= MAX_ENTITYCLUSTERS)
				ent->priv.server->pvs_numclusters = i;
		}
	}

	// we need to do some csqc entity upkeep here
	// get self.SendFlags and clear them
	// (to let the QC know that they've been read)
	if (sendentity)
	{
		sendflags = (unsigned int)PRVM_serveredictfloat(ent, SendFlags);
		PRVM_serveredictfloat(ent, SendFlags) = 0;
		// legacy self.Version system
		if ((version = (unsigned int)PRVM_serveredictfloat(ent, Version)))
		{
			if (sv.csqcentityversion[enumber] != version)
				sendflags = 0xFFFFFF;
			sv.csqcentityversion[enumber] = version;
		}
		// move sendflags into the per-client sendflags
		if (sendflags)
			for (i = 0;i < svs.maxclients;i++)
				svs.clients[i].csqcentitysendflags[enumber] |= sendflags;
		// mark it as inactive for non-csqc networking
		cs->active = ACTIVE_SHARED;
	}

	return true;
}

static void SV_PrepareEntitiesForSending(void)
{
	prvm_prog_t *prog = SVVM_prog;
	int e;
	prvm_edict_t *ent;
	// send all entities that touch the pvs
	sv.numsendentities = 0;
	sv.sendentitiesindex[0] = NULL;
	memset(sv.sendentitiesindex, 0, prog->num_edicts * sizeof(*sv.sendentitiesindex));
	for (e = 1, ent = PRVM_NEXT_EDICT(prog->edicts);e < prog->num_edicts;e++, ent = PRVM_NEXT_EDICT(ent))
	{
		if (!ent->priv.server->free && SV_PrepareEntityForSending(ent, sv.sendentities + sv.numsendentities, e))
		{
			sv.sendentitiesindex[e] = sv.sendentities + sv.numsendentities;
			sv.numsendentities++;
		}
	}
}

#define MAX_LINEOFSIGHTTRACES 64

qboolean SV_CanSeeBox(int numtraces, vec_t eyejitter, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
{
	prvm_prog_t *prog = SVVM_prog;
	float pitchsign;
	float alpha;
	float starttransformed[3], endtransformed[3];
	float boxminstransformed[3], boxmaxstransformed[3];
	float localboxcenter[3], localboxextents[3], localboxmins[3], localboxmaxs[3];
	int blocked = 0;
	int traceindex;
	int originalnumtouchedicts;
	int numtouchedicts = 0;
	int touchindex;
	matrix4x4_t matrix, imatrix;
	dp_model_t *model;
	prvm_edict_t *touch;
	static prvm_edict_t *touchedicts[MAX_EDICTS];
	vec3_t eyemins, eyemaxs, start;
	vec3_t boxmins, boxmaxs;
	vec3_t clipboxmins, clipboxmaxs;
	vec3_t endpoints[MAX_LINEOFSIGHTTRACES];

	numtraces = min(numtraces, MAX_LINEOFSIGHTTRACES);

	// jitter the eye location within this box
	eyemins[0] = eye[0] - eyejitter;
	eyemaxs[0] = eye[0] + eyejitter;
	eyemins[1] = eye[1] - eyejitter;
	eyemaxs[1] = eye[1] + eyejitter;
	eyemins[2] = eye[2] - eyejitter;
	eyemaxs[2] = eye[2] + eyejitter;
	// expand the box a little
	boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
	boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
	boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
	boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
	boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
	boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];

	VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, endpoints[0]);
	for (traceindex = 1;traceindex < numtraces;traceindex++)
		VectorSet(endpoints[traceindex], lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));

	// calculate sweep box for the entire swarm of traces
	VectorCopy(eyemins, clipboxmins);
	VectorCopy(eyemaxs, clipboxmaxs);
	for (traceindex = 0;traceindex < numtraces;traceindex++)
	{
		clipboxmins[0] = min(clipboxmins[0], endpoints[traceindex][0]);
		clipboxmins[1] = min(clipboxmins[1], endpoints[traceindex][1]);
		clipboxmins[2] = min(clipboxmins[2], endpoints[traceindex][2]);
		clipboxmaxs[0] = max(clipboxmaxs[0], endpoints[traceindex][0]);
		clipboxmaxs[1] = max(clipboxmaxs[1], endpoints[traceindex][1]);
		clipboxmaxs[2] = max(clipboxmaxs[2], endpoints[traceindex][2]);
	}

	// get the list of entities in the sweep box
	if (sv_cullentities_trace_entityocclusion.integer)
		numtouchedicts = SV_EntitiesInBox(clipboxmins, clipboxmaxs, MAX_EDICTS, touchedicts);
	if (numtouchedicts > MAX_EDICTS)
	{
		// this never happens
		Con_Printf("SV_EntitiesInBox returned %i edicts, max was %i\n", numtouchedicts, MAX_EDICTS);
		numtouchedicts = MAX_EDICTS;
	}
	// iterate the entities found in the sweep box and filter them
	originalnumtouchedicts = numtouchedicts;
	numtouchedicts = 0;
	for (touchindex = 0;touchindex < originalnumtouchedicts;touchindex++)
	{
		touch = touchedicts[touchindex];
		if (PRVM_serveredictfloat(touch, solid) != SOLID_BSP)
			continue;
		model = SV_GetModelFromEdict(touch);
		if (!model || !model->brush.TraceLineOfSight)
			continue;
		// skip obviously transparent entities
		alpha = PRVM_serveredictfloat(touch, alpha);
		if (alpha && alpha < 1)
			continue;
		if ((int)PRVM_serveredictfloat(touch, effects) & EF_ADDITIVE)
			continue;
		touchedicts[numtouchedicts++] = touch;
	}

	// now that we have a filtered list of "interesting" entities, fire each
	// ray against all of them, this gives us an early-out case when something
	// is visible (which it often is)

	for (traceindex = 0;traceindex < numtraces;traceindex++)
	{
		VectorSet(start, lhrandom(eyemins[0], eyemaxs[0]), lhrandom(eyemins[1], eyemaxs[1]), lhrandom(eyemins[2], eyemaxs[2]));
		// check world occlusion
		if (sv.worldmodel && sv.worldmodel->brush.TraceLineOfSight)
			if (!sv.worldmodel->brush.TraceLineOfSight(sv.worldmodel, start, endpoints[traceindex], boxmins, boxmaxs))
				continue;
		for (touchindex = 0;touchindex < numtouchedicts;touchindex++)
		{
			touch = touchedicts[touchindex];
			model = SV_GetModelFromEdict(touch);
			if(model && model->brush.TraceLineOfSight)
			{
				// get the entity matrix
				pitchsign = SV_GetPitchSign(prog, touch);
				Matrix4x4_CreateFromQuakeEntity(&matrix, PRVM_serveredictvector(touch, origin)[0], PRVM_serveredictvector(touch, origin)[1], PRVM_serveredictvector(touch, origin)[2], pitchsign * PRVM_serveredictvector(touch, angles)[0], PRVM_serveredictvector(touch, angles)[1], PRVM_serveredictvector(touch, angles)[2], 1);
				Matrix4x4_Invert_Simple(&imatrix, &matrix);
				// see if the ray hits this entity
				Matrix4x4_Transform(&imatrix, start, starttransformed);
				Matrix4x4_Transform(&imatrix, endpoints[traceindex], endtransformed);
				Matrix4x4_Transform(&imatrix, boxmins, boxminstransformed);
				Matrix4x4_Transform(&imatrix, boxmaxs, boxmaxstransformed);
				// transform the AABB to local space
				VectorMAM(0.5f, boxminstransformed, 0.5f, boxmaxstransformed, localboxcenter);
				localboxextents[0] = fabs(boxmaxstransformed[0] - localboxcenter[0]);
				localboxextents[1] = fabs(boxmaxstransformed[1] - localboxcenter[1]);
				localboxextents[2] = fabs(boxmaxstransformed[2] - localboxcenter[2]);
				localboxmins[0] = localboxcenter[0] - localboxextents[0];
				localboxmins[1] = localboxcenter[1] - localboxextents[1];
				localboxmins[2] = localboxcenter[2] - localboxextents[2];
				localboxmaxs[0] = localboxcenter[0] + localboxextents[0];
				localboxmaxs[1] = localboxcenter[1] + localboxextents[1];
				localboxmaxs[2] = localboxcenter[2] + localboxextents[2];
				if (!model->brush.TraceLineOfSight(model, starttransformed, endtransformed, localboxmins, localboxmaxs))
				{
					blocked++;
					break;
				}
			}
		}
		// check if the ray was blocked
		if (touchindex < numtouchedicts)
			continue;
		// return if the ray was not blocked
		return true;
	}

	// no rays survived
	return false;
}

static void SV_MarkWriteEntityStateToClient(entity_state_t *s)
{
	prvm_prog_t *prog = SVVM_prog;
	int isbmodel;
	dp_model_t *model;
	prvm_edict_t *ed;
	if (sv.sententitiesconsideration[s->number] == sv.sententitiesmark)
		return;
	sv.sententitiesconsideration[s->number] = sv.sententitiesmark;
	sv.writeentitiestoclient_stats_totalentities++;

	if (s->customizeentityforclient)
	{
		PRVM_serverglobalfloat(time) = sv.time;
		PRVM_serverglobaledict(self) = s->number;
		PRVM_serverglobaledict(other) = sv.writeentitiestoclient_cliententitynumber;
		prog->ExecuteProgram(prog, s->customizeentityforclient, "customizeentityforclient: NULL function");
		if(!PRVM_G_FLOAT(OFS_RETURN) || !SV_PrepareEntityForSending(PRVM_EDICT_NUM(s->number), s, s->number))
			return;
	}

	// never reject player
	if (s->number != sv.writeentitiestoclient_cliententitynumber)
	{
		// check various rejection conditions
		if (s->nodrawtoclient == sv.writeentitiestoclient_cliententitynumber)
			return;
		if (s->drawonlytoclient && s->drawonlytoclient != sv.writeentitiestoclient_cliententitynumber)
			return;
		if (s->effects & EF_NODRAW)
			return;
		// LordHavoc: only send entities with a model or important effects
		if (!s->modelindex && s->specialvisibilityradius == 0)
			return;

		isbmodel = (model = SV_GetModelByIndex(s->modelindex)) != NULL && model->name[0] == '*';
		// viewmodels don't have visibility checking
		if (s->viewmodelforclient)
		{
			if (s->viewmodelforclient != sv.writeentitiestoclient_cliententitynumber)
				return;
		}
		else if (s->tagentity)
		{
			// tag attached entities simply check their parent
			if (!sv.sendentitiesindex[s->tagentity])
				return;
			SV_MarkWriteEntityStateToClient(sv.sendentitiesindex[s->tagentity]);
			if (sv.sententities[s->tagentity] != sv.sententitiesmark)
				return;
		}
		// always send world submodels in newer protocols because they don't
		// generate much traffic (in old protocols they hog bandwidth)
		// but only if sv_cullentities_nevercullbmodels is off
		else if (!(s->effects & EF_NODEPTHTEST) && (!isbmodel || !sv_cullentities_nevercullbmodels.integer || sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE))
		{
			// entity has survived every check so far, check if visible
			ed = PRVM_EDICT_NUM(s->number);

			// if not touching a visible leaf
			if (sv_cullentities_pvs.integer && !r_novis.integer && !r_trippy.integer && sv.writeentitiestoclient_pvsbytes)
			{
				if (ed->priv.server->pvs_numclusters < 0)
				{
					// entity too big for clusters list
					if (sv.worldmodel && sv.worldmodel->brush.BoxTouchingPVS && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, sv.writeentitiestoclient_pvs, ed->priv.server->cullmins, ed->priv.server->cullmaxs))
					{
						sv.writeentitiestoclient_stats_culled_pvs++;
						return;
					}
				}
				else
				{
					int i;
					// check cached clusters list
					for (i = 0;i < ed->priv.server->pvs_numclusters;i++)
						if (CHECKPVSBIT(sv.writeentitiestoclient_pvs, ed->priv.server->pvs_clusterlist[i]))
							break;
					if (i == ed->priv.server->pvs_numclusters)
					{
						sv.writeentitiestoclient_stats_culled_pvs++;
						return;
					}
				}
			}

			// or not seen by random tracelines
			if (sv_cullentities_trace.integer && !isbmodel && sv.worldmodel && sv.worldmodel->brush.TraceLineOfSight && !r_trippy.integer)
			{
				int samples =
					s->number <= svs.maxclients
						? sv_cullentities_trace_samples_players.integer
						:
					s->specialvisibilityradius
						? sv_cullentities_trace_samples_extra.integer
						: sv_cullentities_trace_samples.integer;
				float enlarge = sv_cullentities_trace_enlarge.value;

				if(samples > 0)
				{
					int eyeindex;
					for (eyeindex = 0;eyeindex < sv.writeentitiestoclient_numeyes;eyeindex++)
						if(SV_CanSeeBox(samples, sv_cullentities_trace_eyejitter.value, enlarge, sv.writeentitiestoclient_eyes[eyeindex], ed->priv.server->cullmins, ed->priv.server->cullmaxs))
							break;
					if(eyeindex < sv.writeentitiestoclient_numeyes)
						svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number] =
							realtime + (
								s->number <= svs.maxclients
									? sv_cullentities_trace_delay_players.value
									: sv_cullentities_trace_delay.value
							);
					else if (realtime > svs.clients[sv.writeentitiestoclient_clientnumber].visibletime[s->number])
					{
						sv.writeentitiestoclient_stats_culled_trace++;
						return;
					}
				}
			}
		}
	}

	// this just marks it for sending
	// FIXME: it would be more efficient to send here, but the entity
	// compressor isn't that flexible
	sv.writeentitiestoclient_stats_visibleentities++;
	sv.sententities[s->number] = sv.sententitiesmark;
}

#if MAX_LEVELNETWORKEYES > 0
#define MAX_EYE_RECURSION 1 // increase if recursion gets supported by portals
static void SV_AddCameraEyes(void)
{
	prvm_prog_t *prog = SVVM_prog;
	int e, i, j, k;
	prvm_edict_t *ed;
	static int cameras[MAX_LEVELNETWORKEYES];
	static vec3_t camera_origins[MAX_LEVELNETWORKEYES];
	static int eye_levels[MAX_CLIENTNETWORKEYES];
	int n_cameras = 0;
	vec3_t mi, ma;

	for(i = 0; i < sv.writeentitiestoclient_numeyes; ++i)
		eye_levels[i] = 0;

	// check line of sight to portal entities and add them to PVS
	for (e = 1, ed = PRVM_NEXT_EDICT(prog->edicts);e < prog->num_edicts;e++, ed = PRVM_NEXT_EDICT(ed))
	{
		if (!ed->priv.server->free)
		{
			if(PRVM_serveredictfunction(ed, camera_transform))
			{
				PRVM_serverglobalfloat(time) = sv.time;
				PRVM_serverglobaledict(self) = e;
				PRVM_serverglobaledict(other) = sv.writeentitiestoclient_cliententitynumber;
				VectorCopy(sv.writeentitiestoclient_eyes[0], PRVM_serverglobalvector(trace_endpos));
				VectorCopy(sv.writeentitiestoclient_eyes[0], PRVM_G_VECTOR(OFS_PARM0));
				VectorClear(PRVM_G_VECTOR(OFS_PARM1));
				prog->ExecuteProgram(prog, PRVM_serveredictfunction(ed, camera_transform), "QC function e.camera_transform is missing");
				if(!VectorCompare(PRVM_serverglobalvector(trace_endpos), sv.writeentitiestoclient_eyes[0]))
				{
					VectorCopy(PRVM_serverglobalvector(trace_endpos), camera_origins[n_cameras]);
					cameras[n_cameras] = e;
					++n_cameras;
					if(n_cameras >= MAX_LEVELNETWORKEYES)
						break;
				}
			}
		}
	}

	if(!n_cameras)
		return;

	// i is loop counter, is reset to 0 when an eye got added
	// j is camera index to check
	for(i = 0, j = 0; sv.writeentitiestoclient_numeyes < MAX_CLIENTNETWORKEYES && i < n_cameras; ++i, ++j, j %= n_cameras)
	{
		if(!cameras[j])
			continue;
		ed = PRVM_EDICT_NUM(cameras[j]);
		VectorAdd(PRVM_serveredictvector(ed, origin), PRVM_serveredictvector(ed, mins), mi);
		VectorAdd(PRVM_serveredictvector(ed, origin), PRVM_serveredictvector(ed, maxs), ma);
		for(k = 0; k < sv.writeentitiestoclient_numeyes; ++k)
		if(eye_levels[k] <= MAX_EYE_RECURSION)
		{
			if(SV_CanSeeBox(sv_cullentities_trace_samples.integer, sv_cullentities_trace_eyejitter.value, sv_cullentities_trace_enlarge.value, sv.writeentitiestoclient_eyes[k], mi, ma))
			{
				eye_levels[sv.writeentitiestoclient_numeyes] = eye_levels[k] + 1;
				VectorCopy(camera_origins[j], sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes]);
				// Con_Printf("added eye %d: %f %f %f because we can see %f %f %f .. %f %f %f from eye %d\n", j, sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes][0], sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes][1], sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes][2], mi[0], mi[1], mi[2], ma[0], ma[1], ma[2], k);
				sv.writeentitiestoclient_numeyes++;
				cameras[j] = 0;
				i = 0;
				break;
			}
		}
	}
}
#else
void SV_AddCameraEyes(void)
{
}
#endif

static void SV_WriteEntitiesToClient(client_t *client, prvm_edict_t *clent, sizebuf_t *msg, int maxsize)
{
	prvm_prog_t *prog = SVVM_prog;
	qboolean need_empty = false;
	int i, numsendstates, numcsqcsendstates;
	entity_state_t *s;
	prvm_edict_t *camera;
	qboolean success;
	vec3_t eye;

	// if there isn't enough space to accomplish anything, skip it
	if (msg->cursize + 25 > maxsize)
		return;

	sv.writeentitiestoclient_msg = msg;
	sv.writeentitiestoclient_clientnumber = client - svs.clients;

	sv.writeentitiestoclient_stats_culled_pvs = 0;
	sv.writeentitiestoclient_stats_culled_trace = 0;
	sv.writeentitiestoclient_stats_visibleentities = 0;
	sv.writeentitiestoclient_stats_totalentities = 0;
	sv.writeentitiestoclient_numeyes = 0;

	// get eye location
	sv.writeentitiestoclient_cliententitynumber = PRVM_EDICT_TO_PROG(clent); // LordHavoc: for comparison purposes
	camera = PRVM_EDICT_NUM( client->clientcamera );
	VectorAdd(PRVM_serveredictvector(camera, origin), PRVM_serveredictvector(clent, view_ofs), eye);
	sv.writeentitiestoclient_pvsbytes = 0;
	// get the PVS values for the eye location, later FatPVS calls will merge
	if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
		sv.writeentitiestoclient_pvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, eye, 8, sv.writeentitiestoclient_pvs, sizeof(sv.writeentitiestoclient_pvs), sv.writeentitiestoclient_pvsbytes != 0);

	// add the eye to a list for SV_CanSeeBox tests
	VectorCopy(eye, sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes]);
	sv.writeentitiestoclient_numeyes++;

	// calculate predicted eye origin for SV_CanSeeBox tests
	if (sv_cullentities_trace_prediction.integer)
	{
		vec_t predtime = bound(0, host_client->ping, sv_cullentities_trace_prediction_time.value);
		vec3_t predeye;
		VectorMA(eye, predtime, PRVM_serveredictvector(camera, velocity), predeye);
		if (SV_CanSeeBox(1, 0, 0, eye, predeye, predeye))
		{
			VectorCopy(predeye, sv.writeentitiestoclient_eyes[sv.writeentitiestoclient_numeyes]);
			sv.writeentitiestoclient_numeyes++;
		}
		//if (!sv.writeentitiestoclient_useprediction)
		//	Con_DPrintf("Trying to walk into solid in a pingtime... not predicting for culling\n");
	}

	SV_AddCameraEyes();

	// build PVS from the new eyes
	if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
		for(i = 1; i < sv.writeentitiestoclient_numeyes; ++i)
			sv.writeentitiestoclient_pvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, sv.writeentitiestoclient_eyes[i], 8, sv.writeentitiestoclient_pvs, sizeof(sv.writeentitiestoclient_pvs), sv.writeentitiestoclient_pvsbytes != 0);

	sv.sententitiesmark++;

	for (i = 0;i < sv.numsendentities;i++)
		SV_MarkWriteEntityStateToClient(sv.sendentities + i);

	numsendstates = 0;
	numcsqcsendstates = 0;
	for (i = 0;i < sv.numsendentities;i++)
	{
		s = &sv.sendentities[i];
		if (sv.sententities[s->number] == sv.sententitiesmark)
		{
			if(s->active == ACTIVE_NETWORK)
			{
				if (s->exteriormodelforclient)
				{
					if (s->exteriormodelforclient == sv.writeentitiestoclient_cliententitynumber)
						s->flags |= RENDER_EXTERIORMODEL;
					else
						s->flags &= ~RENDER_EXTERIORMODEL;
				}
				sv.writeentitiestoclient_sendstates[numsendstates++] = s;
			}
			else if(sv.sendentities[i].active == ACTIVE_SHARED)
				sv.writeentitiestoclient_csqcsendstates[numcsqcsendstates++] = s->number;
			else
				Con_Printf("entity %d is in sv.sendentities and marked, but not active, please breakpoint me\n", s->number);
		}
	}

	if (sv_cullentities_stats.integer)
		Con_Printf("client \"%s\" entities: %d total, %d visible, %d culled by: %d pvs %d trace\n", client->name, sv.writeentitiestoclient_stats_totalentities, sv.writeentitiestoclient_stats_visibleentities, sv.writeentitiestoclient_stats_culled_pvs + sv.writeentitiestoclient_stats_culled_trace, sv.writeentitiestoclient_stats_culled_pvs, sv.writeentitiestoclient_stats_culled_trace);

	if(client->entitydatabase5)
		need_empty = EntityFrameCSQC_WriteFrame(msg, maxsize, numcsqcsendstates, sv.writeentitiestoclient_csqcsendstates, client->entitydatabase5->latestframenum + 1);
	else
		EntityFrameCSQC_WriteFrame(msg, maxsize, numcsqcsendstates, sv.writeentitiestoclient_csqcsendstates, 0);

	// force every 16th frame to be not empty (or cl_movement replay takes
	// too long)
	// BTW, this should normally not kick in any more due to the check
	// below, except if the client stopped sending movement frames
	if(client->num_skippedentityframes >= 16)
		need_empty = true;

	// help cl_movement a bit more
	if(client->movesequence != client->lastmovesequence)
		need_empty = true;
	client->lastmovesequence = client->movesequence;

	if (client->entitydatabase5)
		success = EntityFrame5_WriteFrame(msg, maxsize, client->entitydatabase5, numsendstates, sv.writeentitiestoclient_sendstates, client - svs.clients + 1, client->movesequence, need_empty);
	else if (client->entitydatabase4)
	{
		success = EntityFrame4_WriteFrame(msg, maxsize, client->entitydatabase4, numsendstates, sv.writeentitiestoclient_sendstates);
		Protocol_WriteStatsReliable();
	}
	else if (client->entitydatabase)
	{
		success = EntityFrame_WriteFrame(msg, maxsize, client->entitydatabase, numsendstates, sv.writeentitiestoclient_sendstates, client - svs.clients + 1);
		Protocol_WriteStatsReliable();
	}
	else
	{
		success = EntityFrameQuake_WriteFrame(msg, maxsize, numsendstates, sv.writeentitiestoclient_sendstates);
		Protocol_WriteStatsReliable();
	}

	if(success)
		client->num_skippedentityframes = 0;
	else
		++client->num_skippedentityframes;
}

/*
=============
SV_CleanupEnts

=============
*/
static void SV_CleanupEnts (void)
{
	prvm_prog_t *prog = SVVM_prog;
	int		e;
	prvm_edict_t	*ent;

	ent = PRVM_NEXT_EDICT(prog->edicts);
	for (e=1 ; e<prog->num_edicts ; e++, ent = PRVM_NEXT_EDICT(ent))
		PRVM_serveredictfloat(ent, effects) = (int)PRVM_serveredictfloat(ent, effects) & ~EF_MUZZLEFLASH;
}

/*
==================
SV_WriteClientdataToMessage

==================
*/
void SV_WriteClientdataToMessage (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats)
{
	prvm_prog_t *prog = SVVM_prog;
	int		bits;
	int		i;
	prvm_edict_t	*other;
	int		items;
	vec3_t	punchvector;
	int		viewzoom;
	const char *s;
	float	*statsf = (float *)stats;
	float gravity;

//
// send a damage message
//
	if (PRVM_serveredictfloat(ent, dmg_take) || PRVM_serveredictfloat(ent, dmg_save))
	{
		other = PRVM_PROG_TO_EDICT(PRVM_serveredictedict(ent, dmg_inflictor));
		MSG_WriteByte (msg, svc_damage);
		MSG_WriteByte (msg, (int)PRVM_serveredictfloat(ent, dmg_save));
		MSG_WriteByte (msg, (int)PRVM_serveredictfloat(ent, dmg_take));
		for (i=0 ; i<3 ; i++)
			MSG_WriteCoord (msg, PRVM_serveredictvector(other, origin)[i] + 0.5*(PRVM_serveredictvector(other, mins)[i] + PRVM_serveredictvector(other, maxs)[i]), sv.protocol);

		PRVM_serveredictfloat(ent, dmg_take) = 0;
		PRVM_serveredictfloat(ent, dmg_save) = 0;
	}

//
// send the current viewpos offset from the view entity
//
	SV_SetIdealPitch ();		// how much to look up / down ideally

// a fixangle might get lost in a dropped packet.  Oh well.
	if(PRVM_serveredictfloat(ent, fixangle))
	{
		// angle fixing was requested by global thinking code...
		// so store the current angles for later use
		VectorCopy(PRVM_serveredictvector(ent, angles), host_client->fixangle_angles);
		host_client->fixangle_angles_set = TRUE;

		// and clear fixangle for the next frame
		PRVM_serveredictfloat(ent, fixangle) = 0;
	}

	if (host_client->fixangle_angles_set)
	{
		MSG_WriteByte (msg, svc_setangle);
		for (i=0 ; i < 3 ; i++)
			MSG_WriteAngle (msg, host_client->fixangle_angles[i], sv.protocol);
		host_client->fixangle_angles_set = FALSE;
	}

	// the runes are in serverflags, pack them into the items value, also pack
	// in the items2 value for mission pack huds
	// (used only in the mission packs, which do not use serverflags)
	items = (int)PRVM_serveredictfloat(ent, items) | ((int)PRVM_serveredictfloat(ent, items2) << 23) | ((int)PRVM_serverglobalfloat(serverflags) << 28);

	VectorCopy(PRVM_serveredictvector(ent, punchvector), punchvector);

	// cache weapon model name and index in client struct to save time
	// (this search can be almost 1% of cpu time!)
	s = PRVM_GetString(prog, PRVM_serveredictstring(ent, weaponmodel));
	if (strcmp(s, client->weaponmodel))
	{
		strlcpy(client->weaponmodel, s, sizeof(client->weaponmodel));
		client->weaponmodelindex = SV_ModelIndex(s, 1);
	}

	viewzoom = (int)(PRVM_serveredictfloat(ent, viewzoom) * 255.0f);
	if (viewzoom == 0)
		viewzoom = 255;

	bits = 0;

	if ((int)PRVM_serveredictfloat(ent, flags) & FL_ONGROUND)
		bits |= SU_ONGROUND;
	if (PRVM_serveredictfloat(ent, waterlevel) >= 2)
		bits |= SU_INWATER;
	if (PRVM_serveredictfloat(ent, idealpitch))
		bits |= SU_IDEALPITCH;

	for (i=0 ; i<3 ; i++)
	{
		if (PRVM_serveredictvector(ent, punchangle)[i])
			bits |= (SU_PUNCH1<<i);
		if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_NEHAHRABJP && sv.protocol != PROTOCOL_NEHAHRABJP2 && sv.protocol != PROTOCOL_NEHAHRABJP3)
			if (punchvector[i])
				bits |= (SU_PUNCHVEC1<<i);
		if (PRVM_serveredictvector(ent, velocity)[i])
			bits |= (SU_VELOCITY1<<i);
	}

	gravity = PRVM_serveredictfloat(ent, gravity);if (!gravity) gravity = 1.0f;

	memset(stats, 0, sizeof(int[MAX_CL_STATS]));
	stats[STAT_VIEWHEIGHT] = (int)PRVM_serveredictvector(ent, view_ofs)[2];
	stats[STAT_ITEMS] = items;
	stats[STAT_WEAPONFRAME] = (int)PRVM_serveredictfloat(ent, weaponframe);
	stats[STAT_ARMOR] = (int)PRVM_serveredictfloat(ent, armorvalue);
	stats[STAT_WEAPON] = client->weaponmodelindex;
	stats[STAT_HEALTH] = (int)PRVM_serveredictfloat(ent, health);
	stats[STAT_AMMO] = (int)PRVM_serveredictfloat(ent, currentammo);
	stats[STAT_SHELLS] = (int)PRVM_serveredictfloat(ent, ammo_shells);
	stats[STAT_NAILS] = (int)PRVM_serveredictfloat(ent, ammo_nails);
	stats[STAT_ROCKETS] = (int)PRVM_serveredictfloat(ent, ammo_rockets);
	stats[STAT_CELLS] = (int)PRVM_serveredictfloat(ent, ammo_cells);
	stats[STAT_ACTIVEWEAPON] = (int)PRVM_serveredictfloat(ent, weapon);
	stats[STAT_VIEWZOOM] = viewzoom;
	stats[STAT_TOTALSECRETS] = (int)PRVM_serverglobalfloat(total_secrets);
	stats[STAT_TOTALMONSTERS] = (int)PRVM_serverglobalfloat(total_monsters);
	// the QC bumps these itself by sending svc_'s, so we have to keep them
	// zero or they'll be corrected by the engine
	//stats[STAT_SECRETS] = PRVM_serverglobalfloat(found_secrets);
	//stats[STAT_MONSTERS] = PRVM_serverglobalfloat(killed_monsters);

	// movement settings for prediction
	// note: these are not sent in protocols with lower MAX_CL_STATS limits
	stats[STAT_MOVEFLAGS] = MOVEFLAG_VALID
		| (sv_gameplayfix_q2airaccelerate.integer ? MOVEFLAG_Q2AIRACCELERATE : 0)
		| (sv_gameplayfix_nogravityonground.integer ? MOVEFLAG_NOGRAVITYONGROUND : 0)
		| (sv_gameplayfix_gravityunaffectedbyticrate.integer ? MOVEFLAG_GRAVITYUNAFFECTEDBYTICRATE : 0)
	;
	statsf[STAT_MOVEVARS_TICRATE] = sys_ticrate.value;
	statsf[STAT_MOVEVARS_TIMESCALE] = slowmo.value;
	statsf[STAT_MOVEVARS_GRAVITY] = sv_gravity.value;
	statsf[STAT_MOVEVARS_STOPSPEED] = sv_stopspeed.value;
	statsf[STAT_MOVEVARS_MAXSPEED] = sv_maxspeed.value;
	statsf[STAT_MOVEVARS_SPECTATORMAXSPEED] = sv_maxspeed.value; // FIXME: QW has a separate cvar for this
	statsf[STAT_MOVEVARS_ACCELERATE] = sv_accelerate.value;
	statsf[STAT_MOVEVARS_AIRACCELERATE] = sv_airaccelerate.value >= 0 ? sv_airaccelerate.value : sv_accelerate.value;
	statsf[STAT_MOVEVARS_WATERACCELERATE] = sv_wateraccelerate.value >= 0 ? sv_wateraccelerate.value : sv_accelerate.value;
	statsf[STAT_MOVEVARS_ENTGRAVITY] = gravity;
	statsf[STAT_MOVEVARS_JUMPVELOCITY] = sv_jumpvelocity.value;
	statsf[STAT_MOVEVARS_EDGEFRICTION] = sv_edgefriction.value;
	statsf[STAT_MOVEVARS_MAXAIRSPEED] = sv_maxairspeed.value;
	statsf[STAT_MOVEVARS_STEPHEIGHT] = sv_stepheight.value;
	statsf[STAT_MOVEVARS_AIRACCEL_QW] = sv_airaccel_qw.value;
	statsf[STAT_MOVEVARS_AIRACCEL_QW_STRETCHFACTOR] = sv_airaccel_qw_stretchfactor.value;
	statsf[STAT_MOVEVARS_AIRACCEL_SIDEWAYS_FRICTION] = sv_airaccel_sideways_friction.value;
	statsf[STAT_MOVEVARS_FRICTION] = sv_friction.value;
	statsf[STAT_MOVEVARS_WATERFRICTION] = sv_waterfriction.value >= 0 ? sv_waterfriction.value : sv_friction.value;
	statsf[STAT_MOVEVARS_AIRSTOPACCELERATE] = sv_airstopaccelerate.value;
	statsf[STAT_MOVEVARS_AIRSTRAFEACCELERATE] = sv_airstrafeaccelerate.value;
	statsf[STAT_MOVEVARS_MAXAIRSTRAFESPEED] = sv_maxairstrafespeed.value;
	statsf[STAT_MOVEVARS_AIRSTRAFEACCEL_QW] = sv_airstrafeaccel_qw.value;
	statsf[STAT_MOVEVARS_AIRCONTROL] = sv_aircontrol.value;
	statsf[STAT_MOVEVARS_AIRCONTROL_POWER] = sv_aircontrol_power.value;
	statsf[STAT_MOVEVARS_AIRCONTROL_PENALTY] = sv_aircontrol_penalty.value;
	statsf[STAT_MOVEVARS_WARSOWBUNNY_AIRFORWARDACCEL] = sv_warsowbunny_airforwardaccel.value;
	statsf[STAT_MOVEVARS_WARSOWBUNNY_ACCEL] = sv_warsowbunny_accel.value;
	statsf[STAT_MOVEVARS_WARSOWBUNNY_TOPSPEED] = sv_warsowbunny_topspeed.value;
	statsf[STAT_MOVEVARS_WARSOWBUNNY_TURNACCEL] = sv_warsowbunny_turnaccel.value;
	statsf[STAT_MOVEVARS_WARSOWBUNNY_BACKTOSIDERATIO] = sv_warsowbunny_backtosideratio.value;
	statsf[STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW] = sv_airspeedlimit_nonqw.value;
	statsf[STAT_FRAGLIMIT] = fraglimit.value;
	statsf[STAT_TIMELIMIT] = timelimit.value;

	if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
	{
		if (stats[STAT_VIEWHEIGHT] != DEFAULT_VIEWHEIGHT) bits |= SU_VIEWHEIGHT;
		bits |= SU_ITEMS;
		if (stats[STAT_WEAPONFRAME]) bits |= SU_WEAPONFRAME;
		if (stats[STAT_ARMOR]) bits |= SU_ARMOR;
		bits |= SU_WEAPON;
		// FIXME: which protocols support this?  does PROTOCOL_DARKPLACES3 support viewzoom?
		if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
			if (viewzoom != 255)
				bits |= SU_VIEWZOOM;
	}

	if (bits >= 65536)
		bits |= SU_EXTEND1;
	if (bits >= 16777216)
		bits |= SU_EXTEND2;

	// send the data
	MSG_WriteByte (msg, svc_clientdata);
	MSG_WriteShort (msg, bits);
	if (bits & SU_EXTEND1)
		MSG_WriteByte(msg, bits >> 16);
	if (bits & SU_EXTEND2)
		MSG_WriteByte(msg, bits >> 24);

	if (bits & SU_VIEWHEIGHT)
		MSG_WriteChar (msg, stats[STAT_VIEWHEIGHT]);

	if (bits & SU_IDEALPITCH)
		MSG_WriteChar (msg, (int)PRVM_serveredictfloat(ent, idealpitch));

	for (i=0 ; i<3 ; i++)
	{
		if (bits & (SU_PUNCH1<<i))
		{
			if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
				MSG_WriteChar(msg, (int)PRVM_serveredictvector(ent, punchangle)[i]);
			else
				MSG_WriteAngle16i(msg, PRVM_serveredictvector(ent, punchangle)[i]);
		}
		if (bits & (SU_PUNCHVEC1<<i))
		{
			if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
				MSG_WriteCoord16i(msg, punchvector[i]);
			else
				MSG_WriteCoord32f(msg, punchvector[i]);
		}
		if (bits & (SU_VELOCITY1<<i))
		{
			if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
				MSG_WriteChar(msg, (int)(PRVM_serveredictvector(ent, velocity)[i] * (1.0f / 16.0f)));
			else
				MSG_WriteCoord32f(msg, PRVM_serveredictvector(ent, velocity)[i]);
		}
	}

	if (bits & SU_ITEMS)
		MSG_WriteLong (msg, stats[STAT_ITEMS]);

	if (sv.protocol == PROTOCOL_DARKPLACES5)
	{
		if (bits & SU_WEAPONFRAME)
			MSG_WriteShort (msg, stats[STAT_WEAPONFRAME]);
		if (bits & SU_ARMOR)
			MSG_WriteShort (msg, stats[STAT_ARMOR]);
		if (bits & SU_WEAPON)
			MSG_WriteShort (msg, stats[STAT_WEAPON]);
		MSG_WriteShort (msg, stats[STAT_HEALTH]);
		MSG_WriteShort (msg, stats[STAT_AMMO]);
		MSG_WriteShort (msg, stats[STAT_SHELLS]);
		MSG_WriteShort (msg, stats[STAT_NAILS]);
		MSG_WriteShort (msg, stats[STAT_ROCKETS]);
		MSG_WriteShort (msg, stats[STAT_CELLS]);
		MSG_WriteShort (msg, stats[STAT_ACTIVEWEAPON]);
		if (bits & SU_VIEWZOOM)
			MSG_WriteShort (msg, bound(0, stats[STAT_VIEWZOOM], 65535));
	}
	else if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
	{
		if (bits & SU_WEAPONFRAME)
			MSG_WriteByte (msg, stats[STAT_WEAPONFRAME]);
		if (bits & SU_ARMOR)
			MSG_WriteByte (msg, stats[STAT_ARMOR]);
		if (bits & SU_WEAPON)
		{
			if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
				MSG_WriteShort (msg, stats[STAT_WEAPON]);
			else
				MSG_WriteByte (msg, stats[STAT_WEAPON]);
		}
		MSG_WriteShort (msg, stats[STAT_HEALTH]);
		MSG_WriteByte (msg, stats[STAT_AMMO]);
		MSG_WriteByte (msg, stats[STAT_SHELLS]);
		MSG_WriteByte (msg, stats[STAT_NAILS]);
		MSG_WriteByte (msg, stats[STAT_ROCKETS]);
		MSG_WriteByte (msg, stats[STAT_CELLS]);
		if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_QUOTH || IS_OLDNEXUIZ_DERIVED(gamemode))
		{
			for (i = 0;i < 32;i++)
				if (stats[STAT_ACTIVEWEAPON] & (1<<i))
					break;
			MSG_WriteByte (msg, i);
		}
		else
			MSG_WriteByte (msg, stats[STAT_ACTIVEWEAPON]);
		if (bits & SU_VIEWZOOM)
		{
			if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4)
				MSG_WriteByte (msg, bound(0, stats[STAT_VIEWZOOM], 255));
			else
				MSG_WriteShort (msg, bound(0, stats[STAT_VIEWZOOM], 65535));
		}
	}
}

void SV_FlushBroadcastMessages(void)
{
	int i;
	client_t *client;
	if (sv.datagram.cursize <= 0)
		return;
	for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
	{
		if (!client->begun || !client->netconnection || client->unreliablemsg.cursize + sv.datagram.cursize > client->unreliablemsg.maxsize || client->unreliablemsg_splitpoints >= (int)(sizeof(client->unreliablemsg_splitpoint)/sizeof(client->unreliablemsg_splitpoint[0])))
			continue;
		SZ_Write(&client->unreliablemsg, sv.datagram.data, sv.datagram.cursize);
		client->unreliablemsg_splitpoint[client->unreliablemsg_splitpoints++] = client->unreliablemsg.cursize;
	}
	SZ_Clear(&sv.datagram);
}

static void SV_WriteUnreliableMessages(client_t *client, sizebuf_t *msg, int maxsize, int maxsize2)
{
	// scan the splitpoints to find out how many we can fit in
	int numsegments, j, split;
	if (!client->unreliablemsg_splitpoints)
		return;
	// always accept the first one if it's within 1024 bytes, this ensures
	// that very big datagrams which are over the rate limit still get
	// through, just to keep it working
	for (numsegments = 1;numsegments < client->unreliablemsg_splitpoints;numsegments++)
		if (msg->cursize + client->unreliablemsg_splitpoint[numsegments] > maxsize)
			break;
	// the first segment gets an exemption from the rate limiting, otherwise
	// it could get dropped consistently due to a low rate limit
	if (numsegments == 1)
		maxsize = maxsize2;
	// some will fit, so add the ones that will fit
	split = client->unreliablemsg_splitpoint[numsegments-1];
	// note this discards ones that were accepted by the segments scan but
	// can not fit, such as a really huge first one that will never ever
	// fit in a packet...
	if (msg->cursize + split <= maxsize)
		SZ_Write(msg, client->unreliablemsg.data, split);
	// remove the part we sent, keeping any remaining data
	client->unreliablemsg.cursize -= split;
	if (client->unreliablemsg.cursize > 0)
		memmove(client->unreliablemsg.data, client->unreliablemsg.data + split, client->unreliablemsg.cursize);
	// adjust remaining splitpoints
	client->unreliablemsg_splitpoints -= numsegments;
	for (j = 0;j < client->unreliablemsg_splitpoints;j++)
		client->unreliablemsg_splitpoint[j] = client->unreliablemsg_splitpoint[numsegments + j] - split;
}

/*
=======================
SV_SendClientDatagram
=======================
*/
static void SV_SendClientDatagram (client_t *client)
{
	int clientrate, maxrate, maxsize, maxsize2, downloadsize;
	sizebuf_t msg;
	int stats[MAX_CL_STATS];
	static unsigned char sv_sendclientdatagram_buf[NET_MAXMESSAGE];
	double timedelta;

	// obey rate limit by limiting packet frequency if the packet size
	// limiting fails
	// (usually this is caused by reliable messages)
	if (!NetConn_CanSend(client->netconnection))
		return;

	// PROTOCOL_DARKPLACES5 and later support packet size limiting of updates
	maxrate = max(NET_MINRATE, sv_maxrate.integer);
	if (sv_maxrate.integer != maxrate)
		Cvar_SetValueQuick(&sv_maxrate, maxrate);

	// clientrate determines the 'cleartime' of a packet
	// (how long to wait before sending another, based on this packet's size)
	clientrate = bound(NET_MINRATE, client->rate, maxrate);

	switch (sv.protocol)
	{
	case PROTOCOL_QUAKE:
	case PROTOCOL_QUAKEDP:
	case PROTOCOL_NEHAHRAMOVIE:
	case PROTOCOL_NEHAHRABJP:
	case PROTOCOL_NEHAHRABJP2:
	case PROTOCOL_NEHAHRABJP3:
	case PROTOCOL_QUAKEWORLD:
		// no packet size limit support on Quake protocols because it just
		// causes missing entities/effects
		// packets are simply sent less often to obey the rate limit
		maxsize = 1024;
		maxsize2 = 1024;
		break;
	case PROTOCOL_DARKPLACES1:
	case PROTOCOL_DARKPLACES2:
	case PROTOCOL_DARKPLACES3:
	case PROTOCOL_DARKPLACES4:
		// no packet size limit support on DP1-4 protocols because they kick
		// the client off if they overflow, and miss effects
		// packets are simply sent less often to obey the rate limit
		maxsize = sizeof(sv_sendclientdatagram_buf);
		maxsize2 = sizeof(sv_sendclientdatagram_buf);
		break;
	default:
		// DP5 and later protocols support packet size limiting which is a
		// better method than limiting packet frequency as QW does
		//
		// at very low rates (or very small sys_ticrate) the packet size is
		// not reduced below 128, but packets may be sent less often

		// how long are bursts?
		timedelta = host_client->rate_burstsize / (double)client->rate;

		// how much of the burst do we keep reserved?
		timedelta *= 1 - net_burstreserve.value;

		// only try to use excess time
		timedelta = bound(0, realtime - host_client->netconnection->cleartime, timedelta);

		// but we know next packet will be in sys_ticrate, so we can use up THAT bandwidth
		timedelta += sys_ticrate.value;

		// note: packet overhead (not counted in maxsize) is 28 bytes
		maxsize = (int)(clientrate * timedelta) - 28;

		// put it in sound bounds
		maxsize = bound(128, maxsize, 1400);
		maxsize2 = 1400;

		// csqc entities can easily exceed 128 bytes, so disable throttling in
		// mods that use csqc (they are likely to use less bandwidth anyway)
		if((net_usesizelimit.integer == 1) ? (sv.csqc_progsize > 0) : (net_usesizelimit.integer < 1))
			maxsize = maxsize2;

		break;
	}

	if (LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) == LHNETADDRESSTYPE_LOOP && !sv_ratelimitlocalplayer.integer)
	{
		// for good singleplayer, send huge packets
		maxsize = sizeof(sv_sendclientdatagram_buf);
		maxsize2 = sizeof(sv_sendclientdatagram_buf);
		// never limit frequency in singleplayer
		clientrate = 1000000000;
	}

	// while downloading, limit entity updates to half the packet
	// (any leftover space will be used for downloading)
	if (host_client->download_file)
		maxsize /= 2;

	msg.data = sv_sendclientdatagram_buf;
	msg.maxsize = sizeof(sv_sendclientdatagram_buf);
	msg.cursize = 0;
	msg.allowoverflow = false;

	if (host_client->begun)
	{
		// the player is in the game
		MSG_WriteByte (&msg, svc_time);
		MSG_WriteFloat (&msg, sv.time);

		// add the client specific data to the datagram
		SV_WriteClientdataToMessage (client, client->edict, &msg, stats);
		// now update the stats[] array using any registered custom fields
		VM_SV_UpdateCustomStats(client, client->edict, &msg, stats);
		// set host_client->statsdeltabits
		Protocol_UpdateClientStats (stats);

		// add as many queued unreliable messages (effects) as we can fit
		// limit effects to half of the remaining space
		if (client->unreliablemsg.cursize)
			SV_WriteUnreliableMessages (client, &msg, maxsize/2, maxsize2);

		// now write as many entities as we can fit, and also sends stats
		SV_WriteEntitiesToClient (client, client->edict, &msg, maxsize);
	}
	else if (realtime > client->keepalivetime)
	{
		// the player isn't totally in the game yet
		// send small keepalive messages if too much time has passed
		// (may also be sending downloads)
		client->keepalivetime = realtime + 5;
		MSG_WriteChar (&msg, svc_nop);
	}

	// if a download is active, see if there is room to fit some download data
	// in this packet
	downloadsize = min(maxsize*2,maxsize2) - msg.cursize - 7;
	if (host_client->download_file && host_client->download_started && downloadsize > 0)
	{
		fs_offset_t downloadstart;
		unsigned char data[1400];
		downloadstart = FS_Tell(host_client->download_file);
		downloadsize = min(downloadsize, (int)sizeof(data));
		downloadsize = FS_Read(host_client->download_file, data, downloadsize);
		// note this sends empty messages if at the end of the file, which is
		// necessary to keep the packet loss logic working
		// (the last blocks may be lost and need to be re-sent, and that will
		//  only occur if the client acks the empty end messages, revealing
		//  a gap in the download progress, causing the last blocks to be
		//  sent again)
		MSG_WriteChar (&msg, svc_downloaddata);
		MSG_WriteLong (&msg, downloadstart);
		MSG_WriteShort (&msg, downloadsize);
		if (downloadsize > 0)
			SZ_Write (&msg, data, downloadsize);
	}

	// reliable only if none is in progress
	if(client->sendsignon != 2 && !client->netconnection->sendMessageLength)
		SV_WriteDemoMessage(client, &(client->netconnection->message), false);
	// unreliable
	SV_WriteDemoMessage(client, &msg, false);

// send the datagram
	NetConn_SendUnreliableMessage (client->netconnection, &msg, sv.protocol, clientrate, client->rate_burstsize, client->sendsignon == 2);
	if (client->sendsignon == 1 && !client->netconnection->message.cursize)
		client->sendsignon = 2; // prevent reliable until client sends prespawn (this is the keepalive phase)
}

/*
=======================
SV_UpdateToReliableMessages
=======================
*/
static void SV_UpdateToReliableMessages (void)
{
	prvm_prog_t *prog = SVVM_prog;
	int i, j;
	client_t *client;
	const char *name;
	const char *model;
	const char *skin;
	int clientcamera;

// check for changes to be sent over the reliable streams
	for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
	{
		// update the host_client fields we care about according to the entity fields
		host_client->edict = PRVM_EDICT_NUM(i+1);

		// DP_SV_CLIENTNAME
		name = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, netname));
		if (name == NULL)
			name = "";
		// always point the string back at host_client->name to keep it safe
		//strlcpy (host_client->name, name, sizeof (host_client->name));
		if (name != host_client->name) // prevent buffer overlap SIGABRT on Mac OSX
			strlcpy (host_client->name, name, sizeof (host_client->name));
		PRVM_serveredictstring(host_client->edict, netname) = PRVM_SetEngineString(prog, host_client->name);
		if (strcmp(host_client->old_name, host_client->name))
		{
			if (host_client->begun)
				SV_BroadcastPrintf("%s ^7changed name to %s\n", host_client->old_name, host_client->name);
			strlcpy(host_client->old_name, host_client->name, sizeof(host_client->old_name));
			// send notification to all clients
			MSG_WriteByte (&sv.reliable_datagram, svc_updatename);
			MSG_WriteByte (&sv.reliable_datagram, i);
			MSG_WriteString (&sv.reliable_datagram, host_client->name);
			SV_WriteNetnameIntoDemo(host_client);
		}

		// DP_SV_CLIENTCOLORS
		host_client->colors = (int)PRVM_serveredictfloat(host_client->edict, clientcolors);
		if (host_client->old_colors != host_client->colors)
		{
			host_client->old_colors = host_client->colors;
			// send notification to all clients
			MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
			MSG_WriteByte (&sv.reliable_datagram, i);
			MSG_WriteByte (&sv.reliable_datagram, host_client->colors);
		}

		// NEXUIZ_PLAYERMODEL
		model = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, playermodel));
		if (model == NULL)
			model = "";
		// always point the string back at host_client->name to keep it safe
		//strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
		if (model != host_client->playermodel) // prevent buffer overlap SIGABRT on Mac OSX
			strlcpy (host_client->playermodel, model, sizeof (host_client->playermodel));
		PRVM_serveredictstring(host_client->edict, playermodel) = PRVM_SetEngineString(prog, host_client->playermodel);

		// NEXUIZ_PLAYERSKIN
		skin = PRVM_GetString(prog, PRVM_serveredictstring(host_client->edict, playerskin));
		if (skin == NULL)
			skin = "";
		// always point the string back at host_client->name to keep it safe
		//strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
		if (skin != host_client->playerskin) // prevent buffer overlap SIGABRT on Mac OSX
			strlcpy (host_client->playerskin, skin, sizeof (host_client->playerskin));
		PRVM_serveredictstring(host_client->edict, playerskin) = PRVM_SetEngineString(prog, host_client->playerskin);

		// TODO: add an extension name for this [1/17/2008 Black]
		clientcamera = PRVM_serveredictedict(host_client->edict, clientcamera);
		if (clientcamera > 0)
		{
			int oldclientcamera = host_client->clientcamera;
			if (clientcamera >= prog->max_edicts || PRVM_EDICT_NUM(clientcamera)->priv.required->free)
				clientcamera = PRVM_NUM_FOR_EDICT(host_client->edict);
			host_client->clientcamera = clientcamera;

			if (oldclientcamera != host_client->clientcamera && host_client->netconnection)
			{
				MSG_WriteByte(&host_client->netconnection->message, svc_setview);
				MSG_WriteShort(&host_client->netconnection->message, host_client->clientcamera);
			}
		}

		// frags
		host_client->frags = (int)PRVM_serveredictfloat(host_client->edict, frags);
		if(IS_OLDNEXUIZ_DERIVED(gamemode))
			if(!host_client->begun && host_client->netconnection)
				host_client->frags = -666;
		if (host_client->old_frags != host_client->frags)
		{
			host_client->old_frags = host_client->frags;
			// send notification to all clients
			MSG_WriteByte (&sv.reliable_datagram, svc_updatefrags);
			MSG_WriteByte (&sv.reliable_datagram, i);
			MSG_WriteShort (&sv.reliable_datagram, host_client->frags);
		}
	}

	for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
		if (client->netconnection && (client->begun || client->clientconnectcalled)) // also send MSG_ALL to people who are past ClientConnect, but not spawned yet
			SZ_Write (&client->netconnection->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);

	SZ_Clear (&sv.reliable_datagram);
}


/*
=======================
SV_SendClientMessages
=======================
*/
void SV_SendClientMessages(void)
{
	int i, prepared = false;

	if (sv.protocol == PROTOCOL_QUAKEWORLD)
		Sys_Error("SV_SendClientMessages: no quakeworld support\n");

	SV_FlushBroadcastMessages();

// update frags, names, etc
	SV_UpdateToReliableMessages();

// build individual updates
	for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
	{
		if (!host_client->active)
			continue;
		if (!host_client->netconnection)
			continue;

		if (host_client->netconnection->message.overflowed)
		{
			SV_DropClient (true);	// if the message couldn't send, kick off
			continue;
		}

		if (!prepared)
		{
			prepared = true;
			// only prepare entities once per frame
			SV_PrepareEntitiesForSending();
		}
		SV_SendClientDatagram(host_client);
	}

// clear muzzle flashes
	SV_CleanupEnts();
}

static void SV_StartDownload_f(void)
{
	if (host_client->download_file)
		host_client->download_started = true;
}

/*
 * Compression extension negotiation:
 *
 * Server to client:
 *   cl_serverextension_download 2
 *
 * Client to server:
 *   download <filename> <list of zero or more suppported compressions in order of preference>
 * e.g.
 *   download maps/map1.bsp lzo deflate huffman
 *
 * Server to client:
 *   cl_downloadbegin <compressed size> <filename> <compression method actually used>
 * e.g.
 *   cl_downloadbegin 123456 maps/map1.bsp deflate
 *
 * The server may choose not to compress the file by sending no compression name, like:
 *   cl_downloadbegin 345678 maps/map1.bsp
 *
 * NOTE: the "download" command may only specify compression algorithms if
 *       cl_serverextension_download is 2!
 *       If cl_serverextension_download has a different value, the client must
 *       assume this extension is not supported!
 */

static void Download_CheckExtensions(void)
{
	int i;
	int argc = Cmd_Argc();

	// first reset them all
	host_client->download_deflate = false;
	
	for(i = 2; i < argc; ++i)
	{
		if(!strcmp(Cmd_Argv(i), "deflate"))
		{
			host_client->download_deflate = true;
			break;
		}
	}
}

static void SV_Download_f(void)
{
	const char *whichpack, *whichpack2, *extension;
	qboolean is_csqc; // so we need to check only once

	if (Cmd_Argc() < 2)
	{
		SV_ClientPrintf("usage: download <filename> {<extensions>}*\n");
		SV_ClientPrintf("       supported extensions: deflate\n");
		return;
	}

	if (FS_CheckNastyPath(Cmd_Argv(1), false))
	{
		SV_ClientPrintf("Download rejected: nasty filename \"%s\"\n", Cmd_Argv(1));
		return;
	}

	if (host_client->download_file)
	{
		// at this point we'll assume the previous download should be aborted
		Con_DPrintf("Download of %s aborted by %s starting a new download\n", host_client->download_name, host_client->name);
		Host_ClientCommands("\nstopdownload\n");

		// close the file and reset variables
		FS_Close(host_client->download_file);
		host_client->download_file = NULL;
		host_client->download_name[0] = 0;
		host_client->download_expectedposition = 0;
		host_client->download_started = false;
	}

	is_csqc = (sv.csqc_progname[0] && strcmp(Cmd_Argv(1), sv.csqc_progname) == 0);
	
	if (!sv_allowdownloads.integer && !is_csqc)
	{
		SV_ClientPrintf("Downloads are disabled on this server\n");
		Host_ClientCommands("\nstopdownload\n");
		return;
	}

	Download_CheckExtensions();

	strlcpy(host_client->download_name, Cmd_Argv(1), sizeof(host_client->download_name));
	extension = FS_FileExtension(host_client->download_name);

	// host_client is asking to download a specified file
	if (developer_extra.integer)
		Con_DPrintf("Download request for %s by %s\n", host_client->download_name, host_client->name);

	if(is_csqc)
	{
		char extensions[MAX_QPATH]; // make sure this can hold all extensions
		extensions[0] = '\0';
		
		if(host_client->download_deflate)
			strlcat(extensions, " deflate", sizeof(extensions));
		
		Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);

		if(host_client->download_deflate && svs.csqc_progdata_deflated)
			host_client->download_file = FS_FileFromData(svs.csqc_progdata_deflated, svs.csqc_progsize_deflated, true);
		else
			host_client->download_file = FS_FileFromData(svs.csqc_progdata, sv.csqc_progsize, true);
		
		// no, no space is needed between %s and %s :P
		Host_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);

		host_client->download_expectedposition = 0;
		host_client->download_started = false;
		host_client->sendsignon = true; // make sure this message is sent
		return;
	}

	if (!FS_FileExists(host_client->download_name))
	{
		SV_ClientPrintf("Download rejected: server does not have the file \"%s\"\nYou may need to separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
		Host_ClientCommands("\nstopdownload\n");
		return;
	}

	// check if the user is trying to download part of registered Quake(r)
	whichpack = FS_WhichPack(host_client->download_name);
	whichpack2 = FS_WhichPack("gfx/pop.lmp");
	if ((whichpack && whichpack2 && !strcasecmp(whichpack, whichpack2)) || FS_IsRegisteredQuakePack(host_client->download_name))
	{
		SV_ClientPrintf("Download rejected: file \"%s\" is part of registered Quake(r)\nYou must purchase Quake(r) from id Software or a retailer to get this file\nPlease go to http://www.idsoftware.com/games/quake/quake/index.php?game_section=buy\n", host_client->download_name);
		Host_ClientCommands("\nstopdownload\n");
		return;
	}

	// check if the server has forbidden archive downloads entirely
	if (!sv_allowdownloads_inarchive.integer)
	{
		whichpack = FS_WhichPack(host_client->download_name);
		if (whichpack)
		{
			SV_ClientPrintf("Download rejected: file \"%s\" is in an archive (\"%s\")\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name, whichpack);
			Host_ClientCommands("\nstopdownload\n");
			return;
		}
	}

	if (!sv_allowdownloads_config.integer)
	{
		if (!strcasecmp(extension, "cfg"))
		{
			SV_ClientPrintf("Download rejected: file \"%s\" is a .cfg file which is forbidden for security reasons\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
			Host_ClientCommands("\nstopdownload\n");
			return;
		}
	}

	if (!sv_allowdownloads_dlcache.integer)
	{
		if (!strncasecmp(host_client->download_name, "dlcache/", 8))
		{
			SV_ClientPrintf("Download rejected: file \"%s\" is in the dlcache/ directory which is forbidden for security reasons\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
			Host_ClientCommands("\nstopdownload\n");
			return;
		}
	}

	if (!sv_allowdownloads_archive.integer)
	{
		if (!strcasecmp(extension, "pak") || !strcasecmp(extension, "pk3"))
		{
			SV_ClientPrintf("Download rejected: file \"%s\" is an archive\nYou must separately download or purchase the data archives for this game/mod to get this file\n", host_client->download_name);
			Host_ClientCommands("\nstopdownload\n");
			return;
		}
	}

	host_client->download_file = FS_OpenVirtualFile(host_client->download_name, true);
	if (!host_client->download_file)
	{
		SV_ClientPrintf("Download rejected: server could not open the file \"%s\"\n", host_client->download_name);
		Host_ClientCommands("\nstopdownload\n");
		return;
	}

	if (FS_FileSize(host_client->download_file) > 1<<30)
	{
		SV_ClientPrintf("Download rejected: file \"%s\" is very large\n", host_client->download_name);
		Host_ClientCommands("\nstopdownload\n");
		FS_Close(host_client->download_file);
		host_client->download_file = NULL;
		return;
	}

	if (FS_FileSize(host_client->download_file) < 0)
	{
		SV_ClientPrintf("Download rejected: file \"%s\" is not a regular file\n", host_client->download_name);
		Host_ClientCommands("\nstopdownload\n");
		FS_Close(host_client->download_file);
		host_client->download_file = NULL;
		return;
	}

	Con_DPrintf("Downloading %s to %s\n", host_client->download_name, host_client->name);

	/*
	 * we can only do this if we would actually deflate on the fly
	 * which we do not (yet)!
	{
		char extensions[MAX_QPATH]; // make sure this can hold all extensions
		extensions[0] = '\0';
		
		if(host_client->download_deflate)
			strlcat(extensions, " deflate", sizeof(extensions));

		// no, no space is needed between %s and %s :P
		Host_ClientCommands("\ncl_downloadbegin %i %s%s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name, extensions);
	}
	*/
	Host_ClientCommands("\ncl_downloadbegin %i %s\n", (int)FS_FileSize(host_client->download_file), host_client->download_name);

	host_client->download_expectedposition = 0;
	host_client->download_started = false;
	host_client->sendsignon = true; // make sure this message is sent

	// the rest of the download process is handled in SV_SendClientDatagram
	// and other code dealing with svc_downloaddata and clc_ackdownloaddata
	//
	// no svc_downloaddata messages will be sent until sv_startdownload is
	// sent by the client
}

/*
==============================================================================

SERVER SPAWNING

==============================================================================
*/

/*
================
SV_ModelIndex

================
*/
int SV_ModelIndex(const char *s, int precachemode)
{
	int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3) ? 256 : MAX_MODELS);
	char filename[MAX_QPATH];
	if (!s || !*s)
		return 0;
	// testing
	//if (precachemode == 2)
	//	return 0;
	strlcpy(filename, s, sizeof(filename));
	for (i = 2;i < limit;i++)
	{
		if (!sv.model_precache[i][0])
		{
			if (precachemode)
			{
				if (sv.state != ss_loading && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5))
				{
					Con_Printf("SV_ModelIndex(\"%s\"): precache_model can only be done in spawn functions\n", filename);
					return 0;
				}
				if (precachemode == 1)
					Con_Printf("SV_ModelIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
				strlcpy(sv.model_precache[i], filename, sizeof(sv.model_precache[i]));
				if (sv.state == ss_loading)
				{
					// running from SV_SpawnServer which is launched from the client console command interpreter
					sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
				}
				else
				{
					if (svs.threaded)
					{
						// this is running on the server thread, we can't load a model here (it would crash on renderer calls), so only look it up, the svc_precache will cause it to be loaded when it reaches the client
						sv.models[i] = Mod_FindName (sv.model_precache[i], s[0] == '*' ? sv.worldname : NULL);
					}
					else
					{
						// running single threaded, so we can load the model here
						sv.models[i] = Mod_ForName (sv.model_precache[i], true, false, s[0] == '*' ? sv.worldname : NULL);
					}
					MSG_WriteByte(&sv.reliable_datagram, svc_precache);
					MSG_WriteShort(&sv.reliable_datagram, i);
					MSG_WriteString(&sv.reliable_datagram, filename);
				}
				return i;
			}
			Con_Printf("SV_ModelIndex(\"%s\"): not precached\n", filename);
			return 0;
		}
		if (!strcmp(sv.model_precache[i], filename))
			return i;
	}
	Con_Printf("SV_ModelIndex(\"%s\"): i (%i) == MAX_MODELS (%i)\n", filename, i, MAX_MODELS);
	return 0;
}

/*
================
SV_SoundIndex

================
*/
int SV_SoundIndex(const char *s, int precachemode)
{
	int i, limit = ((sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3) ? 256 : MAX_SOUNDS);
	char filename[MAX_QPATH];
	if (!s || !*s)
		return 0;
	// testing
	//if (precachemode == 2)
	//	return 0;
	strlcpy(filename, s, sizeof(filename));
	for (i = 1;i < limit;i++)
	{
		if (!sv.sound_precache[i][0])
		{
			if (precachemode)
			{
				if (sv.state != ss_loading && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5))
				{
					Con_Printf("SV_SoundIndex(\"%s\"): precache_sound can only be done in spawn functions\n", filename);
					return 0;
				}
				if (precachemode == 1)
					Con_Printf("SV_SoundIndex(\"%s\"): not precached (fix your code), precaching anyway\n", filename);
				strlcpy(sv.sound_precache[i], filename, sizeof(sv.sound_precache[i]));
				if (sv.state != ss_loading)
				{
					MSG_WriteByte(&sv.reliable_datagram, svc_precache);
					MSG_WriteShort(&sv.reliable_datagram, i + 32768);
					MSG_WriteString(&sv.reliable_datagram, filename);
				}
				return i;
			}
			Con_Printf("SV_SoundIndex(\"%s\"): not precached\n", filename);
			return 0;
		}
		if (!strcmp(sv.sound_precache[i], filename))
			return i;
	}
	Con_Printf("SV_SoundIndex(\"%s\"): i (%i) == MAX_SOUNDS (%i)\n", filename, i, MAX_SOUNDS);
	return 0;
}

/*
================
SV_ParticleEffectIndex

================
*/
int SV_ParticleEffectIndex(const char *name)
{
	int i, argc, linenumber, effectnameindex;
	int filepass;
	fs_offset_t filesize;
	unsigned char *filedata;
	const char *text;
	const char *textstart;
	//const char *textend;
	char argv[16][1024];
	char filename[MAX_QPATH];
	if (!sv.particleeffectnamesloaded)
	{
		sv.particleeffectnamesloaded = true;
		memset(sv.particleeffectname, 0, sizeof(sv.particleeffectname));
		for (i = 0;i < EFFECT_TOTAL;i++)
			strlcpy(sv.particleeffectname[i], standardeffectnames[i], sizeof(sv.particleeffectname[i]));
		for (filepass = 0;;filepass++)
		{
			if (filepass == 0)
				dpsnprintf(filename, sizeof(filename), "effectinfo.txt");
			else if (filepass == 1)
				dpsnprintf(filename, sizeof(filename), "%s_effectinfo.txt", sv.worldnamenoextension);
			else
				break;
			filedata = FS_LoadFile(filename, tempmempool, true, &filesize);
			if (!filedata)
				continue;
			textstart = (const char *)filedata;
			//textend = (const char *)filedata + filesize;
			text = textstart;
			for (linenumber = 1;;linenumber++)
			{
				argc = 0;
				for (;;)
				{
					if (!COM_ParseToken_Simple(&text, true, false, true) || !strcmp(com_token, "\n"))
						break;
					if (argc < 16)
					{
						strlcpy(argv[argc], com_token, sizeof(argv[argc]));
						argc++;
					}
				}
				if (com_token[0] == 0)
					break; // if the loop exited and it's not a \n, it's EOF
				if (argc < 1)
					continue;
				if (!strcmp(argv[0], "effect"))
				{
					if (argc == 2)
					{
						for (effectnameindex = 1;effectnameindex < MAX_PARTICLEEFFECTNAME;effectnameindex++)
						{
							if (sv.particleeffectname[effectnameindex][0])
							{
								if (!strcmp(sv.particleeffectname[effectnameindex], argv[1]))
									break;
							}
							else
							{
								strlcpy(sv.particleeffectname[effectnameindex], argv[1], sizeof(sv.particleeffectname[effectnameindex]));
								break;
							}
						}
						// if we run out of names, abort
						if (effectnameindex == MAX_PARTICLEEFFECTNAME)
						{
							Con_Printf("%s:%i: too many effects!\n", filename, linenumber);
							break;
						}
					}
				}
			}
			Mem_Free(filedata);
		}
	}
	// search for the name
	for (effectnameindex = 1;effectnameindex < MAX_PARTICLEEFFECTNAME && sv.particleeffectname[effectnameindex][0];effectnameindex++)
		if (!strcmp(sv.particleeffectname[effectnameindex], name))
			return effectnameindex;
	// return 0 if we couldn't find it
	return 0;
}

dp_model_t *SV_GetModelByIndex(int modelindex)
{
	return (modelindex > 0 && modelindex < MAX_MODELS) ? sv.models[modelindex] : NULL;
}

dp_model_t *SV_GetModelFromEdict(prvm_edict_t *ed)
{
	prvm_prog_t *prog = SVVM_prog;
	int modelindex;
	if (!ed || ed->priv.server->free)
		return NULL;
	modelindex = (int)PRVM_serveredictfloat(ed, modelindex);
	return (modelindex > 0 && modelindex < MAX_MODELS) ? sv.models[modelindex] : NULL;
}

/*
================
SV_CreateBaseline

================
*/
static void SV_CreateBaseline (void)
{
	prvm_prog_t *prog = SVVM_prog;
	int i, entnum, large;
	prvm_edict_t *svent;

	// LordHavoc: clear *all* baselines (not just active ones)
	for (entnum = 0;entnum < prog->max_edicts;entnum++)
	{
		// get the current server version
		svent = PRVM_EDICT_NUM(entnum);

		// LordHavoc: always clear state values, whether the entity is in use or not
		svent->priv.server->baseline = defaultstate;

		if (svent->priv.server->free)
			continue;
		if (entnum > svs.maxclients && !PRVM_serveredictfloat(svent, modelindex))
			continue;

		// create entity baseline
		VectorCopy (PRVM_serveredictvector(svent, origin), svent->priv.server->baseline.origin);
		VectorCopy (PRVM_serveredictvector(svent, angles), svent->priv.server->baseline.angles);
		svent->priv.server->baseline.frame = (int)PRVM_serveredictfloat(svent, frame);
		svent->priv.server->baseline.skin = (int)PRVM_serveredictfloat(svent, skin);
		if (entnum > 0 && entnum <= svs.maxclients)
		{
			svent->priv.server->baseline.colormap = entnum;
			svent->priv.server->baseline.modelindex = SV_ModelIndex("progs/player.mdl", 1);
		}
		else
		{
			svent->priv.server->baseline.colormap = 0;
			svent->priv.server->baseline.modelindex = (int)PRVM_serveredictfloat(svent, modelindex);
		}

		large = false;
		if (svent->priv.server->baseline.modelindex & 0xFF00 || svent->priv.server->baseline.frame & 0xFF00)
		{
			large = true;
			if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
				large = false;
		}

		// add to the message
		if (large)
			MSG_WriteByte (&sv.signon, svc_spawnbaseline2);
		else
			MSG_WriteByte (&sv.signon, svc_spawnbaseline);
		MSG_WriteShort (&sv.signon, entnum);

		if (large)
		{
			MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
			MSG_WriteShort (&sv.signon, svent->priv.server->baseline.frame);
		}
		else if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
		{
			MSG_WriteShort (&sv.signon, svent->priv.server->baseline.modelindex);
			MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
		}
		else
		{
			MSG_WriteByte (&sv.signon, svent->priv.server->baseline.modelindex);
			MSG_WriteByte (&sv.signon, svent->priv.server->baseline.frame);
		}
		MSG_WriteByte (&sv.signon, svent->priv.server->baseline.colormap);
		MSG_WriteByte (&sv.signon, svent->priv.server->baseline.skin);
		for (i=0 ; i<3 ; i++)
		{
			MSG_WriteCoord(&sv.signon, svent->priv.server->baseline.origin[i], sv.protocol);
			MSG_WriteAngle(&sv.signon, svent->priv.server->baseline.angles[i], sv.protocol);
		}
	}
}

/*
================
SV_Prepare_CSQC

Load csprogs.dat and comperss it so it doesn't need to be
reloaded on request.
================
*/
static void SV_Prepare_CSQC(void)
{
	fs_offset_t progsize;

	if(svs.csqc_progdata)
	{
		Con_DPrintf("Unloading old CSQC data.\n");
		Mem_Free(svs.csqc_progdata);
		if(svs.csqc_progdata_deflated)
			Mem_Free(svs.csqc_progdata_deflated);
	}

	svs.csqc_progdata = NULL;
	svs.csqc_progdata_deflated = NULL;
	
	sv.csqc_progname[0] = 0;
	svs.csqc_progdata = FS_LoadFile(csqc_progname.string, sv_mempool, false, &progsize);

	if(progsize > 0)
	{
		size_t deflated_size;

		sv.csqc_progsize = (int)progsize;
		sv.csqc_progcrc = CRC_Block(svs.csqc_progdata, progsize);
		strlcpy(sv.csqc_progname, csqc_progname.string, sizeof(sv.csqc_progname));
		Con_DPrintf("server detected csqc progs file \"%s\" with size %i and crc %i\n", sv.csqc_progname, sv.csqc_progsize, sv.csqc_progcrc);

		Con_DPrint("Compressing csprogs.dat\n");
		//unsigned char *FS_Deflate(const unsigned char *data, size_t size, size_t *deflated_size, int level, mempool_t *mempool);
		svs.csqc_progdata_deflated = FS_Deflate(svs.csqc_progdata, progsize, &deflated_size, -1, sv_mempool);
		svs.csqc_progsize_deflated = (int)deflated_size;
		if(svs.csqc_progdata_deflated)
		{
			Con_DPrintf("Deflated: %g%%\n", 100.0 - 100.0 * (deflated_size / (float)progsize));
			Con_DPrintf("Uncompressed: %u\nCompressed:   %u\n", (unsigned)sv.csqc_progsize, (unsigned)svs.csqc_progsize_deflated);
		}
		else
			Con_DPrintf("Cannot compress - need zlib for this. Using uncompressed progs only.\n");
	}
}

/*
================
SV_SaveSpawnparms

Grabs the current state of each client for saving across the
transition to another level
================
*/
void SV_SaveSpawnparms (void)
{
	prvm_prog_t *prog = SVVM_prog;
	int		i, j;

	svs.serverflags = (int)PRVM_serverglobalfloat(serverflags);

	for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
	{
		if (!host_client->active)
			continue;

	// call the progs to get default spawn parms for the new client
		PRVM_serverglobalfloat(time) = sv.time;
		PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
		prog->ExecuteProgram(prog, PRVM_serverfunction(SetChangeParms), "QC function SetChangeParms is missing");
		for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
			host_client->spawn_parms[j] = (&PRVM_serverglobalfloat(parm1))[j];
	}
}

/*
================
SV_SpawnServer

This is called at the start of each level
================
*/

void SV_SpawnServer (const char *server)
{
	prvm_prog_t *prog = SVVM_prog;
	prvm_edict_t *ent;
	int i;
	char *entities;
	dp_model_t *worldmodel;
	char modelname[sizeof(sv.worldname)];
	char vabuf[1024];

	Con_DPrintf("SpawnServer: %s\n", server);

	dpsnprintf (modelname, sizeof(modelname), "maps/%s.bsp", server);

	if (!FS_FileExists(modelname))
	{
		dpsnprintf (modelname, sizeof(modelname), "maps/%s", server);
		if (!FS_FileExists(modelname))
		{
			Con_Printf("SpawnServer: no map file named maps/%s.bsp\n", server);
			return;
		}
	}

//	SV_LockThreadMutex();

	if(cls.state == ca_dedicated)
		Sys_MakeProcessNice();

	if (cls.state != ca_dedicated)
	{
		SCR_BeginLoadingPlaque(false);
		S_StopAllSounds();
	}

	if(sv.active)
	{
		World_End(&sv.world);
		if(PRVM_serverfunction(SV_Shutdown))
		{
			func_t s = PRVM_serverfunction(SV_Shutdown);
			PRVM_serverglobalfloat(time) = sv.time;
			PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
			prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
		}
	}

	// free q3 shaders so that any newly downloaded shaders will be active
	Mod_FreeQ3Shaders();

	worldmodel = Mod_ForName(modelname, false, developer.integer > 0, NULL);
	if (!worldmodel || !worldmodel->TraceBox)
	{
		Con_Printf("Couldn't load map %s\n", modelname);

		if(cls.state == ca_dedicated)
			Sys_MakeProcessMean();

//		SV_UnlockThreadMutex();

		return;
	}

	Collision_Cache_Reset(true);

	// let's not have any servers with no name
	if (hostname.string[0] == 0)
		Cvar_Set ("hostname", "UNNAMED");
	scr_centertime_off = 0;

	svs.changelevel_issued = false;		// now safe to issue another

	// make the map a required file for clients
	Curl_ClearRequirements();
	Curl_RequireFile(modelname);

//
// tell all connected clients that we are going to a new level
//
	if (sv.active)
	{
		client_t *client;
		for (i = 0, client = svs.clients;i < svs.maxclients;i++, client++)
		{
			if (client->netconnection)
			{
				MSG_WriteByte(&client->netconnection->message, svc_stufftext);
				MSG_WriteString(&client->netconnection->message, "reconnect\n");
			}
		}
	}
	else
	{
		// open server port
		NetConn_OpenServerPorts(true);
	}

//
// make cvars consistant
//
	if (coop.integer)
		Cvar_SetValue ("deathmatch", 0);
	// LordHavoc: it can be useful to have skills outside the range 0-3...
	//current_skill = bound(0, (int)(skill.value + 0.5), 3);
	//Cvar_SetValue ("skill", (float)current_skill);
	current_skill = (int)(skill.value + 0.5);

//
// set up the new server
//
	memset (&sv, 0, sizeof(sv));
	// if running a local client, make sure it doesn't try to access the last
	// level's data which is no longer valiud
	cls.signon = 0;

	Cvar_SetValue("halflifebsp", worldmodel->brush.ishlbsp);
	Cvar_SetValue("sv_mapformat_is_quake2", worldmodel->brush.isq2bsp);
	Cvar_SetValue("sv_mapformat_is_quake3", worldmodel->brush.isq3bsp);

	if(*sv_random_seed.string)
	{
		srand(sv_random_seed.integer);
		Con_Printf("NOTE: random seed is %d; use for debugging/benchmarking only!\nUnset sv_random_seed to get real random numbers again.\n", sv_random_seed.integer);
	}

	SV_VM_Setup();

	sv.active = true;

	// set level base name variables for later use
	strlcpy (sv.name, server, sizeof (sv.name));
	strlcpy(sv.worldname, modelname, sizeof(sv.worldname));
	FS_StripExtension(sv.worldname, sv.worldnamenoextension, sizeof(sv.worldnamenoextension));
	strlcpy(sv.worldbasename, !strncmp(sv.worldnamenoextension, "maps/", 5) ? sv.worldnamenoextension + 5 : sv.worldnamenoextension, sizeof(sv.worldbasename));
	//Cvar_SetQuick(&sv_worldmessage, sv.worldmessage); // set later after QC is spawned
	Cvar_SetQuick(&sv_worldname, sv.worldname);
	Cvar_SetQuick(&sv_worldnamenoextension, sv.worldnamenoextension);
	Cvar_SetQuick(&sv_worldbasename, sv.worldbasename);

	sv.protocol = Protocol_EnumForName(sv_protocolname.string);
	if (sv.protocol == PROTOCOL_UNKNOWN)
	{
		char buffer[1024];
		Protocol_Names(buffer, sizeof(buffer));
		Con_Printf("Unknown sv_protocolname \"%s\", valid values are:\n%s\n", sv_protocolname.string, buffer);
		sv.protocol = PROTOCOL_QUAKE;
	}

// load progs to get entity field count
	//PR_LoadProgs ( sv_progs.string );

	sv.datagram.maxsize = sizeof(sv.datagram_buf);
	sv.datagram.cursize = 0;
	sv.datagram.data = sv.datagram_buf;

	sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
	sv.reliable_datagram.cursize = 0;
	sv.reliable_datagram.data = sv.reliable_datagram_buf;

	sv.signon.maxsize = sizeof(sv.signon_buf);
	sv.signon.cursize = 0;
	sv.signon.data = sv.signon_buf;

// leave slots at start for clients only
	//prog->num_edicts = svs.maxclients+1;

	sv.state = ss_loading;
	prog->allowworldwrites = true;
	sv.paused = false;

	sv.time = 1.0;

	Mod_ClearUsed();
	worldmodel->used = true;

	sv.worldmodel = worldmodel;
	sv.models[1] = sv.worldmodel;

//
// clear world interaction links
//
	World_SetSize(&sv.world, sv.worldname, sv.worldmodel->normalmins, sv.worldmodel->normalmaxs, prog);
	World_Start(&sv.world);

	strlcpy(sv.sound_precache[0], "", sizeof(sv.sound_precache[0]));

	strlcpy(sv.model_precache[0], "", sizeof(sv.model_precache[0]));
	strlcpy(sv.model_precache[1], sv.worldname, sizeof(sv.model_precache[1]));
	for (i = 1;i < sv.worldmodel->brush.numsubmodels && i+1 < MAX_MODELS;i++)
	{
		dpsnprintf(sv.model_precache[i+1], sizeof(sv.model_precache[i+1]), "*%i", i);
		sv.models[i+1] = Mod_ForName (sv.model_precache[i+1], false, false, sv.worldname);
	}
	if(i < sv.worldmodel->brush.numsubmodels)
		Con_Printf("Too many submodels (MAX_MODELS is %i)\n", MAX_MODELS);

//
// load the rest of the entities
//
	// AK possible hack since num_edicts is still 0
	ent = PRVM_EDICT_NUM(0);
	memset (ent->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
	ent->priv.server->free = false;
	PRVM_serveredictstring(ent, model) = PRVM_SetEngineString(prog, sv.worldname);
	PRVM_serveredictfloat(ent, modelindex) = 1;		// world model
	PRVM_serveredictfloat(ent, solid) = SOLID_BSP;
	PRVM_serveredictfloat(ent, movetype) = MOVETYPE_PUSH;
	VectorCopy(sv.world.mins, PRVM_serveredictvector(ent, mins));
	VectorCopy(sv.world.maxs, PRVM_serveredictvector(ent, maxs));
	VectorCopy(sv.world.mins, PRVM_serveredictvector(ent, absmin));
	VectorCopy(sv.world.maxs, PRVM_serveredictvector(ent, absmax));

	if (coop.value)
		PRVM_serverglobalfloat(coop) = coop.integer;
	else
		PRVM_serverglobalfloat(deathmatch) = deathmatch.integer;

	PRVM_serverglobalstring(mapname) = PRVM_SetEngineString(prog, sv.name);

// serverflags are for cross level information (sigils)
	PRVM_serverglobalfloat(serverflags) = svs.serverflags;

	// we need to reset the spawned flag on all connected clients here so that
	// their thinks don't run during startup (before PutClientInServer)
	// we also need to set up the client entities now
	// and we need to set the ->edict pointers to point into the progs edicts
	for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
	{
		host_client->begun = false;
		host_client->edict = PRVM_EDICT_NUM(i + 1);
		PRVM_ED_ClearEdict(prog, host_client->edict);
	}

	// load replacement entity file if found
	if (sv_entpatch.integer && (entities = (char *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.ent", sv.worldnamenoextension), tempmempool, true, NULL)))
	{
		Con_Printf("Loaded %s.ent\n", sv.worldnamenoextension);
		PRVM_ED_LoadFromFile(prog, entities);
		Mem_Free(entities);
	}
	else
		PRVM_ED_LoadFromFile(prog, sv.worldmodel->brush.entities);


	// LordHavoc: clear world angles (to fix e3m3.bsp)
	VectorClear(PRVM_serveredictvector(prog->edicts, angles));

// all setup is completed, any further precache statements are errors
//	sv.state = ss_active; // LordHavoc: workaround for svc_precache bug
	prog->allowworldwrites = false;

// run two frames to allow everything to settle
	sv.time = 1.0001;
	for (i = 0;i < sv_init_frame_count.integer;i++)
	{
		sv.frametime = 0.1;
		SV_Physics ();
	}

	// Once all init frames have been run, we consider svqc code fully initialized.
	prog->inittime = realtime;

	if (cls.state == ca_dedicated)
		Mod_PurgeUnused();

// create a baseline for more efficient communications
	if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
		SV_CreateBaseline ();

	sv.state = ss_active; // LordHavoc: workaround for svc_precache bug

// send serverinfo to all connected clients, and set up botclients coming back from a level change
	for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
	{
		host_client->clientconnectcalled = false; // do NOT call ClientDisconnect if he drops before ClientConnect!
		if (!host_client->active)
			continue;
		if (host_client->netconnection)
			SV_SendServerinfo(host_client);
		else
		{
			int j;
			// if client is a botclient coming from a level change, we need to
			// set up client info that normally requires networking

			// copy spawn parms out of the client_t
			for (j=0 ; j< NUM_SPAWN_PARMS ; j++)
				(&PRVM_serverglobalfloat(parm1))[j] = host_client->spawn_parms[j];

			// call the spawn function
			host_client->clientconnectcalled = true;
			PRVM_serverglobalfloat(time) = sv.time;
			PRVM_serverglobaledict(self) = PRVM_EDICT_TO_PROG(host_client->edict);
			prog->ExecuteProgram(prog, PRVM_serverfunction(ClientConnect), "QC function ClientConnect is missing");
			prog->ExecuteProgram(prog, PRVM_serverfunction(PutClientInServer), "QC function PutClientInServer is missing");
			host_client->begun = true;
		}
	}

	// update the map title cvar
	strlcpy(sv.worldmessage, PRVM_GetString(prog, PRVM_serveredictstring(prog->edicts, message)), sizeof(sv.worldmessage)); // map title (not related to filename)
	Cvar_SetQuick(&sv_worldmessage, sv.worldmessage);

	Con_DPrint("Server spawned.\n");
	NetConn_Heartbeat (2);

	if(cls.state == ca_dedicated)
		Sys_MakeProcessMean();

//	SV_UnlockThreadMutex();
}

/////////////////////////////////////////////////////
// SV VM stuff

static void SVVM_begin_increase_edicts(prvm_prog_t *prog)
{
	// links don't survive the transition, so unlink everything
	World_UnlinkAll(&sv.world);
}

static void SVVM_end_increase_edicts(prvm_prog_t *prog)
{
	int i;
	prvm_edict_t *ent;

	// link every entity except world
	for (i = 1, ent = prog->edicts;i < prog->num_edicts;i++, ent++)
		if (!ent->priv.server->free)
			SV_LinkEdict(ent);
}

static void SVVM_init_edict(prvm_prog_t *prog, prvm_edict_t *e)
{
	// LordHavoc: for consistency set these here
	int num = PRVM_NUM_FOR_EDICT(e) - 1;

	e->priv.server->move = false; // don't move on first frame

	if (num >= 0 && num < svs.maxclients)
	{
		// set colormap and team on newly created player entity
		PRVM_serveredictfloat(e, colormap) = num + 1;
		PRVM_serveredictfloat(e, team) = (svs.clients[num].colors & 15) + 1;
		// set netname/clientcolors back to client values so that
		// DP_SV_CLIENTNAME and DP_SV_CLIENTCOLORS will not immediately
		// reset them
		PRVM_serveredictstring(e, netname) = PRVM_SetEngineString(prog, svs.clients[num].name);
		PRVM_serveredictfloat(e, clientcolors) = svs.clients[num].colors;
		// NEXUIZ_PLAYERMODEL and NEXUIZ_PLAYERSKIN
		PRVM_serveredictstring(e, playermodel) = PRVM_SetEngineString(prog, svs.clients[num].playermodel);
		PRVM_serveredictstring(e, playerskin) = PRVM_SetEngineString(prog, svs.clients[num].playerskin);
		// Assign netaddress (IP Address, etc)
		if(svs.clients[num].netconnection != NULL)
		{
			// Acquire Readable Address
			LHNETADDRESS_ToString(&svs.clients[num].netconnection->peeraddress, svs.clients[num].netaddress, sizeof(svs.clients[num].netaddress), false);
			PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(prog, svs.clients[num].netaddress);
		}
		else
			PRVM_serveredictstring(e, netaddress) = PRVM_SetEngineString(prog, "null/botclient");
		if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_idfp[0])
			PRVM_serveredictstring(e, crypto_idfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.client_idfp);
		else
			PRVM_serveredictstring(e, crypto_idfp) = 0;
		PRVM_serveredictfloat(e, crypto_idfp_signed) = (svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_issigned);
		if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.client_keyfp[0])
			PRVM_serveredictstring(e, crypto_keyfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.client_keyfp);
		else
			PRVM_serveredictstring(e, crypto_keyfp) = 0;
		if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.server_keyfp[0])
			PRVM_serveredictstring(e, crypto_mykeyfp) = PRVM_SetEngineString(prog, svs.clients[num].netconnection->crypto.server_keyfp);
		else
			PRVM_serveredictstring(e, crypto_mykeyfp) = 0;
		if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated && svs.clients[num].netconnection->crypto.use_aes)
			PRVM_serveredictstring(e, crypto_encryptmethod) = PRVM_SetEngineString(prog, "AES128");
		else
			PRVM_serveredictstring(e, crypto_encryptmethod) = 0;
		if(svs.clients[num].netconnection != NULL && svs.clients[num].netconnection->crypto.authenticated)
			PRVM_serveredictstring(e, crypto_signmethod) = PRVM_SetEngineString(prog, "HMAC-SHA256");
		else
			PRVM_serveredictstring(e, crypto_signmethod) = 0;
	}
}

static void SVVM_free_edict(prvm_prog_t *prog, prvm_edict_t *ed)
{
	int i;
	int e;

	World_UnlinkEdict(ed);		// unlink from world bsp

	PRVM_serveredictstring(ed, model) = 0;
	PRVM_serveredictfloat(ed, takedamage) = 0;
	PRVM_serveredictfloat(ed, modelindex) = 0;
	PRVM_serveredictfloat(ed, colormap) = 0;
	PRVM_serveredictfloat(ed, skin) = 0;
	PRVM_serveredictfloat(ed, frame) = 0;
	VectorClear(PRVM_serveredictvector(ed, origin));
	VectorClear(PRVM_serveredictvector(ed, angles));
	PRVM_serveredictfloat(ed, nextthink) = -1;
	PRVM_serveredictfloat(ed, solid) = 0;

	VM_RemoveEdictSkeleton(prog, ed);
	World_Physics_RemoveFromEntity(&sv.world, ed);
	World_Physics_RemoveJointFromEntity(&sv.world, ed);

	// make sure csqc networking is aware of the removed entity
	e = PRVM_NUM_FOR_EDICT(ed);
	sv.csqcentityversion[e] = 0;
	for (i = 0;i < svs.maxclients;i++)
		svs.clients[i].csqcentitysendflags[e] = 0xFFFFFF;
}

static void SVVM_count_edicts(prvm_prog_t *prog)
{
	int		i;
	prvm_edict_t	*ent;
	int		active, models, solid, step;

	active = models = solid = step = 0;
	for (i=0 ; i<prog->num_edicts ; i++)
	{
		ent = PRVM_EDICT_NUM(i);
		if (ent->priv.server->free)
			continue;
		active++;
		if (PRVM_serveredictfloat(ent, solid))
			solid++;
		if (PRVM_serveredictstring(ent, model))
			models++;
		if (PRVM_serveredictfloat(ent, movetype) == MOVETYPE_STEP)
			step++;
	}

	Con_Printf("num_edicts:%3i\n", prog->num_edicts);
	Con_Printf("active    :%3i\n", active);
	Con_Printf("view      :%3i\n", models);
	Con_Printf("touch     :%3i\n", solid);
	Con_Printf("step      :%3i\n", step);
}

static qboolean SVVM_load_edict(prvm_prog_t *prog, prvm_edict_t *ent)
{
	// remove things from different skill levels or deathmatch
	if (gamemode != GAME_TRANSFUSION) //Transfusion does this in QC
	{
		if (deathmatch.integer)
		{
			if (((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_DEATHMATCH))
			{
				return false;
			}
		}
		else if ((current_skill <= 0 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_EASY  ))
			|| (current_skill == 1 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_MEDIUM))
			|| (current_skill >= 2 && ((int)PRVM_serveredictfloat(ent, spawnflags) & SPAWNFLAG_NOT_HARD  )))
		{
			return false;
		}
	}
	return true;
}

static void SV_VM_Setup(void)
{
	prvm_prog_t *prog = SVVM_prog;
	PRVM_Prog_Init(prog);

	// allocate the mempools
	// TODO: move the magic numbers/constants into #defines [9/13/2006 Black]
	prog->progs_mempool = Mem_AllocPool("Server Progs", 0, NULL);
	prog->builtins = vm_sv_builtins;
	prog->numbuiltins = vm_sv_numbuiltins;
	prog->max_edicts = 512;
	if (sv.protocol == PROTOCOL_QUAKE)
		prog->limit_edicts = 640; // before quake mission pack 1 this was 512
	else if (sv.protocol == PROTOCOL_QUAKEDP)
		prog->limit_edicts = 2048; // guessing
	else if (sv.protocol == PROTOCOL_NEHAHRAMOVIE)
		prog->limit_edicts = 2048; // guessing!
	else if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
		prog->limit_edicts = 4096; // guessing!
	else
		prog->limit_edicts = MAX_EDICTS;
	prog->reserved_edicts = svs.maxclients;
	prog->edictprivate_size = sizeof(edict_engineprivate_t);
	prog->name = "server";
	prog->extensionstring = vm_sv_extensions;
	prog->loadintoworld = true;

	// all callbacks must be defined (pointers are not checked before calling)
	prog->begin_increase_edicts = SVVM_begin_increase_edicts;
	prog->end_increase_edicts   = SVVM_end_increase_edicts;
	prog->init_edict            = SVVM_init_edict;
	prog->free_edict            = SVVM_free_edict;
	prog->count_edicts          = SVVM_count_edicts;
	prog->load_edict            = SVVM_load_edict;
	prog->init_cmd              = SVVM_init_cmd;
	prog->reset_cmd             = SVVM_reset_cmd;
	prog->error_cmd             = Host_Error;
	prog->ExecuteProgram        = SVVM_ExecuteProgram;

	PRVM_Prog_Load(prog, sv_progs.string, NULL, 0, SV_REQFUNCS, sv_reqfuncs, SV_REQFIELDS, sv_reqfields, SV_REQGLOBALS, sv_reqglobals);

	// some mods compiled with scrambling compilers lack certain critical
	// global names and field names such as "self" and "time" and "nextthink"
	// so we have to set these offsets manually, matching the entvars_t
	// but we only do this if the prog header crc matches, otherwise it's totally freeform
	if (prog->progs_crc == PROGHEADER_CRC || prog->progs_crc == PROGHEADER_CRC_TENEBRAE)
	{
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, modelindex);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, absmin);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, absmax);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ltime);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, movetype);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, solid);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, origin);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, oldorigin);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, velocity);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, angles);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, avelocity);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, punchangle);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, classname);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, model);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frame);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, skin);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, effects);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, mins);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, maxs);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, size);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, touch);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, use);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, think);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, blocked);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, nextthink);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, groundentity);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, health);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, frags);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weapon);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weaponmodel);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, weaponframe);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, currentammo);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_shells);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_nails);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_rockets);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ammo_cells);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, items);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, takedamage);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, chain);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, deadflag);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, view_ofs);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button0);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button1);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, button2);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, impulse);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, fixangle);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, v_angle);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, idealpitch);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, netname);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, enemy);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, flags);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, colormap);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, team);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, max_health);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, teleport_time);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, armortype);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, armorvalue);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, waterlevel);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, watertype);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, ideal_yaw);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, yaw_speed);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, aiment);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, goalentity);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, spawnflags);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, target);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, targetname);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_take);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_save);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, dmg_inflictor);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, owner);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, movedir);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, message);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, sounds);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise1);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise2);
		PRVM_ED_FindFieldOffset_FromStruct(entvars_t, noise3);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, self);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, other);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, world);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, time);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, frametime);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, force_retouch);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, mapname);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, deathmatch);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, coop);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, teamplay);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, serverflags);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, total_secrets);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, total_monsters);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, found_secrets);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, killed_monsters);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm1);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm2);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm3);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm4);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm5);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm6);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm7);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm8);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm9);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm10);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm11);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm12);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm13);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm14);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm15);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, parm16);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_forward);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_up);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, v_right);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_allsolid);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_startsolid);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_fraction);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_endpos);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_normal);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_plane_dist);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_ent);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inopen);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, trace_inwater);
		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, msg_entity);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, main);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, StartFrame);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PlayerPreThink);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PlayerPostThink);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientKill);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientConnect);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, PutClientInServer);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, ClientDisconnect);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, SetNewParms);
//		PRVM_ED_FindGlobalOffset_FromStruct(globalvars_t, SetChangeParms);
	}
	else
		Con_DPrintf("%s: %s system vars have been modified (CRC %i != engine %i), will not load in other engines", prog->name, sv_progs.string, prog->progs_crc, PROGHEADER_CRC);

	// OP_STATE is always supported on server because we add fields/globals for it
	prog->flag |= PRVM_OP_STATE;

	VM_CustomStats_Clear();//[515]: csqc

	SV_Prepare_CSQC();
}

extern cvar_t host_maxwait;
extern cvar_t host_framerate;
static int SV_ThreadFunc(void *voiddata)
{
	prvm_prog_t *prog = SVVM_prog;
	qboolean playing = false;
	double sv_timer = 0;
	double sv_deltarealtime, sv_oldrealtime, sv_realtime;
	double wait;
	int i;
	char vabuf[1024];
	sv_realtime = Sys_DirtyTime();
	while (!svs.threadstop)
	{
		// FIXME: we need to handle Host_Error in the server thread somehow
//		if (setjmp(sv_abortframe))
//			continue;			// something bad happened in the server game

		sv_oldrealtime = sv_realtime;
		sv_realtime = Sys_DirtyTime();
		sv_deltarealtime = sv_realtime - sv_oldrealtime;
		if (sv_deltarealtime < 0 || sv_deltarealtime >= 1800) sv_deltarealtime = 0;

		sv_timer += sv_deltarealtime;

		svs.perf_acc_realtime += sv_deltarealtime;

		// at this point we start doing real server work, and must block on any client activity pertaining to the server (such as executing SV_SpawnServer)
		SV_LockThreadMutex();

		// Look for clients who have spawned
		playing = false;
		if (sv.active)
			for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
				if(host_client->begun)
					if(host_client->netconnection)
						playing = true;
		if(sv.time < 10)
		{
			// don't accumulate time for the first 10 seconds of a match
			// so things can settle
			svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
		}
		else if(svs.perf_acc_realtime > 5)
		{
			svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
			svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
			if(svs.perf_acc_offset_samples > 0)
			{
				svs.perf_offset_max = svs.perf_acc_offset_max;
				svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
				svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
			}
			if(svs.perf_lost > 0 && developer_extra.integer)
				if(playing)
					Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
			svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
		}

		// get new packets
		if (sv.active)
			NetConn_ServerFrame();

		// if the accumulators haven't become positive yet, wait a while
		wait = sv_timer * -1000000.0;
		if (wait >= 1)
		{
			double time0, delta;
			SV_UnlockThreadMutex(); // don't keep mutex locked while sleeping
			if (host_maxwait.value <= 0)
				wait = min(wait, 1000000.0);
			else
				wait = min(wait, host_maxwait.value * 1000.0);
			if(wait < 1)
				wait = 1; // because we cast to int
			time0 = Sys_DirtyTime();
			Sys_Sleep((int)wait);
			delta = Sys_DirtyTime() - time0;if (delta < 0 || delta >= 1800) delta = 0;
			svs.perf_acc_sleeptime += delta;
			continue;
		}

		if (sv.active && sv_timer > 0)
		{
			// execute one server frame
			double advancetime;
			float offset;

			if (sys_ticrate.value <= 0)
				advancetime = min(sv_timer, 0.1); // don't step more than 100ms
			else
				advancetime = sys_ticrate.value;

			if(advancetime > 0)
			{
				offset = sv_timer + (Sys_DirtyTime() - sv_realtime); // LordHavoc: FIXME: I don't understand this line
				++svs.perf_acc_offset_samples;
				svs.perf_acc_offset += offset;
				svs.perf_acc_offset_squared += offset * offset;
				if(svs.perf_acc_offset_max < offset)
					svs.perf_acc_offset_max = offset;
			}

			// only advance time if not paused
			// the game also pauses in singleplayer when menu or console is used
			sv.frametime = advancetime * slowmo.value;
			if (host_framerate.value)
				sv.frametime = host_framerate.value;
			if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
				sv.frametime = 0;

			sv_timer -= advancetime;

			// move things around and think unless paused
			if (sv.frametime)
				SV_Physics();

			// send all messages to the clients
			SV_SendClientMessages();

			if (sv.paused == 1 && sv_realtime > sv.pausedstart && sv.pausedstart > 0)
			{
				PRVM_serverglobalfloat(time) = sv.time;
				prog->globals.fp[OFS_PARM0] = sv_realtime - sv.pausedstart;
				prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
			}

			// send an heartbeat if enough time has passed since the last one
			NetConn_Heartbeat(0);

		}

		// we're back to safe code now
		SV_UnlockThreadMutex();

		// if there is some time remaining from this frame, reset the timers
		if (sv_timer >= 0)
		{
			svs.perf_acc_lost += sv_timer;
			sv_timer = 0;
		}
	}
	return 0;
}

void SV_StartThread(void)
{
	if (!sv_threaded.integer || !Thread_HasThreads())
		return;
	svs.threaded = true;
	svs.threadstop = false;
	svs.threadmutex = Thread_CreateMutex();
	svs.thread = Thread_CreateThread(SV_ThreadFunc, NULL);
}

void SV_StopThread(void)
{
	if (!svs.threaded)
		return;
	svs.threadstop = true;
	Thread_WaitThread(svs.thread, 0);
	Thread_DestroyMutex(svs.threadmutex);
	svs.threaded = false;
}