~armagetronad-dev/armagetronad/armagetronad-old-glancing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
/*

*************************************************************************

ArmageTron -- Just another Tron Lightcycle Game in 3D.
Copyright (C) 2004  Armagetron Advanced Team (http://sourceforge.net/projects/armagetronad/) 

**************************************************************************

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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
  
***************************************************************************

*/

#include "rSDL.h"

// declaration
#ifndef		ARMAGETRONAD_SRC_TRON_GCYCLEMOVEMENT_H_INCLUDED
#include	"gCycleMovement.h"
#endif

#include "tMath.h"

#include "nConfig.h"
#include "nServerInfo.h"

#include "ePlayer.h"
#include "eDebugLine.h"
#include "eGrid.h"
#include "eLagCompensation.h"
#include "eTeam.h"

#include "eTimer.h"

#include "gWall.h"
#include "gSensor.h"
#include "gAIBase.h"

#include "uInput.h"

#include "tRecorder.h"

// #define DEBUG_RUBBER

#ifdef DEBUG_RUBBER
#include <fstream>
#endif

#undef 	INLINE_DEF
#define INLINE_DEF

#ifndef DEDICATED
#define MAXRUBBER 1
#else
#define MAXRUBBER 3
#endif

#ifdef DEBUG
#define DEBUGOUTPUT
#endif

#ifdef DEBUGOUTPUT
#include "tSysTime.h"
static int sg_cycleDebugPrintLevel = 0;
#endif

#include "gCycle.pb.h"

// get rubber values in effect
void sg_RubberValues( ePlayerNetID const * player, REAL speed, REAL & max, REAL & effectiveness );

//  *****************************************************************

static void sg_ArchiveCoord( eCoord & coord, int level )
{
    static char const * section = "_COORD";
    tRecorderSync< eCoord >::Archive( section, level, coord );
}

static void sg_ArchiveReal( REAL & real, int level )
{
    static char const * section = "_REAL";
    tRecorderSync< REAL >::Archive( section, level, real );
}

//  *****************************************************************
// version feature indicating that proper verlet integration should be used
static nVersionFeature sg_verletIntegration( 7 );

// strength of brake
REAL sg_brakeCycle=30;
static nSettingItem<REAL> c_ab("CYCLE_BRAKE",
                               sg_brakeCycle);

REAL sg_cycleBrakeRefill  = 0.0;
REAL sg_cycleBrakeDeplete = 0.0;

// it should look this way, but a VersionFeature is used to control the application of these settings,
// so the nonwatched itmes suffice.
static nSettingItemWatched<REAL> sg_cycleBrakeRefillConf("CYCLE_BRAKE_REFILL",sg_cycleBrakeRefill, nConfItemVersionWatcher::Group_Annoying, 2 );
static nSettingItemWatched<REAL> sg_cycleBrakeDepleteConf("CYCLE_BRAKE_DEPLETE",sg_cycleBrakeDeplete, nConfItemVersionWatcher::Group_Annoying, 2 );

// static nSettingItem<REAL> sg_cycleBrakeRefillConf("CYCLE_BRAKE_REFILL",sg_cycleBrakeRefill );
// static nSettingItem<REAL> sg_cycleBrakeDepleteConf("CYCLE_BRAKE_DEPLETE",sg_cycleBrakeDeplete );

// cycle width: it won't fit into tunnels that are smaller than this
REAL sg_cycleWidth = 0;
static nSettingItemWatched<REAL> c_cw("CYCLE_WIDTH",
                                      sg_cycleWidth, nConfItemVersionWatcher::Group_Bumpy, 14 );

REAL sg_cycleWidthSide = 0;
static nSettingItemWatched<REAL> c_cws("CYCLE_WIDTH_SIDE",
                                       sg_cycleWidthSide, nConfItemVersionWatcher::Group_Bumpy, 14 );
// calculate the gridning distance sparks should start flying at
REAL sg_GetSparksDistance()
{
    if ( sg_cycleWidth < 2 * sg_cycleWidthSide )
        return sg_cycleWidth;
    else if ( sg_cycleWidthSide > 0 )
        return sg_cycleWidthSide * 2;
    else
        return .25; // return 0.2.8.2 default
}

// amout of rubber you use per meter when you squeeze inside a too tight tunnel
// when just barely squeezed
REAL sg_cycleWidthRubberMin = 1;
static nSettingItemWatched<REAL> c_cwrmax("CYCLE_WIDTH_RUBBER_MIN",
        sg_cycleWidthRubberMin, nConfItemVersionWatcher::Group_Bumpy, 14 );
// when squeezed to a point
REAL sg_cycleWidthRubberMax = 1;
static nSettingItemWatched<REAL> c_cwrmin("CYCLE_WIDTH_RUBBER_MAX",
        sg_cycleWidthRubberMax, nConfItemVersionWatcher::Group_Bumpy, 14 );

// base speed of cycle im m/s
static REAL sg_speedCycle=10;
static nSettingItem<REAL> c_s("CYCLE_SPEED",sg_speedCycle);

// minimal speed
static REAL sg_speedCycleMin=.25;
static nSettingItemWatched<REAL> c_smin("CYCLE_SPEED_MIN",
                                        sg_speedCycleMin,
                                        nConfItemVersionWatcher::Group_Bumpy,
                                        9);

// maximal speed
static REAL sg_speedCycleMax=0;
static nSettingItemWatched<REAL> c_smax("CYCLE_SPEED_MAX",
                                        sg_speedCycleMax,
                                        nConfItemVersionWatcher::Group_Bumpy,
                                        14);

REAL sg_speedCycleDecayBelow = 5;
static nSettingItemWatched<REAL> c_sdb("CYCLE_SPEED_DECAY_BELOW",
                                       sg_speedCycleDecayBelow,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       8);

REAL sg_speedCycleDecayAbove = .1;
static nSettingItemWatched<REAL> c_sda("CYCLE_SPEED_DECAY_ABOVE",
                                       sg_speedCycleDecayAbove,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       8);

// start speed of cycle im m/s
static REAL sg_speedCycleStart=20;
static tSettingItem<REAL> c_st("CYCLE_START_SPEED",
                               sg_speedCycleStart);

// min time between turns
REAL sg_delayCycle = .1;
static nSettingItem<REAL> c_d("CYCLE_DELAY",
                              sg_delayCycle);
//bonus for turns in the same direcion
REAL sg_delayCycleDoublebindBonus = 1.;
static nSettingItemWatched<REAL> c_d_d_b("CYCLE_DELAY_DOUBLEBIND_BONUS",
        sg_delayCycleDoublebindBonus, nConfItemVersionWatcher::Group_Bumpy, 14 );

// number of turns buffered exactly
int sg_cycleTurnMemory = 3;
static tSettingItem<int> c_tm("CYCLE_TURN_MEMORY",
                              sg_cycleTurnMemory);

REAL sg_delayCycleTimeBased = 1;
static nSettingItemWatched<REAL> c_dt("CYCLE_DELAY_TIMEBASED",
                                      sg_delayCycleTimeBased,
                                      nConfItemVersionWatcher::Group_Bumpy,
                                      7);

// extra factor to sg_delayCycle applied locally
#ifdef DEDICATED
REAL sg_delayCycleBonus=.95;
static tSettingItem<REAL> c_db("CYCLE_DELAY_BONUS",
                               sg_delayCycleBonus);
#else
REAL sg_delayCycleBonus=1;
#endif

REAL sg_cycleTurnSpeedFactor=.95;
static nSettingItemWatched<REAL> c_ctf("CYCLE_TURN_SPEED_FACTOR",
                                       sg_cycleTurnSpeedFactor,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       7);

// wall acceleration
static REAL sg_accelerationCycle=10;
static nSettingItem<REAL> c_a("CYCLE_ACCEL",
                              sg_accelerationCycle);

// acceleration multiplicators
REAL sg_accelerationCycleSelf = 1;
static nSettingItemWatched<REAL> c_aco("CYCLE_ACCEL_SELF",
                                       sg_accelerationCycleSelf,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       8);

REAL sg_accelerationCycleTeam = 1;
static nSettingItemWatched<REAL> c_act("CYCLE_ACCEL_TEAM",
                                       sg_accelerationCycleTeam,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       14);

REAL sg_accelerationCycleEnemy = 1;
static nSettingItemWatched<REAL> c_ace("CYCLE_ACCEL_ENEMY",
                                       sg_accelerationCycleEnemy,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       14);

REAL sg_accelerationCycleRim = 0;
static nSettingItemWatched<REAL> c_acr("CYCLE_ACCEL_RIM",
                                       sg_accelerationCycleRim,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       8);

REAL sg_accelerationCycleSlingshot = 1;
static nSettingItemWatched<REAL> c_acs("CYCLE_ACCEL_SLINGSHOT",
                                       sg_accelerationCycleSlingshot,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       8);

REAL sg_accelerationCycleTunnel = 1;
static nSettingItemWatched<REAL> c_acu("CYCLE_ACCEL_TUNNEL",
                                       sg_accelerationCycleTunnel,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       14);

// acceleration offset
static REAL sg_accelerationCycleOffs=2;
static nSettingItem<REAL> c_ao("CYCLE_ACCEL_OFFSET",
                               sg_accelerationCycleOffs);


// when is a eWall near?
static REAL sg_nearCycle=6;
static nSettingItem<REAL> c_n("CYCLE_WALL_NEAR",
                              sg_nearCycle);

// boost settings, absolute speed increase applied when you break from a wall
REAL sg_boostCycleSelf = 0;
static nSettingItemWatched<REAL> c_bco("CYCLE_BOOST_SELF",
                                       sg_boostCycleSelf,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       14);

REAL sg_boostCycleTeam = 0;
static nSettingItemWatched<REAL> c_bct("CYCLE_BOOST_TEAM",
                                       sg_boostCycleTeam,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       14);

REAL sg_boostCycleEnemy = 0;
static nSettingItemWatched<REAL> c_bce("CYCLE_BOOST_ENEMY",
                                       sg_boostCycleEnemy,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       14);

REAL sg_boostCycleRim = 0;
static nSettingItemWatched<REAL> c_bcr("CYCLE_BOOST_RIM",
                                       sg_boostCycleRim,
                                       nConfItemVersionWatcher::Group_Bumpy,
                                       14);

// boostFactor settings, speed factor when you break from a wall
REAL sg_boostFactorCycleSelf = 1;
static nSettingItemWatched<REAL> c_bfco("CYCLE_BOOSTFACTOR_SELF",
                                        sg_boostFactorCycleSelf,
                                        nConfItemVersionWatcher::Group_Bumpy,
                                        14);

REAL sg_boostFactorCycleTeam = 1;
static nSettingItemWatched<REAL> c_bfct("CYCLE_BOOSTFACTOR_TEAM",
                                        sg_boostFactorCycleTeam,
                                        nConfItemVersionWatcher::Group_Bumpy,
                                        14);

REAL sg_boostFactorCycleEnemy = 1;
static nSettingItemWatched<REAL> c_bfce("CYCLE_BOOSTFACTOR_ENEMY",
                                        sg_boostFactorCycleEnemy,
                                        nConfItemVersionWatcher::Group_Bumpy,
                                        14);

REAL sg_boostFactorCycleRim = 1;
static nSettingItemWatched<REAL> c_bfcr("CYCLE_BOOSTFACTOR_RIM",
                                        sg_boostFactorCycleRim,
                                        nConfItemVersionWatcher::Group_Bumpy,
                                        14);

// tolerance for packet loss
static REAL sg_packetLossTolerance = 0;
static tSettingItem<REAL> conf_packetLossTolerance ("CYCLE_PACKETLOSS_TOLERANCE", sg_packetLossTolerance);

// tolerance for packet misses: if an intermediate packet is missing
static REAL sg_packetMissTolerance = 3;
static tSettingItem<REAL> conf_packetMissTolerance ("CYCLE_PACKETMISS_TOLERANCE", sg_packetMissTolerance);

// niceness when crashing a eWall
REAL sg_rubberCycle=MAXRUBBER;
static nSettingItem<REAL> c_r("CYCLE_RUBBER",
                              sg_rubberCycle);

REAL sg_rubberCycleTimeBased = 0;
static nSettingItemWatched<REAL> c_rtb("CYCLE_RUBBER_TIMEBASED",
                                       sg_rubberCycleTimeBased,
                                       nConfItemVersionWatcher::Group_Visual,
                                       7);

// allow legacy rubber code
bool sg_rubberCycleLegacy=true;
static nSettingItem<bool> c_rl("CYCLE_RUBBER_LEGACY",
                               sg_rubberCycleLegacy);

// niceness when crashing a eWall, influence of your ping
static REAL sg_rubberCyclePing=3;
static nSettingItem<REAL> c_rp("CYCLE_PING_RUBBER",
                               sg_rubberCyclePing);

// timescale rubber is restored on
REAL sg_rubberCycleTime=10;
static nSettingItemWatched<REAL> c_rt("CYCLE_RUBBER_TIME",
                                      sg_rubberCycleTime,
                                      nConfItemVersionWatcher::Group_Visual,
                                      7);

// max logarithmic approximation speed when rubber is in effect
static REAL sg_rubberCycleSpeed=40;
static nSettingItemWatched<REAL> c_rs("CYCLE_RUBBER_SPEED",
                                      sg_rubberCycleSpeed,
                                      nConfItemVersionWatcher::Group_Cheating,
                                      4);

#ifdef DEDICATED
#define MINDISTANCE_FACTOR 1
#else
#define MINDISTANCE_FACTOR 0
#endif

// minimal distance to a wall rubber will allow
static REAL sg_rubberCycleMinDistance=.001 * MINDISTANCE_FACTOR;
static nSettingItemWatched<REAL> c_rmd("CYCLE_RUBBER_MINDISTANCE",
                                       sg_rubberCycleMinDistance,
                                       nConfItemVersionWatcher::Group_Annoying,
                                       4);

// the length of the wall times this value is added to the previous value
static REAL sg_rubberCycleMinDistanceRatio=.0001 * MINDISTANCE_FACTOR;
static nSettingItemWatched<REAL> c_rmdr("CYCLE_RUBBER_MINDISTANCE_RATIO",
                                        sg_rubberCycleMinDistanceRatio,
                                        nConfItemVersionWatcher::Group_Annoying,
                                        4);

// on an empty rubber reservoir, this value is added as well
static REAL sg_rubberCycleMinDistanceReservoir=0.005 * MINDISTANCE_FACTOR;
static nSettingItemWatched<REAL> c_rmdres("CYCLE_RUBBER_MINDISTANCE_RESERVOIR",
        sg_rubberCycleMinDistanceReservoir,
        nConfItemVersionWatcher::Group_Annoying,
        7);

// and on a not so well prepared grind (if your last turn was not too long ago), this value.
static REAL sg_rubberCycleMinDistanceUnprepared=0.005 * MINDISTANCE_FACTOR;
static nSettingItemWatched<REAL> c_rmdup("CYCLE_RUBBER_MINDISTANCE_UNPREPARED",
        sg_rubberCycleMinDistanceUnprepared ,
        nConfItemVersionWatcher::Group_Annoying,
        7);

// this is the distance the preparation lengt is compared with
static REAL sg_rubberCycleMinDistancePreparation=0.2;
static nSettingItemWatched<REAL> c_rmdp("CYCLE_RUBBER_MINDISTANCE_PREPARATION",
                                        sg_rubberCycleMinDistancePreparation,
                                        nConfItemVersionWatcher::Group_Annoying,
                                        7);

// when connecting to older peers that may be rippable, multiply the minimum distance by this number if the
// wall in front of you is the rim
static REAL sg_rubberCycleMinDistanceLegacy=1;
static nSettingItem<REAL> c_rmdl("CYCLE_RUBBER_MINDISTANCE_LEGACY",
                                 sg_rubberCycleMinDistanceLegacy);

// this feature tracks whether the rip bug was fixed
static nVersionFeature sg_nonRippable(4);

// when adjusting to a wall, allow to get closer at least by this amount
static REAL sg_rubberCycleMinAdjust=.05;
static nSettingItemWatched<REAL> c_rma("CYCLE_RUBBER_MINADJUST",
                                       sg_rubberCycleMinAdjust,
                                       nConfItemVersionWatcher::Group_Annoying,
                                       4);

// during this fraction of the cycle delay time, rubber effectiveness will be reduced...
static REAL sg_rubberCycleDelay=0;
static nSettingItemWatched<REAL> c_rcd("CYCLE_RUBBER_DELAY",
                                       sg_rubberCycleDelay,
                                       nConfItemVersionWatcher::Group_Visual,
                                       6);

// by this factor ( meaning that rubber usage goes up by the inverse )
static REAL sg_rubberCycleDelayBonus=.5;
static nSettingItemWatched<REAL> c_rcdb("CYCLE_RUBBER_DELAY_BONUS",
                                        sg_rubberCycleDelayBonus,
                                        nConfItemVersionWatcher::Group_Visual,
                                        6);

// rubber usage gets increased by this amout after each turn...
static REAL sg_rubberCycleMalusTurn=0;
static nSettingItemWatched<REAL> c_rctm("CYCLE_RUBBER_MALUS_TURN",
                                        sg_rubberCycleMalusTurn,
                                        nConfItemVersionWatcher::Group_Visual,
                                        6);

// but the effect wears off after about this many seconds
static REAL sg_rubberCycleMalusTime=5;
static nSettingItem<REAL> c_rcmd("CYCLE_RUBBER_MALUS_TIME",
                                 sg_rubberCycleMalusTime);

