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