]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/race.qc
80023e76ada42a67139ba3aeeaa1644aeda14db5
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / race.qc
1 #include "race.qh"
2
3 #include "client.qh"
4 #include "portals.qh"
5 #include "scores.qh"
6 #include "spawnpoints.qh"
7 #include "bot/api.qh"
8 #include "command/getreplies.qh"
9 #include "../common/deathtypes/all.qh"
10 #include "../common/notifications/all.qh"
11 #include "../common/mapinfo.qh"
12 #include <common/net_linked.qh>
13 #include "../common/triggers/subs.qh"
14 #include "../lib/warpzone/util_server.qh"
15 #include "../lib/warpzone/common.qh"
16 #include "../common/mutators/mutator/waypoints/waypointsprites.qh"
17
18 IntrusiveList g_race_targets;
19 STATIC_INIT(g_race_targets) { g_race_targets = IL_NEW(); }
20
21 void race_InitSpectator()
22 {
23         if(g_race_qualifying)
24                 if(msg_entity.enemy.race_laptime)
25                         race_SendNextCheckpoint(msg_entity.enemy, 1);
26 }
27
28 void W_Porto_Fail(entity this, float failhard);
29
30 float race_readTime(string map, float pos)
31 {
32         string rr = ((g_cts) ? CTS_RECORD : ((g_ctf) ? CTF_RECORD : RACE_RECORD));
33
34         return stof(db_get(ServerProgsDB, strcat(map, rr, "time", ftos(pos))));
35 }
36
37 string race_readUID(string map, float pos)
38 {
39         string rr = ((g_cts) ? CTS_RECORD : ((g_ctf) ? CTF_RECORD : RACE_RECORD));
40
41         return db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos)));
42 }
43
44 float race_readPos(string map, float t)
45 {
46         for(int i = 1; i <= RANKINGS_CNT; ++i)
47         {
48                 int mytime = race_readTime(map, i);
49                 if(!mytime || mytime > t)
50                         return i;
51         }
52
53         return 0; // pos is zero if unranked
54 }
55
56 void race_writeTime(string map, float t, string myuid)
57 {
58         string rr = ((g_cts) ? CTS_RECORD : ((g_ctf) ? CTF_RECORD : RACE_RECORD));
59
60         float newpos;
61         newpos = race_readPos(map, t);
62
63         float i, prevpos = 0;
64         for(i = 1; i <= RANKINGS_CNT; ++i)
65         {
66                 if(race_readUID(map, i) == myuid)
67                         prevpos = i;
68         }
69         if (prevpos)
70         {
71                 // player improved his existing record, only have to iterate on ranks between new and old recs
72                 for (i = prevpos; i > newpos; --i)
73                 {
74                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
75                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
76                 }
77         }
78         else
79         {
80                 // player has no ranked record yet
81                 for (i = RANKINGS_CNT; i > newpos; --i)
82                 {
83                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
84                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
85                 }
86         }
87
88         // store new time itself
89         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(newpos)), ftos(t));
90         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(newpos)), myuid);
91 }
92
93 string race_readName(string map, float pos)
94 {
95         string rr = ((g_cts) ? CTS_RECORD : ((g_ctf) ? CTF_RECORD : RACE_RECORD));
96
97         return uid2name(db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos))));
98 }
99
100
101 const float MAX_CHECKPOINTS = 255;
102
103 spawnfunc(target_checkpoint);
104
105 .float race_penalty;
106 .float race_penalty_accumulator;
107 .string race_penalty_reason;
108 .float race_checkpoint; // player: next checkpoint that has to be reached
109 .entity race_lastpenalty;
110
111 .entity sprite;
112
113 float race_checkpoint_records[MAX_CHECKPOINTS];
114 string race_checkpoint_recordholders[MAX_CHECKPOINTS];
115 float race_checkpoint_lasttimes[MAX_CHECKPOINTS];
116 float race_checkpoint_lastlaps[MAX_CHECKPOINTS];
117 entity race_checkpoint_lastplayers[MAX_CHECKPOINTS];
118
119 .float race_checkpoint_record[MAX_CHECKPOINTS];
120
121 float race_highest_checkpoint;
122 float race_timed_checkpoint;
123
124 float defrag_ents;
125 float defragcpexists;
126
127 float race_NextCheckpoint(float f)
128 {
129         if(f >= race_highest_checkpoint)
130                 return 0;
131         else
132                 return f + 1;
133 }
134
135 float race_PreviousCheckpoint(float f)
136 {
137         if(f == -1)
138                 return 0;
139         else if(f == 0)
140                 return race_highest_checkpoint;
141         else
142                 return f - 1;
143 }
144
145 // encode as:
146 //   0 = common start/finish
147 // 254 = start
148 // 255 = finish
149 float race_CheckpointNetworkID(float f)
150 {
151         if(race_timed_checkpoint)
152         {
153                 if(f == 0)
154                         return 254; // start
155                 else if(f == race_timed_checkpoint)
156                         return 255; // finish
157         }
158         return f;
159 }
160
161 void race_SendNextCheckpoint(entity e, float spec) // qualifying only
162 {
163         if(!e.race_laptime)
164                 return;
165
166         int cp = e.race_checkpoint;
167         float recordtime = race_checkpoint_records[cp];
168         string recordholder = race_checkpoint_recordholders[cp];
169         if(recordholder == e.netname)
170                 recordholder = "";
171
172         if(!IS_REAL_CLIENT(e))
173                 return;
174
175         if(!spec && !e.cvar_cl_race_cptimes_onlyself) // don't show spectators the player's personal time
176                 msg_entity = e;
177         WRITESPECTATABLE_MSG_ONE(msg_entity, {
178                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
179                 if(spec)
180                 {
181                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING);
182                         //WriteCoord(MSG_ONE, e.race_laptime - e.race_penalty_accumulator);
183                         WriteCoord(MSG_ONE, time - e.race_movetime - e.race_penalty_accumulator);
184                 }
185                 else
186                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_NEXT_QUALIFYING);
187                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player will be at next
188                 WriteInt24_t(MSG_ONE, recordtime);
189                 WriteString(MSG_ONE, recordholder);
190         });
191
192         if(!spec && e.cvar_cl_race_cptimes_onlyself) // don't send to spectators!
193         {
194                 recordtime = e.race_checkpoint_record[cp];
195
196                 // not spectatable
197                 msg_entity = e;
198                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
199                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_NEXT_SELF_QUALIFYING);
200                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player will be at next
201                 WriteInt24_t(MSG_ONE, recordtime);
202         }
203 }
204
205 void race_send_recordtime(float msg)
206 {
207         // send the server best time
208         WriteHeader(msg, TE_CSQC_RACE);
209         WriteByte(msg, RACE_NET_SERVER_RECORD);
210         WriteInt24_t(msg, race_readTime(GetMapname(), 1));
211 }
212
213
214 void race_send_speedaward(float msg)
215 {
216         // send the best speed of the round
217         WriteHeader(msg, TE_CSQC_RACE);
218         WriteByte(msg, RACE_NET_SPEED_AWARD);
219         WriteInt24_t(msg, floor(speedaward_speed+0.5));
220         WriteString(msg, speedaward_holder);
221 }
222
223 void race_send_speedaward_alltimebest(float msg)
224 {
225         // send the best speed
226         WriteHeader(msg, TE_CSQC_RACE);
227         WriteByte(msg, RACE_NET_SPEED_AWARD_BEST);
228         WriteInt24_t(msg, floor(speedaward_alltimebest+0.5));
229         WriteString(msg, speedaward_alltimebest_holder);
230 }
231
232 void race_SendRankings(float pos, float prevpos, float del, float msg)
233 {
234         WriteHeader(msg, TE_CSQC_RACE);
235         WriteByte(msg, RACE_NET_SERVER_RANKINGS);
236         WriteShort(msg, pos);
237         WriteShort(msg, prevpos);
238         WriteShort(msg, del);
239         WriteString(msg, race_readName(GetMapname(), pos));
240         WriteInt24_t(msg, race_readTime(GetMapname(), pos));
241 }
242
243 void race_SendStatus(float id, entity e)
244 {
245         if(!IS_REAL_CLIENT(e))
246                 return;
247
248         float msg;
249         if (id == 0)
250                 msg = MSG_ONE;
251         else
252                 msg = MSG_ALL;
253         msg_entity = e;
254         WRITESPECTATABLE_MSG_ONE(msg_entity, {
255                 WriteHeader(msg, TE_CSQC_RACE);
256                 WriteByte(msg, RACE_NET_SERVER_STATUS);
257                 WriteShort(msg, id);
258                 WriteString(msg, e.netname);
259         });
260 }
261
262 void race_setTime(string map, float t, string myuid, string mynetname, entity e, bool showmessage)
263 {
264         // netname only used TEMPORARILY for printing
265         int newpos = race_readPos(map, t);
266
267         int player_prevpos = 0;
268         for(int i = 1; i <= RANKINGS_CNT; ++i)
269         {
270                 if(race_readUID(map, i) == myuid)
271                         player_prevpos = i;
272         }
273
274         float oldrec;
275         string oldrec_holder;
276         if (player_prevpos && (player_prevpos < newpos || !newpos))
277         {
278                 oldrec = race_readTime(GetMapname(), player_prevpos);
279                 race_SendStatus(0, e); // "fail"
280                 if(showmessage)
281                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FAIL_RANKED, mynetname, player_prevpos, t, oldrec);
282                 return;
283         }
284         else if (!newpos)
285         {
286                 // no ranking, time worse than the worst ranked
287                 oldrec = race_readTime(GetMapname(), RANKINGS_CNT);
288                 race_SendStatus(0, e); // "fail"
289                 if(showmessage)
290                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FAIL_UNRANKED, mynetname, RANKINGS_CNT, t, oldrec);
291                 return;
292         }
293
294         // if we didn't hit a return yet, we have a new record!
295
296         // if the player does not have a UID we can unfortunately not store the record, as the rankings system relies on UIDs
297         if(myuid == "")
298         {
299                 if(showmessage)
300                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_MISSING_UID, mynetname, t);
301                 return;
302         }
303
304         if(uid2name(myuid) == "^1Unregistered Player")
305         {
306                 if(showmessage)
307                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_MISSING_NAME, mynetname, t);
308                 return;
309         }
310
311         oldrec = race_readTime(GetMapname(), newpos);
312         oldrec_holder = race_readName(GetMapname(), newpos);
313
314         // store new ranking
315         race_writeTime(GetMapname(), t, myuid);
316
317         if (newpos == 1 && showmessage)
318         {
319                 write_recordmarker(e, time - TIME_DECODE(t), TIME_DECODE(t));
320                 race_send_recordtime(MSG_ALL);
321         }
322
323         race_SendRankings(newpos, player_prevpos, 0, MSG_ALL);
324         if(rankings_reply)
325                 strunzone(rankings_reply);
326         rankings_reply = strzone(getrankings());
327
328         if(newpos == player_prevpos)
329         {
330                 if(showmessage)
331                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_IMPROVED, mynetname, newpos, t, oldrec);
332                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
333                 else { race_SendStatus(1, e); } // "new time"
334         }
335         else if(oldrec == 0)
336         {
337                 if(showmessage)
338                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_SET, mynetname, newpos, t);
339                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
340                 else { race_SendStatus(2, e); } // "new rank"
341         }
342         else
343         {
344                 if(showmessage)
345                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_BROKEN, mynetname, oldrec_holder, newpos, t, oldrec);
346                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
347                 else { race_SendStatus(2, e); } // "new rank"
348         }
349 }
350
351 void race_deleteTime(string map, float pos)
352 {
353         string rr = ((g_cts) ? CTS_RECORD : ((g_ctf) ? CTF_RECORD : RACE_RECORD));
354
355         for(int i = pos; i <= RANKINGS_CNT; ++i)
356         {
357                 string therank = ftos(i);
358                 if (i == RANKINGS_CNT)
359                 {
360                         db_remove(ServerProgsDB, strcat(map, rr, "time", therank));
361                         db_remove(ServerProgsDB, strcat(map, rr, "crypto_idfp", therank));
362                 }
363                 else
364                 {
365                         db_put(ServerProgsDB, strcat(map, rr, "time", therank), ftos(race_readTime(GetMapname(), i+1)));
366                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", therank), race_readUID(GetMapname(), i+1));
367                 }
368         }
369
370         race_SendRankings(pos, 0, 1, MSG_ALL);
371         if(pos == 1)
372                 race_send_recordtime(MSG_ALL);
373
374         if(rankings_reply)
375                 strunzone(rankings_reply);
376         rankings_reply = strzone(getrankings());
377 }
378
379 void race_SendTime(entity e, float cp, float t, float tvalid)
380 {
381         float snew, l;
382
383         if(g_race_qualifying)
384                 t += e.race_penalty_accumulator;
385
386         t = TIME_ENCODE(t); // make integer
387
388         if(tvalid)
389         if(cp == race_timed_checkpoint) // finish line
390         if (!e.race_completed)
391         {
392                 float s;
393                 if(g_race_qualifying)
394                 {
395                         s = PlayerScore_Add(e, SP_RACE_FASTEST, 0);
396                         if(!s || t < s)
397                                 PlayerScore_Add(e, SP_RACE_FASTEST, t - s);
398                 }
399                 else
400                 {
401                         s = PlayerScore_Add(e, SP_RACE_FASTEST, 0);
402                         if(!s || t < s)
403                                 PlayerScore_Add(e, SP_RACE_FASTEST, t - s);
404
405                         s = PlayerScore_Add(e, SP_RACE_TIME, 0);
406                         snew = TIME_ENCODE(time - game_starttime);
407                         PlayerScore_Add(e, SP_RACE_TIME, snew - s);
408                         l = PlayerTeamScore_Add(e, SP_RACE_LAPS, ST_RACE_LAPS, 1);
409
410                         if(autocvar_fraglimit)
411                                 if(l >= autocvar_fraglimit)
412                                         race_StartCompleting();
413
414                         if(race_completing)
415                         {
416                                 e.race_completed = 1;
417                                 MAKE_INDEPENDENT_PLAYER(e);
418                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FINISHED, e.netname);
419                                 ClientData_Touch(e);
420                         }
421                 }
422         }
423
424         if(g_race_qualifying)
425         {
426                 float recordtime;
427                 float myrecordtime;
428                 string recordholder;
429
430                 if(tvalid)
431                 {
432                         recordtime = race_checkpoint_records[cp];
433                         myrecordtime = e.race_checkpoint_record[cp];
434                         recordholder = strcat1(race_checkpoint_recordholders[cp]); // make a tempstring copy, as we'll possibly strunzone it!
435                         if(recordholder == e.netname)
436                                 recordholder = "";
437
438                         if(t != 0)
439                         {
440                                 if(cp == race_timed_checkpoint)
441                                 {
442                                         race_setTime(GetMapname(), t, e.crypto_idfp, e.netname, e, true);
443                                         MUTATOR_CALLHOOK(Race_FinalCheckpoint, e);
444                                 }
445                                 if(t < recordtime || recordtime == 0)
446                                 {
447                                         race_checkpoint_records[cp] = t;
448                                         if(race_checkpoint_recordholders[cp])
449                                                 strunzone(race_checkpoint_recordholders[cp]);
450                                         race_checkpoint_recordholders[cp] = strzone(e.netname);
451                                         if(g_race_qualifying)
452                                                 FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it) && it.race_checkpoint == cp, LAMBDA(race_SendNextCheckpoint(it, 0)));
453                                 }
454
455                                 if(t < myrecordtime || myrecordtime == 0)
456                                         e.race_checkpoint_record[cp] = t; // resending done below
457                         }
458                 }
459                 else
460                 {
461                         // dummies
462                         t = 0;
463                         recordtime = 0;
464                         myrecordtime = 0;
465                         recordholder = "";
466                 }
467
468                 if(IS_REAL_CLIENT(e))
469                 {
470                         msg_entity = e;
471                         if(g_race_qualifying)
472                         {
473                                 WRITESPECTATABLE_MSG_ONE(e, {
474                                         if(it == e && e.cvar_cl_race_cptimes_onlyself)
475                                                 continue;
476                                         WriteHeader(MSG_ONE, TE_CSQC_RACE);
477                                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_QUALIFYING);
478                                         WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
479                                         WriteInt24_t(MSG_ONE, t); // time to that intermediate
480                                         WriteInt24_t(MSG_ONE, recordtime); // previously best time
481                                         WriteString(MSG_ONE, recordholder); // record holder
482                                 });
483
484                                 if(e.cvar_cl_race_cptimes_onlyself)
485                                 {
486                                         msg_entity = e;
487                                         WriteHeader(MSG_ONE, TE_CSQC_RACE);
488                                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_SELF_QUALIFYING);
489                                         WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
490                                         WriteInt24_t(MSG_ONE, t); // time to that intermediate
491                                         WriteInt24_t(MSG_ONE, myrecordtime); // previously best time
492                                 }
493                         }
494                 }
495         }
496         else // RACE! Not Qualifying
497         {
498                 float mylaps, lother, othtime;
499                 entity oth = race_checkpoint_lastplayers[cp];
500                 if(oth)
501                 {
502                         mylaps = PlayerScore_Add(e, SP_RACE_LAPS, 0);
503                         lother = race_checkpoint_lastlaps[cp];
504                         othtime = race_checkpoint_lasttimes[cp];
505                 }
506                 else
507                         mylaps = lother = othtime = 0;
508
509                 if(IS_REAL_CLIENT(e))
510                 {
511                         msg_entity = e;
512                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
513                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
514                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_RACE);
515                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
516                                 if(e == oth)
517                                 {
518                                         WriteInt24_t(MSG_ONE, 0);
519                                         WriteByte(MSG_ONE, 0);
520                                         WriteByte(MSG_ONE, 0);
521                                 }
522                                 else
523                                 {
524                                         WriteInt24_t(MSG_ONE, TIME_ENCODE(time - race_checkpoint_lasttimes[cp]));
525                                         WriteByte(MSG_ONE, mylaps - lother);
526                                         WriteByte(MSG_ONE, etof(oth)); // record holder
527                                 }
528                         });
529                 }
530
531                 race_checkpoint_lastplayers[cp] = e;
532                 race_checkpoint_lasttimes[cp] = time;
533                 race_checkpoint_lastlaps[cp] = mylaps;
534
535                 if(IS_REAL_CLIENT(oth))
536                 {
537                         msg_entity = oth;
538                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
539                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
540                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT);
541                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
542                                 if(e == oth)
543                                 {
544                                         WriteInt24_t(MSG_ONE, 0);
545                                         WriteByte(MSG_ONE, 0);
546                                         WriteByte(MSG_ONE, 0);
547                                 }
548                                 else
549                                 {
550                                         WriteInt24_t(MSG_ONE, TIME_ENCODE(time - othtime));
551                                         WriteByte(MSG_ONE, lother - mylaps);
552                                         WriteByte(MSG_ONE, etof(e) - 1); // record holder
553                                 }
554                         });
555                 }
556         }
557 }
558
559 void race_ClearTime(entity e)
560 {
561         e.race_checkpoint = 0;
562         e.race_laptime = 0;
563         e.race_movetime = e.race_movetime_frac = e.race_movetime_count = 0;
564         e.race_penalty_accumulator = 0;
565         e.race_lastpenalty = NULL;
566
567         if(!IS_REAL_CLIENT(e))
568                 return;
569
570         msg_entity = e;
571         WRITESPECTATABLE_MSG_ONE(msg_entity, {
572                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
573                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_CLEAR); // next
574         });
575 }
576
577 void checkpoint_passed(entity this, entity player)
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, 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)) {
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)) {
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)) {
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)) {
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, true,
832         {
833                 entity cpt = it;
834                 FOREACH_ENTITY_STRING(target, cpt.targetname,
835                 {
836                         vector org = (it.absmin + it.absmax) * 0.5;
837                         if(cpt.race_checkpoint == 0)
838                                 WaypointSprite_SpawnFixed(WP_RaceStart, org, it, sprite, RADARICON_NONE);
839                         else
840                                 WaypointSprite_SpawnFixed(WP_RaceCheckpoint, org, it, sprite, RADARICON_NONE);
841
842                         it.sprite.realowner = cpt;
843                         it.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
844                 });
845         });
846
847         if (race_timed_checkpoint) {
848                 if (defrag_ents) {
849                         IL_EACH(g_race_targets, true,
850                         {
851                                 entity cpt = it;
852                                 if(it.classname == "target_startTimer" || it.classname == "target_stopTimer") {
853                                         FOREACH_ENTITY_STRING(target, cpt.targetname, {
854                                                 WaypointSprite_UpdateSprites(it.sprite, ((cpt.classname == "target_startTimer") ? WP_RaceStart : WP_RaceFinish), WP_Null, WP_Null);
855                                         });
856                                 }
857                                 if(it.classname == "target_checkpoint") {
858                                         if(it.race_checkpoint == -2)
859                                                 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
860                                 }
861                         });
862                         if (defragcpexists != -1) {
863                                 float largest_cp_id = 0;
864                                 for (entity cp = NULL; (cp = find(cp, classname, "target_checkpoint"));) {
865                                         if (cp.race_checkpoint > largest_cp_id) {
866                                                 largest_cp_id = cp.race_checkpoint;
867                     }
868                 }
869                                 for (entity cp = NULL; (cp = find(cp, classname, "target_stopTimer"));) {
870                                         cp.race_checkpoint = largest_cp_id + 1; // finish line
871                 }
872                                 race_highest_checkpoint = largest_cp_id + 1;
873                                 race_timed_checkpoint = largest_cp_id + 1;
874                         } else {
875                                 for (entity cp = NULL; (cp = find(cp, classname, "target_stopTimer"));) {
876                                         cp.race_checkpoint = 255; // finish line
877                 }
878                                 race_highest_checkpoint = 255;
879                                 race_timed_checkpoint = 255;
880                         }
881                 } else {
882                         IL_EACH(g_racecheckpoints, it.sprite,
883                         {
884                                 if (it.race_checkpoint == 0) {
885                                         WaypointSprite_UpdateSprites(it.sprite, WP_RaceStart, WP_Null, WP_Null);
886                 } else if (it.race_checkpoint == race_timed_checkpoint) {
887                                         WaypointSprite_UpdateSprites(it.sprite, WP_RaceFinish, WP_Null, WP_Null);
888                                 }
889             });
890                 }
891         }
892
893         if (defrag_ents) {
894                 for (entity trigger = NULL; (trigger = find(trigger, classname, "trigger_multiple")); ) {
895                         for (entity targ = NULL; (targ = find(targ, targetname, trigger.target)); ) {
896                                 if (targ.classname == "target_checkpoint" || targ.classname == "target_startTimer" || targ.classname == "target_stopTimer") {
897                                         trigger.wait = 0;
898                                         trigger.delay = 0;
899                                         targ.wait = 0;
900                                         targ.delay = 0;
901
902                     // These just make the game crash on some maps with oddly shaped triggers.
903                     // (on the other hand they used to fix the case when two players ran through a checkpoint at once,
904                     // and often one of them just passed through without being registered. Hope it's fixed  in a better way now.
905                     // (happened on item triggers too)
906                     //
907                                         //targ.wait = -2;
908                                         //targ.delay = 0;
909
910                                         //setsize(targ, trigger.mins, trigger.maxs);
911                                         //setorigin(targ, trigger.origin);
912                                         //remove(trigger);
913                                 }
914             }
915         }
916         }
917 }
918
919 vector trigger_race_checkpoint_spawn_evalfunc(entity this, entity player, entity spot, vector current)
920 {
921         if(g_race_qualifying)
922         {
923                 // spawn at first
924                 if(this.race_checkpoint != 0)
925                         return '-1 0 0';
926                 if(spot.race_place != race_lowest_place_spawn)
927                         return '-1 0 0';
928         }
929         else
930         {
931                 if(this.race_checkpoint != player.race_respawn_checkpoint)
932                         return '-1 0 0';
933                 // try reusing the previous spawn
934                 if(this == player.race_respawn_spotref || spot == player.race_respawn_spotref)
935                         current.x += SPAWN_PRIO_RACE_PREVIOUS_SPAWN;
936                 if(this.race_checkpoint == 0)
937                 {
938                         int pl = player.race_place;
939                         if(pl > race_highest_place_spawn)
940                                 pl = 0;
941                         if(pl == 0 && !player.race_started)
942                                 pl = race_highest_place_spawn; // use last place if he has not even touched finish yet
943                         if(spot.race_place != pl)
944                                 return '-1 0 0';
945                 }
946         }
947         return current;
948 }
949
950 spawnfunc(trigger_race_checkpoint)
951 {
952         vector o;
953         if(!g_race && !g_cts) { delete(this); return; }
954
955         EXACTTRIGGER_INIT;
956
957         this.use = checkpoint_use;
958         if (!(this.spawnflags & 1))
959                 settouch(this, checkpoint_touch);
960
961         o = (this.absmin + this.absmax) * 0.5;
962         tracebox(o, PL_MIN_CONST, PL_MAX_CONST, o - '0 0 1' * (o.z - this.absmin.z), MOVE_NORMAL, this);
963         waypoint_spawnforitem_force(this, trace_endpos);
964         this.nearestwaypointtimeout = -1;
965
966         if(this.message == "")
967                 this.message = "went backwards";
968         if (this.message2 == "")
969                 this.message2 = "was pushed backwards by";
970         if (this.race_penalty_reason == "")
971                 this.race_penalty_reason = "missing a checkpoint";
972
973         this.race_checkpoint = this.cnt;
974
975         if(this.race_checkpoint > race_highest_checkpoint)
976         {
977                 race_highest_checkpoint = this.race_checkpoint;
978                 if(this.spawnflags & 8)
979                         race_timed_checkpoint = this.race_checkpoint;
980                 else
981                         race_timed_checkpoint = 0;
982         }
983
984         if(!this.race_penalty)
985         {
986                 if(this.race_checkpoint)
987                         WaypointSprite_SpawnFixed(WP_RaceCheckpoint, o, this, sprite, RADARICON_NONE);
988                 else
989                         WaypointSprite_SpawnFixed(WP_RaceStartFinish, o, this, sprite, RADARICON_NONE);
990         }
991
992         this.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
993         this.spawn_evalfunc = trigger_race_checkpoint_spawn_evalfunc;
994
995         IL_PUSH(g_racecheckpoints, this);
996
997         InitializeEntity(this, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
998 }
999
1000 spawnfunc(target_checkpoint) // defrag entity
1001 {
1002         if(!g_race && !g_cts) { delete(this); return; }
1003         defrag_ents = 1;
1004
1005         // if this is targeted, then it probably isn't a trigger
1006         bool is_trigger = !boolean(!this.nottargeted && this.targetname != "");
1007
1008         if(is_trigger)
1009                 EXACTTRIGGER_INIT;
1010
1011         this.use = checkpoint_use;
1012         if (is_trigger && !(this.spawnflags & 1))
1013                 settouch(this, checkpoint_touch);
1014
1015         vector org = this.origin;
1016
1017         // bots should only pathfind to this if it is a valid touchable trigger
1018         if(is_trigger)
1019         {
1020                 org = (this.absmin + this.absmax) * 0.5;
1021                 tracebox(org, PL_MIN_CONST, PL_MAX_CONST, org - '0 0 1' * (org.z - this.absmin.z), MOVE_NORMAL, this);
1022                 waypoint_spawnforitem_force(this, trace_endpos);
1023                 this.nearestwaypointtimeout = -1;
1024         }
1025
1026         if(this.message == "")
1027                 this.message = "went backwards";
1028         if (this.message2 == "")
1029                 this.message2 = "was pushed backwards by";
1030         if (this.race_penalty_reason == "")
1031                 this.race_penalty_reason = "missing a checkpoint";
1032
1033         if(this.classname == "target_startTimer")
1034                 this.race_checkpoint = 0;
1035         else
1036                 this.race_checkpoint = -2;
1037
1038         race_timed_checkpoint = 1;
1039
1040         IL_PUSH(g_race_targets, this);
1041
1042         InitializeEntity(this, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
1043 }
1044
1045 spawnfunc(target_startTimer) { spawnfunc_target_checkpoint(this); }
1046 spawnfunc(target_stopTimer) { spawnfunc_target_checkpoint(this); }
1047
1048 void race_AbandonRaceCheck(entity p)
1049 {
1050         if(race_completing && !p.race_completed)
1051         {
1052                 p.race_completed = 1;
1053                 MAKE_INDEPENDENT_PLAYER(p);
1054                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_ABANDONED, p.netname);
1055                 ClientData_Touch(p);
1056         }
1057 }
1058
1059 void race_StartCompleting()
1060 {
1061         race_completing = 1;
1062         FOREACH_CLIENT(IS_PLAYER(it) && IS_DEAD(it), LAMBDA(race_AbandonRaceCheck(it)));
1063 }
1064
1065 void race_PreparePlayer(entity this)
1066 {
1067         race_ClearTime(this);
1068         this.race_place = 0;
1069         this.race_started = 0;
1070         this.race_respawn_checkpoint = 0;
1071         this.race_respawn_spotref = NULL;
1072 }
1073
1074 void race_RetractPlayer(entity this)
1075 {
1076         if(!g_race && !g_cts)
1077                 return;
1078         if(this.race_respawn_checkpoint == 0 || this.race_respawn_checkpoint == race_timed_checkpoint)
1079                 race_ClearTime(this);
1080         this.race_checkpoint = this.race_respawn_checkpoint;
1081 }
1082
1083 spawnfunc(info_player_race)
1084 {
1085         if(!g_race && !g_cts) { delete(this); return; }
1086         ++race_spawns;
1087         spawnfunc_info_player_deathmatch(this);
1088
1089         if(this.race_place > race_highest_place_spawn)
1090                 race_highest_place_spawn = this.race_place;
1091         if(this.race_place < race_lowest_place_spawn)
1092                 race_lowest_place_spawn = this.race_place;
1093 }
1094
1095 void race_ClearRecords()
1096 {
1097         float i;
1098
1099         for(i = 0; i < MAX_CHECKPOINTS; ++i)
1100         {
1101                 race_checkpoint_records[i] = 0;
1102                 if(race_checkpoint_recordholders[i])
1103                         strunzone(race_checkpoint_recordholders[i]);
1104                 race_checkpoint_recordholders[i] = string_null;
1105         }
1106
1107         FOREACH_CLIENT(true, LAMBDA(
1108                 float p = it.race_place;
1109                 race_PreparePlayer(it);
1110                 it.race_place = p;
1111         ));
1112 }
1113
1114 void race_ImposePenaltyTime(entity pl, float penalty, string reason)
1115 {
1116         if(g_race_qualifying)
1117         {
1118                 pl.race_penalty_accumulator += penalty;
1119                 if(IS_REAL_CLIENT(pl))
1120                 {
1121                         msg_entity = pl;
1122                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
1123                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1124                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_QUALIFYING);
1125                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1126                                 WriteString(MSG_ONE, reason);
1127                         });
1128                 }
1129         }
1130         else
1131         {
1132                 pl.race_penalty = time + penalty;
1133                 if(IS_REAL_CLIENT(pl))
1134                 {
1135                         msg_entity = pl;
1136                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
1137                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1138                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_RACE);
1139                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1140                                 WriteString(MSG_ONE, reason);
1141                         });
1142                 }
1143         }
1144 }
1145
1146 void penalty_touch(entity this, entity toucher)
1147 {
1148         EXACTTRIGGER_TOUCH(this, toucher);
1149         if(toucher.race_lastpenalty != this)
1150         {
1151                 toucher.race_lastpenalty = this;
1152                 race_ImposePenaltyTime(toucher, this.race_penalty, this.race_penalty_reason);
1153         }
1154 }
1155
1156 void penalty_use(entity this, entity actor, entity trigger)
1157 {
1158         race_ImposePenaltyTime(actor, this.race_penalty, this.race_penalty_reason);
1159 }
1160
1161 spawnfunc(trigger_race_penalty)
1162 {
1163         // TODO: find out why this wasnt done:
1164         //if(!g_cts && !g_race) { remove(this); return; }
1165
1166         EXACTTRIGGER_INIT;
1167
1168         this.use = penalty_use;
1169         if (!(this.spawnflags & 1))
1170                 settouch(this, penalty_touch);
1171
1172         if (this.race_penalty_reason == "")
1173                 this.race_penalty_reason = "missing a checkpoint";
1174         if (!this.race_penalty)
1175                 this.race_penalty = 5;
1176 }
1177
1178 float race_GetFractionalLapCount(entity e)
1179 {
1180         // interesting metrics (idea by KrimZon) to maybe sort players in the
1181         // scoreboard, immediately updates when overtaking
1182         //
1183         // requires the track to be built so you never get farther away from the
1184         // next checkpoint, though, and current Xonotic race maps are not built that
1185         // way
1186         //
1187         // also, this code is slow and would need optimization (i.e. "next CP"
1188         // links on CP entities)
1189
1190         float l;
1191         l = PlayerScore_Add(e, SP_RACE_LAPS, 0);
1192         if(e.race_completed)
1193                 return l; // not fractional
1194
1195         vector o0, o1;
1196         float bestfraction, fraction;
1197         entity lastcp;
1198         float nextcpindex, lastcpindex;
1199
1200         nextcpindex = max(e.race_checkpoint, 0);
1201         lastcpindex = e.race_respawn_checkpoint;
1202         lastcp = e.race_respawn_spotref;
1203
1204         if(nextcpindex == lastcpindex)
1205                 return l; // finish
1206
1207         bestfraction = 1;
1208         IL_EACH(g_racecheckpoints, true,
1209         {
1210                 if(it.race_checkpoint != lastcpindex)
1211                         continue;
1212                 if(lastcp)
1213                         if(it != lastcp)
1214                                 continue;
1215                 o0 = (it.absmin + it.absmax) * 0.5;
1216                 IL_EACH(g_racecheckpoints, true,
1217                 {
1218                         if(it.race_checkpoint != nextcpindex)
1219                                 continue;
1220                         o1 = (it.absmin + it.absmax) * 0.5;
1221                         if(o0 == o1)
1222                                 continue;
1223                         fraction = bound(0.0001, vlen(e.origin - o1) / vlen(o0 - o1), 1);
1224                         if(fraction < bestfraction)
1225                                 bestfraction = fraction;
1226                 });
1227         });
1228
1229         // we are at CP "nextcpindex - bestfraction"
1230         // race_timed_checkpoint == 4: then nextcp==4 means 0.9999x, nextcp==0 means 0.0000x
1231         // race_timed_checkpoint == 0: then nextcp==0 means 0.9999x
1232         float c, nc;
1233         nc = race_highest_checkpoint + 1;
1234         c = ((nextcpindex - race_timed_checkpoint + nc + nc - 1) % nc) + 1 - bestfraction;
1235
1236         return l + c / nc;
1237 }