// time tolerance when interpreting client commands
static REAL sg_timeTolerance=.1;
static nSettingItemWatched<REAL> c_tt( "CYCLE_TIME_TOLERANCE",
                                       sg_timeTolerance,
                                       nConfItemVersionWatcher::Group_Visual,
                                       6 );

static int sg_cycleMaxRefCount = 30000;
static tSettingItem<int> conf_sgCycleMaxRefCount ("CYCLE_MAX_REFCOUNT", sg_cycleMaxRefCount );

static void blocks(const gSensor &s, const gCycleMovement *c, int lr)
{
    if ( nCLIENT == sn_GetNetState() )
        return;

    if (s.type == gSENSOR_RIM)
        gAIPlayer::CycleBlocksRim(c, lr);
    else if (s.type == gSENSOR_TEAMMATE || ( s.type == gSENSOR_ENEMY && s.ehit ) )
    {
        gPlayerWall *w = dynamic_cast<gPlayerWall*>(s.ehit->GetWall());
        if (w)
        {
            // int turn     = c->Grid()->WindingNumber();
            //	  int halfTurn = turn >> 1;

            // calculate the winding number.
            int windingBefore = c->WindingNumber();  // we start driving in c's direction
            // we need to make a sharp turn in the lr-direction
            //	  windingBefore   += lr * halfTurn;

            // after the transfer, we need to drive in the direction of the other
            // wall:
            int windingAfter = w->WindingNumber();

            // if the other wall drives in the opposite direction, we
            // need to turn around again:
            //	  if (s.lr == lr)
            // windingAfter -= lr * halfTurn;

            // make the winding difference a multiple of the winding number
            /*
              int compensation = ((windingAfter - windingBefore - halfTurn) % turn)
              + halfTurn;
              while (compensation < -halfTurn)
              compensation += turn;
            */

            // only if the two walls are parallel/antiparallel, there is true blocking.
            if (((windingBefore - windingAfter) & 1) == 0)
                gAIPlayer::CycleBlocksWay(c, w->Cycle(),
                                          lr, s.lr,
                                          w->Pos(s.ehit->Ratio(s.before_hit)),
                                          - windingAfter + windingBefore);
        }
    }
}

// enemy influence settings
static REAL sg_enemyFriendTimePenalty = 2500.0f;  //!< penalty for teammate influence
// REAL sg_enemySelfTimePenalty = 5000.0f;    //!< penalty for self influence
static REAL sg_enemyDeadTimePenalty = 0.0f;       //!< penalty for influence from dead players
REAL sg_suicideTimeout = 10000.0f;         //!< influences older than this don't count as kill cause
static REAL sg_enemyCurrentTimeInfluence = 0.0f;  //!< blends in the current time into the relevant time

static tSettingItem<REAL> sg_enemyFriendTimePenaltyConf( "ENEMY_TEAMMATE_PENALTY", sg_enemyFriendTimePenalty );
static tSettingItem<REAL> sg_enemyDeadTimePenaltyConf( "ENEMY_DEAD_PENALTY", sg_enemyDeadTimePenalty );
static tSettingItem<REAL> sg_suicideTimeoutConf( "ENEMY_SUICIDE_TIMEOUT", sg_suicideTimeout );
static tSettingItem<REAL> sg_enemyCurrentTimeInfluenceConf( "ENEMY_CURRENTTIME_INFLUENCE", sg_enemyCurrentTimeInfluence );

// the last enemy possibly responsible for our death
const ePlayerNetID* gEnemyInfluence::GetEnemy() const
{
    return lastEnemyInfluence.GetPointer();
}

REAL gEnemyInfluence::GetTime() const
{
    return lastTime;
}

gEnemyInfluence::gEnemyInfluence()
{
    lastTime = -sg_suicideTimeout;
}

// add the result of the sensor scan to our data
void gEnemyInfluence::AddSensor( const gSensor& sensor, REAL timePenalty, gCycleMovement * thisCycle )
{
    // the client has no need for this, it does not execute AI code
    if ( sn_GetNetState() == nCLIENT )
        return;

    // check if the sensor hit an enemy wall
    // if ( sensor.type != gSENSOR_ENEMY )
    //    return;

    // get the wall
    if ( !sensor.ehit )
        return;

    eWall* wall = sensor.ehit->GetWall();
    if ( !wall )
        return;

    // faraway walls count less.
    if( sensor.GetOwner() )
    {
        REAL speed = sensor.GetOwner()->Speed();
        if( speed > 0 )
        {
            REAL distance = sensor.Direction().Norm() * sensor.hit;
            timePenalty += distance/speed;
        }
    }

    AddWall( wall, sensor.before_hit, timePenalty, thisCycle );
}

// add the interaction with a wall to our data
void gEnemyInfluence::AddWall( const eWall * wall, eCoord const & pos, REAL timePenalty, gCycleMovement * thisCycle )
{
    // the client has no need for this, it does not execute AI code
    if ( sn_GetNetState() == nCLIENT )
        return;

    // see if it is a player wall
    gPlayerWall const * playerWall = dynamic_cast<gPlayerWall const *>( wall );
    if ( !playerWall )
        return;

    // get the approximate time the wall was drawn
    REAL alpha = .5f;
    // try to get a more accurate value
    if ( playerWall->Edge() )
    {
        // get the position of the collision point
        alpha = playerWall->Edge()->Ratio( pos );
    }
    REAL timeBuilt = playerWall->Time( alpha );

    AddWall( playerWall, timeBuilt, timePenalty, thisCycle );
}

// add the interaction with a wall to our data
void gEnemyInfluence::AddWall( const gPlayerWall * wall, REAL timeBuilt, REAL timePenalty, gCycleMovement * thisCycle )
{
    // the client has no need for this, it does not execute AI code
    if ( sn_GetNetState() == nCLIENT )
        return;

    if ( !wall )
        return;

    // get the cycle
    gCycle *cycle = wall->Cycle();
    if ( !cycle )
        return;

    // don't count self influence
    if ( thisCycle == cycle )
        return;

    REAL time = timeBuilt;
    if ( thisCycle )
    {
        REAL currentTime = thisCycle->LastTime();
        time += ( currentTime - time ) * sg_enemyCurrentTimeInfluence;
    }
    time -= timePenalty;

    // get the player
    ePlayerNetID* player = cycle->Player();
    if ( !player )
        return;

    // don't accept milkers.
    if ( thisCycle && !ePlayerNetID::Enemies( thisCycle->Player(), player ) )
    {
        return;
    }

    // if the player is not our enemy, add extra time penalty
    if ( thisCycle->Player() && player->CurrentTeam() == thisCycle->Player()->CurrentTeam() )
    {
        // the time shall be at most the time of the last turn, it should count as suicide if
        // I drive into your three mile long wall
        if ( time > cycle->GetLastTurnTime() )
            time = cycle->GetLastTurnTime();
        time -= sg_enemyFriendTimePenalty;
    }
    const ePlayerNetID* pInfluence = this->lastEnemyInfluence.GetPointer();

    // calculate effective last time. Add malus if the player is dead.
    REAL lastEffectiveTime = lastTime;
    if ( !pInfluence  || !pInfluence->Object() ||  !pInfluence->Object()->Alive() )
    {
        lastEffectiveTime -= sg_enemyDeadTimePenalty;
    }

    // same for the current influence
    REAL effectiveTime = time;
    if ( !cycle->Alive() )
    {
        effectiveTime -= sg_enemyDeadTimePenalty;
    }

    // if the new influence is newer, take it.
    if ( effectiveTime > lastEffectiveTime || !bool(lastEnemyInfluence) )
    {
        lastEnemyInfluence = player;
        lastTime		   = time;
    }
}

// *******************************************************************************************
// *
// *	gCycleMovement
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

// gCycleMovement::gCycleMovement()
// {
//	this->Init_gCycleCore();
// }

// *******************************************************************************************
// *
// *	gCycleMovement
// *
// *******************************************************************************************
//!
//!		@param	other	the source to copy from
//!
// *******************************************************************************************

// gCycleMovement::gCycleMovement( gCycleMovement const & other )
// {
// 	this->Init_gCycleCore();
//	this->CopyFrom( other );
//}

// *******************************************************************************************
// *
// *	operator =
// *
// *******************************************************************************************
//!
//!		@param	other	the source to copy from
//!		@return			a reference to this
//!
// *******************************************************************************************

gCycleMovement & gCycleMovement::operator= ( gCycleMovement const & other )
{
    this->CopyFrom( other );
    return *this;
}

// *******************************************************************************************
// *
// *	init_gCycleCore
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

//void gCycleMovement::Init_gCycleCore()
//{
//    assert(0); // TODO: implement me
//}

// *******************************************************************************************
// *
// *	finit_gCycleCore
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

//void gCycleMovement::Finit_gCycleCore()
//{
//    assert(0); // TODO: implement me
//}

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

static float sg_speedMultiplier = 1.0f;
static nSettingItem<float> conf_mult ("REAL_CYCLE_SPEED_FACTOR", sg_speedMultiplier);

// *******************************************************************************************
// *
// *	RubberSpeed
// *
// *******************************************************************************************
//!
//!		@return 	the rubber speed (decay rate of the distance to the wall in front)
//!
// *******************************************************************************************

float gCycleMovement::RubberSpeed()
{
    return sg_rubberCycleSpeed;
}

// *******************************************************************************************
// *
// *	SpeedMultiplier
// *
// *******************************************************************************************
//!
//!		@return 	the number all speed settings get multiplied by
//!
// *******************************************************************************************

float gCycleMovement::SpeedMultiplier( void )
{
    return sg_speedMultiplier;
}

// *******************************************************************************************
// *
// *	SetSpeedMultiplier
// *
// *******************************************************************************************
//!
//!		@param	mul	the number all speed settings get multiplied by
//!
// *******************************************************************************************

void gCycleMovement::SetSpeedMultiplier( REAL mul )
{
    conf_mult.Set( mul );
}

// for the given maximal acceleration, calculate the top speed
static REAL sg_MaxSpeed( REAL maxAcceleration )
{
    if ( sg_speedCycleDecayAbove > 0 )
        return sg_speedCycle + maxAcceleration / sg_speedCycleDecayAbove;
    else
        return sg_speedCycle * 100;
}

// *******************************************************************************************
// *
// *	MaximalSpeed
// *
// *******************************************************************************************
//!
//!		@return 	the maximal speed a cycle can reach
//!
// *******************************************************************************************

float gCycleMovement::MaximalSpeed( void )
{
    // determine the maximal acceleration by walls
    REAL maxWallAcceleration = 0;
    REAL wallAcceleration = sg_accelerationCycleTeam * sg_accelerationCycle;
    if ( wallAcceleration > maxWallAcceleration )
        maxWallAcceleration = wallAcceleration;
    wallAcceleration = sg_accelerationCycleEnemy * sg_accelerationCycle;
    if ( wallAcceleration > maxWallAcceleration )
        maxWallAcceleration = wallAcceleration;
    wallAcceleration = sg_accelerationCycleRim * sg_accelerationCycle;
    if ( wallAcceleration > maxWallAcceleration )
        maxWallAcceleration = wallAcceleration;

    // self acceleration is tricky: slingshot countermeasures have to be taken into account
    REAL wallAccelerationSelf = sg_accelerationCycleSelf * sg_accelerationCycle;

    {
        // different combinations are now possible to get a maximum. It could be a single wall:
        REAL wallAccelerationSingle = maxWallAcceleration;
        if ( wallAccelerationSingle < wallAccelerationSelf )
            wallAccelerationSingle = wallAccelerationSelf;

        // it could be a slingshot, one arbitrary wall and one own wall:
        REAL wallAccelerationSlingshot = ( wallAccelerationSingle + wallAccelerationSelf ) * sg_accelerationCycleSlingshot;

        // or a tunnel, two foreign walls:
        REAL wallAccelerationTunnel = ( maxWallAcceleration ) * sg_accelerationCycleTunnel;


        // take the maximum
        if ( maxWallAcceleration < wallAccelerationSlingshot )
            maxWallAcceleration = wallAccelerationSlingshot;
        if ( maxWallAcceleration < wallAccelerationTunnel )
            maxWallAcceleration = wallAccelerationTunnel;
    }

    // use wall accel formula to take wall distance into account
    maxWallAcceleration *= ( 1/sg_accelerationCycleOffs - 1/(sg_accelerationCycleOffs+sg_nearCycle ) );

    // maximal sustainable speed from that
    REAL maxSpeed = sg_MaxSpeed( maxWallAcceleration );

    // what if the brake is a booster?
    if ( sg_brakeCycle < 0 )
    {
        // what if it can be applied infinitely?
        REAL maxSpeedBoost = sg_MaxSpeed( maxWallAcceleration - sg_brakeCycle );

        // but the boost can permanently only be applied at this efficiency
        REAL efficiency = 1;
        if ( sg_cycleBrakeRefill + sg_cycleBrakeDeplete > 0 )
            efficiency = sg_cycleBrakeRefill/(sg_cycleBrakeRefill + sg_cycleBrakeDeplete);

        // maximal permanent speed
        REAL maxSpeedPermanent = sg_MaxSpeed( maxWallAcceleration - sg_brakeCycle*efficiency );

        // if the boost is limited, don't let the result be larger than what you can achieve by
        // accelerating from the max speed attainable from walls
        if ( sg_cycleBrakeDeplete > 0 )
        {
            REAL boostTime = 1/sg_cycleBrakeDeplete;
            REAL maxSpeedBoost2 = maxSpeedPermanent - boostTime * sg_brakeCycle;
            if ( maxSpeedBoost2 < maxSpeedBoost )
                maxSpeedBoost = maxSpeedBoost2;
        }

        // take over the result
        maxSpeed = maxSpeedBoost;
    }

    // start speed
    if ( sg_speedCycleStart > maxSpeed )
        maxSpeed = sg_speedCycleStart;

    // apply multiplier
    return sg_speedMultiplier * maxSpeed;
}

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

// *******************************************************************************************
// *
// *	WindingNumber
// *
// *******************************************************************************************
//!
//!		@return		number of right turns taken minus the number of left turns
//!
// *******************************************************************************************

int gCycleMovement::WindingNumber( void ) const
{
    return windingNumber_;
}

// *******************************************************************************************
// *
// *	SetWindingNumberWrapped
// *
// *******************************************************************************************
//!
//!		@param newWindingNumberWrapped		new wrapped winding number taken from the current driving direction
//!
// *******************************************************************************************

void gCycleMovement::SetWindingNumberWrapped ( int newWindingNumberWrapped )
{
    // calculate the difference in the wrapped winding number
    int difference = newWindingNumberWrapped - windingNumberWrapped_;

    // wrap it into the interval [-WN/2,WN/2]
    if (2 * difference <= -Grid()->WindingNumber())
        difference += Grid()->WindingNumber();
    if (2 * difference >= Grid()->WindingNumber())
        difference -= Grid()->WindingNumber();

    // commit changes
    windingNumberWrapped_ = newWindingNumberWrapped;
    windingNumber_ += difference;
}

// *******************************************************************************************
// *
// *	Direction
// *
// *******************************************************************************************
//!
//!		@return	the currend driving direction
//!
// *******************************************************************************************

eCoord gCycleMovement::Direction( void ) const
{
    return dirDrive;
}

//! @returns the driving direction when the cycle was last spawned

eCoord gCycleMovement::SpawnDirection() const {
    return dirSpawn;
}

// *******************************************************************************************
// *
// *	Killer
// *
// *******************************************************************************************
//!
//!		@return	the potential killer of this cycle
//!
// *******************************************************************************************

eGameObject const * gCycleMovement::Killer() const
{
    ePlayerNetID const * killer = enemyInfluence.GetEnemy();
    if( killer )
    {
        eNetGameObject * killerObject = killer->Object();
        if( killerObject )
        {
            return killerObject;
        }
    }

    // not found? Assume the object closest to the death position is responsible
    gCycleMovement * nearest = NULL;
    float bestDist = 0;
    for( int i = grid->GameObjectsInteresting().Len()-1; i >= 0; --i )
    {
        gCycleMovement * candidate = dynamic_cast< gCycleMovement * >( grid->GameObjectsInteresting()(i) );
        if( candidate && candidate->Alive() && candidate != this )
        {
            REAL dist = (Position() - candidate->Position()).NormSquared();
            if ( !nearest || bestDist > dist )
            {
                bestDist = dist;
                nearest = candidate;
            }
        }
    }
    return nearest;
}

// *******************************************************************************************
// *
// *	LastDirection
// *
// *******************************************************************************************
//!
//!		@return	the last driving direction
//!
// *******************************************************************************************

eCoord gCycleMovement::LastDirection( void ) const
{
    return lastDirDrive;
}

// *******************************************************************************************
// *
// *	Speed
// *
// *******************************************************************************************
//!
//!		@return	the current speed
//!
// *******************************************************************************************

REAL gCycleMovement::Speed( void ) const
{
    REAL ret = verletSpeed_ + .5f * lastTimestep_ * acceleration;
    return ret > 0 ? ret : 0;
}

// *******************************************************************************************
// *
// *	Alive
// *
// *******************************************************************************************
//!
//!		@return		true if the cycle is still alive
//!
// *******************************************************************************************

bool gCycleMovement::Alive() const
{
    return alive_ > 0;
}

