Fetch all the "max score for song" entries in one go instead of one at a time.
[ccbs] / bigscreen / groupscreen.cpp
1 #include <cstdio>
2 #include <algorithm>
3 #include <map>
4
5 #include "groupscreen.h"
6 #include "fetch_group.h"
7 #include "fetch_max_score_for_songs.h"
8 #include "fetch_max_score_for_player.h"
9 #include "fetch_needs_update.h"
10 #include "fetch_highscore.h"
11 #include "fonts.h"
12
13 GroupScreen::GroupScreen(pqxx::connection &conn, unsigned tournament, unsigned round, unsigned parallel)
14         : tournament(tournament), round(round), parallel(parallel), scores_changed(conn, "scores"), conn(conn), valid(false)
15 {
16 }
17
18 GroupScreen::~GroupScreen()
19 {
20 }
21
22 bool GroupScreen::check_invalidated()
23 {
24         if (!valid)
25                 return true;
26         if (!scores_changed.get_flag())
27                 return false;
28
29         bool needs_update;
30         conn.perform(FetchNeedsUpdate(last_updated, tournament, round, parallel, &needs_update));
31
32         if (!needs_update)
33                 scores_changed.reset_flag();
34         
35         return needs_update;
36 }
37
38 void GroupScreen::draw(unsigned char *buf)
39 {
40         std::vector<TextDefer> td;
41         
42         scores_changed.reset_flag();
43
44         /*
45          * We'll probably need some values from here later on (although not all), just fetch them
46          * all while we're at it.
47          */
48         std::map<unsigned, unsigned> song_scores;
49         conn.perform(FetchMaxScoreForSongs(tournament, &song_scores));
50         
51         Group group;
52         conn.perform(FetchGroup(tournament, round, parallel, &group));
53         gettimeofday(&last_updated, NULL);
54
55         memset(buf, 0, 800 * 600 * 4);
56
57         // main heading
58         char heading[64];
59         if (parallel == 0) {
60                 std::sprintf(heading, "Round %u", round);
61         } else {
62                 std::sprintf(heading, "Round %u, Group %u", round, parallel);
63         }
64
65         {
66                 unsigned width = my_draw_text(heading, NULL, 48.0);
67                 my_draw_text_deferred(td, heading, 48.0, 800/2 - width/2, 60);
68         }
69         
70         // Find out how wide each column has to be. First try unlimited width (ie.
71         // long titles for everything); if that gets too long, try again with short
72         // titles for chosen songs.
73         unsigned width[16], num_scores;
74         unsigned max_num_width = my_draw_text("8888", NULL, 22.0);
75         unsigned sumwidth;
76         for (unsigned mode = 0; mode < 2; ++mode) {
77                 for (unsigned i = 0; i < 16; ++i)
78                         width[i] = 0;
79
80                 for (std::vector<Player>::const_iterator i = group.players.begin(); i != group.players.end(); ++i) {
81                         unsigned col = 1;
82                         width[0] = std::max(width[0], my_draw_text(i->nick, NULL, 18.0));
83
84                         for (std::vector<Score>::const_iterator j = i->scores.begin(); j != i->scores.end(); ++j, ++col) {
85                                 if (j->chosen) {
86                                         width[col] = std::max(width[col], my_draw_text((mode == 0) ? j->song.title : j->song.short_title, NULL, 12.0) + 
87                                                         max_num_width + 10);
88                                 } else {                
89                                         width[col] = std::max(width[col], my_draw_text(j->song.short_title, NULL, 12.0));
90                                         width[col] = std::max(width[col], max_num_width);
91                                 }
92                         }
93                 }
94
95                 num_scores = group.players[0].scores.size();
96
97                 width[num_scores + 1] = std::max(my_draw_text("Total", NULL, 12.0), max_num_width);
98                 width[num_scores + 2] = my_draw_text("Rank", NULL, 12.0);
99
100                 // if we're at long titles and that works, don't try the short ones
101                 sumwidth = 0;
102                         
103                 for (unsigned i = 0; i <= num_scores + 2; ++i)
104                         sumwidth += width[i] + 20;
105                         
106                 if (sumwidth < 780)
107                         break;
108         }
109
110         /* 
111          * If we have space to go, distribute as much as we can to the chosen song column, so we won't have
112          * total and rank jumping around.
113          */
114         if (sumwidth < 780) {
115                 int first_chosen_col = -1;
116                 unsigned col = 1;
117
118                 for (std::vector<Score>::const_iterator i = group.players[0].scores.begin(); i != group.players[0].scores.end(); ++i, ++col) {
119                         if (i->chosen) {
120                                 first_chosen_col = col;
121                                 break;
122                         }
123                 }
124
125                 if (first_chosen_col != -1) {
126                         width[first_chosen_col] += 780 - sumwidth;
127                 }
128         }
129
130         // make column headings from the first player's songs
131         unsigned col = 1;
132         unsigned x = 40 + width[0];
133         for (std::vector<Score>::const_iterator i = group.players[0].scores.begin(); i != group.players[0].scores.end(); ++i, ++col) {
134                 if (!i->chosen) {
135                         unsigned this_width = my_draw_text(i->song.short_title, NULL, 12.0);
136                         my_draw_text_deferred(td, i->song.short_title, 12.0, x + width[col] / 2 - this_width / 2, 100);
137                 }
138                 x += width[col] + 20;
139         }
140
141         my_draw_text_deferred(td, "Total", 12.0, x + width[num_scores + 1] / 2 - my_draw_text("Total", NULL, 12.0) / 2, 100);
142         x += width[num_scores + 1] + 20;
143         my_draw_text_deferred(td, "Rank", 12.0, x + width[num_scores + 2] / 2 - my_draw_text("Rank", NULL, 12.0) / 2, 100);
144         
145         // show all the players and the scores
146         unsigned show_players = std::min(group.players.size(), 9U);
147         unsigned y = (show_players <= 7) ? 140 : (140 - (show_players - 7) * 5);
148         
149         unsigned row = 0;
150         for (std::vector<Player>::const_iterator i = group.players.begin(); i != group.players.end() && row < 9; ++i, ++row) {
151                 my_draw_text_deferred(td, i->nick, 18.0, 20, y);
152
153                 unsigned x = 40 + width[0];
154
155                 unsigned col = 1;
156                 for (std::vector<Score>::const_iterator j = i->scores.begin(); j != i->scores.end(); ++j, ++col) {
157                         char text[16] = "";
158                         if (j->score != -1) {
159                                 std::sprintf(text, "%u", j->score);
160                         }
161         
162                         unsigned this_width = my_draw_text(text, NULL, 22.0);
163                         if (j->chosen) {
164                                 my_draw_text_deferred(td, text, 22.0, x + max_num_width - this_width, y);
165
166                                 // draw the long name if we can, otherwise use the short one
167                                 if (my_draw_text(j->song.title, NULL, 12.0) > width[col]) {
168                                         my_draw_text_deferred(td, j->song.short_title, 12.0, x + max_num_width + 10, y);
169                                 } else {
170                                         my_draw_text_deferred(td, j->song.title, 12.0, x + max_num_width + 10, y);
171                                 }
172                         } else {
173                                 my_draw_text_deferred(td, text, 22.0, x + width[col] / 2 - this_width / 2, y);
174                         }
175                         x += width[col] + 20;
176                 }
177
178                 // draw total
179                 {
180                         char text[16];
181                         std::sprintf(text, "%u", i->total);
182                         
183                         unsigned this_width = my_draw_text(text, NULL, 22.0);
184                         my_draw_text_deferred(td, text, 22.0, x + width[num_scores + 1] / 2 - this_width / 2, y);
185                         x += width[num_scores + 1] + 20;
186                 }
187
188                 if (show_players > 7)
189                         y += 40 - (show_players - 7) * 4;
190                 else 
191                         y += 40;
192         }
193         
194         /*
195          * Approximate (but probably working quite well in practice) heuristic
196          * for finding the min and max rank of a player works as follows:
197          *
198          * First of all, find out, for each player in the group, what the
199          * maximum remaining score possibly can be (the minimum score is of
200          * course identical to the player's current total). For a random song,
201          * this is of course 1000 * (maximum feet rating) (but of course, that
202          * depends on whether we can play single or double! for now, assume
203          * double is okay, but this logic will be deferred to FetchMaxScore
204          * anyhow); for a random song, we simply pick the highest-ranking song
205          * we can find, EXCEPT those the player has chosen earlier AND the
206          * random songs this round, AND all random songs from elimination rounds
207          * (ie. rounds with only one group). (Phew!) This doesn't solve problems
208          * we'd face with more than one chosen song, but it should be good enough.
209          *
210          * After we've found the max and min scores for all players, it's a simple
211          * matter of sorting; the best attainable rank for player X is obtained if 
212          * X gets max score and all others get min score, the worst attainable rank
213          * is obtained if X gets min score and all others get max score.
214          *
215          * This is a bit SQL-heavy, but heck...
216          */
217         std::vector<unsigned> max_score, min_score;
218         for (std::vector<Player>::const_iterator i = group.players.begin(); i != group.players.end(); ++i) {
219                 unsigned min_score_tp = 0, max_score_tp = 0;
220                 for (std::vector<Score>::const_iterator j = i->scores.begin(); j != i->scores.end(); ++j, ++col) {
221                         if (j->score != -1) {
222                                 // already given
223                                 min_score_tp += j->score;
224                                 max_score_tp += j->score;
225                         } else {
226                                 unsigned max_score_this_song;
227                                 if (j->song.id != -1) {
228                                         // random song, or we know what song the player picked
229                                         max_score_this_song = song_scores[j->song.id];
230                                 } else {
231                                         conn.perform(FetchMaxScoreForPlayer(tournament, i->id, round, &max_score_this_song));
232                                 }
233                                 max_score_tp += max_score_this_song;
234                         }
235                 }
236                 max_score.push_back(max_score_tp);
237                 min_score.push_back(min_score_tp);
238         }
239
240         // now finally find min and max rank, and draw it all
241         y = (show_players <= 7) ? 140 : (140 - (show_players - 7) * 5);
242         for (unsigned i = 0; i < show_players; ++i) {
243                 unsigned best_rank = 1, worst_rank = 1;
244                 for (unsigned j = 0; j < group.players.size(); ++j) {
245                         if (i == j)
246                                 continue;
247
248                         if (max_score[i] < min_score[j])
249                                 ++best_rank;
250                         if (min_score[i] <= max_score[j])
251                                 ++worst_rank;
252                 }
253
254                 char text[16];
255                 if (best_rank == worst_rank)
256                         std::sprintf(text, "%u", best_rank);
257                 else
258                         std::sprintf(text, "%u-%u", best_rank, worst_rank);
259                 
260                 unsigned this_width = my_draw_text(text, NULL, 22.0);
261                 my_draw_text_deferred(td, text, 22.0, x + width[num_scores + 2] / 2 - this_width / 2, y);
262
263                 if (show_players > 7)
264                         y += 40 - (show_players - 7) * 4;
265                 else 
266                         y += 40;
267         }
268                 
269         /*
270          * Next up (at the bottom) is "who's playing, what will he/she be playing, and
271          * optionally, how much to lead/win and how much to secure qualification" (the
272          * last one only in the final round). We assume playing is done in a modified
273          * zigzag; all the random songs are played first in zigzag/wrapping order (player
274          * 1 song 1, player 2 song 2, player 3 song 3, player 1 song 2, player 2 song 3,
275          * player 3 song 1, etc... assuming three songs and three players) and then all
276          * the chosen songs are played (we assume only one chosen song).
277          *
278          * The lines are as follows:
279          *
280          * <player>
281          * <song>
282          * High score: <hs> by <hsplayer> at <hsevent>
283          * Needs to lead: <leadscore>
284          * Needs to secure qualification: <qualscore>
285          * Needs to win group: <winscore>
286          */
287         
288         /* Find the first player with the fewest songs played. */
289         unsigned min_played_songs = 9999, num_random_songs = 0;
290         Player *next_player = NULL;
291         for (std::vector<Player>::iterator i = group.players.begin(); i != group.players.end(); ++i) {
292                 unsigned this_played = 0, this_random_songs = 0;
293                 for (std::vector<Score>::const_iterator j = i->scores.begin(); j != i->scores.end(); ++j, ++col) {
294                         if (j->score != -1)
295                                 ++this_played;
296                         if (!j->chosen)
297                                 ++this_random_songs;
298                 }
299
300                 if (this_played < min_played_songs) {
301                         min_played_songs = this_played;
302                         next_player = &(*i);
303                         num_random_songs = this_random_songs;  // should be equal for all
304                 }
305         }
306
307         /* Find out what song this player is supposed to play next; try random songs first */ 
308         Score *next_song = NULL;
309
310         for (unsigned i = 0; i < num_random_songs; ++i) {
311                 unsigned j = (i + next_player->position - 1) % num_random_songs;
312                 if (next_player->scores[j].score == -1) {
313                         next_song = &(next_player->scores[j]);
314                         break;
315                 }
316         }
317
318         // then all songs, if that didn't work out (slightly icky, but hey)
319         if (next_song == NULL) {
320                 for (unsigned i = 0; i < num_scores; ++i) {
321                         unsigned j = (i + next_player->position) % num_scores;
322                         if (next_player->scores[j].score == -1) {
323                                 next_song = &(next_player->scores[j]);
324                                 break;
325                         }
326                 }
327         }
328
329         if (next_song != NULL) {
330                 widestring text = widestring("Next player: ") + next_player->nick;
331                 unsigned this_width = my_draw_text(text, NULL, 24.0);
332                 my_draw_text(text, buf, 24.0, 400 - this_width/2, 420);
333
334                 if (next_song->song.id != -1) {
335                         this_width = my_draw_text(next_song->song.title, NULL, 20.0);
336                         my_draw_text(next_song->song.title, buf, 20.0, 400 - this_width/2, 457);
337
338                         Highscore hs;
339                         conn.perform(FetchHighscore(next_song->song.id, &hs));
340                         
341                         if (hs.score != -1) {
342                                 text = widestring("High score: ") + widestring(pqxx::to_string(hs.score)) +
343                                         widestring(", by ") + hs.nick + widestring(" in ") + hs.tournament_name;
344                                 this_width = my_draw_text(text, NULL, 16.0);
345                                 my_draw_text(text, buf, 16.0, 400 - this_width/2, 487);
346                         }
347                 }
348
349                 // only show lead/win/qualify for the last song
350                 if (min_played_songs == num_scores - 1) {
351                         /*
352                          * Find out how much we need to lead, how much we need to be guaranteed
353                          * to win the group, and how much we need to secure qualification. (FIXME:
354                          * do the last one :-) )
355                          */
356                         
357                         // find the best score we can get
358                         unsigned max_score_this_song;
359                         if (next_song->song.id != -1) {
360                                 // random song, or we know what song the player picked
361                                 max_score_this_song = song_scores[next_song->song.id];
362                         } else {
363                                 conn.perform(FetchMaxScoreForPlayer(tournament, next_player->id, round, &max_score_this_song));
364                         }
365
366                         unsigned y = 520;
367                         
368                         // see what score this player must beat to lead
369                         unsigned lead_beat = 0, win_beat = 0;
370                         for (unsigned i = 0; i < group.players.size(); ++i) {
371                                 if (group.players[i].id == next_player->id)
372                                         continue;
373                                 
374                                 lead_beat = std::max(lead_beat, group.players[i].total);
375                         }
376
377                         // find the best max score among the others
378                         for (unsigned i = 0; i < group.players.size(); ++i) {
379                                 if (group.players[i].id == next_player->id)
380                                         continue;
381
382                                 win_beat = std::max(win_beat, max_score[i]);
383                         }
384
385                         /*
386                          * There's a somewhat subtle point here. Normally, what a player would be interested in
387                          * with regard to qualification would be a set of three values:
388                          *
389                          * 1. How much is the absolute minimum required to qualify, given that all others
390                          *    fail?
391                          * 2. How much will give a reasonable chance of qualifying, given the expected performance
392                          *    of all the others?
393                          * 3. How much will be enough to secure qualification, no matter what?
394                          *
395                          * Given perfect guessing, #2 would be "how much is needed to qualify"; however, it is
396                          * completely impossible to give an exact value for that, and we're not into the guessing
397                          * games. :-) #1 is often so low it's completely unrealistic (ie. far enough from #2 that
398                          * it's not interesting), but #3, the most conservative estimate, is often a good measure.
399                          * #3 is "how much is needed to _secure_ qualification", and that is usually what we
400                          * print out when it's possible.
401                          *
402                          * However, in a few situations, #1 and #3 will be the exact same value, from which it
403                          * follows (from the squeeze law, or just common sense :-) ) that #2 will be the same
404                          * value as #1 and #3. (This usually happens near or at the end of a group.) In that
405                          * case, we know the value we seek (ie. "how much is needed to qualify"), so we drop
406                          * the word "secure" and just print it as-is.
407                          *
408                          * To find #1 and #3, we sort and pick out the values we need to beat in the best and
409                          * the worst case.
410                          */
411                         int qualify_beat_worst_case = -1, qualify_beat_best_case = -1;
412
413                         if (group.num_qualifying > 0) {
414                                 std::vector<unsigned> tmp;
415                                 
416                                 for (unsigned i = 0; i < group.players.size(); ++i) {
417                                         if (group.players[i].id == next_player->id)
418                                                 continue;
419                                         tmp.push_back(max_score[i]);
420                                 }
421                                 std::sort(tmp.begin(), tmp.end());
422                                 qualify_beat_worst_case = tmp[tmp.size() - group.num_qualifying];
423                                 
424                                 std::vector<unsigned> tmp2;
425                                 for (unsigned i = 0; i < group.players.size(); ++i) {
426                                         if (group.players[i].id == next_player->id)
427                                                 continue;
428                                         tmp2.push_back(min_score[i]);
429                                 }
430
431                                 std::sort(tmp2.begin(), tmp2.end());
432                                 qualify_beat_best_case = tmp2[tmp2.size() - group.num_qualifying];
433                         }
434                         
435                         // print out the lines we can attain
436                         if (next_player->total + max_score_this_song > lead_beat && (lead_beat != win_beat)) {
437                                 int lead_need = std::max(lead_beat - next_player->total + 1, 0U);
438                                 
439                                 text = widestring("Needs to lead: ") + widestring(pqxx::to_string(lead_need));
440                                 this_width = my_draw_text(text, NULL, 18.0);
441                                 my_draw_text(text, buf, 18.0, 400 - this_width/2, y);
442
443                                 y += 30;
444                         }
445                         
446                         if (next_player->total + max_score_this_song > win_beat) {
447                                 int win_need = std::max(win_beat - next_player->total + 1, 0U);
448                                 
449                                 text = widestring("Needs to win: ") + widestring(pqxx::to_string(win_need));
450
451                                 this_width = my_draw_text(text, NULL, 18.0);
452                                 my_draw_text(text, buf, 18.0, 400 - this_width/2, y);
453
454                                 y += 30;
455                         }
456
457                         if (next_player->total + max_score_this_song > qualify_beat_worst_case && (qualify_beat_worst_case != win_beat)) {
458                                 int qual_need = std::max(qualify_beat_worst_case - next_player->total + 1, 0U);
459                                 
460                                 if (qualify_beat_worst_case == qualify_beat_best_case) {
461                                         text = widestring("Needs to qualify: ") + widestring(pqxx::to_string(qual_need));
462                                 } else {
463                                         text = widestring("Needs to secure qualification: ") + widestring(pqxx::to_string(qual_need));
464                                 }
465                                 
466                                 this_width = my_draw_text(text, NULL, 18.0);
467                                 my_draw_text(text, buf, 18.0, 400 - this_width/2, y);
468
469                                 y += 30;
470                         }
471                 }
472         }
473         
474         valid = true;
475         draw_all_deferred_text(buf, td, last_text);
476         last_text = td;
477 }
478