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