// *******************************************************************************************
// *
// *	Vulnerable
// *
// *******************************************************************************************
//!
//!		@return		true if the cycle is vulnerable
//!
// *******************************************************************************************

bool gCycleMovement::Vulnerable() const
{
    return true;
}

// *******************************************************************************************
// *
// *	CanMakeTurn
// *
// *******************************************************************************************
//!
//!	@param  direction the direction of the planned turn
//!		@return	true if a new turn is possible right now
//!
// *******************************************************************************************

bool gCycleMovement::CanMakeTurn( int direction ) const
{
    return pendingTurns.empty() && CanMakeTurn( lastTime, direction );
}

// *******************************************************************************************
// *
// *	CanMakeTurn
// *
// *******************************************************************************************
//!
//!     @param  time the time to check
//!	@param  direction the direction of the planned turn
//!		@return	true if a new turn is possible at the given time
//!
// *******************************************************************************************

bool gCycleMovement::CanMakeTurn( REAL time, int direction ) const
{
    return time >= GetNextTurn(direction);
}

// *******************************************************************************************
// *
// *	GetTurnDelay
// *
// *******************************************************************************************
//!
//!		@return	the delay between turns in seconds
//!
// *******************************************************************************************

REAL gCycleMovement::GetTurnDelay( void ) const
{
    // the basic delay as it was before 0.2.8 looked like this:
    REAL baseDelay   = sg_delayCycle*sg_delayCycleBonus/SpeedMultiplier();

    // we're modifying it by a power law to make speed turns easier or harder:
    REAL speedFactor = verletSpeed_/(sg_speedCycle*SpeedMultiplier());

    return baseDelay * pow( speedFactor, sg_delayCycleTimeBased-1 );
}

//!		@return	the delay between turns in seconds
REAL gCycleMovement::GetTurnDelayDb( void ) const
{
    // the basic delay as it was before 0.2.8 looked like this:
    REAL baseDelay   = sg_delayCycle*sg_delayCycleBonus/SpeedMultiplier()*sg_delayCycleDoublebindBonus;

    // we're modifying it by a power law to make speed turns easier or harder:
    REAL speedFactor = verletSpeed_/(sg_speedCycle*SpeedMultiplier());

    return baseDelay * pow( speedFactor, sg_delayCycleTimeBased-1 );
}

// *******************************************************************************************
// *
// *	GetNextTurn
// *
// *******************************************************************************************
//!
//!		@return	the time of the next possible turn
//!
// *******************************************************************************************

REAL gCycleMovement::GetNextTurn( int direction ) const
{
    float right,left;
#ifdef DEBUG_X
    std::cerr << "GetNextTurn: " << direction << std::endl;
#endif
    if(direction == 1) {
        right = lastTurnTimeRight_ + GetTurnDelayDb();
        left = lastTurnTimeLeft_ + GetTurnDelay();
    } else {
        right = lastTurnTimeLeft_ + GetTurnDelayDb();
        left = lastTurnTimeRight_ + GetTurnDelay();
    }
#ifdef DEBUG_X
    std::cerr << "GetTurnDelay: " << GetTurnDelay() << std::endl;
    std::cerr << "GetTurnDelayDb: " << GetTurnDelayDb() << std::endl;
    std::cerr << "lastTurnTimeRight_: " << lastTurnTimeRight_ << std::endl;
    std::cerr << "lastTurnTimeLeft_: " << lastTurnTimeLeft_ << std::endl;
    std::cerr << "right: " << right << std::endl;
    std::cerr << "left: " << left << std::endl;
#endif
    return left > right ? left : right;
}

// *******************************************************************************************
// *
// *	AddDestination
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

void gCycleMovement::AddDestination( void )
{
    if ( sn_GetNetState() == nCLIENT )
    {
        gDestination* dest = tNEW(gDestination)(*this);
        //	dest->position = dest->position + dest->direction.Turn( 0, 10.0f );
        AddDestination( dest );
    }
}

// *******************************************************************************************
// *
// *	AddDestination
// *
// *******************************************************************************************
//!
//!		@param	dest		the destination to add
//!
// *******************************************************************************************

void gCycleMovement::AddDestination( gDestination * dest )
{
    //  con << "got new dest " << dest->position << "," << dest->direction
    // << "," << dest->distance << "\n";

    dest->InsertIntoList(&destinationList);

    // if the next destination already has been used, this destination will never be used
    if (dest->next && dest->next->hasBeenUsed){
        delete dest;
        return;
    }

    this->RequestSimulation();

    this->NotifyNewDestination( dest );

    // repeat insertion: position may have changed
    dest->InsertIntoList(&destinationList);
}

// *******************************************************************************************
// *
// *	GetCurrentDestination
// *
// *******************************************************************************************
//!
//!		@return		the destination this cycle is driving towards right now
//!
// *******************************************************************************************

gDestination * gCycleMovement::GetCurrentDestination( void ) const
{
    return currentDestination;
}

// *******************************************************************************************
// *
// *	AdvanceDestination
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

void gCycleMovement::AdvanceDestination( void )
{
    // not implemented
    tASSERT(0);
}

// *******************************************************************************************
// *
// *	NotifyNewDestination
// *
// *******************************************************************************************
//!
//!		@param	dest	   the new destination the cycle is notified about
//!
// *******************************************************************************************

void gCycleMovement::NotifyNewDestination( gDestination * dest )
{
    this->OnNotifyNewDestination( dest );
}

// *******************************************************************************************
// *
// *	DoIsDestinationUsed
// *
// *******************************************************************************************
//!
//!		@param	dest	the destination to test
//!		@return			true if the destination is still in active use
//!
// *******************************************************************************************

bool gCycleMovement::DoIsDestinationUsed( const gDestination * dest ) const
{
    return ( destinationList == currentDestination || destinationList == lastDestination );
}

// *******************************************************************************************
// *
// *	DistanceToDestination
// *
// *******************************************************************************************
//!
//!		@param	dest	the destination to measure the distance to
//!		@return			the distance to the destination
//!
// *******************************************************************************************

REAL gCycleMovement::DistanceToDestination( gDestination & dest ) const
{
    // read future direction from destination
    eCoord dirTurned = dest.direction;

    REAL divisor = ( dirDrive * dirTurned );
    if ( divisor < EPS && divisor > -EPS )
    {
        REAL F = eCoord::F( dirTurned, dirDrive );
        if ( F > 0 )
        {
            // destination direction and driving direction coincide; we have to
            // make up a new turned direction

            // no need to worry if brake status changed
            if ( ( braking != 0 ) != dest.braking )
            {
                return eCoord::F( dest.position - pos, dirDrive )/dirDrive.NormSquared();
            }

            // we'd have to turn in this direction to reach the destination
            int side = (dest.position - pos) * dirDrive > 0 ? -1 : 1;

            // pretend to turn in that direction and fetch driving vector
            int w = windingNumberWrapped_;
            Grid()->Turn(w, side);
            dirTurned = Grid()->GetDirection( w );

            // recalculate divisor
            divisor = ( dirDrive * dirTurned );
            tASSERT( fabs( divisor ) > EPS );
        }
        else
        {
            // destination direction and driving direction are opposed. This must be a grave error,
            // so we'll make something up
            return eCoord::F( dest.position - pos, dirDrive )/dirDrive.NormSquared();
        }
    }

    // calculate when a turn would need to be made that aligns
    // this cycle with the destination
    return ( ( dest.position - pos ) * dirTurned ) / divisor;
}

// *******************************************************************************************
// *
// *	OnNotifyNewDestination
// *
// *******************************************************************************************
//!
//!		@param	dest	   the new destination
//!
// *******************************************************************************************

void gCycleMovement::OnNotifyNewDestination( gDestination * dest )
{
    // go back one destination if the new destination appears to be older than the current one
    if ((!currentDestination || currentDestination == dest->next ) &&
            sn_GetNetState()!=nSTANDALONE && ( Owner() != ::sn_myNetID || !destinationList ) )
    {
        currentDestination=dest;
        // con << "setting new cd\n";
    }
}

// *******************************************************************************************
// *
// *	OnDropTempWall
// *
// *******************************************************************************************
//!
//!		@param	wall	   the wall the other cycle is grinding
//!		@param	pos	       the position of the grind
//!     @param  dir        the direction the raycast triggering the gridding comes from
//!
// *******************************************************************************************

void gCycleMovement::OnDropTempWall( gPlayerWall * wall, eCoord const & pos, eCoord const & dir )
{
}

// *******************************************************************************************
// *
// *   GetDestinationBefore
// *
// *******************************************************************************************
//!
//!        @param  sync     the sync data received from the server
//!        @param  first    the first candidate for the return value
//!        @return          the destination entry that was last processed on the server
//!
// *******************************************************************************************

gDestination * gCycleMovement::GetDestinationBefore( const SyncData & sync, gDestination * first )
{
    // message IDs smaller than 16 don't exist
    if ( sync.messageID != 1 )
    {
        gDestination * ret = first;

        // deterimine last passed destination by the message ID
        while ( ret && ret->messageID != sync.messageID )
            ret = ret->next;

        // return match
        return ret;
    }
    else
    {
        // calculate the distance of the last turn of the sync
        REAL syncLastTurnDistance = sync.distance - ( sync.pos - sync.lastTurn ).Norm();

        // message ID not available; must use heuristics
        gDestination * run = first;         // destination iterator
        gDestination * bestMatch = NULL;    // the best message that fit the sync data and that lies before the sync
        REAL bestMatchDistance = 1E+20;     // the distance of the best message to the sync
        bool braking = false;               // braking causes trouble here. Activate extra checks if brakes are involved
        while ( run )
        {
            // calculate discrepancy of last turn distance of sync to the current message's distance
            REAL distanceBefore = syncLastTurnDistance - run->distance;
            REAL distanceAfter  = run->distance - sync.distance;


            // the allowed values for run->distance are inside the interval [ syncLastTurnDistance,sync.distance ]
            // distance is a metric that is positive outside of the interval and
            // negative inside it, with minimum in the center.
            REAL distance = distanceBefore < distanceAfter ? distanceBefore : distanceAfter;

            // activate brake trouble compensation
            if ( distance < 0 && ( run->braking || sync.braking ) )
            {
                // void previous match
                if ( !braking )
                    bestMatchDistance += 1;
                braking = true;
            }

            // clamp distance to nonnegative values to give points inside the allowed interval
            // equal chances
            if ( distance < 0 )
                distance = 0;

            // prefer destinations close to the end of the allowed interval if braking is involved, else destinations close to the beginning
            if ( braking )
            {
                distance += fabs( distanceAfter + .01 * distanceBefore ) * .0001;
            }
            else
            {
                distance += fabs( distanceBefore ) * .1;
            }

            // see if brake status and driving direction match; this is a must
            if ( eCoord::F( run->direction, sync.dir ) > .9*sync.dir.NormSquared() && run->braking == ( sync.braking != 0 ) )
            {
                if ( !bestMatch || distance < bestMatchDistance )
                {
                    bestMatch = run;
                    bestMatchDistance = distance;
                }
            }
            run = run->next;
        }

        // con << bestMatchDistance << "\n";

        // return match
        return bestMatch;
    }
}

// *******************************************************************************************
// *
// *	EdgeIsDangerous
// *
// *******************************************************************************************
//!
//!		@param	wall	the wall to check for danger
//!		@param	time	the time of the possible collision
//!		@param	alpha	the local wall coordinate of the collision
//!		@return			true if the wall is dangerous
//!
// *******************************************************************************************

bool gCycleMovement::EdgeIsDangerous( const eWall * wall, REAL time, REAL alpha ) const
{
    if (!wall)
        return false;

    const gPlayerWall *w = dynamic_cast<const gPlayerWall*>(wall);
    if (w)
    {
        // have we entered a hole? Is the wall breaking down? Have we passed behind the end?
        if ( !w->IsDangerous( alpha, time ) )
            return false;

        // get time the wall was built
        // REAL builtTime = w->Time(alpha);

        //gCycleMovement *otherPlayer=w->CycleMovement();
        //if (otherPlayer==this && time < builtTime+2.5*GetTurnDelay() )
        //    return false;        // impossible to make such a small circle
        // no, not impossible, just moderately unlikely.
    }

    return true; // it is a real eWall.
}

// *******************************************************************************************
// *
// *	Turn
// *
// *******************************************************************************************
//!
//!		@param	dir	negative for left turns, positive for right turns
//!		@return		true if the turning was successful
//!
// *******************************************************************************************

bool gCycleMovement::Turn( REAL dir )
{
    if (dir>0)
        return Turn(1);
    else if (dir<0)
        return Turn(-1);
    else
        return false;
}

// *******************************************************************************************
// *
// *	Turn
// *
// *******************************************************************************************
//!
//!		@param	dir	+1 for right turns, -1 for left turns
//!		@return		true if the turning was successful
//!
// *******************************************************************************************

bool gCycleMovement::Turn( int dir )
{
    return DoTurn( dir );
}

static void sg_DropTempWall( eCoord const & dir, gSensor const & sensor )
{
    tASSERT( sensor.ehit );

    if (sn_GetNetState() != nCLIENT )
    {
        // if the wall is temporary, let its cycle drop it so it gets copied into the grid
        // and makes less phasing problems
        // don't drop parallel walls
        eCoord vec = sensor.ehit->Vec();
        if ( fabs( dir * vec ) < vec.Norm() * .5 )
            return;

        // get the wall
        eWall * ew = sensor.ehit->GetWall();
        tASSERT( ew );
        gPlayerWall* w = dynamic_cast< gPlayerWall * >( ew );

        // check if wall exists
        if ( w )
        {
            // get the cycle
            gCycleMovement* other = w->CycleMovement();

            // let it drop wall
            if ( other )
                other->DropTempWall( w, sensor.before_hit, dir );
        }
    }
}

//! information about obstacle encountered by MaxSpaceAhead
struct gMaxSpaceAheadHitInfo
{
    eCoord            pos;                           //!< the location it was hit at
    REAL              offset;                        //!< offset from mindistance values, to be subtracted from wall distacne

    tJUST_CONTROLLED_PTR< eHalfEdge const > edge;    //!< the edge that was hit
    tJUST_CONTROLLED_PTR< gPlayerWall > playerWall;  //!< the player wall that was hit
    REAL wallAlpha;                                  //!< the wall alpha value of the hit

    gMaxSpaceAheadHitInfo()
            : offset(0), wallAlpha(.5)
    {}
};

// clearer of that data
gMaxSpaceAheadHitInfoClearer::gMaxSpaceAheadHitInfoClearer( gMaxSpaceAheadHitInfo * & info )
        : info_( info ){}

gMaxSpaceAheadHitInfoClearer::~gMaxSpaceAheadHitInfoClearer()
{
    gMaxSpaceAheadHitInfo * info = info_;
    if ( info )
    {
        // we can't have the edges lingering around with possibly incomplete data
        info->edge = NULL;
        info->playerWall = NULL;
    }
}


// checks for gaps
// front: front sensor
// side: side sensor
// dir: direction side sensor is pointing at
// norm: length of front wall
// def: default gap size to return
// tolerance: filled with value small compared to geometry
static REAL sg_Gap( gSensor const & front, gSensor const & side, eCoord const & dir, REAL norm, REAL def, REAL & tolerance )
{
    if ( side.ehit && side.ehit->Other() )
    {
        // determine the distance of the two endpoints of the side edge
        // to the wall in front of us
        REAL gap1 = ( front.ehit->Vec()*( *side.ehit->Point() - *front.ehit->Point() ) )/norm;
        REAL gap2 = ( front.ehit->Vec()*( *side.ehit->Other()->Point() - *front.ehit->Point() ) )/norm;

        // correct for orientation using the current driving direction
        REAL sign = (dir * front.ehit->Vec())/norm;
        if ( sign != 0 )
        {
            sign = 1/sign;
            gap1 *= sign;
            gap2 *= sign;
        }

        // if both values are positive, update the cache with the smaller one
        tolerance = ( fabs(gap1) + fabs(gap2) ) * EPS * 10;
        REAL minGap = gap1 < gap2 ? gap1 : gap2;

        return minGap;
    }
    else
    {
        // return something close to the front wall
        tolerance = EPS * 10 * front.hit;
        return def;
    }
}

/*
// determines the built time of a sensor hit
static REAL sg_BuildTime( eSensor const & sensor )
{
    if( !sensor.ehit )
    {
        return 0;
    }

    eWall * wall = sensor.ehit->GetWall();
    if( !wall )
    {
        return 0;
    }

    // see if it is a player wall
    gPlayerWall const * playerWall = dynamic_cast<gPlayerWall const *>( wall );
    if ( !playerWall )
        return 0;

    // get the approximate time the wall was drawn
    REAL alpha = .5f;
    // try to get a more accurate value
    if ( playerWall->Edge() )
    {
        // get the position of the collision point
        alpha = playerWall->Edge()->Ratio( sensor.before_hit );
    }
    
    return playerWall->Time( alpha );
}
*/

// checks whether the path between side1 and side2 is a 'backdoor', a 'cheap' way
// out of a trap. Open play etiquette demands that you follow enemies that trap you and
// not turn around and escape round the back.
static bool sg_GapBackdoorHelper( gSensor const & side1, gSensor const & side2, int dir )
{
    // assume side1 is the side with the enemy trail.
    if( side1.type != gSENSOR_ENEMY )
    {
        return true;
    }

    // it also needs to lead *away* from us
    if( side1.lr != dir )
    {
        return true;
    }

    /* Bad idea. produces false positives.
    // and if the other side is our own wall...
    if( side2.type == gSENSOR_TEAMMATE || side2.type == gSENSOR_SELF )
    {
        // then side1 needs to be newer.
        REAL time1 = sg_BuildTime( side1 );
        REAL time2 = sg_BuildTime( side2 );

        if( time1 < time2 )
        {
            return true;
        }
    }
    */

    return false;
}

