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