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