static bool sg_GapBackdoor( gSensor const & side1, gSensor const & side2, int dir )
{
    if( !side1.ehit || !side2.ehit )
    {
        return true;
    }

    // going between two of your own wall is not backdooring
    if( side1.type == gSENSOR_SELF && side2.type == gSENSOR_SELF )
    {
        return false;
    }

    return sg_GapBackdoorHelper( side1, side2, dir ) &&
        sg_GapBackdoorHelper( side2, side1, -dir );
}

static REAL sg_rubberCycleMinDistanceGap = .0f;        // if != 0, CYCLE_RUBBER_MINDISTANCE effectively is never bigger than this value times the size of any detected gaps the cylce can squeeze through.
static REAL sg_rubberCycleMinDistanceGapBackdoor = .0f;// if != 0, CYCLE_RUBBER_MINDISTANCE effectively is never bigger than this value times the size of any detected backdoor gaps the cylce can squeeze through. If = 0, sg_rubberCycleMinDistanceGap applies.
static REAL sg_rubberCycleMinDistanceGapSide = .5f;   // Gaps may be detected only if the cycle is able to drive into them in this time

static nSettingItemWatched<REAL> c_rcmdg("CYCLE_RUBBER_MINDISTANCE_GAP",
        sg_rubberCycleMinDistanceGap, nConfItemVersionWatcher::Group_Bumpy, 14 );
static nSettingItemWatched<REAL> c_rcmdgbd("CYCLE_RUBBER_MINDISTANCE_GAP_BACKDOOR",
        sg_rubberCycleMinDistanceGapBackdoor, nConfItemVersionWatcher::Group_Bumpy, 17 );
static nSettingItem<REAL> c_rcmdgs("CYCLE_RUBBER_MINDISTANCE_GAP_SIDE",
                                   sg_rubberCycleMinDistanceGapSide);

// *******************************************************************************************
// *
// *	MaxSpaceAhead
// *
// *******************************************************************************************
//!     determines how much a given cycle is allowed to drive ahead without getting too close to the next wall. Looks exactly lookAhead into the future.
//!
//!		@param	cycle the cycle to investigate
//!     @param  lookAhead minimum distance to look ahead
//!     @param  rubber expected to be used up until we hit the wall
//!     @param  extra info storage space
//!		@return		distance from the cycle to the next wall
//!
// *******************************************************************************************

// *******************************************************************************************
// *
// *	GetMaxSpaceAhead
// *
// *******************************************************************************************
//!     determines how much this cycle is allowed to drive ahead without getting too close to the next wall. Looks exactly lookAhead into the future.
//!
//!     @param      maxReport maximal distance to report
//!		@return		distance from the cycle to the next wall
//!
// *******************************************************************************************

REAL gCycleMovement::GetMaxSpaceAhead( REAL maxReport ) const
{
    // refresh hit info if required
    if ( refreshSpaceAhead_ )
    {
        refreshSpaceAhead_ = false;

        // make sure the raycast is long enoigh
        REAL lookAhead = maxSpaceMaxCast_;
        if ( maxReport > lookAhead )
        {
            lookAhead = maxReport;
        }

        sg_ArchiveReal( lookAhead, 9 );

        // store data here for later
        gMaxSpaceAheadHitInfo info;

        // calculate the relevant minimal distance
        REAL mindistance = sg_rubberCycleMinDistance;
        {
            // get rubber values
            REAL rubber_granted, rubberEffectiveness;
            sg_RubberValues( player, verletSpeed_, rubber_granted, rubberEffectiveness );

            // add the reservoir dependant term
            if ( rubber_granted > 0 )
            {
                // rubber usage speed
                REAL rubberUsageSpeed = verletSpeed_ * ( 1 - rubberSpeedFactor ) / rubberEffectiveness;
                // rubber used till end of frame
                REAL rubberUsed = rubberUsageSpeed * lastTimestep_;

                // fill ratio of rubber at the end of the next frame
                REAL filling = ( GetRubber() + rubberUsed )/rubber_granted;
                if ( filling > 1 )
                    filling = 1;
                mindistance += sg_rubberCycleMinDistanceReservoir * (1-filling);
            }

            // add the bad preparation dependant term
            if ( sg_rubberCycleMinDistancePreparation > 0 )
            {
                REAL badPreparation = sg_rubberCycleMinDistancePreparation/( sg_rubberCycleMinDistancePreparation + ( this->LastTime() - this->GetLastTurnTime() ) );
                mindistance += sg_rubberCycleMinDistanceUnprepared * badPreparation;
            }
        }
        sg_ArchiveReal( mindistance, 9 );

        // since we are going to subtract the rubber min distance from the found hit, we'll still have to llok a bit further:
        lookAhead += mindistance * sg_rubberCycleMinDistanceLegacy * 2;

        // be a little nice and don't drive into the eWall if turning is allowed
        gSensor fr( const_cast< gCycleMovement* >(this), this->Position(), this->Direction() );
        {
            REAL speed = this->Speed();
            if ( speed > 0 )
                fr.SetInverseSpeed( 1 / speed );
        }
        fr.detect( lookAhead );

        info.edge = fr.ehit;
        info.pos  = fr.before_hit;

        if ( fr.ehit )
        {
            {
                // get the wall of the hit
                eWall * w = info.edge->GetWall();
                if ( !w && info.edge->Other() )
                {
                    info.edge = info.edge->Other();
                    w = info.edge->GetWall();
                }

                gPlayerWall * wall = dynamic_cast< gPlayerWall * >( w );
                if ( wall && wall->Cycle() )
                {
                    // get the position of the hit and store everything
                    info.wallAlpha = info.edge->Ratio( info.pos );
                    info.playerWall = wall;
                }
            }

#ifdef DEBUG
            {
                gSensor fr2( const_cast< gCycleMovement* >( this ), this->Position(), this->Direction() );
                fr2.detect( lookAhead );
            }
#endif

            REAL stopDistance = 0.1;
            if ( fr.ehit )
            {
                REAL norm = fr.ehit->Vec().Norm();
                stopDistance = mindistance + sg_rubberCycleMinDistanceRatio * norm;

                ::sg_DropTempWall( this->Direction(), fr );

                // enforce "open" play: every successive grind to a wall can get closer and closer.

                REAL rubberCycleMinDistanceGapDistance = sg_rubberCycleMinDistanceGapSide * Speed();


                if ( sg_rubberCycleMinDistanceGap > 0 || sg_rubberCycleMinDistanceGapBackdoor > 0 )
                {
                    // determine the width of the gap previous grinders left
                    for ( int dir = -1; dir < 2; dir += 2 )
                    {
                        // see if cached value is still good
                        REAL & gapCache = gap_[(dir+1)/2];
                        bool & keepLooking = keepLookingForGap_[(dir+1)/2];
                        bool & backdoor = gapIsBackdoor_[(dir+1)/2];

                        if ( gapCache > fr.hit && keepLooking )
                        {
                            // determine next direction when turning into dir
                            int wn = windingNumberWrapped_;
                            Grid()->Turn(wn, dir);
                            eCoord dirCast = Grid()->GetDirection(wn);

                            bool gapFound = false;
                            for ( int back = 0; back <= 2; ++back )
                            {
                                // determine next direction when turning into dir
                                int wn2 = wn;
                                Grid()->Turn(wn2, back);
                                eCoord dirCast2 = Grid()->GetDirection(wn2);

                                // send out a side sensor
                                gSensor side( const_cast< gCycleMovement * >( this ),
                                              this->Position(),
                                              ( dirCast + dirCast2 ) * .5 );

                                side.detect( rubberCycleMinDistanceGapDistance );

                                // only allow non-hit default search for the ray that goes straight to the side
                                if ( back != 0 && !side.ehit )
                                    continue;

                                REAL tolerance;
                                REAL minGap = sg_Gap( fr, side, dirDrive, norm, fr.hit * .5, tolerance );
                                while ( minGap > tolerance )
                                {
                                    // last test: see if there really is a gap after that wall ends
                                    gSensor side2( const_cast< gCycleMovement * >( this ),
                                                   this->Position() + this->Direction() * ( fr.hit - minGap * .9 ),
                                                   dirCast );
                                    side2.detect( rubberCycleMinDistanceGapDistance );

                                    // if this sensor did not hit or hit farther than the first sensor, the gap is real
                                    if ( fabs(side2.hit - side.hit) < tolerance )
                                    {
                                        // true gap not found yet
                                        REAL dumpTolerance;
                                        REAL lastMinGap = minGap;
                                        minGap = sg_Gap( fr, side2, dirDrive, norm, minGap * .5, dumpTolerance );
                                        // no improvement? give up.
                                        if ( minGap >= lastMinGap * .9 )
                                            break;
                                    }
                                    else
                                    {
                                        gapFound = true;

                                        // true gap found, is it smaller than the last one?
                                        if ( minGap < gapCache )
                                        {
                                            gapCache = minGap;

                                            backdoor = sg_GapBackdoor( fr, side, dir );

                                            // bail out of outer loop
                                            back = 100;
                                        }

                                        // bail out of inner loop
                                        break;
                                    }
                                }
                            }

                            // no gap to see anywhere
                            if ( ! gapFound )
                            {
                                // don't waste time looking from now on
                                keepLooking = false;

                                // if there was no gap detected so far, there is no gap.
                                if ( gapCache > 5E+19 )
                                {
                                    gapCache = 0;
                                    backdoor = false;
                                }
                            }
                        }
                    }

                    // fetch cache, ignoring zeroes
                    int gapIndex = ( ( gap_[0] > 0 ? gap_[0] : 1E+30 ) < ( gap_[1] > 0 ? gap_[1] : 1E+30 ) ) ? 0 : 1;
                    REAL gap =  gap_[gapIndex];
                    if ( gap > 0 )
                    {
                        // find correct gap factor. Normal...
                        REAL gapFactor = sg_rubberCycleMinDistanceGap;
                        if( sg_rubberCycleMinDistanceGapBackdoor > 0 && gapIsBackdoor_[gapIndex] )
                        {
                            // or backdoor.
                            gapFactor = sg_rubberCycleMinDistanceGapBackdoor;
                        }
                            
                        if ( gapFactor > 0 )
                        { 
                            if( gapFactor > 1 )
                            {
                                // larger that 1 gap factors just increase the minimal stop distance.
                                stopDistance *= gapFactor;
                            }
                            else
                            {
                                // apply gap factor to measured gap
                                REAL minDistanceGap = gap * gapFactor;

                                // smaller then 1 gap factors are relative to the measured gap.
                                if ( stopDistance > minDistanceGap )
                                {
                                    stopDistance = minDistanceGap;
                                }
                            }
                        }
                    }
                }
            }
            sg_ArchiveReal( stopDistance, 9 );


            // revert to almost old rubber logic if old clients are connected. This may cause rips, but we don't care.
            if ( sg_rubberCycleLegacy && !sg_nonRippable.Supported() && stopDistance > .001 )
                stopDistance = .001;

            // if there is a rippable peer connected and the wall is the rim wall, add extra distance
            //if ( fr.type == gSENSOR_RIM && !sg_nonRippable.Supported() )
            //    stopDistance *= sg_rubberCycleMinDistanceLegacy;

            REAL space = fr.hit;
            sg_ArchiveReal( space, 9 );

            // see if we just did a turn
            REAL distSinceLastTurn = this->GetDistanceSinceLastTurn();

            // we want to get closer to the wall by at least some percentage
            REAL maxStop = ( distSinceLastTurn + space ) * ( 1 - sg_rubberCycleMinAdjust );
            if ( maxStop < stopDistance )
            {
                stopDistance = maxStop;
            }

            sg_ArchiveReal( stopDistance, 9 );

            // add safety
            REAL safety = this->Position().Norm() * 2 * EPS;

            info.offset = stopDistance + safety;

            sg_ArchiveReal( space, 9 );

            // create new hit info
            if ( !maxSpaceHit_ )
                maxSpaceHit_ = tNEW( gMaxSpaceAheadHitInfo );

            // store information
            *maxSpaceHit_ = info;
        }
        else
        {
            // delete information
            delete maxSpaceHit_;
            maxSpaceHit_ = NULL;
        }
    }

    // information up to date? Good, just take the distance to the collision point.
    REAL ret = 1E+30;
    if ( maxSpaceHit_ )
    {
        ret = eCoord::F( dirDrive, maxSpaceHit_->pos - pos ) - maxSpaceHit_->offset;
    }

    // clamp it and return.
    if ( ret > maxReport )
        ret = maxReport;
    return ret;
}

// *******************************************************************************************
// *
// *	MaxSpaceAhead
// *
// *******************************************************************************************
//!     determines how much a given cycle is allowed to drive ahead without getting too close to the next wall. Looks at least lookAhead into the future, but never reports more than maxReport as result. The next timestep is assumed to be ts seconds long.

//!		@param	cycle the cycle to investigate
//!     @param  ts the next timestep
//!     @param  lookAhead minimum distance to look ahead
//!     @param  maxReport maximum return value
//!		@return		distance from the cycle to the next wall
//!
// *******************************************************************************************

/*
float MaxSpaceAhead( const gCycleMovement* cycle, float ts, float lookAhead, float maxReport )
{
    // lookahead should be at least the next expected timestep ( times two for safety )
    REAL step=cycle->Speed() * ts * 2;
    if ( lookAhead < step )
        lookAhead = step;

    // lookahead should be at least maxReport
    if ( lookAhead < maxReport )
        lookAhead = maxReport;

    REAL space = MaxSpaceAhead( cycle, lookAhead );

    if ( space < maxReport )
        return space;
    else
        return maxReport;
}
*/

// feature indicating that a client sends the time of turn commands
static nVersionFeature sg_CommandTime( 4 );

// server side feature of lag sliding correction code
static nVersionFeature sg_AntiLag( 5 );

// flag indicating whether to use the logic to prevent lag sliding only when every connected client can benefit from it
static bool sg_fairAntiLagSliding=true;
static nSettingItem<bool> c_fals("CYCLE_FAIR_ANTILAG",sg_fairAntiLagSliding);

// check if we should apply anti-lag-sliding code
static bool sg_UseAntiLagSliding( const eNetGameObject* obj )
{
    tASSERT( obj );

    // cant do anyting for old clients that don't send the time of commands
    if ( !sg_CommandTime.Supported( obj->Owner() ) )
        return false;

    // likewise if the server does not support anti lag code and this is the client
    if ( sn_GetNetState() == nCLIENT && !sg_AntiLag.Supported( obj->Owner() ) )
        return false;

    // check whether the command time is sent by everyone or at least the object owner ( depending on fairness )
    if ( sg_fairAntiLagSliding )
    {
        return sg_CommandTime.Supported();
    }
    else
    {
        // we already checked whether the command time was sent
        return true;
    }
}

// while an object of this class exists, turn delay is ignored
class gTurnDelayOverride
{
public:
    explicit gTurnDelayOverride( bool override )
    {
        delay_ = sg_delayCycle;
        if ( override )
            sg_delayCycle = 0.0f;
    }

    explicit gTurnDelayOverride( REAL factor )
    {
        delay_ = sg_delayCycle;
        sg_delayCycle *= factor;
    }

    ~gTurnDelayOverride()
    {
        sg_delayCycle = delay_;
    }
private:
    REAL delay_;
};

static nVersionFeature sg_noRedundantBrakeCommands( 13 );

// *******************************************************************************************
// *
// *	Timestep
// *
// *******************************************************************************************
//!
//!		@param	currentTime	the time to simulate up to
//!		@return	true if the cycle is to be deleted
//!
// *******************************************************************************************

