]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/race.qc
Store record type into a global to avoid some gamemode checks
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / race.qc
1 #include "race.qh"
2
3 #include <common/deathtypes/all.qh>
4 #include <common/gamemodes/_mod.qh>
5 #include <common/gamemodes/rules.qh>
6 #include <common/mapobjects/subs.qh>
7 #include <common/mapobjects/triggers.qh>
8 #include <common/mutators/mutator/waypoints/waypointsprites.qh>
9 #include <common/net_linked.qh>
10 #include <common/notifications/all.qh>
11 #include <common/state.qh>
12 #include <common/stats.qh>
13 #include <common/vehicles/sv_vehicles.qh>
14 #include <common/weapons/_all.qh>
15 #include <common/weapons/weapon/porto.qh>
16 #include <lib/warpzone/common.qh>
17 #include <lib/warpzone/util_server.qh>
18 #include <server/bot/api.qh>
19 #include <server/cheats.qh>
20 #include <server/client.qh>
21 #include <server/command/getreplies.qh>
22 #include <server/damage.qh>
23 #include <server/gamelog.qh>
24 #include <server/intermission.qh>
25 #include <server/main.qh>
26 #include <server/mutators/_mod.qh>
27 #include <server/portals.qh>
28 #include <server/scores.qh>
29 #include <server/spawnpoints.qh>
30 #include <server/weapons/common.qh>
31 #include <server/world.qh>
32
33 .string stored_netname; // TODO: store this information independently of race-based gamemodes
34
35 string uid2name(string myuid)
36 {
37         string s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
38
39         // FIXME remove this later after 0.6 release
40         // convert old style broken records to correct style
41         if(s == "")
42         {
43                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
44                 if(s != "")
45                 {
46                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
47                         db_remove(ServerProgsDB, strcat("uid2name", myuid));
48                 }
49         }
50
51         if(s == "")
52                 s = "^1Unregistered Player";
53         return s;
54 }
55
56 void write_recordmarker(entity pl, float tstart, float dt)
57 {
58     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
59
60     // also write a marker into demo files for demotc-race-record-extractor to find
61     stuffcmd(pl,
62              strcat(
63                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
64                  " ", ftos(tstart), " ", ftos(dt), "\n"));
65 }
66
67 IntrusiveList g_race_targets;
68 IntrusiveList g_racecheckpoints;
69 STATIC_INIT(g_race)
70 {
71         g_race_targets = IL_NEW();
72         g_racecheckpoints = IL_NEW();
73 }
74
75 void race_InitSpectator()
76 {
77         if(g_race_qualifying)
78                 if(msg_entity.enemy.race_laptime)
79                         race_SendNextCheckpoint(msg_entity.enemy, 1);
80 }
81
82 float race_readTime(string map, float pos)
83 {
84         return stof(db_get(ServerProgsDB, strcat(map, record_type, "time", ftos(pos))));
85 }
86
87 string race_readUID(string map, float pos)
88 {
89         return db_get(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(pos)));
90 }
91
92 float race_readPos(string map, float t)
93 {
94         for(int i = 1; i <= RANKINGS_CNT; ++i)
95         {
96                 int mytime = race_readTime(map, i);
97                 if(!mytime || mytime > t)
98                         return i;
99         }
100
101         return 0; // pos is zero if unranked
102 }
103
104 void race_writeTime(string map, float t, string myuid)
105 {
106         float newpos;
107         newpos = race_readPos(map, t);
108
109         float i, prevpos = 0;
110         for(i = 1; i <= RANKINGS_CNT; ++i)
111         {
112                 if(race_readUID(map, i) == myuid)
113                         prevpos = i;
114         }
115         if (prevpos)
116         {
117                 // player improved his existing record, only have to iterate on ranks between new and old recs
118                 for (i = prevpos; i > newpos; --i)
119                 {
120                         db_put(ServerProgsDB, strcat(map, record_type, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
121                         db_put(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
122                 }
123         }
124         else
125         {
126                 // player has no ranked record yet
127                 for (i = RANKINGS_CNT; i > newpos; --i)
128                 {
129                         float other_time = race_readTime(map, i - 1);
130                         if (other_time) {
131                                 db_put(ServerProgsDB, strcat(map, record_type, "time", ftos(i)), ftos(other_time));
132                                 db_put(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
133                         }
134                 }
135         }
136
137         // store new time itself
138         db_put(ServerProgsDB, strcat(map, record_type, "time", ftos(newpos)), ftos(t));
139         db_put(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(newpos)), myuid);
140 }
141
142 string race_readName(string map, float pos)
143 {
144         return uid2name(db_get(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(pos))));
145 }
146
147 void race_checkAndWriteName(entity player)
148 {
149         if(CS_CVAR(player).cvar_cl_allow_uidtracking == 1 && CS_CVAR(player).cvar_cl_allow_uid2name == 1)
150         {
151                 if (!player.stored_netname)
152                         player.stored_netname = strzone(uid2name(player.crypto_idfp));
153                 if(player.stored_netname != player.netname)
154                 {
155                         db_put(ServerProgsDB, strcat("/uid2name/", player.crypto_idfp), player.netname);
156                         strcpy(player.stored_netname, player.netname);
157                 }
158         }
159 }
160
161
162 const float MAX_CHECKPOINTS = 255;
163
164 .float race_penalty;
165 .float race_penalty_accumulator;
166 .string race_penalty_reason;
167 .float race_checkpoint; // player: next checkpoint that has to be reached
168 .entity race_lastpenalty;
169
170 .entity sprite;
171
172 float race_checkpoint_records[MAX_CHECKPOINTS];
173 string race_checkpoint_recordholders[MAX_CHECKPOINTS];
174 float race_checkpoint_lasttimes[MAX_CHECKPOINTS];
175 float race_checkpoint_lastlaps[MAX_CHECKPOINTS];
176 entity race_checkpoint_lastplayers[MAX_CHECKPOINTS];
177
178 .float race_checkpoint_record[MAX_CHECKPOINTS];
179
180 float race_highest_checkpoint;
181 float race_timed_checkpoint;
182
183 float defrag_ents;
184 float defragcpexists;
185
186 float race_NextCheckpoint(float f)
187 {
188         if(f >= race_highest_checkpoint)
189                 return 0;
190         else
191                 return f + 1;
192 }
193
194 float race_PreviousCheckpoint(float f)
195 {
196         if(f == -1)
197                 return 0;
198         else if(f == 0)
199                 return race_highest_checkpoint;
200         else
201                 return f - 1;
202 }
203
204 // encode as:
205 //   0 = common start/finish
206 // 254 = start
207 // 255 = finish
208 float race_CheckpointNetworkID(float f)
209 {
210         if(race_timed_checkpoint)
211         {
212                 if(f == 0)
213                         return 254; // start
214                 else if(f == race_timed_checkpoint)
215                         return 255; // finish
216         }
217         return f;
218 }
219
220 void race_SendNextCheckpoint(entity e, float spec) // qualifying only
221 {
222         if(!e.race_laptime)
223                 return;
224
225         int cp = e.race_checkpoint;
226         float recordtime = race_checkpoint_records[cp];
227         float myrecordtime = e.race_checkpoint_record[cp];
228         string recordholder = race_checkpoint_recordholders[cp];
229         if(recordholder == e.netname)
230                 recordholder = "";
231
232         if(!IS_REAL_CLIENT(e))
233                 return;
234
235         if(!spec)
236                 msg_entity = e;
237         WRITESPECTATABLE_MSG_ONE(msg_entity, {
238                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
239                 if(spec)
240                 {
241                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING);
242                         //WriteCoord(MSG_ONE, e.race_laptime - e.race_penalty_accumulator);
243                         WriteCoord(MSG_ONE, time - e.race_movetime - e.race_penalty_accumulator);
244                 }
245                 else
246                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_NEXT_QUALIFYING);
247                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player will be at next
248                 WriteInt24_t(MSG_ONE, recordtime);
249                 if(!spec)
250                         WriteInt24_t(MSG_ONE, myrecordtime);
251                 WriteString(MSG_ONE, recordholder);
252         });
253 }
254
255 void race_send_recordtime(float msg)
256 {
257         // send the server best time
258         WriteHeader(msg, TE_CSQC_RACE);
259         WriteByte(msg, RACE_NET_SERVER_RECORD);
260         WriteInt24_t(msg, race_readTime(GetMapname(), 1));
261 }
262
263
264 void race_send_speedaward(float msg)
265 {
266         // send the best speed of the round
267         WriteHeader(msg, TE_CSQC_RACE);
268         WriteByte(msg, RACE_NET_SPEED_AWARD);
269         WriteInt24_t(msg, floor(speedaward_speed+0.5));
270         WriteString(msg, speedaward_holder);
271 }
272
273 void race_send_speedaward_alltimebest(float msg)
274 {
275         // send the best speed
276         WriteHeader(msg, TE_CSQC_RACE);
277         WriteByte(msg, RACE_NET_SPEED_AWARD_BEST);
278         WriteInt24_t(msg, floor(speedaward_alltimebest+0.5));
279         WriteString(msg, speedaward_alltimebest_holder);
280 }
281
282 void race_send_rankings_cnt(float msg)
283 {
284         WriteHeader(msg, TE_CSQC_RACE);
285         WriteByte(msg, RACE_NET_RANKINGS_CNT);
286         int m = min(RANKINGS_CNT, autocvar_g_cts_send_rankings_cnt);
287         WriteByte(msg, m);
288 }
289
290 void race_SendRankings(float pos, float prevpos, float del, float msg)
291 {
292         WriteHeader(msg, TE_CSQC_RACE);
293         WriteByte(msg, RACE_NET_SERVER_RANKINGS);
294         WriteShort(msg, pos);
295         WriteShort(msg, prevpos);
296         WriteShort(msg, del);
297         WriteString(msg, race_readName(GetMapname(), pos));
298         WriteInt24_t(msg, race_readTime(GetMapname(), pos));
299 }
300
301 void race_SendStatus(float id, entity e)
302 {
303         if(!IS_REAL_CLIENT(e))
304                 return;
305
306         float msg;
307         if (id == 0)
308                 msg = MSG_ONE;
309         else
310                 msg = MSG_ALL;
311         msg_entity = e;
312         WRITESPECTATABLE_MSG_ONE(msg_entity, {
313                 WriteHeader(msg, TE_CSQC_RACE);
314                 WriteByte(msg, RACE_NET_SERVER_STATUS);
315                 WriteShort(msg, id);
316                 WriteString(msg, e.netname);
317         });
318 }
319
320 void race_setTime(string map, float t, string myuid, string mynetname, entity e, bool showmessage)
321 {
322         // netname only used TEMPORARILY for printing
323         int newpos = race_readPos(map, t);
324
325         int player_prevpos = 0;
326         for(int i = 1; i <= RANKINGS_CNT; ++i)
327         {
328                 if(race_readUID(map, i) == myuid)
329                         player_prevpos = i;
330         }
331
332         float oldrec;
333         string oldrec_holder;
334         if (player_prevpos && (player_prevpos < newpos || !newpos))
335         {
336                 oldrec = race_readTime(GetMapname(), player_prevpos);
337                 race_SendStatus(0, e); // "fail"
338                 if(showmessage)
339                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FAIL_RANKED, mynetname, player_prevpos, t, oldrec);
340                 return;
341         }
342         else if (!newpos)
343         {
344                 // no ranking, time worse than the worst ranked
345                 oldrec = race_readTime(GetMapname(), RANKINGS_CNT);
346                 race_SendStatus(0, e); // "fail"
347                 if(showmessage)
348                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FAIL_UNRANKED, mynetname, RANKINGS_CNT, t, oldrec);
349                 return;
350         }
351
352         // if we didn't hit a return yet, we have a new record!
353
354         // if the player does not have a UID we can unfortunately not store the record, as the rankings system relies on UIDs
355         if(myuid == "")
356         {
357                 if(showmessage)
358                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_MISSING_UID, mynetname, t);
359                 return;
360         }
361
362         if(uid2name(myuid) == "^1Unregistered Player")
363         {
364                 if(showmessage)
365                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_MISSING_NAME, mynetname, t);
366                 return;
367         }
368
369         oldrec = race_readTime(GetMapname(), newpos);
370         oldrec_holder = race_readName(GetMapname(), newpos);
371
372         // store new ranking
373         race_writeTime(GetMapname(), t, myuid);
374
375         if (newpos == 1 && showmessage)
376         {
377                 write_recordmarker(e, time - TIME_DECODE(t), TIME_DECODE(t));
378                 race_send_recordtime(MSG_ALL);
379         }
380
381         race_SendRankings(newpos, player_prevpos, 0, MSG_ALL);
382         strcpy(rankings_reply, getrankings());
383
384         if(newpos == player_prevpos)
385         {
386                 if(showmessage)
387                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_IMPROVED, mynetname, newpos, t, oldrec);
388                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
389                 else { race_SendStatus(1, e); } // "new time"
390         }
391         else if(oldrec == 0)
392         {
393                 if(showmessage)
394                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_SET, mynetname, newpos, t);
395                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
396                 else { race_SendStatus(2, e); } // "new rank"
397         }
398         else
399         {
400                 if(showmessage)
401                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_BROKEN, mynetname, oldrec_holder, newpos, t, oldrec);
402                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
403                 else { race_SendStatus(2, e); } // "new rank"
404         }
405 }
406
407 void race_deleteTime(string map, float pos)
408 {
409         for(int i = pos; i <= RANKINGS_CNT; ++i)
410         {
411                 string therank = ftos(i);
412                 if (i == RANKINGS_CNT)
413                 {
414                         db_remove(ServerProgsDB, strcat(map, record_type, "time", therank));
415                         db_remove(ServerProgsDB, strcat(map, record_type, "crypto_idfp", therank));
416                 }
417                 else
418                 {
419                         db_put(ServerProgsDB, strcat(map, record_type, "time", therank), ftos(race_readTime(GetMapname(), i+1)));
420                         db_put(ServerProgsDB, strcat(map, record_type, "crypto_idfp", therank), race_readUID(GetMapname(), i+1));
421                 }
422         }
423
424         race_SendRankings(pos, 0, 1, MSG_ALL);
425         if(pos == 1)
426                 race_send_recordtime(MSG_ALL);
427
428         strcpy(rankings_reply, getrankings());
429 }
430
431 void race_SendTime(entity e, float cp, float t, float tvalid)
432 {
433         float snew, l;
434
435         if(g_race_qualifying)
436                 t += e.race_penalty_accumulator;
437
438         t = TIME_ENCODE(t); // make integer
439
440         if(tvalid)
441         if(cp == race_timed_checkpoint) // finish line
442         if (!CS(e).race_completed)
443         {
444                 float s;
445                 if(g_race_qualifying)
446                 {
447                         s = GameRules_scoring_add(e, RACE_FASTEST, 0);
448                         if(!s || t < s)
449                                 GameRules_scoring_add(e, RACE_FASTEST, t - s);
450                 }
451                 else
452                 {
453                         s = GameRules_scoring_add(e, RACE_FASTEST, 0);
454                         if(!s || t < s)
455                                 GameRules_scoring_add(e, RACE_FASTEST, t - s);
456
457                         s = GameRules_scoring_add(e, RACE_TIME, 0);
458                         snew = TIME_ENCODE(time - game_starttime);
459                         GameRules_scoring_add(e, RACE_TIME, snew - s);
460                         l = GameRules_scoring_add_team(e, RACE_LAPS, 1);
461
462                         if(autocvar_fraglimit)
463                                 if(l >= autocvar_fraglimit)
464                                         race_StartCompleting();
465
466                         if(race_completing)
467                         {
468                                 CS(e).race_completed = 1;
469                                 MAKE_INDEPENDENT_PLAYER(e);
470                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FINISHED, e.netname);
471                                 ClientData_Touch(e);
472                         }
473                 }
474         }
475
476         if(g_race_qualifying)
477         {
478                 float recordtime;
479                 string recordholder;
480
481                 if(tvalid)
482                 {
483                         recordtime = race_checkpoint_records[cp];
484                         float myrecordtime = e.race_checkpoint_record[cp];
485                         recordholder = strcat1(race_checkpoint_recordholders[cp]); // make a tempstring copy, as we'll possibly strunzone it!
486                         if(recordholder == e.netname)
487                                 recordholder = "";
488
489                         if(t != 0)
490                         {
491                                 if(cp == race_timed_checkpoint)
492                                 {
493                                         race_setTime(GetMapname(), t, e.crypto_idfp, e.netname, e, true);
494                                         MUTATOR_CALLHOOK(Race_FinalCheckpoint, e);
495                                 }
496                                 if(t < myrecordtime || myrecordtime == 0)
497                                         e.race_checkpoint_record[cp] = t; // resending done below
498
499                                 if(t < recordtime || recordtime == 0)
500                                 {
501                                         race_checkpoint_records[cp] = t;
502                                         strcpy(race_checkpoint_recordholders[cp], e.netname);
503                                         if(g_race_qualifying)
504                                                 FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it) && it.race_checkpoint == cp, { race_SendNextCheckpoint(it, 0); });
505                                 }
506
507                         }
508                 }
509                 else
510                 {
511                         // dummies
512                         t = 0;
513                         recordtime = 0;
514                         recordholder = "";
515                 }
516
517                 if(IS_REAL_CLIENT(e))
518                 {
519                         if(g_race_qualifying)
520                         {
521                                 FOREACH_CLIENT(IS_REAL_CLIENT(it),
522                                 {
523                                         if(it == e || (IS_SPEC(it) && it.enemy == e))
524                                         {
525                                                 msg_entity = it;
526                                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
527                                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_QUALIFYING);
528                                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
529                                                 WriteInt24_t(MSG_ONE, t); // time to that intermediate
530                                                 WriteInt24_t(MSG_ONE, recordtime); // previously best time
531                                                 WriteInt24_t(MSG_ONE, ((tvalid) ? it.race_checkpoint_record[cp] : 0)); // previously best time
532                                                 WriteString(MSG_ONE, recordholder); // record holder
533                                         }
534                                 });
535                         }
536                 }
537         }
538         else // RACE! Not Qualifying
539         {
540                 float mylaps, lother, othtime;
541                 entity oth = race_checkpoint_lastplayers[cp];
542                 if(oth)
543                 {
544                         mylaps = GameRules_scoring_add(e, RACE_LAPS, 0);
545                         lother = race_checkpoint_lastlaps[cp];
546                         othtime = race_checkpoint_lasttimes[cp];
547                 }
548                 else
549                         mylaps = lother = othtime = 0;
550
551                 if(IS_REAL_CLIENT(e))
552                 {
553                         msg_entity = e;
554                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
555                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
556                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_RACE);
557                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
558                                 if(e == oth)
559                                 {
560                                         WriteInt24_t(MSG_ONE, 0);
561                                         WriteByte(MSG_ONE, 0);
562                                         WriteByte(MSG_ONE, 0);
563                                 }
564                                 else
565                                 {
566                                         WriteInt24_t(MSG_ONE, TIME_ENCODE(time - race_checkpoint_lasttimes[cp]));
567                                         WriteByte(MSG_ONE, mylaps - lother);
568                                         WriteByte(MSG_ONE, etof(oth)); // record holder
569                                 }
570                         });
571                 }
572
573                 race_checkpoint_lastplayers[cp] = e;
574                 race_checkpoint_lasttimes[cp] = time;
575                 race_checkpoint_lastlaps[cp] = mylaps;
576
577                 if(IS_REAL_CLIENT(oth))
578                 {
579                         msg_entity = oth;
580                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
581                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
582                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT);
583                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
584                                 if(e == oth)
585                                 {
586                                         WriteInt24_t(MSG_ONE, 0);
587                                         WriteByte(MSG_ONE, 0);
588                                         WriteByte(MSG_ONE, 0);
589                                 }
590                                 else
591                                 {
592                                         WriteInt24_t(MSG_ONE, TIME_ENCODE(time - othtime));
593                                         WriteByte(MSG_ONE, lother - mylaps);
594                                         WriteByte(MSG_ONE, etof(e) - 1); // record holder
595                                 }
596                         });
597                 }
598         }
599 }
600
601 void race_ClearTime(entity e)
602 {
603         e.race_checkpoint = 0;
604         e.race_laptime = 0;
605         e.race_movetime = e.race_movetime_frac = e.race_movetime_count = 0;
606         e.race_penalty_accumulator = 0;
607         e.race_lastpenalty = NULL;
608
609         if(!IS_REAL_CLIENT(e))
610                 return;
611
612         msg_entity = e;
613         WRITESPECTATABLE_MSG_ONE(msg_entity, {
614                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
615                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_CLEAR); // next
616         });
617 }
618
619 void checkpoint_passed(entity this, entity player)
620 {
621         if(IS_VEHICLE(player) && player.owner)
622                 player = player.owner;
623
624         if(player.personal && autocvar_g_allow_checkpoints)
625                 return; // practice mode!
626
627         if(player.classname == "porto")
628         {
629                 // do not allow portalling through checkpoints
630                 trace_plane_normal = normalize(-1 * player.velocity);
631                 W_Porto_Fail(player, 0);
632                 return;
633         }
634
635         string oldmsg; // used twice
636
637         /*
638          * Trigger targets
639          */
640         if (!((this.spawnflags & 2) && (IS_PLAYER(player))))
641         {
642                 oldmsg = this.message;
643                 this.message = "";
644                 SUB_UseTargets(this, player, player);
645                 this.message = oldmsg;
646         }
647
648         if (!IS_PLAYER(player))
649                 return;
650
651         /*
652          * Remove unauthorized equipment
653          */
654         Portal_ClearAll(player);
655
656         player.porto_forbidden = 2; // decreased by 1 each StartFrame
657
658         if(defrag_ents)
659         {
660                 if(this.race_checkpoint == -2)
661                 {
662                         this.race_checkpoint = player.race_checkpoint;
663                 }
664
665                 int cp_amount = 0, largest_cp_id = 0;
666                 IL_EACH(g_race_targets, it.classname == "target_checkpoint",
667                 {
668                         cp_amount += 1;
669                         if(it.race_checkpoint > largest_cp_id) // update the finish id if someone hit a new checkpoint
670                         {
671                                 if(!largest_cp_id)
672                                 {
673                                         IL_EACH(g_race_targets, it.classname == "target_checkpoint",
674                                         {
675                                                 if(it.race_checkpoint == -2) // set defragcpexists to -1 so that the cp id file will be rewritten when someone finishes
676                                                         defragcpexists = -1;
677                                         });
678                                 }
679
680                                 largest_cp_id = it.race_checkpoint;
681                                 IL_EACH(g_race_targets, it.classname == "target_stopTimer",
682                                 {
683                                         it.race_checkpoint = largest_cp_id + 1; // finish line
684                                 });
685                                 race_highest_checkpoint = largest_cp_id + 1;
686                                 race_timed_checkpoint = largest_cp_id + 1;
687                         }
688                 });
689
690                 if(!cp_amount)
691                 {
692                         IL_EACH(g_race_targets, it.classname == "target_stopTimer",
693                         {
694                                 it.race_checkpoint = 1;
695                         });
696                         race_highest_checkpoint = 1;
697                         race_timed_checkpoint = 1;
698                 }
699         }
700
701         if((player.race_checkpoint == -1 && this.race_checkpoint == 0) || (player.race_checkpoint == this.race_checkpoint))
702         {
703                 if(this.race_penalty)
704                 {
705                         if(player.race_lastpenalty != this)
706                         {
707                                 player.race_lastpenalty = this;
708                                 race_ImposePenaltyTime(player, this.race_penalty, this.race_penalty_reason);
709                         }
710                 }
711
712                 if(player.race_penalty)
713                         return;
714
715                 /*
716                  * Trigger targets
717                  */
718                 if(this.spawnflags & 2)
719                 {
720                         oldmsg = this.message;
721                         this.message = "";
722                         SUB_UseTargets(this, player, player); // TODO: should we be using other for the trigger here?
723                         this.message = oldmsg;
724                 }
725
726                 if(player.race_respawn_checkpoint != this.race_checkpoint || !player.race_started)
727                         player.race_respawn_spotref = this; // this is not a spot but a CP, but spawnpoint selection will deal with that
728                 player.race_respawn_checkpoint = this.race_checkpoint;
729                 player.race_checkpoint = race_NextCheckpoint(this.race_checkpoint);
730                 player.race_started = 1;
731
732                 race_SendTime(player, this.race_checkpoint, player.race_movetime, boolean(player.race_laptime));
733
734                 if(!this.race_checkpoint) // start line
735                 {
736                         player.race_laptime = time;
737                         player.race_movetime = player.race_movetime_frac = player.race_movetime_count = 0;
738                         player.race_penalty_accumulator = 0;
739                         player.race_lastpenalty = NULL;
740                 }
741
742                 if(g_race_qualifying)
743                         race_SendNextCheckpoint(player, 0);
744
745                 if(defrag_ents && defragcpexists < 0 && this.classname == "target_stopTimer")
746                 {
747                         float fh;
748                         defragcpexists = fh = fopen(strcat("maps/", GetMapname(), ".defragcp"), FILE_WRITE);
749                         if(fh >= 0)
750                         {
751                                 IL_EACH(g_race_targets, it.classname == "target_checkpoint",
752                                 {
753                                         fputs(fh, strcat(it.targetname, " ", ftos(it.race_checkpoint), "\n"));
754                                 });
755                         }
756                         fclose(fh);
757                 }
758         }
759         else if(player.race_checkpoint == race_NextCheckpoint(this.race_checkpoint))
760         {
761                 // ignored
762         }
763         else
764         {
765                 if(this.spawnflags & 4)
766                         Damage (player, this, this, 10000, DEATH_HURTTRIGGER.m_id, DMG_NOWEP, player.origin, '0 0 0');
767         }
768 }
769
770 void checkpoint_touch(entity this, entity toucher)
771 {
772         EXACTTRIGGER_TOUCH(this, toucher);
773         checkpoint_passed(this, toucher);
774 }
775
776 void checkpoint_use(entity this, entity actor, entity trigger)
777 {
778         if(trigger.classname == "info_player_deathmatch") // a spawn, a spawn
779                 return;
780
781         checkpoint_passed(this, actor);
782 }
783
784 bool race_waypointsprite_visible_for_player(entity this, entity player, entity view)
785 {
786         entity own = this.owner;
787         if(this.realowner)
788                 own = this.realowner; // target support
789
790         if(view.race_checkpoint == -1 || own.race_checkpoint == -2)
791                 return true;
792         else if(view.race_checkpoint == own.race_checkpoint)
793                 return true;
794         else
795                 return false;
796 }
797
798 void trigger_race_checkpoint_verify(entity this)
799 {
800     static bool have_verified;
801         if (have_verified) return;
802         have_verified = true;
803
804         bool qual = g_race_qualifying;
805
806         int pl_race_checkpoint = 0;
807         int pl_race_place = 0;
808
809         if (g_race) {
810                 for (int i = 0; i <= race_highest_checkpoint; ++i) {
811                         pl_race_checkpoint = race_NextCheckpoint(i);
812
813                         // race only (middle of the race)
814                         g_race_qualifying = false;
815                         pl_race_place = 0;
816                         if (!Spawn_FilterOutBadSpots(this, findchain(classname, "info_player_deathmatch"), 0, false, true)) {
817                                 error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(pl_race_place), " (used for respawning in race) - bailing out"));
818             }
819
820                         if (i == 0) {
821                                 // qualifying only
822                                 g_race_qualifying = 1;
823                                 pl_race_place = race_lowest_place_spawn;
824                                 if (!Spawn_FilterOutBadSpots(this, findchain(classname, "info_player_deathmatch"), 0, false, true)) {
825                                         error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(pl_race_place), " (used for qualifying) - bailing out"));
826                 }
827
828                                 // race only (initial spawn)
829                                 g_race_qualifying = 0;
830                                 for (int p = 1; p <= race_highest_place_spawn; ++p) {
831                                         pl_race_place = p;
832                                         if (!Spawn_FilterOutBadSpots(this, findchain(classname, "info_player_deathmatch"), 0, false, true)) {
833                                                 error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(pl_race_place), " (used for initially spawning in race) - bailing out"));
834                     }
835                                 }
836                         }
837                 }
838         } else if (!defrag_ents) {
839                 // qualifying only
840                 pl_race_checkpoint = race_NextCheckpoint(0);
841                 g_race_qualifying = 1;
842                 pl_race_place = race_lowest_place_spawn;
843                 if (!Spawn_FilterOutBadSpots(this, findchain(classname, "info_player_deathmatch"), 0, false, true)) {
844                         error(strcat("Checkpoint 0 misses a spawnpoint with race_place==", ftos(pl_race_place), " (used for qualifying) - bailing out"));
845         }
846         } else {
847                 pl_race_checkpoint = race_NextCheckpoint(0);
848                 g_race_qualifying = 1;
849                 pl_race_place = 0; // there's only one spawn on defrag maps
850
851                 // check if a defragcp file already exists, then read it and apply the checkpoint order
852                 float fh;
853                 float len;
854                 string l;
855
856                 defragcpexists = fh = fopen(strcat("maps/", GetMapname(), ".defragcp"), FILE_READ);
857                 if (fh >= 0) {
858                         while ((l = fgets(fh))) {
859                                 len = tokenize_console(l);
860                                 if (len != 2) {
861                                         defragcpexists = -1; // something's wrong in the defrag cp file, set defragcpexists to -1 so that it will be rewritten when someone finishes
862                                         continue;
863                                 }
864                                 for (entity cp = NULL; (cp = find(cp, classname, "target_checkpoint"));) {
865                                         if (argv(0) == cp.targetname) {
866                                                 cp.race_checkpoint = stof(argv(1));
867                     }
868                 }
869                         }
870                         fclose(fh);
871                 }
872         }
873
874         g_race_qualifying = qual;
875
876         IL_EACH(g_race_targets, it.classname == "target_checkpoint" || it.classname == "target_startTimer" || it.classname == "target_stopTimer",
877         {
878                 if(it.targetname == "" || !it.targetname) // somehow this is a case...
879                         continue;
880                 entity cpt = it;
881                 FOREACH_ENTITY_STRING(target, cpt.targetname,
882                 {
883                         vector org = (it.absmin + it.absmax) * 0.5;
884                         if(cpt.race_checkpoint == 0)
885                                 WaypointSprite_SpawnFixed(WP_RaceStart, org, it, sprite, RADARICON_NONE);
886                         else
887                                 WaypointSprite_SpawnFixed(WP_RaceCheckpoint, org, it, sprite, RADARICON_NONE);
888
889                         it.sprite.realowner = cpt;
890                         it.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
891                 });
892         });
893
894         if (race_timed_checkpoint) {
895                 if (defrag_ents) {
896                         IL_EACH(g_race_targets, it.classname == "target_checkpoint" || it.classname == "target_startTimer" || it.classname == "target_stopTimer",
897                         {
898                                 entity cpt = it;
899                                 if(it.classname == "target_startTimer" || it.classname == "target_stopTimer") {
900                                         if(it.targetname == "" || !it.targetname) // somehow this is a case...
901                                                 continue;
902                                         FOREACH_ENTITY_STRING(target, cpt.targetname, {
903                                                 if(it.sprite)
904                                                         WaypointSprite_UpdateSprites(it.sprite, ((cpt.classname == "target_startTimer") ? WP_RaceStart : WP_RaceFinish), WP_Null, WP_Null);
905                                         });
906                                 }
907                                 if(it.classname == "target_checkpoint") {
908                                         if(it.race_checkpoint == -2)
909                                                 defragcpexists = -1; // something's wrong with the defrag cp file or it has not been written yet, set defragcpexists to -1 so that it will be rewritten when someone finishes
910                                 }
911                         });
912                         if (defragcpexists != -1) {
913                                 float largest_cp_id = 0;
914                                 for (entity cp = NULL; (cp = find(cp, classname, "target_checkpoint"));) {
915                                         if (cp.race_checkpoint > largest_cp_id) {
916                                                 largest_cp_id = cp.race_checkpoint;
917                     }
918                 }
919                                 for (entity cp = NULL; (cp = find(cp, classname, "target_stopTimer"));) {
920                                         cp.race_checkpoint = largest_cp_id + 1; // finish line
921                 }
922                                 race_highest_checkpoint = largest_cp_id + 1;
923                                 race_timed_checkpoint = largest_cp_id + 1;
924                         } else {
925                                 for (entity cp = NULL; (cp = find(cp, classname, "target_stopTimer"));) {
926                                         cp.race_checkpoint = 255; // finish line
927                 }
928                                 race_highest_checkpoint = 255;
929                                 race_timed_checkpoint = 255;
930                         }
931                 } else {
932                         IL_EACH(g_racecheckpoints, it.sprite,
933                         {
934                                 if (it.race_checkpoint == 0) {
935                                         WaypointSprite_UpdateSprites(it.sprite, WP_RaceStart, WP_Null, WP_Null);
936                 } else if (it.race_checkpoint == race_timed_checkpoint) {
937                                         WaypointSprite_UpdateSprites(it.sprite, WP_RaceFinish, WP_Null, WP_Null);
938                                 }
939             });
940                 }
941         }
942
943         if (defrag_ents) {
944                 for (entity trigger = NULL; (trigger = find(trigger, classname, "trigger_multiple")); ) {
945                         for (entity targ = NULL; (targ = find(targ, targetname, trigger.target)); ) {
946                                 if (targ.classname == "target_checkpoint" || targ.classname == "target_startTimer" || targ.classname == "target_stopTimer") {
947                                         trigger.wait = 0;
948                                         trigger.delay = 0;
949                                         targ.wait = 0;
950                                         targ.delay = 0;
951
952                     // These just make the game crash on some maps with oddly shaped triggers.
953                     // (on the other hand they used to fix the case when two players ran through a checkpoint at once,
954                     // and often one of them just passed through without being registered. Hope it's fixed  in a better way now.
955                     // (happened on item triggers too)
956                     //
957                                         //targ.wait = -2;
958                                         //targ.delay = 0;
959
960                                         //setsize(targ, trigger.mins, trigger.maxs);
961                                         //setorigin(targ, trigger.origin);
962                                         //remove(trigger);
963                                 }
964             }
965         }
966         }
967 }
968
969 vector trigger_race_checkpoint_spawn_evalfunc(entity this, entity player, entity spot, vector current)
970 {
971         if(g_race_qualifying)
972         {
973                 // spawn at first
974                 if(this.race_checkpoint != 0)
975                         return '-1 0 0';
976                 if(spot.race_place != race_lowest_place_spawn)
977                         return '-1 0 0';
978         }
979         else
980         {
981                 if(this.race_checkpoint != player.race_respawn_checkpoint)
982                         return '-1 0 0';
983                 // try reusing the previous spawn
984                 if(this == player.race_respawn_spotref || spot == player.race_respawn_spotref)
985                         current.x += SPAWN_PRIO_RACE_PREVIOUS_SPAWN;
986                 if(this.race_checkpoint == 0)
987                 {
988                         int pl = player.race_place;
989                         if(pl > race_highest_place_spawn)
990                                 pl = 0;
991                         if(pl == 0 && !player.race_started)
992                                 pl = race_highest_place_spawn; // use last place if he has not even touched finish yet
993                         if(spot.race_place != pl)
994                                 return '-1 0 0';
995                 }
996         }
997         return current;
998 }
999
1000 spawnfunc(trigger_race_checkpoint)
1001 {
1002         vector o;
1003         if(!g_race && !g_cts) { delete(this); return; }
1004
1005         EXACTTRIGGER_INIT;
1006
1007         this.use = checkpoint_use;
1008         if (!(this.spawnflags & 1))
1009                 settouch(this, checkpoint_touch);
1010
1011         o = (this.absmin + this.absmax) * 0.5;
1012         tracebox(o, PL_MIN_CONST, PL_MAX_CONST, o - '0 0 1' * (o.z - this.absmin.z), MOVE_NORMAL, this);
1013         waypoint_spawnforitem_force(this, trace_endpos);
1014         this.nearestwaypointtimeout = -1;
1015
1016         if(this.message == "")
1017                 this.message = "went backwards";
1018         if (this.message2 == "")
1019                 this.message2 = "was pushed backwards by";
1020         if (this.race_penalty_reason == "")
1021                 this.race_penalty_reason = "missing a checkpoint";
1022
1023         this.race_checkpoint = this.cnt;
1024
1025         if(this.race_checkpoint > race_highest_checkpoint)
1026         {
1027                 race_highest_checkpoint = this.race_checkpoint;
1028                 if(this.spawnflags & 8)
1029                         race_timed_checkpoint = this.race_checkpoint;
1030                 else
1031                         race_timed_checkpoint = 0;
1032         }
1033
1034         if(!this.race_penalty)
1035         {
1036                 if(this.race_checkpoint)
1037                         WaypointSprite_SpawnFixed(WP_RaceCheckpoint, o, this, sprite, RADARICON_NONE);
1038                 else
1039                         WaypointSprite_SpawnFixed(WP_RaceStartFinish, o, this, sprite, RADARICON_NONE);
1040         }
1041
1042         this.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
1043         this.spawn_evalfunc = trigger_race_checkpoint_spawn_evalfunc;
1044
1045         IL_PUSH(g_racecheckpoints, this);
1046
1047         InitializeEntity(this, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
1048 }
1049
1050 void target_checkpoint_setup(entity this)
1051 {
1052         if(!g_race && !g_cts) { delete(this); return; }
1053         defrag_ents = 1;
1054
1055         // if this is targeted, then it probably isn't a trigger
1056         bool is_trigger = this.targetname == "";
1057
1058         if(is_trigger)
1059                 EXACTTRIGGER_INIT;
1060
1061         this.use = checkpoint_use;
1062         if (is_trigger && !(this.spawnflags & 1))
1063                 settouch(this, checkpoint_touch);
1064
1065         vector org = this.origin;
1066
1067         // bots should only pathfind to this if it is a valid touchable trigger
1068         if(is_trigger)
1069         {
1070                 org = (this.absmin + this.absmax) * 0.5;
1071                 tracebox(org, PL_MIN_CONST, PL_MAX_CONST, org - '0 0 1' * (org.z - this.absmin.z), MOVE_NORMAL, this);
1072                 waypoint_spawnforitem_force(this, trace_endpos);
1073                 this.nearestwaypointtimeout = -1;
1074         }
1075
1076         if(this.message == "")
1077                 this.message = "went backwards";
1078         if (this.message2 == "")
1079                 this.message2 = "was pushed backwards by";
1080         if (this.race_penalty_reason == "")
1081                 this.race_penalty_reason = "missing a checkpoint";
1082
1083         if(this.classname == "target_startTimer")
1084                 this.race_checkpoint = 0;
1085         else
1086                 this.race_checkpoint = -2;
1087
1088         race_timed_checkpoint = 1;
1089
1090         IL_PUSH(g_race_targets, this);
1091
1092         InitializeEntity(this, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
1093 }
1094
1095 spawnfunc(target_checkpoint)
1096 {
1097         // xonotic defrag entity
1098         target_checkpoint_setup(this);
1099 }
1100
1101 // compatibility entity names
1102 spawnfunc(target_startTimer) { target_checkpoint_setup(this); }
1103 spawnfunc(target_stopTimer) { target_checkpoint_setup(this); }
1104
1105 void race_AbandonRaceCheck(entity p)
1106 {
1107         if(race_completing && !CS(p).race_completed)
1108         {
1109                 CS(p).race_completed = 1;
1110                 MAKE_INDEPENDENT_PLAYER(p);
1111                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_ABANDONED, p.netname);
1112                 ClientData_Touch(p);
1113         }
1114 }
1115
1116 void race_StartCompleting()
1117 {
1118         race_completing = 1;
1119         FOREACH_CLIENT(IS_PLAYER(it) && IS_DEAD(it), { race_AbandonRaceCheck(it); });
1120 }
1121
1122 void race_PreparePlayer(entity this)
1123 {
1124         race_ClearTime(this);
1125         this.race_place = 0;
1126         this.race_started = 0;
1127         this.race_respawn_checkpoint = 0;
1128         this.race_respawn_spotref = NULL;
1129 }
1130
1131 void race_RetractPlayer(entity this)
1132 {
1133         if(!g_race && !g_cts)
1134                 return;
1135         if(this.race_respawn_checkpoint == 0 || this.race_respawn_checkpoint == race_timed_checkpoint)
1136                 race_ClearTime(this);
1137         this.race_checkpoint = this.race_respawn_checkpoint;
1138 }
1139
1140 spawnfunc(info_player_race)
1141 {
1142         if(!g_race && !g_cts) { delete(this); return; }
1143         ++race_spawns;
1144         spawnfunc_info_player_deathmatch(this);
1145
1146         if(this.race_place > race_highest_place_spawn)
1147                 race_highest_place_spawn = this.race_place;
1148         if(this.race_place < race_lowest_place_spawn)
1149                 race_lowest_place_spawn = this.race_place;
1150 }
1151
1152 void race_ClearRecords()
1153 {
1154         for(int j = 0; j < MAX_CHECKPOINTS; ++j)
1155         {
1156                 race_checkpoint_records[j] = 0;
1157                 strfree(race_checkpoint_recordholders[j]);
1158         }
1159
1160         FOREACH_CLIENT(true, {
1161                 float p = it.race_place;
1162                 race_PreparePlayer(it);
1163                 it.race_place = p;
1164         });
1165 }
1166
1167 void race_ImposePenaltyTime(entity pl, float penalty, string reason)
1168 {
1169         if(g_race_qualifying)
1170         {
1171                 pl.race_penalty_accumulator += penalty;
1172                 if(IS_REAL_CLIENT(pl))
1173                 {
1174                         msg_entity = pl;
1175                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
1176                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1177                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_QUALIFYING);
1178                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1179                                 WriteString(MSG_ONE, reason);
1180                         });
1181                 }
1182         }
1183         else
1184         {
1185                 pl.race_penalty = time + penalty;
1186                 if(IS_REAL_CLIENT(pl))
1187                 {
1188                         msg_entity = pl;
1189                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
1190                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1191                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_RACE);
1192                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1193                                 WriteString(MSG_ONE, reason);
1194                         });
1195                 }
1196         }
1197 }
1198
1199 void penalty_touch(entity this, entity toucher)
1200 {
1201         EXACTTRIGGER_TOUCH(this, toucher);
1202         if(toucher.race_lastpenalty != this)
1203         {
1204                 toucher.race_lastpenalty = this;
1205                 race_ImposePenaltyTime(toucher, this.race_penalty, this.race_penalty_reason);
1206         }
1207 }
1208
1209 void penalty_use(entity this, entity actor, entity trigger)
1210 {
1211         race_ImposePenaltyTime(actor, this.race_penalty, this.race_penalty_reason);
1212 }
1213
1214 spawnfunc(trigger_race_penalty)
1215 {
1216         // TODO: find out why this wasnt done:
1217         //if(!g_cts && !g_race) { remove(this); return; }
1218
1219         EXACTTRIGGER_INIT;
1220
1221         this.use = penalty_use;
1222         if (!(this.spawnflags & 1))
1223                 settouch(this, penalty_touch);
1224
1225         if (this.race_penalty_reason == "")
1226                 this.race_penalty_reason = "missing a checkpoint";
1227         if (!this.race_penalty)
1228                 this.race_penalty = 5;
1229 }
1230
1231 float race_GetFractionalLapCount(entity e)
1232 {
1233         // interesting metrics (idea by KrimZon) to maybe sort players in the
1234         // scoreboard, immediately updates when overtaking
1235         //
1236         // requires the track to be built so you never get farther away from the
1237         // next checkpoint, though, and current Xonotic race maps are not built that
1238         // way
1239         //
1240         // also, this code is slow and would need optimization (i.e. "next CP"
1241         // links on CP entities)
1242
1243         float l;
1244         l = GameRules_scoring_add(e, RACE_LAPS, 0);
1245         if(CS(e).race_completed)
1246                 return l; // not fractional
1247
1248         vector o0, o1;
1249         float bestfraction, fraction;
1250         entity lastcp;
1251         float nextcpindex, lastcpindex;
1252
1253         nextcpindex = max(e.race_checkpoint, 0);
1254         lastcpindex = e.race_respawn_checkpoint;
1255         lastcp = e.race_respawn_spotref;
1256
1257         if(nextcpindex == lastcpindex)
1258                 return l; // finish
1259
1260         bestfraction = 1;
1261         IL_EACH(g_racecheckpoints, true,
1262         {
1263                 if(it.race_checkpoint != lastcpindex)
1264                         continue;
1265                 if(lastcp)
1266                         if(it != lastcp)
1267                                 continue;
1268                 o0 = (it.absmin + it.absmax) * 0.5;
1269                 IL_EACH(g_racecheckpoints, true,
1270                 {
1271                         if(it.race_checkpoint != nextcpindex)
1272                                 continue;
1273                         o1 = (it.absmin + it.absmax) * 0.5;
1274                         if(o0 == o1)
1275                                 continue;
1276                         fraction = bound(0.0001, vlen(e.origin - o1) / vlen(o0 - o1), 1);
1277                         if(fraction < bestfraction)
1278                                 bestfraction = fraction;
1279                 });
1280         });
1281
1282         // we are at CP "nextcpindex - bestfraction"
1283         // race_timed_checkpoint == 4: then nextcp==4 means 0.9999x, nextcp==0 means 0.0000x
1284         // race_timed_checkpoint == 0: then nextcp==0 means 0.9999x
1285         float c, nc;
1286         nc = race_highest_checkpoint + 1;
1287         c = ((nextcpindex - race_timed_checkpoint + nc + nc - 1) % nc) + 1 - bestfraction;
1288
1289         return l + c / nc;
1290 }