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