bool gCycleMovement::Timestep( REAL currentTime )
{
/*
    static int count = 1;
    ++count;
    if ( count == 0 )
    {
        int xc;
        xc = 0;
    }
*/

    // request regeneration of maximum space
    refreshSpaceAhead_ = true;

    // clear out dangerous info when we're done
    gMaxSpaceAheadHitInfoClearer hitInfoClearer( maxSpaceHit_ );

    // clamp stuff to finite values
    clamp( rubber, 0, sg_rubberCycle );

    // keep this cycle alive
    tJUST_CONTROLLED_PTR< gCycleMovement > keep( this->GetRefcount()>0 ? this : 0 );

    // don't make a fuss about negative timesteps
    // if ( currentTime < lastTime )
    // {
    //     return TimestepCore( currentTime );
    // }

    // remove old destinations
    //REAL lag = 1;
    //if ( player )
    //    lag = player->ping;
    // REAL lagDistance = lag * Speed() * 10;

    while(destinationList && destinationList->hasBeenUsed && !IsDestinationUsed( destinationList ) )
        delete destinationList;

    // calculate timestep
    REAL dt = currentTime - lastTime;

    sg_ArchiveReal( dt, 9 );

    bool vetoSimulationRequest = false; // set if the simulation was aborted even though events are still there to be taken care of

    // if (currentTime > lastTime)
    {
        int timeout=10;
        bool forceTurn = false; // force turning at the next iteration
        bool overrideTurnDelay=false; // override the turn delay system, turn immediately

        // only simulate forward in time
        while (pendingTurns.empty() && currentDestination && timeout > 0 )
        {
            timeout --;

            // the distance to the next destination
            REAL dist_to_dest = DistanceToDestination( *currentDestination );
            sg_ArchiveReal( dist_to_dest, 9 );

            REAL ts=currentTime - lastTime;
            sg_ArchiveReal( ts, 9 );

            sg_ArchiveReal( verletSpeed_, 9 );
            sg_ArchiveReal( acceleration, 9 );

            // our speed
            REAL avgspeed=verletSpeed_;
            CalculateAcceleration();
            if (acceleration > 0)
                avgspeed += acceleration * SpeedMultiplier() * ts * .5;

            // will rubber slow the cycle down to a crawl, so that the command time will be
            // a better indication when to turn than the position?
            bool rubberActive = false;

            // check if the path to the destination is clear for the next timesteps
            sg_ArchiveReal( rubberSpeedFactor, 9 );
            REAL distToWall=1E+30;
            if ( rubberSpeedFactor < .999 )
            {
                // take rubber activity into account
                rubberActive = true;
                avgspeed *= rubberSpeedFactor;
                if ( avgspeed < EPS )
                    avgspeed = EPS;

                sg_ArchiveReal( avgspeed, 9 );

                // don't drive into a wall, turn before getting too close
                REAL lookahead = ( fabs(ts * avgspeed)+fabs(dist_to_dest) ) * 2;
 
                distToWall = GetMaxSpaceAhead( lookahead );

                // don't turn after passing a wall, if timing allows
                if ( dist_to_dest > distToWall )
                    dist_to_dest = distToWall;
            }

            // static bool breakp = false;

            // the time left until the turn happened on the client
            // REAL timeLeft = currentDestination->GetGameTime() - lastTime;

            // the earliest and latest allowed time to turn
            REAL turnTime = currentDestination->GetGameTime();
            REAL earliestTurnTime = turnTime - sg_timeTolerance - 100;
            REAL latestTurnTime   = turnTime + sg_timeTolerance;

            // if rubber is active and anti lag sliding code should be enabled,
            // then allow no too early or late turns
            if ( sg_UseAntiLagSliding( this ) )
            {
                if ( rubberActive )
                {
                    // smoothly make the allowed time interval smaller with increased rubber use
                    earliestTurnTime = turnTime - sg_timeTolerance * rubberSpeedFactor;
                    latestTurnTime = turnTime + sg_timeTolerance * rubberSpeedFactor;

                    // clamp latest turn time so we don't drive into the wall
                    if ( verletSpeed_ > 0 )
                    {
                        REAL maxRubber, effectiveness;
                        sg_RubberValues( Player(), verletSpeed_, maxRubber, effectiveness );

                        // see when we'll die (be a little careful, the .9 is a fudge factor)
                        REAL rubberLeft = (maxRubber - rubber)*.9;
                        REAL stepLeft   = rubberLeft + distToWall;
                        REAL timeLeft   = stepLeft/verletSpeed_;
                        REAL deathTime  = lastTime + timeLeft;

                        // can't do a thing if the player wants to die
                        if ( deathTime < turnTime )
                            deathTime = turnTime;

                        // clamp latest possible time
                        if ( latestTurnTime > deathTime )
                            latestTurnTime = deathTime;
                    }
                }
                else
                {
                    // just clamp the latest turn time
                    earliestTurnTime = turnTime - sg_timeTolerance;
                }
            }

            sg_ArchiveReal( dist_to_dest, 9 );

            REAL simulateAhead = MaxSimulateAhead();

            if ( dist_to_dest > ( ts + simulateAhead ) * avgspeed && currentTime < latestTurnTime )
            {
                vetoSimulationRequest = true;
                break; // no need to worry; we won't reach the next destination
            }

            if ( currentTime + simulateAhead < earliestTurnTime && sg_CommandTime.Supported( Owner() ) )
            {
                vetoSimulationRequest = true;
                break; // the turn is too far in the future
            }

            // if ( currentTime < turnTime + EPS )
            //    simulateAhead = 0;

            // determine whether to turn left or right (coping with weird axis settings)
            int turnTo=0;
            // and whether between the last and next destination, there was one missing that
            // we didn't receive.
            bool missed=false;

            {
                REAL t = currentDestination->direction * dirDrive;
                bool turn = true;

                missed  = (fabs(t)<.01);
                if (int(braking) != int(currentDestination->braking))
                {
                    turn = false;
                    missed=!missed;
                }

                // detect false misses: if the last destination's message ID is just
                // one below the current destination's message ID, it's a fake
                if ( missed && lastDestination && lastDestination->messageID == currentDestination->messageID-1 )
                {
                    missed = false;
                    if ( ( dirDrive - currentDestination->direction ).NormSquared() < EPS )
                    {
                        turn = false;
                        turnTo = 0;
                    }
                }

                // if the destination is dead ahead, it can't be a fake, either
                if ( missed && sn_GetNetState() == nSERVER && !sg_noRedundantBrakeCommands.Supported( Owner() ) )
                {
                    // calculate difference in expected position at the destination's time and the transmitted position
                    REAL timeToDest = currentDestination->GetGameTime() - lastTime;
                    eCoord posDelta = pos + dirDrive * ( timeToDest * ( verletSpeed_ + .5f * acceleration * timeToDest ) ) - currentDestination->position;
                    REAL deltaParallel = eCoord::F( posDelta, dirDrive );
                    REAL deltaOrthogonal = posDelta * dirDrive;

                    // if it's small, that's not a miss
                    REAL tolerance = verletSpeed_ * GetTurnDelay();
                    if ( fabs(deltaParallel) < tolerance && fabs(deltaOrthogonal) < tolerance * .5 )
                    {
                        missed = false;
                        if ( ( dirDrive - currentDestination->direction ).NormSquared() < EPS )
                        {
                            turn = false;
                        }
                    }
                }

                // see if we missed a turn by, say, just counting?
                if ( turns < currentDestination->turns - 1 )
                    missed = true;

                if ( turn )
                {
                    // the direction we need to drive in
                    // see which direction we drive into after a left or right turn
                    int wn = windingNumberWrapped_;
                    Grid()->Turn(wn, 1);
                    eCoord dirPlus = Grid()->GetDirection(wn);
                    wn = windingNumberWrapped_;
                    Grid()->Turn(wn, -1);
                    eCoord dirMinus = Grid()->GetDirection(wn);

                    if ( missed )
                    {
                        eCoord dirTurn = (currentDestination->position - pos);

                        // see witch of the alternatives comes closer to the desired direction
                        turnTo = ( ( fabs( dirMinus * dirTurn ) - .1 * eCoord::F( dirMinus, dirTurn ) )/dirTurn.NormSquared() < ( fabs( dirPlus * dirTurn ) - .1 * eCoord::F( dirPlus, dirTurn ) )/dirTurn.NormSquared() ) ? -1 : +1;
                    }
                    else
                    {
                        // just see which axis gets closer
                        eCoord dirTurn = currentDestination->direction;

                        turnTo = ( ( dirMinus - dirTurn ).NormSquared() < ( dirPlus - dirTurn ).NormSquared() ) ? -1 : +1;

                    }
                }
            }

            // can we turn already?
            bool canTurn = ( turnTo == 0 || CanMakeTurn(turnTo) || overrideTurnDelay );

            if ( lastTime >= earliestTurnTime && canTurn && ( forceTurn || dist_to_dest < 0.01 || timeout <= 0 || lastTime >= latestTurnTime ) ){
                forceTurn = false;

#ifdef DEBUG
                if ( turnTo != 0 )
                {
                    static REAL checkFactor = .9f;
                    gTurnDelayOverride check( checkFactor );
                    if ( !CanMakeTurn( turnTo ) )
                    {
                        con << "Early turn!\n";
                        // st_Breakpoint();
                    }
                }
#endif


                // con << timeLeft << ", " << earlyTurnTolerance << ", " << rubberActive << ", " << dist_to_dest << "\n";

                // the destination is very close or we gave up. Now is the time to turn towards
                // it or turn to the direction it gives us

                // bring us to the exact location to avoid lag sliding due to
                // disagreement between client and server.
                // but only if we are reasonably close ( don't want cheating )
                // and use a correct move that kills us if we cross a wall.

                /*
                         if ( dist_to_dest < .1 && dist_to_dest > -.1 )
                         {
                             Move( pos + dirDrive * dist_to_dest, currentTime, currentTime );
                         }
                #ifdef DEBUG
                         else
                         {
                             if ( breakp )
                             {
                                 int x;
                                 x = 0;
                             }
                             con << "gCycle::Timestep: Could not completely reach destination.\n";
                             breakp = true;
                         }
                #endif			
                */

                // con << "Turn: " << lastTime << ", " << dist_to_dest << ", " << currentDestination->position << ", " << pos << "\n";

                //eDebugLine::SetTimeout(2);
                //eDebugLine::SetColor( 0,1,1 );
                //eDebugLine::Draw( currentDestination->position, 0, currentDestination->position, 8 );
                //eDebugLine::SetColor( 0,0,1 );
                //eDebugLine::Draw( pos, 0, pos, 8 );

                bool used = false; // flag indicating whether the current destination has been used

                if (!missed){ // then we did not miss a destination
                    used = true;

                    if (turnTo != 0)
                    {
#ifdef DEBUG
#ifdef DEDICATED
                        eCoord slide = this->pos - currentDestination->position;
                        if ( Player() && slide.NormSquared() > .01 )
                            con << "Lag slide for " << Player()->GetUserName() << ": "  << slide << ", rubberSpeedFactor " << rubberSpeedFactor << "\n";
#endif
#endif
                        gTurnDelayOverride override( overrideTurnDelay );
                        Turn(turnTo);
                    }
                    else{
                        AccelerationDiscontinuity();
                        braking = currentDestination->braking;
                        if (sn_GetNetState()!=nCLIENT)
                            RequestSync();
                    }

                    /*
                      con << "turning alon " << currentDestination->position << "," 
                      << currentDestination->direction << "," 
                      << currentDestination->distance << "\n";
                    */
                }
                else
                {

                    // Uh oh. Turn commands are missing. We should wait as long as possible, it must
                    // already be on its way.
                    if ( lastTime > currentTime - Lag()*sg_packetMissTolerance )
                        return !Alive();

                    if ( turns >= currentDestination->turns - 1 )
                    {
                        // OK, we missed exactly one turn. Don't panic. Just turn
                        // towards the destination:
                        REAL side = (currentDestination->position - pos) * dirDrive;
                        if ( fabs(side)>verletSpeed_ * GetTurnDelay() * .2 )
                        {
                            gTurnDelayOverride override( overrideTurnDelay );
                            Turn(turnTo);
                        }
                        else
                            used = true;
                    }
                    else
                    {
                        // missed more than one turn. Drat. Ignore and hope for the best.
                        // st_Breakpoint();
                        ++turns;
                    }
                    /*
                      con << "turning to   " << currentDestination->position << "," 
                      << currentDestination->direction << "," 
                      << currentDestination->distance << "\n";
                    */

                }

                overrideTurnDelay = false;

                if ( used )
                {
                    // only the server marks destinations as used; the client has to reuse them sometimes.
                    currentDestination->hasBeenUsed = (sn_GetNetState()!=nCLIENT);
                    lastDestination = currentDestination;

                    // advance
                    currentDestination = currentDestination->next;
                }


                while (currentDestination && currentDestination->hasBeenUsed)
                {
                    // breakp = false;
                    currentDestination = currentDestination->next;
                }
            }
            else
            {
                // ok, the dest is right ahead, but not close enough.
                // how long does it take at least
                // (therefore the strange average speed) to get there?
                sg_ArchiveReal( avgspeed, 9 );
                REAL tsTodo = dist_to_dest/avgspeed;
                /*
                         if ( tsTodo > timeLeft )
                         {
                             tsTodo = timeLeft;
                         }
                */
                sg_ArchiveReal( tsTodo, 9 );

                // we can't turn now, simulate until we can
                if ( !canTurn )
                {
                    REAL nextTurn = GetNextTurn(turnTo);
                    REAL turnStep = nextTurn - lastTime;

                    // clamp timestep values
                    if ( turnTime < nextTurn )
                        turnTime = nextTurn;
                    if ( earliestTurnTime < nextTurn )
                        earliestTurnTime = nextTurn;
                    if ( latestTurnTime < nextTurn )
                        latestTurnTime = nextTurn;

                    if ( ts + + simulateAhead > turnStep )
                    {
                        // if we can simulate to the turn in the next step, do so, overriding
                        // the turn delay then.
                        tsTodo = turnStep;
                        overrideTurnDelay = true;
                    }
                    else
                    {
                        // not enough time to simulate to turn possibility; skip out of loop
                        vetoSimulationRequest = true;
                        break;
                    }
                }
                else
                {
                    sg_ArchiveReal( tsTodo, 9 );
                    // don't turn too late
                    REAL maxts = latestTurnTime - lastTime;
                    sg_ArchiveReal( maxts, 9 );
                    if ( tsTodo > maxts )
                    {
                        // force turn on next iteration, we'll be there
                        forceTurn = true;
                        tsTodo = maxts;
                    }

                    // don't turn too early
                    REAL mints = earliestTurnTime - lastTime;
                    // sg_ArchiveReal( mints, 9 );
                    if ( tsTodo < mints )
                    {
                        tsTodo = mints;
                    }
                }

                if ( tsTodo < 0 )
                {
                    // should never happen
                    st_Breakpoint();
                    return !Alive();
                }
                if ( tsTodo > ts + simulateAhead )
                {
                    tsTodo = ts + simulateAhead ;
                    forceTurn = false;
                    overrideTurnDelay = false;

                    // quit from here if there is nothing to do
                    if ( tsTodo <= EPS )
                        break;
                }
	#ifdef DEBUG
                if ( tsTodo < 0 )
                    con << "Negative timestep!\n";
	#endif
                sg_ArchiveReal( tsTodo, 9 );

                // core simulation
                if ( tsTodo > EPS )
                {
                    TimestepCore( lastTime + tsTodo, false );
                }
                else
                {
                    // already nothing to do, turn on next iteration
                    forceTurn = true;
                }
            }
        }
    }

    // simulate exactly to the time of the next turn if it is in reach
    if ( !pendingTurns.empty())
    {
        REAL nextTurn = GetNextTurn(pendingTurns.front());
        if(currentTime>nextTurn) {
            if ( nextTurn > lastTime )
                TimestepCore( nextTurn );

            //con << "Executing delayed turn at time " << lastTime << "\n";
            Turn(pendingTurns.front());
            pendingTurns.pop_front();
        }
    }

    // do the rest of the timestep
    bool ret = false;
    if ( currentTime > lastTime )
        ret = TimestepCore( currentTime );

    // if we get here and turns are left pending within our reach,
    // request the function gets called again right away.
    if( !vetoSimulationRequest &&
        ( currentDestination || 
          ( !pendingTurns.empty() && GetNextTurn( pendingTurns.front() < currentTime + MaxSimulateAhead() ) != 0 )
            )
        )
    {
        RequestSimulation();
    }

    return ret;
}

// *******************************************************************************************
// *
// *	AddRef
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

void gCycleMovement::AddRef( void )
{
    eNetGameObject::AddRef();
    if ( GetRefcount() > sg_cycleMaxRefCount && Alive() )
    {
        // during the kill, further refcounts will be added, so we need to pump
        // up the limit
        int backup = sg_cycleMaxRefCount;
        sg_cycleMaxRefCount += 100;
        Kill();
        sg_cycleMaxRefCount = backup;
    }
}

// *******************************************************************************************
// *
// *	gCycleMovement
// *
// *******************************************************************************************
//!
//!		@param	grid			the grid the cycle will live on
//!		@param	pos				start position
//!		@param	dir				start direction
//!		@param	player			player owning this cycle
//!		@param	autodelete		should the cycle get deleted when it gets killed?
//!
// *******************************************************************************************

gCycleMovement::gCycleMovement( eGrid * grid, const eCoord & pos, const eCoord & dir, ePlayerNetID * player, bool autodelete )
        :eNetGameObject(grid, pos,dir,player,autodelete),
        destinationList(NULL),currentDestination(NULL),lastDestination(NULL),
        dirDrive(dir),
        acceleration(0),
        totalZoneAcceleration(0),
        lastTimestep_(0),
        verletSpeed_(sg_speedCycleStart * SpeedMultiplier()),
        pendingTurns()
{
    windingNumberWrapped_ = windingNumber_ = Grid()->DirectionWinding(dir);

    MyInitAfterCreation();
}

// *******************************************************************************************
// *
// *	gCycleMovement
// *
// *******************************************************************************************
//!
//!		@param	message		network message to read everything from
//!
// *******************************************************************************************

gCycleMovement::gCycleMovement( Game::CycleMovementSync const & sync, nSenderInfo const & sender )
        :eNetGameObject( sync.base(), sender ),
        destinationList(NULL),currentDestination(NULL),lastDestination(NULL),
        dirDrive(1,0),
        acceleration(0),
        totalZoneAcceleration(0),
        lastTimestep_(0),
        verletSpeed_(5)
{
    windingNumberWrapped_ = windingNumber_ = 2;

    // MyInitAfterCreation();
}

// *******************************************************************************************
// *
// *	~gCycleMovement
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

