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