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