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