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