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