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