gCycleMovement::~gCycleMovement( void )
{
    lastDestination = NULL;
    currentDestination = NULL;

    while(destinationList)
    {
        gDestination* dest = destinationList;
        delete dest;
    }

    verletSpeed_=distance=0;

    delete maxSpaceHit_;
    maxSpaceHit_ = NULL;
}

void gCycleMovement::RequestSync(bool ack)
{
    // no more syncs when you're dead
    if ( !Alive() )
    { 
       return;
    }

    // delegate
    eNetGameObject::RequestSync( ack );
}

void gCycleMovement::RequestSync(int user,bool ack)
{
    // no more syncs when you're dead
    if ( !Alive() )
    {
        return;
    }

    // delegate
    eNetGameObject::RequestSync( user, ack );
}

void gCycleMovement::OnRemoveFromGame()
{
    delete maxSpaceHit_;
    maxSpaceHit_ = NULL;

    eNetGameObject::OnRemoveFromGame();
}

// *******************************************************************************************
// *
// *	CopyFrom
// *
// *******************************************************************************************
//!
//!		@param	other	the cycle to copy everything from
//!
// *******************************************************************************************

void gCycleMovement::CopyFrom( const gCycleMovement & other )
{
#ifdef DEBUG_X
    // calculate position update
    eCoord posUpdate = other.Position() - this->Position();

    // only update direction if the positions are out of sync
    REAL lag = 1;
    if ( player )
        lag = player->ping;

    REAL tol = this->speed * lag;
    if ( posUpdate.NormSquared() > tol*tol )// && eCoord::F( dirDrive, other.dirDrive ) < .5 )
    {
        con << "Out of sync!\n";
        //		dir 			= other.Direction();

        // get second opinion
        tJUST_CONTROLLED_PTR<gCycleExtrapolator> extrapolator = tNEW( gCycleExtrapolator )(grid, pos, dir );
        gCycleExtrapolator& secondOpinion = *extrapolator;
        secondOpinion.CopyFrom( sg_usedMessage, *this );
        eGameObject::TimestepThis( other.lastTime, &secondOpinion );
    }
#endif

    dirDrive 		= other.dirDrive;

    // transfer position and time
    currentFace = other.currentFace;
    pos = other.Position();
    lastTime = other.LastTime();
    // Move( other.Position(), LastTime(), other.LastTime() );
    // Move( other.Position() + other.Direction() * ( ( lastTime - other.LastTime() ) * other.Speed() ), LastTime(), other.LastTime() );

    // std::cout << "copy: " << brakingReservoir << ":" << braking << "\n";

    // transfer additional data
    team            = other.team;
    distance        = other.distance;
    lastTimestep_   = other.lastTimestep_;
    verletSpeed_    = other.verletSpeed_;
    acceleration    = other.acceleration;
    rubber	        = other.rubber;
    rubberMalus     = other.rubberMalus;
    brakingReservoir= other.brakingReservoir;
    windingNumber_          = other.windingNumber_;
    windingNumberWrapped_   = other.windingNumberWrapped_;

    tASSERT(isfinite(distance));

    // std::cout << "copy: " << brakingReservoir << ":" << braking << "\n";

#ifdef DEBUG_X
    if ( turns != other.turns )
    {
        con << "Client/Server turn mismatch:" << turns << " != " << other.turns << "\n";
    }
#endif

    // update number of turns if the player is not turning wildly
    REAL right = GetNextTurn(1);
    REAL left  = GetNextTurn(-1);
    if ( lastTime > (right > left ? right : left) + 2 * GetTurnDelay() )
        turns			= other.turns;
}

static nVersionFeature sg_sendCorrectLastTurn(8);

// *******************************************************************************************
// *
// *	CopyFrom
// *
// *******************************************************************************************
//!
//!		@param	sync	   	the network sync data to copy the most important data from
//!		@param	other		the cycle to copy the rest of the information from
//!
// *******************************************************************************************

void gCycleMovement::CopyFrom( const SyncData & sync, const gCycleMovement & other )
{
    // fetch values from sync
    dir = dirDrive 	= sync.dir;
    lastTimestep_   = 0;
    verletSpeed_ 	= sync.speed;
    rubber			= sync.rubber;
    rubberMalus     = sync.rubberMalus;
    braking			= sync.braking;
    distance		= sync.distance;
    turns			= sync.turns;
    brakingReservoir= sync.brakingReservoir;
    // std::cout << "fromsync: " << brakingReservoir << ":" << braking << "\n";

    tASSERT(isfinite(distance));

    // reset winding number and acceleration
    this->SetWindingNumberWrapped( Grid()->DirectionWinding(dirDrive) );
    acceleration	= 0;

    // fetch values from other
    // rubber = other.rubber;
    SetPlayer( other.Player() );
    currentFace         = other.currentFace;

    {
        //this->currentDestination = other.destinationList;
        //while ( currentDestination && currentDestination->messageID != sync.messageID )
        //    currentDestination = currentDestination->next;

        // deterimine last passed destination by the message ID
        this->currentDestination = GetDestinationBefore( sync, other.destinationList );

        bool trustDestination = true;
        if ( currentDestination && sn_GetNetState() == nCLIENT && !sg_sendCorrectLastTurn.Supported(0) )
        {
            // the server may send wrong information in the rare case that
            // our last turn command was not promptly executed. Sanity check:
            // if the relevant information from the alleged last destination
            // differs from the current state, it is already the next destination.
            if ( ( currentDestination->braking != (bool)braking ) || fabs( currentDestination->direction * dirDrive ) > .01 )
                trustDestination = false;
        }

        // we only need the next one
        if ( trustDestination && currentDestination )
            currentDestination = currentDestination->next;
    }

    // let extrapolator find its face ( and set position and time )
    MoveSafely( sync.pos, sync.time, sync.time );

    // set last turn
    lastTurnTimeRight_ = lastTurnTimeLeft_ = -100;
}

// *******************************************************************************************
// *
// *	InitAfterCreation
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

void gCycleMovement::InitAfterCreation( void )
{
#ifdef DEBUG
    if (!isfinite(verletSpeed_))
        st_Breakpoint();
#endif
    eNetGameObject::InitAfterCreation();
#ifdef DEBUG
    if (!isfinite(verletSpeed_))
        st_Breakpoint();
#endif
    MyInitAfterCreation();
}

// version feature indicating that proper scaling of the base acceleration with the speed multiplier is used
static nVersionFeature sg_correctAccelerationScaling( 8 );

// calculate essential rubber values
void sg_RubberValues( ePlayerNetID const * player, REAL speed, REAL & max, REAL & effectiveness )
{
    // base values
    max=sg_rubberCycle;
    effectiveness=1;

    // make rubber more effective for high ping players
    if ( player )
    {
        if ( max > 0 )
            // either by increasing the effectiveness...
            effectiveness *= ( max + player->ping * sg_rubberCyclePing )/max;
        else
            // or the reservoir.
            max += player->ping * sg_rubberCyclePing;
    }

    {
        // modify rubber effectiveness by a speed dependant power law
        REAL speedFactor = speed/(sg_speedCycle*gCycleMovement::SpeedMultiplier());

        effectiveness *= pow( speedFactor, sg_rubberCycleTimeBased );
    }
}

// *******************************************************************************************
// *
// *	AccelerationDiscontinuity
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

void gCycleMovement::AccelerationDiscontinuity()
{
    // make fake 0 timestep
    verletSpeed_ = Speed();
    lastTimestep_ = 0;
}

// *******************************************************************************************
// *
// *	CalculateAcceleration
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

void gCycleMovement::CalculateAcceleration()
{
    tASSERT( good( verletSpeed_ ) );

    // reset usage variables
    brakeUsage = 0.0f;
    rubberUsage = 0.0f;

    // calculate acceleration
    acceleration=0;

    // brake: it's only available since this version...
    static nVersionFeature brakeDepletion(2);

    // and servers starting from this version disable it my modifying config items
    static nVersionFeature brakeDepletionHandledWithConfig(10);

    // simply use the configured brake always on the server
    // and on the client if the server should have disabled it, but does not.

    if ( sn_GetNetState() != nCLIENT || brakeDepletion.Supported() || brakeDepletionHandledWithConfig.Supported(0) )
    {
        if(braking)
        {
            if ( brakingReservoir > 0.0 )
            {
                brakeUsage = sg_cycleBrakeDeplete;
                acceleration-=sg_brakeCycle * SpeedMultiplier();
            }
            else
                brakingReservoir = 0.0f;
        }
        else
        {
            if ( brakingReservoir < 1.0 )
            {
                brakeUsage = -sg_cycleBrakeRefill;
            }
            else
                brakingReservoir = 1.0f;
        }
    }
    else
    {
        if(braking)
        {
            acceleration-=sg_brakeCycle * SpeedMultiplier();
        }
    }

    sg_ArchiveReal( acceleration, 9 );

    REAL baseSpeed = sg_speedCycle * SpeedMultiplier();
    if ( verletSpeed_ <= ( sg_correctAccelerationScaling.Supported() ? baseSpeed : sg_speedCycle ) )
        acceleration+=( baseSpeed - verletSpeed_) * sg_speedCycleDecayBelow;
    else
        acceleration+=( baseSpeed - verletSpeed_) * sg_speedCycleDecayAbove;

    tASSERT( good( acceleration ) );
    sg_ArchiveReal( acceleration, 9 );

    // sense near wall behind us, accelerate more
    REAL totalWallAcceleration = 0; // total acceleration by walls
    REAL tunnelWidth           = 0; // with of the tunnel the cycle is in
    REAL sideWidth             = sg_cycleWidthSide * 2; // minimal distance to wall
    bool slingshot  = true;         // flag indicating whether the cycle is between two walls
    bool oneOwnWall = false;        // flag indicating whether one of the walls is your own
    for(int d=1;d>=-1;d-=2){
        // the direction to cast the acceleration rays in
        eCoord dirCast = dirDrive.Turn(-1,d);
        gSensor rear(this,pos,dirCast);
        rear.detect(sg_nearCycle);

        enemyInfluence.AddSensor( rear, 0, this );

        if (rear.ehit && rear.hit < sg_cycleWidth + .1f )
            blocks(rear, this, -d);

        if ( 0 != rear.ehit )
        {
            sg_ArchiveReal( rear.hit, 9 );

            // update the minimal wall distance
            if ( sideWidth > rear.hit )
                sideWidth = rear.hit;

            // drop walls that are grinded
            if ( rear.hit < verletSpeed_ * .01 )
                ::sg_DropTempWall( dirCast, rear );

            // see if the wall is parallel to the driving direction, only then should it add speed
            eCoord wallVec = rear.ehit->Vec();
            if ( fabs( eCoord::F( wallVec, dirDrive  ) ) > .9 * dirDrive.NormSquared() )
            {
                // detect uncanny timing of earlier turns, only check outside corner grinds
                if ( uncannyTimingToReport_ && player && ( lastTurnTimeRight_ - lastTurnTimeLeft_ ) * d < 0 )
                {
                    // check that the wall we're grinding was there before we turned
                    bool wasMe = true;
                    gPlayerWall * w = dynamic_cast< gPlayerWall * >( rear.ehit->GetWall() );
                    if( !w && rear.ehit->Other() )
                        w = dynamic_cast< gPlayerWall * >( rear.ehit->Other()->GetWall() );

                    if ( w )
                    {
                        REAL lastTurnTime = GetLastTurnTime();
                        if( lastTurnTime < w->Time(0) &&
                            lastTurnTime < w->Time(1) )
                        {
                            wasMe = false;
                        }
                    }

                    if ( wasMe )
                    {
                        uncannyTimingToReport_ = false;

                        // don't count grinding own or teammate wall on the outside, it may
                        // be a practiced pattern
                        if( rear.type != gSENSOR_SELF && rear.type != gSENSOR_TEAMMATE )
                        {
                            REAL timing = rear.hit/(verletSpeed_ + 1E-10);

                            // extra factor: when the number of axes is not 4,
                            // the effective speed at which the cycle would increase
                            // the here detected distance is reduced. Thus, we
                            // need to divide the timing by that speed factor.
                            REAL factor = -lastDirDrive*dirDrive*d;
                            if(factor > 0 && factor < 1)
                                timing /= factor;

                            player->AnalyzeTiming( timing );
                        }
                    }
                }
                

                // enemyInfluence.AddSensor( rear, 1 );
                REAL wallAcceleration=SpeedMultiplier() * sg_accelerationCycle * ((1/(rear.hit+sg_accelerationCycleOffs))
                                      -(1/(sg_nearCycle+sg_accelerationCycleOffs)));

                tunnelWidth += rear.hit;

                // apply modificators
                switch (rear.type)
                {
                case gSENSOR_SELF:
                    wallAcceleration *= sg_accelerationCycleSelf;
                    oneOwnWall = true;
                    break;
                case gSENSOR_TEAMMATE:
                    wallAcceleration *= sg_accelerationCycleTeam;
                    break;
                case gSENSOR_ENEMY:
                    wallAcceleration *= sg_accelerationCycleEnemy;
                    break;
                case gSENSOR_RIM:
                    wallAcceleration *= sg_accelerationCycleRim;
                    break;
                case gSENSOR_NONE:
                    wallAcceleration = 0;
                    slingshot = false;
                    break;

                }

                sg_ArchiveReal( wallAcceleration, 9 );
                totalWallAcceleration += wallAcceleration;
            }
            else
            {
                slingshot = false;
            }
        }
        else
        {
            slingshot = false;
        }

        sg_ArchiveReal( totalWallAcceleration, 9 );
    }

    // kill cycle if it is inside a too narrow channel
    if ( ( slingshot && tunnelWidth < sg_cycleWidth ) || sideWidth < sg_cycleWidthSide )
    {
        tunnelWidth = 0;
        REAL sideWidth = sg_cycleWidthSide * 2;

        // check again with sensors to the front, both sensor pairs need
        // to see a narrow tunnel
        for(int d=1;d>=-1;d-=2)
        {
            // the direction to cast the acceleration rays in
            eCoord dirCast = dirDrive.Turn(1,d);
            gSensor front(this,pos,dirCast);
            front.detect(sg_nearCycle);

            if ( front.ehit && front.ehit->Other() )
            {
                sg_ArchiveReal( front.hit, 9 );

                // update the minimal wall distance
                if ( sideWidth > front.hit )
                    sideWidth = front.hit;

                tunnelWidth += front.hit;
            }
            else
            {
                tunnelWidth += sg_cycleWidth;
            }
        }

        if ( tunnelWidth < sg_cycleWidth || sideWidth < sg_cycleWidthSide )
        {
            // determine the space available measured in the space allowed
            REAL available1 = 1;
            REAL available2 = 1;
            if ( sg_cycleWidth > 0 )
                available1 = tunnelWidth/sg_cycleWidth;
            if ( sg_cycleWidthSide > 0 )
                available2 = sideWidth/sg_cycleWidthSide;
            REAL available = available1 < available2 ? available1 : available2;

            // get rubber values
            // REAL rubberGranted, rubberEffectiveness;
            // sg_RubberValues( player, verletSpeed_, rubberGranted, rubberEffectiveness );

            // calculate rubber usage from squeezing
            rubberUsage = sg_cycleWidthRubberMax + ( sg_cycleWidthRubberMin - sg_cycleWidthRubberMax ) * available;
        }
    }

    // apply slingshot/tunnel multiplier
    if ( slingshot )
    {
        if ( oneOwnWall )
            totalWallAcceleration *= sg_accelerationCycleSlingshot;
        else
            totalWallAcceleration *= sg_accelerationCycleTunnel;
    }

    // apply wall acceleration
    acceleration += totalWallAcceleration;
    acceleration += totalZoneAcceleration;
    totalZoneAcceleration = 0.0; // This comes from external influence and should be applied only once per Timestep

    tASSERT( good( acceleration ) );
    sg_ArchiveReal( acceleration, 9 );

    tASSERT( good( verletSpeed_ ) );
}

// *******************************************************************************************
// *
// *	ApplyAcceleration
// *
// *******************************************************************************************
//!
//!		@param	dt		length of timestep
//!
// *******************************************************************************************

