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