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