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