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