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