void gCycleMovement::ApplyAcceleration( REAL dt )
{
    sg_ArchiveReal( verletSpeed_, 9 );
    sg_ArchiveReal( dt, 9 );
    sg_ArchiveReal( acceleration, 9 );

    // the speed needs to be simulated for this half frame and half of the last frame
    REAL verletTimestep = sg_verletIntegration.Supported() ? .5 * ( dt + lastTimestep_ ) : dt;
    lastTimestep_ = dt;

    sg_ArchiveReal( verletTimestep, 9 );

    // don't use euler timesteps for large cycle speed decays
    bool properDecay = false;
    REAL maxTimestep = verletTimestep > dt ? verletTimestep : dt;
    if ( sg_speedCycleDecayBelow * maxTimestep > .1 || sg_speedCycleDecayAbove * maxTimestep > .1 )
    {
        REAL speedDecay = 0;
        REAL baseSpeed = sg_speedCycle * SpeedMultiplier();
        if ( verletSpeed_ < ( sg_correctAccelerationScaling.Supported() ? baseSpeed : sg_speedCycle ) )
            speedDecay = sg_speedCycleDecayBelow;
        else
            speedDecay = sg_speedCycleDecayAbove;

        if ( speedDecay * maxTimestep > .1 && dt > EPS )
        {
            // ok, really, a  better simulation is needed
            properDecay = true;

            // that's what CalculateAcceleration extrapolates
            REAL decayAcceleration = ( baseSpeed - verletSpeed_) * speedDecay;
            // throw it away
            acceleration -= decayAcceleration;

            tASSERT( good( acceleration ) );

            // adapt base speed as the limit speed with the current decay and acceleration
            baseSpeed += acceleration/speedDecay;

            // do a proper decay
            verletSpeed_ = baseSpeed + ( verletSpeed_ - baseSpeed ) * exp( -speedDecay * verletTimestep );

            // calculate new acceleration based purely on the decay, the external acceleration
            // is factored into baseSpeed now. Add extra decay factor so that
            // Speed() returns the most accurate current speed available.
            acceleration = ( baseSpeed - verletSpeed_) * ( 1 - exp( -speedDecay * dt * .5f ) ) / ( .5f * dt );

            tASSERT( good( acceleration ) );
        }
    }

    // if decay wasn't handled properly (because it didn't need to), use euler/verlet
    tASSERT( good( acceleration ) );
    if ( !properDecay )
        verletSpeed_+=acceleration*verletTimestep;
    tASSERT( good( verletSpeed_ ) );

    // clamp speed
    REAL minSpeed = sg_speedCycle*SpeedMultiplier()*sg_speedCycleMin;
    REAL maxSpeed = ( 100 + sg_speedCycle*SpeedMultiplier() )* 100000;
    if ( sg_speedCycleMax > 0 )
    {
        maxSpeed = sg_speedCycle*SpeedMultiplier()*sg_speedCycleMax;
    }

    sg_ArchiveReal( minSpeed, 9 );
    sg_ArchiveReal( maxSpeed, 9 );
    sg_ArchiveReal( acceleration, 9 );

    if ( clamp( verletSpeed_, minSpeed, maxSpeed ) )
        acceleration = 0;

    sg_ArchiveReal( acceleration, 9 );

    sg_ArchiveReal( verletSpeed_, 9 );
}

// *******************************************************************************************
// *
// *	DoTurn
// *
// *******************************************************************************************
//!
//!		@param	dir +1 for right turns, -1 for left turns
//!		@return		true of the turn could be executed right now, false if it was queued
//!
// *******************************************************************************************

bool gCycleMovement::DoTurn( int dir )
{
    if ( turns == 0 )
        turns = 1;

    if (dir >  1) dir =  1;
    if (dir < -1) dir = -1;

    REAL nextTurnTime = GetNextTurn( dir );
    if ( nextTurnTime <= lastTime )
    {
        // prepare for uncanny timing checks if the turn was user-controlled
        if( sn_GetNetState() == nSERVER && nextTurnTime + .05 < lastTime )
        {
            // if rubber was used in this turn, check for depletion timing
            if( rubberSpeedFactor < 1 )
            {
                /*
                  // turns out this is a bad idea; default clients cheat and
                  // often produce perfectly timed grinds.
                  // Maybe they'll send additional timing information one day
                  // and this can be reactivated.

                REAL rubber_granted, rubberEffectiveness;
                // get rubber values
                sg_RubberValues( player, verletSpeed_, rubber_granted, rubberEffectiveness );
                rubberEffectiveness /= (1 + rubberMalus );

                // get timing from it
                REAL timing = (rubber_granted - rubber)*rubberEffectiveness/verletSpeed_;

                if( currentDestination )
                {
                    if( sg_CommandTime.Supported( Owner() ) )
                    {
                        // take net fluctiations into account
                        timing += fabs(currentDestination->gameTime - lastTime);
                    }
                    else
                    {
                        // do the same, but via locations. Less accurate.
                        timing += (currentDestination->position - pos).Norm()/(verletSpeed_*rubberSpeedFactor+1E-10);
                    }
                }

                // add space left after rubber ran out
                timing += GetMaxSpaceAhead( maxSpaceMaxCast_ )/(verletSpeed_ + 1E-10);
                
                // and report
                // player->AnalyzeTiming( timing );
                */
                uncannyTimingToReport_ = false;
            }
            else
            {
                // mark the turn. Later, during grind detection, we can
                // measure the quality of an outside corner grind.
                uncannyTimingToReport_ = true;
            }
        }

        // request regeneration of maximum space
        refreshSpaceAhead_ = true;

        // notify that no rubber is currently used (may be a lie, but a timestep correcting
        // it will surely follow)
        rubberSpeedFactor = 1;

        // store last postion
        lastTurnPos_ = pos;

        turns++;
        /*
        if( sn_GetNetState() != nSERVER )
        {
            // simulate lost turns
            turns+=2;
        }
        */

        AccelerationDiscontinuity();
        verletSpeed_ *= sg_cycleTurnSpeedFactor;
        rubberMalus  += sg_rubberCycleMalusTurn;

        gap_[0] = gap_[1] = 1E+30;
        keepLookingForGap_[0] = keepLookingForGap_[1] = true;
        gapIsBackdoor_[0] = gapIsBackdoor_[1] = true;

        // turn winding numbers
        int wn = windingNumberWrapped_;
        Grid()->Turn(wn, dir);
        this->SetWindingNumberWrapped( wn );

        eCoord nextDirDrive = Grid()->GetDirection(windingNumberWrapped_);

        // send out a sensor a bit backwards and forwards into the turn direction to
        // copy all temporary walls into the grid
        {
            REAL range = .1 * Speed();
            eCoord dirCast = nextDirDrive;
            gSensor gridder1( this, Position(), dirCast );
            gridder1.detect( range );
            if ( gridder1.ehit )
                ::sg_DropTempWall( nextDirDrive, gridder1 );

            gSensor gridder3( this, Position() - dirCast * (range*.5), dirCast );
            gridder3.detect( range );
            if ( gridder3.ehit )
                ::sg_DropTempWall( nextDirDrive, gridder3 );

            // the ray backwards should detect walls that affected the acceleration;
            // they can also give a boost. Increase the range.
            if ( range < sg_nearCycle )
                range = sg_nearCycle;

            gSensor gridder2( this, Position(), -dirCast );
            gridder2.detect( range );
            if ( gridder2.ehit )
            {
                ::sg_DropTempWall( nextDirDrive, gridder2 );

                // apply the boost. Calculate wall distance
                REAL dist = gridder2.hit;

                // calculate the factor acceleration would be multiplied with
                REAL accellerationFactorOffset = 1/(sg_nearCycle+sg_accelerationCycleOffs);
                REAL accelerationFactor = (1/(dist+sg_accelerationCycleOffs)) - accellerationFactorOffset;
                // this would be the maximal acceleration factor
                REAL accelerationFactorMax = (1/sg_accelerationCycleOffs) - accellerationFactorOffset;

                if( accelerationFactorMax > 0 && dist < sg_nearCycle )
                {
                    // select boost settings according to wall type
                    // apply modificators
                    REAL boost = 0, boostFactor = 1;
                    switch (gridder2.type)
                    {
                    case gSENSOR_SELF:
                        boost = sg_boostCycleSelf;
                        boostFactor = sg_boostFactorCycleSelf;
                        break;
                    case gSENSOR_TEAMMATE:
                        boost = sg_boostCycleTeam;
                        boostFactor = sg_boostFactorCycleTeam;
                        break;
                    case gSENSOR_ENEMY:
                        boost = sg_boostCycleEnemy;
                        boostFactor = sg_boostFactorCycleEnemy;
                        break;
                    case gSENSOR_RIM:
                        boost = sg_boostCycleRim;
                        boostFactor = sg_boostFactorCycleRim;
                        break;
                    case gSENSOR_NONE:
                        break;
                    }

                    // apply acceleration factor to boost
                    boostFactor = 1 + ( boostFactor - 1 ) * accelerationFactor / accelerationFactorMax;
                    boost *= SpeedMultiplier() * accelerationFactor / accelerationFactorMax;

                    // apply boost to speed
                    verletSpeed_ = verletSpeed_ * boostFactor + boost;
                    tASSERT( good( verletSpeed_ ) );
                }
            }

            // if edges have been inserted into the grid, find a new current face.
            FindCurrentFace();
        }

        // update driving directions
        lastDirDrive = dirDrive;

        if(dir == 1)
            lastTurnTimeRight_ = lastTime;
        else
            lastTurnTimeLeft_ = lastTime;

        dirDrive = nextDirDrive;

#ifdef DEBUGOUTPUT
        if ( sg_cycleDebugPrintLevel > 0 )
            con << Player()->GetName() << " turned " << pos << "," << dirDrive << " " << tSysTimeFloat() << "\n";
#endif

        return true;
    }
    else {
        int maxPendingTurns=sg_cycleTurnMemory;
        int size = pendingTurns.size();
        // std::cerr << "size of " << &pendingTurns << ": " << size << std::endl;
        if (size <= maxPendingTurns)
            pendingTurns.push_back(dir);
        else {
            if(pendingTurns.empty()) return false; //just to be sure
            if(pendingTurns.back() != dir) {
                pendingTurns.pop_back(); //opposite turns cancel so the cycle still moves into the expected direction
            }
            else {
                pendingTurns.push_back(dir); //add it anyways...
            }
        }
    }

    return false;
}

// *******************************************************************************************
// *
// *	RightBeforeDeath
// *
// *******************************************************************************************
//!
//!		@param	numTries	number of times this function will be called approximately before the cycle will be killed
//!
// *******************************************************************************************

void gCycleMovement::RightBeforeDeath( int numTries )
{
}

// *******************************************************************************************
// *
// *	Die
// *
// *******************************************************************************************
//!
//!		@param	time	the time of death
//!
// *******************************************************************************************

void gCycleMovement::Die( REAL time )
{
    // only do something if you are alive
    if ( alive_ == 1 )
    {
        alive_ = -1;
        deathTime = time;
    }

    // or complete death if you died only recently
    if ( alive_ == -1 )
    {
        alive_ = 0;
    }
}

class gRecursionGuard
{
public:
    gRecursionGuard( bool & guard )
            : guard_( guard )
    {
        guard_ = false;
    }
    ~gRecursionGuard()
    {
        guard_ = true;
    }
private:
    bool & guard_;
};

// *******************************************************************************************
// *
// *	TimestepCore
// *
// *******************************************************************************************
//!
//!		@param	currentTime		time to simulate up to
//!		@return					true if the cycle is to be killed
//!
// *******************************************************************************************

