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