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