bool gCycleMovement::TimestepCore( REAL currentTime, bool calculateAcceleration )
{
    // eCoord oldpos=pos;
    REAL lastSpeed=verletSpeed_;

    REAL ts=(currentTime-lastTime);

    // calculate acceleration
    if ( calculateAcceleration )
        this->CalculateAcceleration();

    // ApplyAcceleration modifies the acceleration, so we need to back it up
    REAL lastAcceleration=acceleration;

    // calculate when the braking reservoir will run dry and simulate to that point
    {
        static bool recurse = true;
        if (recurse && brakingReservoir > 0 && brakeUsage > 0 && brakingReservoir - ts * brakeUsage < 0 )
        {
            gRecursionGuard guard( recurse );

            // calculate the time the brake will run out
            REAL brakeTime = lastTime + brakingReservoir/brakeUsage;
            if ( TimestepCore( brakeTime, false ) )
                return true;
            AccelerationDiscontinuity();
            brakingReservoir = -EPS;
            return TimestepCore( currentTime );
        }
    }

    // apply acceleration
    if ( sg_verletIntegration.Supported() )
        this->ApplyAcceleration( ts );

    //eDebugLine::SetTimeout( 2 );
    //eDebugLine::SetColor(1,1,0);
    //eDebugLine::Draw(pos, 4, pos, 4 + 20 * ts);

    sg_ArchiveCoord( pos, 9 );
    sg_ArchiveReal( ts, 9 );
    sg_ArchiveReal( verletSpeed_, 9 );

#ifdef DEBUG
    if ( ts > 2.0f )
    {
        int x;
        x = 0;
    }

    if ( verletSpeed_ > 30.0f )
    {
        int x;
        x = 0;
    }

    if ( acceleration > 100.0f )
    {
        int x;
        x = 0;
    }
#endif

    clamp(ts, -10, 10);

    REAL step=verletSpeed_*ts;
    tASSERT(isfinite(step));

    int numTries = 0;
    bool emergency = false;

    rubberSpeedFactor = 1;

    // be a little nice and don't drive into the wall
    REAL rubber_granted, rubberEffectiveness;

    // get rubber values
    sg_RubberValues( player, verletSpeed_, rubber_granted, rubberEffectiveness );

    // rubber effectiveness right now
    rubberEffectiveness /= (1 + rubberMalus );

    // reduce it further if cycle turned recently
    {
        REAL delayTime = (lastTurnTimeRight_ > lastTurnTimeLeft_ ? lastTurnTimeRight_ : lastTurnTimeLeft_) + GetTurnDelay() * sg_rubberCycleDelay;
        if ( lastTime < delayTime )
        {
            rubberEffectiveness *= sg_rubberCycleDelayBonus;

            // if the target time is after the rubber delay ends...
            if( currentTime > delayTime )
            {
                static bool recurse = true;
                if (recurse)
                {
                    gRecursionGuard guard( recurse );

                    verletSpeed_=lastSpeed;
                    acceleration=lastAcceleration;
                    // do two small timesteps
                    return TimestepCore( delayTime, false ) || TimestepCore( currentTime );
                }
            }
        }
    }

    sg_ArchiveReal( rubberEffectiveness, 9 );

    tASSERT( rubber >= 0 );

    // TODO: solve smooth position correction trouble with rubber
    if ( player && ( rubber_granted > rubber || sn_GetNetState() == nCLIENT || !Vulnerable() ) && sg_rubberCycleSpeed > 0 && step > -EPS && ( sn_GetNetState() == nCLIENT || rubberEffectiveness > 0 ) )
    {
        // ignore zero effectiveness, this happens only on the client
        if ( rubberEffectiveness <= 0 )
            rubberEffectiveness = 1E+20;

        // formerly: rubberFactor = .5
        REAL beta = ts * sg_rubberCycleSpeed;
        REAL neededSpace = 0;
        REAL rubberFactor;
        if ( beta > .001 )
        {
            rubberFactor = 1 - exp( -beta );
            neededSpace = step/rubberFactor;
        }
        else
        {
            rubberFactor = beta;        // better accuracy than the full formula

            // a lot of factors can be cut out of this one (avoiding a division by zero for ts=0)
            neededSpace = verletSpeed_/sg_rubberCycleSpeed;
        }

        // rubberFactor must not be too close to 1, otherwise we get precision trouble
        if ( rubberFactor > .999 )
            rubberFactor = .999;

        // revert to old rubber logic if old clients are connected
        if ( sg_rubberCycleLegacy && !sg_nonRippable.Supported() && rubberFactor < .5f )
            rubberFactor = .5f;

        // space we need to look ahead
        if ( neededSpace < step*3 || ts < -EPS )
            neededSpace = step*3;

        // determine how long we can drive on
        // REAL space = GetMaxSpaceAhead( this, neededSpace, ts * step * rubberFactor / rubberEffectiveness, &hitInfo );
        REAL space = GetMaxSpaceAhead( neededSpace );

#ifdef DEBUG_RUBBER
        if ( Player() && space < 1E+15)
        {
            std::ofstream f( Player()->GetUserName() + "_rubber", std::ios::app );
            f << lastTime << " " << space << "\n";
        }
#endif

        // if the available space in front is less than the space needed to slow down via
        // the rubber brake, activate rubber and slow down
        if ( space < neededSpace )
        {
            // the minimal space rubber gets active at
            REAL rubberStartSpace = verletSpeed_/sg_rubberCycleSpeed;
            static bool recurse = true;
            if ( space > rubberStartSpace && recurse )
            {
                // rubber will not be active immediately, simulate to the time it will
                gRecursionGuard guard( recurse );

                // calculate the time rubber will get active at
                REAL ratio = ( space - rubberStartSpace )/step;
                if ( ratio > EPS && ratio < 1 - EPS )
                {
                    REAL rubberGetsActiveTime = lastTime + ( currentTime - lastTime ) * ratio;

                    verletSpeed_=lastSpeed;
                    acceleration=lastAcceleration;
                    return TimestepCore( rubberGetsActiveTime, false ) || TimestepCore( currentTime );
                }
            }
#ifdef DEDICATED
            else
            {
                // see if the wall we're about to hit comes from its cycle's future. If so,
                // it is a prediction wall and we shouldn't actually use rubber before we
                // have to.
                if ( maxSpaceHit_ && maxSpaceHit_->playerWall )
                {
                    gPlayerWall * wall = maxSpaceHit_->playerWall;

                    // get the position of the hit
                    REAL alpha = maxSpaceHit_->wallAlpha;

                    // get the distance of the wall
                    REAL wallDist = wall->Pos( alpha );
                    // get the distance the cycle is simulated up to
                    REAL cycleDist = wall->CycleMovement()->distance;
                    // comparing these two gives an accurate criterion whether the wall is extrapolated

                    REAL minLag = se_GameTime() - lastTime - LagThreshold();
                    if ( cycleDist < wallDist && ( minLag < Lag() || minLag < wall->CycleMovement()->Lag() ) )
                    {
                        // it is an extrapolation wall and we are allowed to delay simulation a bit.
                        // so let's abort here.
                        verletSpeed_=lastSpeed;
                        acceleration=lastAcceleration;

                        return false;
                    }
                }
            }
#endif

            // see if the obstacle will go away during this timestep.
            // if it does, simulate in two steps to make the simulation more accurate.
            {
                // get the wall
                if ( maxSpaceHit_ && maxSpaceHit_->playerWall )
                {
                    gPlayerWall * wall = maxSpaceHit_->playerWall;

                    // get the position of the hit
                    REAL alpha = maxSpaceHit_->wallAlpha;

                    // use binary search to find the time the wall goes away. Not
                    // the fastest way, but it doesn't depend on wall internals, and
                    // it shouldn't be called often anyway.
                    REAL tolerance = 0.001;
                    if ( !wall->IsDangerous( alpha, currentTime ) && currentTime > lastTime + tolerance )
                    {
                        // take movement speed into account, we won't hit the wall for
                        // another distanceOffset seconds
                        REAL distanceOffset = 0;
                        {
                            REAL speed = Speed();
                            if ( speed > 0 )
                                distanceOffset = space/speed;
                        }

                        REAL minTime = lastTime + distanceOffset;
                        REAL maxTime = currentTime + distanceOffset;
                        while ( minTime + tolerance < maxTime )
                        {
                            REAL midTime = .5 * ( minTime + maxTime );
                            if ( wall->IsDangerous( alpha, midTime ) )
                                minTime = midTime;
                            else
                                maxTime = midTime;
                        }

                        maxTime -= distanceOffset;
                        // minTime -= distanceOffset;

                        // split simulation into two parts, one up to the point the wall turns harmless
                        {
                            static bool recurse = true;
                            if (recurse)
                            {
                                gRecursionGuard guard( recurse );

                                verletSpeed_=lastSpeed;
                                acceleration=lastAcceleration;
                                return TimestepCore( maxTime, false ) || TimestepCore( currentTime );
                            }
                        }
                    }
                }
            }

            /*
            // debug output for sensitive space/time diagrams
            static REAL lastTimePrinted = 0;
            if ( currentTime > lastTimePrinted && Player() )
            {
                lastTimePrinted = currentTime;
                std::ofstream f( Player()->GetUserName() + "_space", std::ios::app );
                f << lastTime << " " << log(space) << "\n";
            }
            */

            // notify AIs of it
            emergency = true;

            // calculate the step the rubber code should do based on the decay factor
            // calculated earler
            REAL rubberStep = space * rubberFactor;
            if ( rubberStep > step )
                rubberStep = step;

            // clamp the step
            if (step<0)
                step=0;

            // calculate the amount of rubber needed for the desired brake effect
            REAL rubberneeded = step - rubberStep;
            if (rubberneeded < 0)
                rubberneeded = 0;

            // clamp rubberneeded to the amout of rubber available
            REAL rubberAvailable = ( rubber_granted - rubber ) * rubberEffectiveness;
            if ( sn_GetNetState() != nCLIENT && rubberneeded > rubberAvailable && Vulnerable() )
            {
                // rubber will run out this frame.
                // split simulation into two parts, one up to the point rubber runs out
                {
                    REAL ratio = rubberAvailable/rubberneeded;

                    if ( ratio > .01 && ratio < .99 && currentTime - lastTime > .001 )
                    {
                        REAL runOutTime = lastTime + ( currentTime - lastTime ) * ratio;
                        static bool recurse = true;
                        if (recurse)
                        {
                            gRecursionGuard guard( recurse );
                            // need many attempts
                            verletSpeed_=lastSpeed;
                            acceleration=lastAcceleration;
                            return TimestepCore( runOutTime, false ) || TimestepCore( currentTime );
                        }
                    }
                }

                rubberneeded = rubberAvailable;
                // con << "Deep!\n";
            }

            // update rubber usage
            rubber += rubberneeded / rubberEffectiveness;

            numTries = int((sg_rubberCycleTime * ( rubber_granted - rubber ) - 1 )/(sg_rubberCycleTime * step*1.5 + 1));
            int numTriesSpace = int(space*10/verletSpeed_);
            if ( numTriesSpace < numTries )
                numTriesSpace = 0;

            if ( step > 0 )
                rubberSpeedFactor = 1 - rubberneeded/step;
            else
                // better algorithm for zero steps
                rubberSpeedFactor = space / neededSpace;

            // clamp
            if ( rubberSpeedFactor < 0 )
                rubberSpeedFactor = 0;

            // correct the step to take, don't go backwards.
            step -= rubberneeded;
            if (step<0)
                step=0;

            //{
            //    rubber+=step;
            //    step=0;
            //}
        }
    }

    tASSERT( rubber >= 0 );

    sg_ArchiveReal( step, 9 );

    // don't go back further than the last turn
    if( step < 0 )
    {
        REAL min = -GetDistanceSinceLastTurn();
        if( step < min )
        {
            step = min;
        }
    }

    // move forward
    eCoord nextpos;
    if ( verletSpeed_ >0 )
        nextpos=pos+dirDrive*step;
    else
        nextpos=pos;

    eCoord lastPos = pos;
    tJUST_CONTROLLED_PTR< eFace > lastFace = currentFace;
    try
    {
#ifdef DEBUG
        static int run = 0;
        run++;
        if ( run == -1 )
        {
            st_Breakpoint();
        }
#endif
        Move(nextpos,lastTime,currentTime);
#ifdef DEBUG
        {
            if ( step > 0 && ( nextpos - pos ).NormSquared() > 1 )
            {
                con << "Wrong move! run = " << run << ", nextpos = " << nextpos << ", pos = " << pos << "\n";
            }
        }
#endif

        tASSERT(isfinite(distance));
        tASSERT(isfinite(step));
        distance += step;
        lastTimeAlive_ = currentTime;
    }
    catch ( gCycleStop const & )
    {
        // undo simulation done so far and stop
        pos = lastPos;
        verletSpeed_ = lastSpeed;
        acceleration = lastAcceleration;
        currentFace = lastFace;
        numTries = 0;

        // don't simulate further
        return false;
    }
    catch ( gCycleDeath const & )
    {
        rubberSpeedFactor = 0;

        // the cycle should die in this movement. Prevent it if there is rubber left.
        // if RUBBER_MINDISTANCE is negative and the player is not an AI, the cycle dies anyway.
        if ( rubberEffectiveness <= 0 || step >= (rubber_granted-rubber)*rubberEffectiveness || ( sg_rubberCycleMinDistance < 0 && Player() && Player()->IsHuman() ) )
        {
            // last survival chance: packet loss protection. Determine whether it should be in effect..
            bool toleratePacketLoss = false;
            if (!currentDestination)
            {
                // calculate time tolerance to capture packet loss...
                REAL tolerance = Lag() * sg_packetLossTolerance;

                // add lag credit on top of that
                if ( Owner() > 0 )
                    tolerance += eLag::Credit( Owner() );

                // add lag fluctuation to the mix
                if ( sn_GetNetState() == nSERVER && player && player->Owner() != 0 )
                {
                    REAL varianceTolerance = 2 * sqrtf( sn_Connections[ player->Owner() ].ping.GetSnailAverager().GetDataVariance() );
                    // clamp it, high fluctuations are the player's own problem
                    if ( varianceTolerance > tolerance )
                        varianceTolerance = tolerance;
                    tolerance += varianceTolerance;
                }

                // if time has not progressed beyond tolerance, protection may be in effect
                toleratePacketLoss = ( se_GameTime() - Lag() - lastTimeAlive_ < tolerance );
            }

            // ... and apply it.
            if ( toleratePacketLoss )
            {
                pos = lastPos;
                verletSpeed_ = lastSpeed;
                acceleration = lastAcceleration;
                currentFace = lastFace;
                numTries = 0;
                emergency = true;

                // don't simulate further
                return false;
            }
            else
            {
                // no, no straw left. Rethrow and get killed.
                rubber = rubber_granted;

                // update distance to include the really covered space
                tASSERT(isfinite(distance));
                distance += eCoord::F( dirDrive, pos - lastPos )/dirDrive.NormSquared();
                tASSERT(isfinite(distance));

                throw;
            }
        }
        else
        {
            pos = lastPos;
            currentFace = lastFace;
            rubber += step/rubberEffectiveness;
            if ( rubber < 0 )
                rubber = 0;

            numTries = 0;
            emergency = true;
        }
    }

    tASSERT( rubber >= 0 );

    // use up rubber from tunneling (calculated by CalculateAcceleration
    if ( rubberEffectiveness > 0 )
    {
        rubber += rubberUsage * ts * verletSpeed_ / rubberEffectiveness;            }
    else if ( rubberUsage > 0 )
    {
        rubber = rubber_granted + 10;
    }
    rubberUsage = 0;

    // decide over kill
    bool rubberUsedUp = false;
    if ( rubber > rubber_granted || ( sg_cycleWidthRubberMax == 0 && sg_cycleWidthRubberMin == 0 ) )
    {
        if ( sn_GetNetState() != nCLIENT )
        {
            throw gCycleDeath( pos );
        }
        else
        {
            rubber = rubber_granted;
            rubberUsedUp = true;
        }
    }

    // use up brake
    brakingReservoir -= brakeUsage * ts;
    clamp( brakingReservoir, 0, 1 );

    // let rubber decay
    if ( sg_rubberCycleTime > 0 )
        rubber /= (1+ts/sg_rubberCycleTime);
    else
        rubber = 0;

    // let rubber decay
    if ( sg_rubberCycleMalusTime > 0 )
        rubberMalus /= (1+ts/sg_rubberCycleMalusTime);
    else
        rubberMalus = 0;


    // clamp rubber ( mostly for client side HUD display )
    if ( rubber >= rubber_granted )
    {
        rubber = rubber_granted;
        rubberUsedUp = true;
    }

    // record time rubber went out
    if( rubberUsedUp )
    {
        if ( rubberDepleteTime_ <= 0 )
        {
            rubberDepleteTime_ = lastTime;
        }
    }
    else
    {
        rubberDepleteTime_ = 0;
    }

    lastTime=currentTime;

    // give the AI a chance to evade just in time
    if (emergency)
    {
        RightBeforeDeath(numTries);
    }

#ifdef DEBUGOUTPUT
    if ( sg_cycleDebugPrintLevel > 1 )
        con << Player()->GetName() << " moved " << pos << "," << dirDrive << " " << tSysTimeFloat() << "\n";
#endif

    /*
    // debug output for sensitive rubber/time diagrams
    static REAL lastTimePrinted = 0;
    if ( currentTime > lastTimePrinted && Player() )
    {
        lastTimePrinted = currentTime;
        std::ofstream f( Player()->GetUserName() + "_rubber", std::ios::app );
        f << currentTime << " " << rubber << "\n";
    }
    */

    // apply acceleration
    if ( !sg_verletIntegration.Supported() )
        this->ApplyAcceleration( ts );

    tASSERT(isfinite(distance));

    tASSERT( rubber >= 0 );

    // call base timestep
    return eNetGameObject::Timestep(currentTime);
}

// *******************************************************************************************
// *
// *	MyInitAfterCreation
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

void gCycleMovement::MyInitAfterCreation( void )
{
#ifdef DEBUG
    // con << "creating cycle.\n";
#endif
    brakingReservoir = 1.0f;
    rubberDepleteTime_ = 0.0f;

    braking = false;

    uncannyTimingToReport_ = false;

    acceleration = 0;

    refreshSpaceAhead_ = true;
    maxSpaceMaxCast_ = 0.0;
    maxSpaceHit_ = NULL;

    dir=dirDrive;
    lastDirDrive=dirDrive;
    lastTurnPos_=pos;

    distance=0;
    // wallContDistance = 5;
    rubber=0.0f;
    rubberMalus=0.0f;
    rubberSpeedFactor=1.0f;

    gap_[0] = gap_[1] = 1E+30;
    keepLookingForGap_[0] = keepLookingForGap_[1] = true;
    gapIsBackdoor_[0] = gapIsBackdoor_[1] = true;

    alive_ = 1;

    z=.75;

    turns=1;

    pendingTurns.clear();
    lastTurnTimeRight_ = lastTurnTimeLeft_=lastTime-10;

    lastTimeAlive_ = lastTime;

    if (!isfinite(verletSpeed_)){
        st_Breakpoint();
        verletSpeed_ = 1;
    }

    if (verletSpeed_ < .1)
        verletSpeed_=.1;

#ifdef DEBUGOUTPUT
    if ( sg_cycleDebugPrintLevel > 0 )
        con << Player()->GetName() << " created " << pos << "," << dirDrive << " " << tSysTimeFloat() << "\n";
#endif
}

// *******************************************************************************************
// *
// *	Init_gCycleCore
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

//void gCycleMovement::Init_gCycleCore( void )
//{
//    assert(0); // implement me
//}

// *******************************************************************************************
// *
// *	Finit_gCycleCore
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

//void gCycleMovement::Finit_gCycleCore( void )
//{
//    assert(0); // implement me
//}

// *******************************************************************************************
// *
// *	gCycleMovement
// *
// *******************************************************************************************
//!
//!
// *******************************************************************************************

//gCycleMovement::gCycleMovement( void )
//{
//    assert(0); // implement me
//}

// *******************************************************************************************
// *
// *	gCycleMovement
// *
// *******************************************************************************************
//!
//!		@param	other
//!
// *******************************************************************************************

//gCycleMovement::gCycleMovement( gCycleMovement const & other )
//{
//    assert(0); // implement me
//}

// *******************************************************************************************
// *
// *	operator =
// *
// *******************************************************************************************
//!
//!		@param	other
//!		@return
//!
// *******************************************************************************************

//gCycleMovement & gCycleMovement::operator =( gCycleMovement const & other )
//{
//    assert(0); // implement me
//    return gCycleMovement();
//}

// *******************************************************************************************
// *
// *	CopyFrom
// *
// *******************************************************************************************
//!
//!		@param	other
//!
// *******************************************************************************************

//void gCycleMovement::CopyFrom( const gCycleMovement & other )
//{
//   assert(0); // implement me
//}

// *******************************************************************************************
// *
// *	DoGetDistanceSinceLastTurn
// *
// *******************************************************************************************
//!
//!		@return		the distance driven since the last turn
//!
// *******************************************************************************************

REAL gCycleMovement::DoGetDistanceSinceLastTurn( void ) const
{
    return eCoord::F( dirDrive, pos - lastTurnPos_ )/dirDrive.NormSquared();
}

// *******************************************************************************************
// *
// *	RubberMalusActive
// *
// *******************************************************************************************
//!
//!		@return
//!
// *******************************************************************************************

bool gCycleMovement::RubberMalusActive( void )
{
    return sg_rubberCycleMalusTurn > 0;
}

// *******************************************************************************************
// *
// *	MoveSafely
// *
// *******************************************************************************************
//!
//!		@param	dest	   the destination position
//!		@param	startTime  the start time of the movement
//!		@param	endTime	   the end time of the movement
//!
// *******************************************************************************************

void gCycleMovement::MoveSafely( const eCoord & dest, REAL startTime, REAL endTime )
{
    static bool recursing = false;
    if ( !recursing )
    {
        recursing = true;
        try
        {
            // try a regular move
            Move( dest, startTime, endTime );
        }
        catch( eDeath & death )
        {
            // and play dead if that doesn't work right
            short lastAlive = alive_;
            alive_ = 0;
            Move( dest, startTime, endTime );
            alive_ = lastAlive;
        }
    }
    else
    {
        // play dead if another safe move is already in process. Sometimes,
        // crossing a wall of a live cycle causes that cycle to be moved with
        // this function, and "killing" it temporarily avoids an endless
        // recursion in that case.
        short lastAlive = alive_;
        alive_ = 0;
        Move( dest, startTime, endTime );
        alive_ = lastAlive;
    }
}

REAL GetTurnSpeedFactor(void) {
    return sg_cycleTurnSpeedFactor;
}

void gCycleMovement::AddZoneAcceleration( REAL zoneAcceleration )
{
    totalZoneAcceleration += zoneAcceleration;
}

static void sg_FillCyclePhysics()
{
    // fetch base values
    REAL speed = sg_speedCycle * gCycleMovement::SpeedMultiplier();
    REAL rubber = sg_rubberCycle;
    REAL maxSpeed = gCycleMovement::MaximalSpeed();

    REAL delay = sg_delayCycle/gCycleMovement::SpeedMultiplier();
    if( su_doubleBindTimeout > delay )
    {
        delay = su_doubleBindTimeout;
        if( delay > .05 )
        {
            delay = .05;
        }
    }

    nServerInfo::SettingsDigest & digest = *nCallbackFillServerInfo::ToFill();
    digest.cycleDelay_ = delay;
    digest.acceleration_ = (maxSpeed-speed)/(speed+.001);
    digest.rubberWallHump_ = rubber/(speed*delay);
    // if humping is possible basically, check whether it's prevented or handicaped by
    // cycle_rubber_delay
    if( digest.rubberWallHump_ > 1 && sg_rubberCycleDelay > 0 )
    {
        REAL rubberDelayCount = sg_rubberCycleDelay > .999 ? .999 : sg_rubberCycleDelay;
        REAL bonus = sg_rubberCycleDelayBonus > 0 ? sg_rubberCycleDelayBonus : 0;
        digest.rubberWallHump_ *= bonus/(rubberDelayCount+bonus*(1-rubberDelayCount));
        // but not too much.
        if( digest.rubberWallHump_ < 1 )
        {
            digest.rubberWallHump_ = 1;
        }
    }
    digest.rubberHitWallRatio_ = rubber/(speed*sg_rubberCycleTime);
}

static nCallbackFillServerInfo sg_fillCyclePhysics(sg_FillCyclePhysics);