]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/scores.qc
Merge branch 'master' into z411/bai-server
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / scores.qc
1 #include "scores.qh"
2
3 #include <common/mapinfo.qh>
4 #include <common/mutators/base.qh>
5 #include <common/net_linked.qh>
6 #include <common/playerstats.qh>
7 #include <common/scores.qh>
8 #include <common/state.qh>
9 #include <common/stats.qh>
10 #include <common/teams.qh>
11 #include <common/weapons/_all.qh>
12 #include <server/client.qh>
13 #include <server/command/common.qh>
14 #include <server/intermission.qh>
15 #include <server/mutators/_mod.qh>
16 #include <server/round_handler.qh>
17 #include <server/world.qh>
18
19 .entity scorekeeper;
20 entity teamscorekeepers[16];
21 float teamscores_entities_count;
22 var .float scores_primary;
23 var .float teamscores_primary;
24 float scores_flags_primary;
25 float teamscores_flags_primary;
26
27 vector ScoreField_Compare(entity t1, entity t2, .float field, float fieldflags, vector previous, bool strict) // returns: cmp value, best prio
28 {
29         if(!strict && !(fieldflags & SFL_SORT_PRIO_MASK)) // column does not sort
30                 return previous;
31         if((fieldflags & SFL_SORT_PRIO_MASK) < previous.y)
32                 return previous;
33         if (t1.(field) == t2.(field))
34                 return previous;
35
36         previous.y = fieldflags & SFL_SORT_PRIO_MASK;
37
38         if(fieldflags & SFL_ZERO_IS_WORST)
39         {
40                 if (t1.(field) == 0)
41                 {
42                         previous.x = -1;
43                         return previous;
44                 }
45                 else if (t2.(field) == 0)
46                 {
47                         previous.x = +1;
48                         return previous;
49                 }
50         }
51
52         if (fieldflags & SFL_LOWER_IS_BETTER)
53                 previous.x = (t2.(field) - t1.(field));
54         else
55                 previous.x = (t1.(field) - t2.(field));
56
57         return previous;
58 }
59
60 /*
61  * teamscore entities
62  */
63
64 bool TeamScore_SendEntity(entity this, entity to, float sendflags)
65 {
66         float i, longflags;
67
68         WriteHeader(MSG_ENTITY, ENT_CLIENT_TEAMSCORES);
69         int t = this.team - 1;
70         assert(t, eprint(this));
71         WriteByte(MSG_ENTITY, t);
72
73         longflags = 0;
74         for(i = 0; i < MAX_TEAMSCORE; ++i)
75                 if(this.(teamscores(i)) > 127 || this.(teamscores(i)) <= -128)
76                         longflags |= BIT(i);
77
78 #if MAX_TEAMSCORE <= 8
79         WriteByte(MSG_ENTITY, sendflags);
80         WriteByte(MSG_ENTITY, longflags);
81 #else
82         WriteShort(MSG_ENTITY, sendflags);
83         WriteShort(MSG_ENTITY, longflags);
84 #endif
85         for(i = 0; i < MAX_TEAMSCORE; ++i)
86                 if(sendflags & BIT(i))
87                 {
88                         if(longflags & BIT(i))
89                                 WriteInt24_t(MSG_ENTITY, this.(teamscores(i)));
90                         else
91                                 WriteChar(MSG_ENTITY, this.(teamscores(i)));
92                 }
93
94         return true;
95 }
96
97 void TeamScore_Spawn(float t, string name)
98 {
99         entity ts = new_pure(csqc_score_team);
100         ts.netname = name; // not used yet, FIXME
101         ts.team = t;
102         Net_LinkEntity(ts, false, 0, TeamScore_SendEntity);
103         teamscorekeepers[t - 1] = ts;
104         ++teamscores_entities_count;
105         PlayerStats_GameReport_AddTeam(t);
106 }
107
108 float TeamScore_AddToTeam(int t, float scorefield, float score)
109 {
110         entity s;
111
112         if(game_stopped)
113         {
114                 score = 0;
115         }
116
117         if(!scores_initialized) return 0; // FIXME remove this when everything uses this system
118         if(t <= 0 || t >= 16)
119         {
120                 if(game_stopped)
121                         return 0;
122                 error("Adding score to invalid team!");
123         }
124         s = teamscorekeepers[t - 1];
125         if(!s)
126         {
127                 if(game_stopped)
128                         return 0;
129                 error("Adding score to unknown team!");
130         }
131         if(score)
132                 if(teamscores_label(scorefield) != "")
133                         s.SendFlags |= BIT(scorefield);
134         return (s.(teamscores(scorefield)) += score);
135 }
136
137 float TeamScore_Add(entity player, float scorefield, float score)
138 {
139         return TeamScore_AddToTeam(player.team, scorefield, score);
140 }
141
142 float TeamScore_Compare(entity t1, entity t2, bool strict)
143 {
144         if(!t1 || !t2) return (!t2) - !t1;
145
146         vector result = '0 0 0';
147         float i;
148         for(i = 0; i < MAX_TEAMSCORE; ++i)
149         {
150                 var .float f;
151                 f = teamscores(i);
152                 result = ScoreField_Compare(t1, t2, f, teamscores_flags(i), result, strict);
153         }
154
155         if (result.x == 0 && strict)
156                 result.x = t1.team - t2.team;
157
158         return result.x;
159 }
160
161 /*
162  * the scoreinfo entity
163  */
164
165 void ScoreInfo_SetLabel_PlayerScore(PlayerScoreField i, string label, float scoreflags)
166 {
167         scores_label(i) = label;
168         scores_flags(i) = scoreflags;
169         if((scoreflags & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
170         {
171                 scores_primary = scores(i);
172                 scores_flags_primary = scoreflags;
173         }
174         if(label != "")
175         {
176                 PlayerStats_GameReport_AddEvent(strcat(PLAYERSTATS_TOTAL, label));
177                 PlayerStats_GameReport_AddEvent(strcat(PLAYERSTATS_SCOREBOARD, label));
178         }
179 }
180
181 void ScoreInfo_SetLabel_TeamScore(float i, string label, float scoreflags)
182 {
183         teamscores_label(i) = label;
184         teamscores_flags(i) = scoreflags;
185         if((scoreflags & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
186         {
187                 teamscores_primary = teamscores(i);
188                 teamscores_flags_primary = scoreflags;
189         }
190         if(label != "")
191         {
192                 PlayerStats_GameReport_AddEvent(strcat(PLAYERSTATS_TOTAL, label));
193                 PlayerStats_GameReport_AddEvent(strcat(PLAYERSTATS_SCOREBOARD, label));
194         }
195 }
196
197 bool ScoreInfo_SendEntity(entity this, entity to, int sf)
198 {
199         float i;
200         WriteHeader(MSG_ENTITY, ENT_CLIENT_SCORES_INFO);
201         WriteRegistered(Gametypes, MSG_ENTITY, MapInfo_LoadedGametype);
202         FOREACH(Scores, true, {
203                 WriteString(MSG_ENTITY, scores_label(it));
204                 WriteByte(MSG_ENTITY, scores_flags(it));
205         });
206         for(i = 0; i < MAX_TEAMSCORE; ++i)
207         {
208                 WriteString(MSG_ENTITY, teamscores_label(i));
209                 WriteByte(MSG_ENTITY, teamscores_flags(i));
210         }
211         // prevent sending the welcome message again when score types are sent again because the scoring system has changed
212         // it can happen in some game modes like Race when the qualyfing session ends and the race starts
213         // NOTE: CS(this) is not initialized yet when a local client connects to a local dedicated server
214         bool welcome_msg_too = (!CS(this) || time < CS(this).jointime + 5);
215         WriteByte(MSG_ENTITY, welcome_msg_too);
216         // welcome message is sent here because it needs to know the gametype
217         if (welcome_msg_too)
218                 SendWelcomemessage_msg_type(this, false, MSG_ENTITY);
219         return true;
220 }
221
222 void ScoreInfo_Init(int teams)
223 {
224         if(scores_initialized)
225         {
226                 scores_initialized.SendFlags |= 1; // force a resend
227         }
228         else
229         {
230                 scores_initialized = new_pure(ent_client_scoreinfo);
231                 Net_LinkEntity(scores_initialized, false, 0, ScoreInfo_SendEntity);
232         }
233         if(teams & BIT(0))
234                 TeamScore_Spawn(NUM_TEAM_1, "Red");
235         if(teams & BIT(1))
236                 TeamScore_Spawn(NUM_TEAM_2, "Blue");
237         if(teams & BIT(2))
238                 TeamScore_Spawn(NUM_TEAM_3, "Yellow");
239         if(teams & BIT(3))
240                 TeamScore_Spawn(NUM_TEAM_4, "Pink");
241 }
242
243 /*
244  * per-player score entities
245  */
246
247 bool PlayerScore_SendEntity(entity this, entity to, float sendflags)
248 {
249         WriteHeader(MSG_ENTITY, ENT_CLIENT_SCORES);
250         WriteByte(MSG_ENTITY, etof(this.owner));
251
252         int longflags = 0;
253         FOREACH(Scores, true, {
254             int p = 1 << (i % 16);
255                 if (this.(scores(it)) > 127 || this.(scores(it)) <= -128)
256                         longflags |= p;
257     });
258
259         WriteShort(MSG_ENTITY, sendflags);
260         WriteShort(MSG_ENTITY, longflags);
261         FOREACH(Scores, true, {
262             int p = 1 << (i % 16);
263                 if (sendflags & p)
264                 {
265                         if(longflags & p)
266                                 WriteInt24_t(MSG_ENTITY, this.(scores(it)));
267                         else
268                                 WriteChar(MSG_ENTITY, this.(scores(it)));
269                 }
270     });
271
272         return true;
273 }
274
275 float PlayerScore_Clear(entity player)
276 {
277         entity sk;
278
279         if(teamscores_entities_count)
280                 return 0;
281
282         if(MUTATOR_CALLHOOK(ForbidPlayerScore_Clear)) return 0;
283
284         sk = CS(player).scorekeeper;
285         FOREACH(Scores, true, {
286                 if(sk.(scores(it)) != 0)
287                         //if(scores_label(it) != "")
288                         sk.SendFlags |= (2 ** (i % 16));
289                 if(i != SP_ELO.m_id)
290                         sk.(scores(it)) = 0;
291         });
292
293         return 1;
294 }
295
296 void Score_ClearAll()
297 {
298         entity sk;
299         float t;
300         FOREACH_CLIENTSLOT(true, {
301                 sk = CS(it).scorekeeper;
302                 if (!sk) continue;
303                 FOREACH(Scores, true, {
304                         if(sk.(scores(it)) != 0)
305                                 //if(scores_label(it) != "")
306                                 sk.SendFlags |= (2 ** (i % 16));
307                         if(i != SP_ELO.m_id)
308                                 sk.(scores(it)) = 0;
309                 });
310         });
311         for(t = 0; t < 16; ++t)
312         {
313                 sk = teamscorekeepers[t];
314                 if(!sk)
315                         continue;
316                 for(int j = 0; j < MAX_TEAMSCORE; ++j)
317                 {
318                         if(sk.(teamscores(j)) != 0)
319                                 //if(teamscores_label(j) != "")
320                                 sk.SendFlags |= (2 ** j);
321                         sk.(teamscores(j)) = 0;
322                 }
323         }
324 }
325
326 void PlayerScore_Attach(entity player)
327 {
328         if(CS(player).scorekeeper)
329                 error("player already has a scorekeeper");
330         entity sk = new_pure(scorekeeper);
331         sk.owner = player;
332         Net_LinkEntity(sk, false, 0, PlayerScore_SendEntity);
333         CS(player).scorekeeper = sk;
334 }
335
336 void PlayerScore_Detach(entity player)
337 {
338         if(!CS(player).scorekeeper)
339                 error("player has no scorekeeper");
340         delete(CS(player).scorekeeper);
341         CS(player).scorekeeper = NULL;
342 }
343
344 float PlayerScore_Add(entity player, PlayerScoreField scorefield, float score)
345 {
346         bool mutator_returnvalue = MUTATOR_CALLHOOK(AddPlayerScore, scorefield, score, player);
347         score = M_ARGV(1, float);
348
349         if(!mutator_returnvalue && game_stopped)
350         {
351                 score = 0;
352         }
353
354         if(!scores_initialized) return 0; // FIXME remove this when everything uses this system
355         entity s = CS(player).scorekeeper;
356         if(!s)
357         {
358                 if(game_stopped)
359                         return 0;
360                 LOG_WARN("Adding score to unknown player!");
361                 return 0;
362         }
363         if(!score)
364         {
365                 return s.(scores(scorefield));
366         }
367         //if(scores_label(scorefield) != "")
368         s.SendFlags |= (2 ** (scorefield.m_id % 16));
369         if(!warmup_stage)
370                 PlayerStats_GameReport_Event_Player(s.owner, strcat(PLAYERSTATS_TOTAL, scores_label(scorefield)), score);
371         s.(scores(scorefield)) += score;
372         MUTATOR_CALLHOOK(AddedPlayerScore, scorefield, score, player);
373         return s.(scores(scorefield));
374 }
375
376 float PlayerScore_Set(entity player, PlayerScoreField scorefield, float score)
377 {
378         if(!scores_initialized) return 0; // FIXME remove this when everything uses this system
379         entity s = CS(player).scorekeeper;
380         if(!s)
381         {
382                 if(game_stopped)
383                         return 0;
384                 LOG_WARN("Setting score of unknown player!");
385                 return 0;
386         }
387
388         float oldscore = s.(scores(scorefield));
389         if(oldscore == score)
390                 return oldscore;
391
392         if(scores_label(scorefield) != "")
393                 s.SendFlags |= BIT(scorefield.m_id % 16);
394         s.(scores(scorefield)) = score;
395         return s.(scores(scorefield));
396 }
397
398 float PlayerTeamScore_Add(entity player, PlayerScoreField pscorefield, float tscorefield, float score)
399 {
400         float r;
401         r = PlayerScore_Add(player, pscorefield, score);
402         if(teamscores_entities_count) // only for teamplay
403                 r = TeamScore_Add(player, tscorefield, score);
404         return r;
405 }
406
407 float PlayerScore_Compare(entity t1, entity t2, bool strict)
408 {
409         if(!t1 || !t2) return (!t2) - !t1;
410
411         vector result = '0 0 0';
412         FOREACH(Scores, true, {
413                 var .float f = scores(it);
414                 result = ScoreField_Compare(t1, t2, f, scores_flags(it), result, strict);
415         });
416
417         if (result.x == 0 && strict)
418                 result.x = t1.owner.playerid - t2.owner.playerid;
419
420         return result.x;
421 }
422
423 bool Score_NewLeader()
424 {
425         if(teamplay) {
426                 if (WinningConditionHelper_winnerteam != WinningConditionHelper_winnerteam_last && (WinningConditionHelper_secondteam || WinningConditionHelper_equality))
427                 {
428                         WinningConditionHelper_winnerteam_last = WinningConditionHelper_winnerteam;
429                         return true;
430                 }
431         } else {
432                 if (WinningConditionHelper_winner != WinningConditionHelper_winner_last && (WinningConditionHelper_second || WinningConditionHelper_equality))
433                 {
434                         WinningConditionHelper_winner_last = WinningConditionHelper_winner;
435                         return true;
436                 }
437         }
438         return false;
439 }
440
441 void WinningConditionHelper(entity this)
442 {
443         float c;
444         string s;
445         float fullstatus;
446         entity winnerscorekeeper;
447         entity secondscorekeeper;
448         entity sk;
449
450         // format:
451         // gametype:P<pure>:S<slots>::plabel,plabel:tlabel,tlabel:teamid:tscore,tscore:teamid:tscore,tscore
452         // score labels always start with a symbol or with lower case
453         // so to match pure, match for :P0:
454         // to match full, match for :S0:
455
456         fullstatus = autocvar_g_full_getstatus_responses;
457
458         s = GetGametype();
459         s = strcat(s, ":", autocvar_g_xonoticversion);
460         s = strcat(s, ":P", ftos(cvar_purechanges_count));
461         s = strcat(s, ":S", ftos(nJoinAllowed(this, NULL)));
462         s = strcat(s, ":F", ftos(serverflags));
463         s = strcat(s, ":T", sv_termsofservice_url_escaped);
464         s = strcat(s, ":M", modname);
465         s = strcat(s, "::", GetPlayerScoreString(NULL, (fullstatus ? 1 : 2)));
466
467         if(teamscores_entities_count)
468         {
469                 float t;
470
471                 s = strcat(s, ":", GetTeamScoreString(0, 1));
472                 for(t = 0; t < 16; ++t)
473                         if(teamscorekeepers[t])
474                                 s = strcat(s, ":", ftos(t+1), ":", GetTeamScoreString(t+1, 1));
475
476                 WinningConditionHelper_winnerteam = -1;
477                 WinningConditionHelper_secondteam = -1;
478                 winnerscorekeeper = NULL;
479                 secondscorekeeper = NULL;
480                 for(t = 0; t < 16; ++t)
481                 {
482                         sk = teamscorekeepers[t];
483                         c = TeamScore_Compare(winnerscorekeeper, sk, 1);
484                         if(c < 0)
485                         {
486                                 WinningConditionHelper_secondteam = WinningConditionHelper_winnerteam;
487                                 WinningConditionHelper_winnerteam = t + 1;
488                                 secondscorekeeper = winnerscorekeeper;
489                                 winnerscorekeeper = sk;
490                         }
491                         else
492                         {
493                                 c = TeamScore_Compare(secondscorekeeper, sk, 1);
494                                 if(c < 0)
495                                 {
496                                         WinningConditionHelper_secondteam = t + 1;
497                                         secondscorekeeper = sk;
498                                 }
499                         }
500                 }
501
502                 WinningConditionHelper_equality = (TeamScore_Compare(winnerscorekeeper, secondscorekeeper, 0) == 0);
503                 if(WinningConditionHelper_equality)
504                         WinningConditionHelper_winnerteam = WinningConditionHelper_secondteam = -1;
505
506                 WinningConditionHelper_topscore = winnerscorekeeper.teamscores_primary;
507                 WinningConditionHelper_secondscore = secondscorekeeper.teamscores_primary;
508                 WinningConditionHelper_lowerisbetter = (teamscores_flags_primary & SFL_LOWER_IS_BETTER);
509                 WinningConditionHelper_zeroisworst = (teamscores_flags_primary & SFL_ZERO_IS_WORST);
510
511                 WinningConditionHelper_winner = NULL; // not supported in teamplay
512                 WinningConditionHelper_second = NULL; // not supported in teamplay
513         }
514         else
515         {
516                 WinningConditionHelper_winner = NULL;
517                 WinningConditionHelper_second = NULL;
518                 winnerscorekeeper = NULL;
519                 secondscorekeeper = NULL;
520                 FOREACH_CLIENT(IS_PLAYER(it), {
521                         sk = CS(it).scorekeeper;
522                         c = PlayerScore_Compare(winnerscorekeeper, sk, true);
523                         if(c < 0)
524                         {
525                                 WinningConditionHelper_second = WinningConditionHelper_winner;
526                                 WinningConditionHelper_winner = it;
527                                 secondscorekeeper = winnerscorekeeper;
528                                 winnerscorekeeper = sk;
529                         }
530                         else
531                         {
532                                 c = PlayerScore_Compare(secondscorekeeper, sk, true);
533                                 if(c < 0)
534                                 {
535                                         WinningConditionHelper_second = it;
536                                         secondscorekeeper = sk;
537                                 }
538                         }
539                 });
540
541                 WinningConditionHelper_equality = (PlayerScore_Compare(winnerscorekeeper, secondscorekeeper, false) == 0);
542                 if(WinningConditionHelper_equality)
543                 {
544                         WinningConditionHelper_equality_one = WinningConditionHelper_winner;
545                         WinningConditionHelper_equality_two = WinningConditionHelper_second;
546                         WinningConditionHelper_winner = WinningConditionHelper_second = NULL;
547                 }
548                 else
549                 {
550                         WinningConditionHelper_equality_one = WinningConditionHelper_equality_two = NULL;
551                 }
552
553                 WinningConditionHelper_topscore = winnerscorekeeper.scores_primary;
554                 WinningConditionHelper_secondscore = secondscorekeeper.scores_primary;
555                 WinningConditionHelper_lowerisbetter = (scores_flags_primary & SFL_LOWER_IS_BETTER);
556                 WinningConditionHelper_zeroisworst = (scores_flags_primary & SFL_ZERO_IS_WORST);
557
558                 WinningConditionHelper_winnerteam = -1; // no teamplay
559                 WinningConditionHelper_secondteam = -1; // no teamplay
560         }
561
562         if(WinningConditionHelper_topscore == 0)
563         {
564                 if(scores_flags_primary & SFL_ZERO_IS_WORST)
565                 {
566                         if(WinningConditionHelper_lowerisbetter)
567                                 WinningConditionHelper_topscore = 999999999;
568                         else
569                                 WinningConditionHelper_topscore = -999999999;
570                 }
571                 if(player_count == 0) // special case: empty servers DO end the match at a 0:0 tie
572                         WinningConditionHelper_equality = 0;
573         }
574
575         if(WinningConditionHelper_secondscore == 0)
576         {
577                 if(scores_flags_primary & SFL_ZERO_IS_WORST)
578                 {
579                         if(WinningConditionHelper_lowerisbetter)
580                                 WinningConditionHelper_secondscore = 999999999;
581                         else
582                                 WinningConditionHelper_secondscore = -999999999;
583                 }
584         }
585
586         strcpy(worldstatus, s);
587
588         FOREACH_CLIENT(true, {
589                 string s = "";
590                 if(fullstatus)
591                 {
592                         s = GetPlayerScoreString(it, 1);
593                         s = strcat(s, IS_REAL_CLIENT(it) ? ":human" : ":bot");
594                         if(!(IS_PLAYER(it) || INGAME_JOINED(it)))
595                                 s = strcat(s, ":spectator");
596                 }
597                 else
598                 {
599                         if (IS_PLAYER(it) || INGAME_JOINED(it))
600                                 s = GetPlayerScoreString(it, 2);
601                         else
602                                 s = "-666";
603                 }
604
605                 strcpy(it.clientstatus, s);
606         });
607 }
608
609 string GetScoreLogLabel(string label, float fl)
610 {
611         if(fl & SFL_LOWER_IS_BETTER)
612                 label = strcat(label, "<");
613         if((fl & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
614                 label = strcat(label, "!!");
615         else if((fl & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
616                 label = strcat(label, "!");
617         return label;
618 }
619
620 string GetPlayerScoreString(entity pl, float shortString)
621 {
622         string out;
623         entity sk;
624         float f;
625         string l;
626
627         out = "";
628         if(!pl)
629         {
630                 // label
631                 FOREACH(Scores, true, {
632                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
633                         {
634                                 f = scores_flags(it);
635                                 l = scores_label(it);
636                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
637                         }
638         });
639                 if(shortString < 2)
640                 FOREACH(Scores, true, {
641                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
642                         {
643                                 f = scores_flags(it);
644                                 l = scores_label(it);
645                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
646                         }
647         });
648                 if(shortString < 1)
649                 FOREACH(Scores, true, {
650                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
651                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
652                         {
653                                 f = scores_flags(it);
654                                 l = scores_label(it);
655                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
656                         }
657         });
658                 out = substring(out, 0, strlen(out) - 1);
659         }
660         else if((sk = CS(pl).scorekeeper))
661         {
662                 FOREACH(Scores, true, {
663                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
664                                 out = strcat(out, ftos(sk.(scores(it))), ",");
665         });
666                 if(shortString < 2)
667                 FOREACH(Scores, true, {
668                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
669                                 out = strcat(out, ftos(sk.(scores(it))), ",");
670         });
671                 if(shortString < 1)
672                 FOREACH(Scores, true, {
673                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
674                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
675                                 out = strcat(out, ftos(sk.(scores(it))), ",");
676         });
677                 out = substring(out, 0, strlen(out) - 1);
678         }
679         return out;
680 }
681
682 string GetTeamScoreString(float tm, float shortString)
683 {
684         string out;
685         entity sk;
686         float i, f;
687         string l;
688
689         out = "";
690         if(tm == 0)
691         {
692                 // label
693                 for(i = 0; i < MAX_TEAMSCORE; ++i)
694                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
695                         {
696                                 f = teamscores_flags(i);
697                                 l = teamscores_label(i);
698                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
699                         }
700                 if(shortString < 2)
701                 for(i = 0; i < MAX_TEAMSCORE; ++i)
702                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
703                         {
704                                 f = teamscores_flags(i);
705                                 l = teamscores_label(i);
706                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
707                         }
708                 if(shortString < 1)
709                 for(i = 0; i < MAX_TEAMSCORE; ++i)
710                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
711                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
712                         {
713                                 f = teamscores_flags(i);
714                                 l = teamscores_label(i);
715                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
716                         }
717                 out = substring(out, 0, strlen(out) - 1);
718         }
719         else if((sk = teamscorekeepers[tm - 1]))
720         {
721                 for(i = 0; i < MAX_TEAMSCORE; ++i)
722                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
723                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
724                 if(shortString < 2)
725                 for(i = 0; i < MAX_TEAMSCORE; ++i)
726                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
727                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
728                 if(shortString < 1)
729                 for(i = 0; i < MAX_TEAMSCORE; ++i)
730                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
731                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
732                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
733                 out = substring(out, 0, strlen(out) - 1);
734         }
735         return out;
736 }
737
738 float PlayerTeamScore_Compare(entity p1, entity p2, float teams, bool strict)
739 {
740         if(teams && teamscores_entities_count)
741         {
742                 if(p1.team != p2.team)
743                 {
744                         entity t1, t2;
745                         float r;
746                         t1 = teamscorekeepers[p1.team - 1];
747                         t2 = teamscorekeepers[p2.team - 1];
748                         r = TeamScore_Compare(t1, t2, ((teams >= 0) ? 1 : strict));
749                         return r;
750                 }
751                 if(teams < 0)
752                         return 0;
753         }
754
755         return PlayerScore_Compare(CS(p1).scorekeeper, CS(p2).scorekeeper, strict);
756 }
757
758 entity PlayerScore_Sort(.float field, int teams, bool strict, bool nospectators)
759 {
760         entity p, plist, pprev, pbest, pbestprev, pfirst, plast;
761         float i, j;
762
763         plist = NULL;
764
765         FOREACH_CLIENT(true, { it.(field) = 0; });
766
767         FOREACH_CLIENT(CS(it).scorekeeper,
768         {
769                 if(nospectators)
770                         if(it.frags == FRAGS_SPECTATOR)
771                                 continue;
772
773                 it.chain = plist;
774                 plist = it;
775         });
776         // Now plist points to the whole list.
777
778         pfirst = plast = NULL;
779
780         i = j = 0;
781         while(plist)
782         {
783                 pprev = pbestprev = NULL;
784                 pbest = plist;
785                 for(p = plist; (pprev = p), (p = p.chain); )
786                 {
787                         if(PlayerTeamScore_Compare(p, pbest, teams, strict) > 0)
788                         {
789                                 pbest = p;
790                                 pbestprev = pprev;
791                         }
792                 }
793
794                 // remove pbest out of the chain
795                 if(pbestprev == NULL)
796                         plist = pbest.chain;
797                 else
798                         pbestprev.chain = pbest.chain;
799                 pbest.chain = NULL;
800
801                 ++i;
802                 if(!plast || PlayerTeamScore_Compare(plast, pbest, teams, strict))
803                         j = i;
804
805                 pbest.(field) = j;
806
807                 if (!pfirst)
808                         pfirst = pbest;
809                 if(plast)
810                         plast.chain = pbest;
811                 plast = pbest;
812         }
813
814         return pfirst;
815 }
816
817 float TeamScore_GetCompareValue(float t)
818 {
819         float s;
820         entity sk;
821
822         if(t <= 0 || t >= 16)
823         {
824                 if(game_stopped)
825                         return 0;
826                 error("Reading score of invalid team!");
827         }
828
829         sk = teamscorekeepers[t - 1];
830         if (!sk)
831                 return -999999999;
832         s = sk.teamscores_primary;
833         if(teamscores_flags_primary & SFL_ZERO_IS_WORST)
834                 if(!s)
835                         return -999999999;
836         if(teamscores_flags_primary & SFL_LOWER_IS_BETTER)
837                 s = -s;
838         return s;
839 }
840
841 const float NAMEWIDTH = 22;
842 const float SCORESWIDTH = 58;
843 // TODO put this somewhere in common?
844 string Score_NicePrint_ItemColor(float vflags)
845 {
846         if(vflags & SFL_SORT_PRIO_PRIMARY)
847                 return "^3";
848         else if(vflags & SFL_SORT_PRIO_SECONDARY)
849                 return "^5";
850         else
851                 return "^7";
852 }
853
854 void Score_NicePrint_Team(entity to, float t, float w)
855 {
856         string s, s2;
857         float i;
858         entity sk;
859         float fl, sc;
860         s = "";
861
862         sk = teamscorekeepers[t - 1];
863         if(sk)
864         {
865                 s = strcat(s, Team_ColoredFullName(t));
866                 for(i = 0; i < MAX_TEAMSCORE; ++i)
867                         if(teamscores_label(i) != "")
868                         {
869                                 fl = teamscores_flags(i);
870                                 sc = sk.(teamscores(i));
871                                 s = strcat(s, " ", Score_NicePrint_ItemColor(fl), ScoreString(fl, sc));
872                         }
873         }
874         else
875                 s = "Scores:";
876
877         s = strcat(s, strpad(max(0, NAMEWIDTH - strlennocol(s)), ""));
878
879         FOREACH(Scores, true, {
880                 if(scores_label(it) != "")
881                 {
882                         fl = scores_flags(it);
883                         s2 = scores_label(it);
884                         s = strcat(s, " ", Score_NicePrint_ItemColor(fl), strpad(-w, substring(s2, 0, w)));
885                 }
886     });
887
888         print_to(to, s);
889 }
890
891 void Score_NicePrint_Player(entity to, entity p, float w)
892 {
893         string s;
894         float i;
895         entity sk;
896         float fl, sc;
897         s = "  ";
898
899         sk = CS(p).scorekeeper;
900
901         s = strcat(s, playername(p.netname, p.team, false));
902         for (;;)
903         {
904                 i = strlennocol(s) - NAMEWIDTH;
905                 if(i > 0)
906                         s = substring(s, 0, strlen(s) - i);
907                 else
908                 {
909                         s = strcat(s, strpad(i, ""));
910                         break;
911                 }
912         }
913
914         FOREACH(Scores, true, {
915                 if(scores_label(it) != "")
916                 {
917                         fl = scores_flags(it);
918                         sc = sk.(scores(it));
919                         s = strcat(s, " ", Score_NicePrint_ItemColor(fl), strpad(-w, ScoreString(fl, sc)));
920                 }
921     });
922
923         print_to(to, s);
924 }
925
926 void Score_NicePrint_Spectators(entity to)
927 {
928         print_to(to, "Spectators:");
929 }
930
931 void Score_NicePrint_Spectator(entity to, entity p)
932 {
933         print_to(to, strcat("  ", playername(p.netname, p.team, false)));
934 }
935
936 .float score_dummyfield;
937 void Score_NicePrint(entity to)
938 {
939         entity p;
940         float w;
941
942         int t = 0;
943         FOREACH(Scores, true, {
944                 if(scores_label(it) != "")
945                         ++t;
946     });
947         w = bound(6, floor(SCORESWIDTH / t - 1), 9);
948
949         p = PlayerScore_Sort(score_dummyfield, 1, true, false);
950         t = -1;
951
952         if(!teamscores_entities_count)
953                 Score_NicePrint_Team(to, t, w);
954         while(p)
955         {
956                 if(teamscores_entities_count)
957                         if(t != p.team)
958                                 Score_NicePrint_Team(to, p.team, w);
959                 Score_NicePrint_Player(to, p, w);
960                 t = p.team;
961                 p = p.chain;
962         }
963
964         t = 0;
965         FOREACH_CLIENT(!IS_PLAYER(it), {
966                 if (!t)
967                         Score_NicePrint_Spectators(to);
968                 Score_NicePrint_Spectator(to, it);
969                 t = 1;
970         });
971 }
972
973 void PlayerScore_PlayerStats(entity p)
974 {
975         entity s = CS(p).scorekeeper;
976         FOREACH(Scores, true, {
977                 if(s.(scores(it)) != 0 && scores_label(it) != "")
978                         PlayerStats_GameReport_Event_Player(s.owner,
979                                 strcat(PLAYERSTATS_SCOREBOARD, scores_label(it)), s.(scores(it)));
980         });
981 }
982
983 void PlayerScore_TeamStats()
984 {
985         entity sk;
986         float t, i;
987         for(t = 0; t < 16; ++t)
988         {
989                 sk = teamscorekeepers[t];
990                 if(!sk)
991                         continue;
992                 for(i = 0; i < MAX_TEAMSCORE; ++i)
993                         if(sk.(teamscores(i)) != 0 && teamscores_label(i) != "")
994                                 // the +1 is important here!
995                                 PlayerStats_GameReport_Event_Team(t+1,
996                                         strcat(PLAYERSTATS_SCOREBOARD, teamscores_label(i)), sk.(teamscores(i)));
997         }
998 }