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