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