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