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