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