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