]> 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         return true;
212 }
213
214 void ScoreInfo_Init(int teams)
215 {
216         if(scores_initialized)
217         {
218                 scores_initialized.SendFlags |= 1; // force a resend
219         }
220         else
221         {
222                 scores_initialized = new_pure(ent_client_scoreinfo);
223                 Net_LinkEntity(scores_initialized, false, 0, ScoreInfo_SendEntity);
224         }
225         if(teams & BIT(0))
226                 TeamScore_Spawn(NUM_TEAM_1, "Red");
227         if(teams & BIT(1))
228                 TeamScore_Spawn(NUM_TEAM_2, "Blue");
229         if(teams & BIT(2))
230                 TeamScore_Spawn(NUM_TEAM_3, "Yellow");
231         if(teams & BIT(3))
232                 TeamScore_Spawn(NUM_TEAM_4, "Pink");
233 }
234
235 /*
236  * per-player score entities
237  */
238
239 bool PlayerScore_SendEntity(entity this, entity to, float sendflags)
240 {
241         WriteHeader(MSG_ENTITY, ENT_CLIENT_SCORES);
242         WriteByte(MSG_ENTITY, etof(this.owner));
243
244         int longflags = 0;
245         FOREACH(Scores, true, {
246             int p = 1 << (i % 16);
247                 if (this.(scores(it)) > 127 || this.(scores(it)) <= -128)
248                         longflags |= p;
249     });
250
251         WriteShort(MSG_ENTITY, sendflags);
252         WriteShort(MSG_ENTITY, longflags);
253         FOREACH(Scores, true, {
254             int p = 1 << (i % 16);
255                 if (sendflags & p)
256                 {
257                         if(longflags & p)
258                                 WriteInt24_t(MSG_ENTITY, this.(scores(it)));
259                         else
260                                 WriteChar(MSG_ENTITY, this.(scores(it)));
261                 }
262     });
263
264         return true;
265 }
266
267 float PlayerScore_Clear(entity player)
268 {
269         entity sk;
270
271         if(teamscores_entities_count)
272                 return 0;
273
274         if(MUTATOR_CALLHOOK(ForbidPlayerScore_Clear)) return 0;
275
276         sk = CS(player).scorekeeper;
277         FOREACH(Scores, true, {
278                 if(sk.(scores(it)) != 0)
279                         //if(scores_label(it) != "")
280                         sk.SendFlags |= (2 ** (i % 16));
281                 if(i != SP_ELO.m_id)
282                         sk.(scores(it)) = 0;
283         });
284
285         return 1;
286 }
287
288 void Score_ClearAll()
289 {
290         entity sk;
291         float t;
292         FOREACH_CLIENTSLOT(true, {
293                 sk = CS(it).scorekeeper;
294                 if (!sk) continue;
295                 FOREACH(Scores, true, {
296                         if(sk.(scores(it)) != 0)
297                                 //if(scores_label(it) != "")
298                                 sk.SendFlags |= (2 ** (i % 16));
299                         if(i != SP_ELO.m_id)
300                                 sk.(scores(it)) = 0;
301                 });
302         });
303         for(t = 0; t < 16; ++t)
304         {
305                 sk = teamscorekeepers[t];
306                 if(!sk)
307                         continue;
308                 for(int j = 0; j < MAX_TEAMSCORE; ++j)
309                 {
310                         if(sk.(teamscores(j)) != 0)
311                                 //if(teamscores_label(j) != "")
312                                 sk.SendFlags |= (2 ** j);
313                         sk.(teamscores(j)) = 0;
314                 }
315         }
316 }
317
318 void PlayerScore_Attach(entity player)
319 {
320         if(CS(player).scorekeeper)
321                 error("player already has a scorekeeper");
322         entity sk = new_pure(scorekeeper);
323         sk.owner = player;
324         Net_LinkEntity(sk, false, 0, PlayerScore_SendEntity);
325         CS(player).scorekeeper = sk;
326 }
327
328 void PlayerScore_Detach(entity player)
329 {
330         if(!CS(player).scorekeeper)
331                 error("player has no scorekeeper");
332         delete(CS(player).scorekeeper);
333         CS(player).scorekeeper = NULL;
334 }
335
336 float PlayerScore_Add(entity player, PlayerScoreField scorefield, float score)
337 {
338         bool mutator_returnvalue = MUTATOR_CALLHOOK(AddPlayerScore, scorefield, score, player);
339         score = M_ARGV(1, float);
340
341         if(!mutator_returnvalue && game_stopped)
342         {
343                 score = 0;
344         }
345
346         if(!scores_initialized) return 0; // FIXME remove this when everything uses this system
347         entity s = CS(player).scorekeeper;
348         if(!s)
349         {
350                 if(game_stopped)
351                         return 0;
352                 LOG_WARN("Adding score to unknown player!");
353                 return 0;
354         }
355         if(!score)
356         {
357                 return s.(scores(scorefield));
358         }
359         //if(scores_label(scorefield) != "")
360         s.SendFlags |= (2 ** (scorefield.m_id % 16));
361         if(!warmup_stage)
362                 PlayerStats_GameReport_Event_Player(s.owner, strcat(PLAYERSTATS_TOTAL, scores_label(scorefield)), score);
363         s.(scores(scorefield)) += score;
364         MUTATOR_CALLHOOK(AddedPlayerScore, scorefield, score, player);
365         return s.(scores(scorefield));
366 }
367
368 float PlayerScore_Set(entity player, PlayerScoreField scorefield, float score)
369 {
370         if(!scores_initialized) return 0; // FIXME remove this when everything uses this system
371         entity s = CS(player).scorekeeper;
372         if(!s)
373         {
374                 if(game_stopped)
375                         return 0;
376                 LOG_WARN("Setting score of unknown player!");
377                 return 0;
378         }
379
380         float oldscore = s.(scores(scorefield));
381         if(oldscore == score)
382                 return oldscore;
383
384         if(scores_label(scorefield) != "")
385                 s.SendFlags |= BIT(scorefield.m_id % 16);
386         s.(scores(scorefield)) = score;
387         return s.(scores(scorefield));
388 }
389
390 float PlayerTeamScore_Add(entity player, PlayerScoreField pscorefield, float tscorefield, float score)
391 {
392         float r;
393         r = PlayerScore_Add(player, pscorefield, score);
394         if(teamscores_entities_count) // only for teamplay
395                 r = TeamScore_Add(player, tscorefield, score);
396         return r;
397 }
398
399 float PlayerScore_Compare(entity t1, entity t2, bool strict)
400 {
401         if(!t1 || !t2) return (!t2) - !t1;
402
403         vector result = '0 0 0';
404         FOREACH(Scores, true, {
405                 var .float f = scores(it);
406                 result = ScoreField_Compare(t1, t2, f, scores_flags(it), result, strict);
407         });
408
409         if (result.x == 0 && strict)
410                 result.x = t1.owner.playerid - t2.owner.playerid;
411
412         return result.x;
413 }
414
415 bool Score_NewLeader()
416 {
417         if(teamplay) {
418                 if (WinningConditionHelper_winnerteam != WinningConditionHelper_winnerteam_last && (WinningConditionHelper_secondteam || WinningConditionHelper_equality))
419                 {
420                         WinningConditionHelper_winnerteam_last = WinningConditionHelper_winnerteam;
421                         return true;
422                 }
423         } else {
424                 if (WinningConditionHelper_winner != WinningConditionHelper_winner_last && (WinningConditionHelper_second || WinningConditionHelper_equality))
425                 {
426                         WinningConditionHelper_winner_last = WinningConditionHelper_winner;
427                         return true;
428                 }
429         }
430         return false;
431 }
432
433 void WinningConditionHelper(entity this)
434 {
435         float c;
436         string s;
437         float fullstatus;
438         entity winnerscorekeeper;
439         entity secondscorekeeper;
440         entity sk;
441
442         // format:
443         // gametype:P<pure>:S<slots>::plabel,plabel:tlabel,tlabel:teamid:tscore,tscore:teamid:tscore,tscore
444         // score labels always start with a symbol or with lower case
445         // so to match pure, match for :P0:
446         // to match full, match for :S0:
447
448         fullstatus = autocvar_g_full_getstatus_responses;
449
450         s = GetGametype();
451         s = strcat(s, ":", autocvar_g_xonoticversion);
452         s = strcat(s, ":P", ftos(cvar_purechanges_count));
453         s = strcat(s, ":S", ftos(nJoinAllowed(this, NULL)));
454         s = strcat(s, ":F", ftos(serverflags));
455         s = strcat(s, ":T", sv_termsofservice_url_escaped);
456         s = strcat(s, ":M", modname);
457         s = strcat(s, "::", GetPlayerScoreString(NULL, (fullstatus ? 1 : 2)));
458
459         if(teamscores_entities_count)
460         {
461                 float t;
462
463                 s = strcat(s, ":", GetTeamScoreString(0, 1));
464                 for(t = 0; t < 16; ++t)
465                         if(teamscorekeepers[t])
466                                 s = strcat(s, ":", ftos(t+1), ":", GetTeamScoreString(t+1, 1));
467
468                 WinningConditionHelper_winnerteam = -1;
469                 WinningConditionHelper_secondteam = -1;
470                 winnerscorekeeper = NULL;
471                 secondscorekeeper = NULL;
472                 for(t = 0; t < 16; ++t)
473                 {
474                         sk = teamscorekeepers[t];
475                         c = TeamScore_Compare(winnerscorekeeper, sk, 1);
476                         if(c < 0)
477                         {
478                                 WinningConditionHelper_secondteam = WinningConditionHelper_winnerteam;
479                                 WinningConditionHelper_winnerteam = t + 1;
480                                 secondscorekeeper = winnerscorekeeper;
481                                 winnerscorekeeper = sk;
482                         }
483                         else
484                         {
485                                 c = TeamScore_Compare(secondscorekeeper, sk, 1);
486                                 if(c < 0)
487                                 {
488                                         WinningConditionHelper_secondteam = t + 1;
489                                         secondscorekeeper = sk;
490                                 }
491                         }
492                 }
493
494                 WinningConditionHelper_equality = (TeamScore_Compare(winnerscorekeeper, secondscorekeeper, 0) == 0);
495                 if(WinningConditionHelper_equality)
496                         WinningConditionHelper_winnerteam = WinningConditionHelper_secondteam = -1;
497
498                 WinningConditionHelper_topscore = winnerscorekeeper.teamscores_primary;
499                 WinningConditionHelper_secondscore = secondscorekeeper.teamscores_primary;
500                 WinningConditionHelper_lowerisbetter = (teamscores_flags_primary & SFL_LOWER_IS_BETTER);
501                 WinningConditionHelper_zeroisworst = (teamscores_flags_primary & SFL_ZERO_IS_WORST);
502
503                 WinningConditionHelper_winner = NULL; // not supported in teamplay
504                 WinningConditionHelper_second = NULL; // not supported in teamplay
505         }
506         else
507         {
508                 WinningConditionHelper_winner = NULL;
509                 WinningConditionHelper_second = NULL;
510                 winnerscorekeeper = NULL;
511                 secondscorekeeper = NULL;
512                 FOREACH_CLIENT(IS_PLAYER(it), {
513                         sk = CS(it).scorekeeper;
514                         c = PlayerScore_Compare(winnerscorekeeper, sk, true);
515                         if(c < 0)
516                         {
517                                 WinningConditionHelper_second = WinningConditionHelper_winner;
518                                 WinningConditionHelper_winner = it;
519                                 secondscorekeeper = winnerscorekeeper;
520                                 winnerscorekeeper = sk;
521                         }
522                         else
523                         {
524                                 c = PlayerScore_Compare(secondscorekeeper, sk, true);
525                                 if(c < 0)
526                                 {
527                                         WinningConditionHelper_second = it;
528                                         secondscorekeeper = sk;
529                                 }
530                         }
531                 });
532
533                 WinningConditionHelper_equality = (PlayerScore_Compare(winnerscorekeeper, secondscorekeeper, false) == 0);
534                 if(WinningConditionHelper_equality)
535                 {
536                         WinningConditionHelper_equality_one = WinningConditionHelper_winner;
537                         WinningConditionHelper_equality_two = WinningConditionHelper_second;
538                         WinningConditionHelper_winner = WinningConditionHelper_second = NULL;
539                 }
540                 else
541                 {
542                         WinningConditionHelper_equality_one = WinningConditionHelper_equality_two = NULL;
543                 }
544
545                 WinningConditionHelper_topscore = winnerscorekeeper.scores_primary;
546                 WinningConditionHelper_secondscore = secondscorekeeper.scores_primary;
547                 WinningConditionHelper_lowerisbetter = (scores_flags_primary & SFL_LOWER_IS_BETTER);
548                 WinningConditionHelper_zeroisworst = (scores_flags_primary & SFL_ZERO_IS_WORST);
549
550                 WinningConditionHelper_winnerteam = -1; // no teamplay
551                 WinningConditionHelper_secondteam = -1; // no teamplay
552         }
553
554         if(WinningConditionHelper_topscore == 0)
555         {
556                 if(scores_flags_primary & SFL_ZERO_IS_WORST)
557                 {
558                         if(WinningConditionHelper_lowerisbetter)
559                                 WinningConditionHelper_topscore = 999999999;
560                         else
561                                 WinningConditionHelper_topscore = -999999999;
562                 }
563                 if(player_count == 0) // special case: empty servers DO end the match at a 0:0 tie
564                         WinningConditionHelper_equality = 0;
565         }
566
567         if(WinningConditionHelper_secondscore == 0)
568         {
569                 if(scores_flags_primary & SFL_ZERO_IS_WORST)
570                 {
571                         if(WinningConditionHelper_lowerisbetter)
572                                 WinningConditionHelper_secondscore = 999999999;
573                         else
574                                 WinningConditionHelper_secondscore = -999999999;
575                 }
576         }
577
578         strcpy(worldstatus, s);
579
580         FOREACH_CLIENT(true, {
581                 string s = "";
582                 if(fullstatus)
583                 {
584                         s = GetPlayerScoreString(it, 1);
585                         s = strcat(s, IS_REAL_CLIENT(it) ? ":human" : ":bot");
586                         if(!(IS_PLAYER(it) || INGAME_JOINED(it)))
587                                 s = strcat(s, ":spectator");
588                 }
589                 else
590                 {
591                         if (IS_PLAYER(it) || INGAME_JOINED(it))
592                                 s = GetPlayerScoreString(it, 2);
593                         else
594                                 s = "-666";
595                 }
596
597                 strcpy(it.clientstatus, s);
598         });
599 }
600
601 string GetScoreLogLabel(string label, float fl)
602 {
603         if(fl & SFL_LOWER_IS_BETTER)
604                 label = strcat(label, "<");
605         if((fl & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
606                 label = strcat(label, "!!");
607         else if((fl & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
608                 label = strcat(label, "!");
609         return label;
610 }
611
612 string GetPlayerScoreString(entity pl, float shortString)
613 {
614         string out;
615         entity sk;
616         float f;
617         string l;
618
619         out = "";
620         if(!pl)
621         {
622                 // label
623                 FOREACH(Scores, true, {
624                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
625                         {
626                                 f = scores_flags(it);
627                                 l = scores_label(it);
628                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
629                         }
630         });
631                 if(shortString < 2)
632                 FOREACH(Scores, true, {
633                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
634                         {
635                                 f = scores_flags(it);
636                                 l = scores_label(it);
637                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
638                         }
639         });
640                 if(shortString < 1)
641                 FOREACH(Scores, true, {
642                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
643                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
644                         {
645                                 f = scores_flags(it);
646                                 l = scores_label(it);
647                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
648                         }
649         });
650                 out = substring(out, 0, strlen(out) - 1);
651         }
652         else if((sk = CS(pl).scorekeeper))
653         {
654                 FOREACH(Scores, true, {
655                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
656                                 out = strcat(out, ftos(sk.(scores(it))), ",");
657         });
658                 if(shortString < 2)
659                 FOREACH(Scores, true, {
660                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
661                                 out = strcat(out, ftos(sk.(scores(it))), ",");
662         });
663                 if(shortString < 1)
664                 FOREACH(Scores, true, {
665                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
666                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
667                                 out = strcat(out, ftos(sk.(scores(it))), ",");
668         });
669                 out = substring(out, 0, strlen(out) - 1);
670         }
671         return out;
672 }
673
674 string GetTeamScoreString(float tm, float shortString)
675 {
676         string out;
677         entity sk;
678         float i, f;
679         string l;
680
681         out = "";
682         if(tm == 0)
683         {
684                 // label
685                 for(i = 0; i < MAX_TEAMSCORE; ++i)
686                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
687                         {
688                                 f = teamscores_flags(i);
689                                 l = teamscores_label(i);
690                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
691                         }
692                 if(shortString < 2)
693                 for(i = 0; i < MAX_TEAMSCORE; ++i)
694                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
695                         {
696                                 f = teamscores_flags(i);
697                                 l = teamscores_label(i);
698                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
699                         }
700                 if(shortString < 1)
701                 for(i = 0; i < MAX_TEAMSCORE; ++i)
702                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
703                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
704                         {
705                                 f = teamscores_flags(i);
706                                 l = teamscores_label(i);
707                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
708                         }
709                 out = substring(out, 0, strlen(out) - 1);
710         }
711         else if((sk = teamscorekeepers[tm - 1]))
712         {
713                 for(i = 0; i < MAX_TEAMSCORE; ++i)
714                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
715                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
716                 if(shortString < 2)
717                 for(i = 0; i < MAX_TEAMSCORE; ++i)
718                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
719                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
720                 if(shortString < 1)
721                 for(i = 0; i < MAX_TEAMSCORE; ++i)
722                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
723                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
724                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
725                 out = substring(out, 0, strlen(out) - 1);
726         }
727         return out;
728 }
729
730 float PlayerTeamScore_Compare(entity p1, entity p2, float teams, bool strict)
731 {
732         if(teams && teamscores_entities_count)
733         {
734                 if(p1.team != p2.team)
735                 {
736                         entity t1, t2;
737                         float r;
738                         t1 = teamscorekeepers[p1.team - 1];
739                         t2 = teamscorekeepers[p2.team - 1];
740                         r = TeamScore_Compare(t1, t2, ((teams >= 0) ? 1 : strict));
741                         return r;
742                 }
743                 if(teams < 0)
744                         return 0;
745         }
746
747         return PlayerScore_Compare(CS(p1).scorekeeper, CS(p2).scorekeeper, strict);
748 }
749
750 entity PlayerScore_Sort(.float field, int teams, bool strict, bool nospectators)
751 {
752         entity p, plist, pprev, pbest, pbestprev, pfirst, plast;
753         float i, j;
754
755         plist = NULL;
756
757         FOREACH_CLIENT(true, { it.(field) = 0; });
758
759         FOREACH_CLIENT(CS(it).scorekeeper,
760         {
761                 if(nospectators)
762                         if(it.frags == FRAGS_SPECTATOR)
763                                 continue;
764
765                 it.chain = plist;
766                 plist = it;
767         });
768         // Now plist points to the whole list.
769
770         pfirst = plast = NULL;
771
772         i = j = 0;
773         while(plist)
774         {
775                 pprev = pbestprev = NULL;
776                 pbest = plist;
777                 for(p = plist; (pprev = p), (p = p.chain); )
778                 {
779                         if(PlayerTeamScore_Compare(p, pbest, teams, strict) > 0)
780                         {
781                                 pbest = p;
782                                 pbestprev = pprev;
783                         }
784                 }
785
786                 // remove pbest out of the chain
787                 if(pbestprev == NULL)
788                         plist = pbest.chain;
789                 else
790                         pbestprev.chain = pbest.chain;
791                 pbest.chain = NULL;
792
793                 ++i;
794                 if(!plast || PlayerTeamScore_Compare(plast, pbest, teams, strict))
795                         j = i;
796
797                 pbest.(field) = j;
798
799                 if (!pfirst)
800                         pfirst = pbest;
801                 if(plast)
802                         plast.chain = pbest;
803                 plast = pbest;
804         }
805
806         return pfirst;
807 }
808
809 float TeamScore_GetCompareValue(float t)
810 {
811         float s;
812         entity sk;
813
814         if(t <= 0 || t >= 16)
815         {
816                 if(game_stopped)
817                         return 0;
818                 error("Reading score of invalid team!");
819         }
820
821         sk = teamscorekeepers[t - 1];
822         if (!sk)
823                 return -999999999;
824         s = sk.teamscores_primary;
825         if(teamscores_flags_primary & SFL_ZERO_IS_WORST)
826                 if(!s)
827                         return -999999999;
828         if(teamscores_flags_primary & SFL_LOWER_IS_BETTER)
829                 s = -s;
830         return s;
831 }
832
833 const float NAMEWIDTH = 22;
834 const float SCORESWIDTH = 58;
835 // TODO put this somewhere in common?
836 string Score_NicePrint_ItemColor(float vflags)
837 {
838         if(vflags & SFL_SORT_PRIO_PRIMARY)
839                 return "^3";
840         else if(vflags & SFL_SORT_PRIO_SECONDARY)
841                 return "^5";
842         else
843                 return "^7";
844 }
845
846 void Score_NicePrint_Team(entity to, float t, float w)
847 {
848         string s, s2;
849         float i;
850         entity sk;
851         float fl, sc;
852         s = "";
853
854         sk = teamscorekeepers[t - 1];
855         if(sk)
856         {
857                 s = strcat(s, Team_ColoredFullName(t));
858                 for(i = 0; i < MAX_TEAMSCORE; ++i)
859                         if(teamscores_label(i) != "")
860                         {
861                                 fl = teamscores_flags(i);
862                                 sc = sk.(teamscores(i));
863                                 s = strcat(s, " ", Score_NicePrint_ItemColor(fl), ScoreString(fl, sc));
864                         }
865         }
866         else
867                 s = "Scores:";
868
869         s = strcat(s, strpad(max(0, NAMEWIDTH - strlennocol(s)), ""));
870
871         FOREACH(Scores, true, {
872                 if(scores_label(it) != "")
873                 {
874                         fl = scores_flags(it);
875                         s2 = scores_label(it);
876                         s = strcat(s, " ", Score_NicePrint_ItemColor(fl), strpad(-w, substring(s2, 0, w)));
877                 }
878     });
879
880         print_to(to, s);
881 }
882
883 void Score_NicePrint_Player(entity to, entity p, float w)
884 {
885         string s;
886         float i;
887         entity sk;
888         float fl, sc;
889         s = "  ";
890
891         sk = CS(p).scorekeeper;
892
893         s = strcat(s, playername(p.netname, p.team, false));
894         for (;;)
895         {
896                 i = strlennocol(s) - NAMEWIDTH;
897                 if(i > 0)
898                         s = substring(s, 0, strlen(s) - i);
899                 else
900                 {
901                         s = strcat(s, strpad(i, ""));
902                         break;
903                 }
904         }
905
906         FOREACH(Scores, true, {
907                 if(scores_label(it) != "")
908                 {
909                         fl = scores_flags(it);
910                         sc = sk.(scores(it));
911                         s = strcat(s, " ", Score_NicePrint_ItemColor(fl), strpad(-w, ScoreString(fl, sc)));
912                 }
913     });
914
915         print_to(to, s);
916 }
917
918 void Score_NicePrint_Spectators(entity to)
919 {
920         print_to(to, "Spectators:");
921 }
922
923 void Score_NicePrint_Spectator(entity to, entity p)
924 {
925         print_to(to, strcat("  ", playername(p.netname, p.team, false)));
926 }
927
928 .float score_dummyfield;
929 void Score_NicePrint(entity to)
930 {
931         entity p;
932         float w;
933
934         int t = 0;
935         FOREACH(Scores, true, {
936                 if(scores_label(it) != "")
937                         ++t;
938     });
939         w = bound(6, floor(SCORESWIDTH / t - 1), 9);
940
941         p = PlayerScore_Sort(score_dummyfield, 1, true, false);
942         t = -1;
943
944         if(!teamscores_entities_count)
945                 Score_NicePrint_Team(to, t, w);
946         while(p)
947         {
948                 if(teamscores_entities_count)
949                         if(t != p.team)
950                                 Score_NicePrint_Team(to, p.team, w);
951                 Score_NicePrint_Player(to, p, w);
952                 t = p.team;
953                 p = p.chain;
954         }
955
956         t = 0;
957         FOREACH_CLIENT(!IS_PLAYER(it), {
958                 if (!t)
959                         Score_NicePrint_Spectators(to);
960                 Score_NicePrint_Spectator(to, it);
961                 t = 1;
962         });
963 }
964
965 void PlayerScore_PlayerStats(entity p)
966 {
967         entity s = CS(p).scorekeeper;
968         FOREACH(Scores, true, {
969                 if(s.(scores(it)) != 0 && scores_label(it) != "")
970                         PlayerStats_GameReport_Event_Player(s.owner,
971                                 strcat(PLAYERSTATS_SCOREBOARD, scores_label(it)), s.(scores(it)));
972         });
973 }
974
975 void PlayerScore_TeamStats()
976 {
977         entity sk;
978         float t, i;
979         for(t = 0; t < 16; ++t)
980         {
981                 sk = teamscorekeepers[t];
982                 if(!sk)
983                         continue;
984                 for(i = 0; i < MAX_TEAMSCORE; ++i)
985                         if(sk.(teamscores(i)) != 0 && teamscores_label(i) != "")
986                                 // the +1 is important here!
987                                 PlayerStats_GameReport_Event_Team(t+1,
988                                         strcat(PLAYERSTATS_SCOREBOARD, teamscores_label(i)), sk.(teamscores(i)));
989         }
990 }