OpenTTD Source: src/highscore_gui.cpp Source File

OpenTTD Source 15.3

highscore_gui.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "stdafx.h"
11#include "highscore.h"
12#include "gfx_func.h"
13#include "table/sprites.h"
14#include "window_gui.h"
15#include "window_func.h"
16#include "network/network.h"
17#include "command_func.h"
18#include "company_func.h"
19#include "company_base.h"
20#include "strings_func.h"
21#include "hotkeys.h"
22#include "zoom_func.h"
23#include "misc_cmd.h"
24#include "timer/timer.h"
25#include "timer/timer_game_calendar.h"
26
27#include "widgets/highscore_widget.h"
28
29#include "table/strings.h"
30
31#include "safeguards.h"
32
33 struct EndGameHighScoreBaseWindow : Window {
34 SpriteID background_img{};
35 int8_t rank = 0;
36
37 EndGameHighScoreBaseWindow(WindowDesc &desc) : Window(desc)
38 {
39 this->InitNested();
40 this->flags.Reset(WindowFlag::WhiteBorder);
41 ResizeWindow(this, _screen.width - this->width, _screen.height - this->height);
42 }
43
44 /* Always draw a maximized window and within it the centered background */
45 void SetupHighScoreEndWindow()
46 {
47 /* Resize window to "full-screen". */
48 if (this->width != _screen.width || this->height != _screen.height) ResizeWindow(this, _screen.width - this->width, _screen.height - this->height);
49
50 this->DrawWidgets();
51
52 /* Fill with the appropriate background colour instead of leaving default window colour */
53 GfxFillRect(Rect{0, 0, this->width, this->height}, PixelColour{105}, FILLRECT_OPAQUE);
54
55 /* Standard background slices are 50 pixels high, but it's designed
56 * for 480 pixels total. 96% of 500 is 480. */
57 Dimension dim = GetSpriteSize(this->background_img);
58 auto total_height = dim.height * 96 / 10;
59 Point pt = this->GetTopLeft(dim.width, total_height);
60
61 /* Original graphics contain some transparency, which assumes a black background. */
62 GfxFillRect(pt.x, pt.y, pt.x + dim.width - 1, pt.y + total_height - 1, PC_BLACK);
63
64 /* Center Highscore/Endscreen background */
65 for (uint i = 0; i < 10; i++) { // the image is split into 10 50px high parts
66 DrawSprite(this->background_img + i, PAL_NONE, pt.x, pt.y + (i * dim.height));
67 }
68 }
69
71 Point GetTopLeft(int x, int y)
72 {
73 Point pt = {std::max(0, (_screen.width / 2) - (x / 2)), std::max(0, (_screen.height / 2) - (y / 2))};
74 return pt;
75 }
76
77 void OnClick([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget, [[maybe_unused]] int click_count) override
78 {
79 this->Close();
80 }
81
82 EventState OnKeyPress([[maybe_unused]] char32_t key, uint16_t keycode) override
83 {
84 /* All keys are 'handled' by this window but we want to make
85 * sure that 'quit' still works correctly. Not handling the
86 * quit key is enough so the main toolbar can handle it. */
87 if (IsQuitKey(keycode)) return ES_NOT_HANDLED;
88
89 switch (keycode) {
90 /* Keys for telling we want to go on */
91 case WKC_RETURN:
92 case WKC_ESC:
93 case WKC_SPACE:
94 this->Close();
95 return ES_HANDLED;
96
97 default:
98 /* We want to handle all keys; we don't want windows in
99 * the background to open. Especially the ones that do
100 * locate themselves based on the status-/toolbars. */
101 return ES_HANDLED;
102 }
103 }
104};
105
107 struct EndGameWindow : EndGameHighScoreBaseWindow {
108 EndGameWindow(WindowDesc &desc) : EndGameHighScoreBaseWindow(desc)
109 {
110 /* Pause in single-player to have a look at the highscore at your own leisure */
111 if (!_networking) Command<CMD_PAUSE>::Post(PauseMode::Normal, true);
112
113 this->background_img = SPR_TYCOON_IMG1_BEGIN;
114
115 if (_local_company != COMPANY_SPECTATOR) {
116 const Company *c = Company::Get(_local_company);
117 if (c->old_economy[0].performance_history == SCORE_MAX) {
118 this->background_img = SPR_TYCOON_IMG2_BEGIN;
119 }
120 }
121
122 /* In a network game show the endscores of the custom difficulty 'network' which is
123 * a TOP5 of that game, and not an all-time TOP5. */
124 if (_networking) {
125 this->window_number = SP_MULTIPLAYER;
126 this->rank = SaveHighScoreValueNetwork();
127 } else {
128 /* in singleplayer mode _local company is always valid */
129 const Company *c = Company::Get(_local_company);
130 this->window_number = SP_CUSTOM;
131 this->rank = SaveHighScoreValue(c);
132 }
133
134 MarkWholeScreenDirty();
135 }
136
137 void Close([[maybe_unused]] int data = 0) override
138 {
139 if (!_networking) Command<CMD_PAUSE>::Post(PauseMode::Normal, false); // unpause
140 if (_game_mode != GM_MENU && !_exit_game) ShowHighscoreTable(this->window_number, this->rank);
141 this->EndGameHighScoreBaseWindow::Close();
142 }
143
144 void OnPaint() override
145 {
146 this->SetupHighScoreEndWindow();
147 Point pt = this->GetTopLeft(ScaleSpriteTrad(640), ScaleSpriteTrad(480));
148
149 const Company *c = Company::GetIfValid(_local_company);
150 if (c == nullptr) return;
151
152 /* We need to get performance from last year because the image is shown
153 * at the start of the new year when these things have already been copied */
154 if (this->background_img == SPR_TYCOON_IMG2_BEGIN) { // Tycoon of the century \o/
155 DrawStringMultiLine(pt.x + ScaleSpriteTrad(15), pt.x + ScaleSpriteTrad(640) - ScaleSpriteTrad(25), pt.y + ScaleSpriteTrad(90), pt.y + ScaleSpriteTrad(160),
156 GetString(STR_HIGHSCORE_PRESIDENT_OF_COMPANY_ACHIEVES_STATUS, c->index, c->index, EndGameGetPerformanceTitleFromValue(c->old_economy[0].performance_history)),
157 TC_FROMSTRING, SA_CENTER);
158 } else {
159 DrawStringMultiLine(pt.x + ScaleSpriteTrad(36), pt.x + ScaleSpriteTrad(640), pt.y + ScaleSpriteTrad(140), pt.y + ScaleSpriteTrad(206),
160 GetString(STR_HIGHSCORE_COMPANY_ACHIEVES_STATUS, c->index, EndGameGetPerformanceTitleFromValue(c->old_economy[0].performance_history)),
161 TC_FROMSTRING, SA_CENTER);
162 }
163 }
164};
165
166 struct HighScoreWindow : EndGameHighScoreBaseWindow {
167 bool game_paused_by_player = false;
168
169 HighScoreWindow(WindowDesc &desc, int difficulty, int8_t ranking) : EndGameHighScoreBaseWindow(desc)
170 {
171 /* pause game to show the chart */
172 this->game_paused_by_player = _pause_mode == PauseMode::Normal;
173 if (!_networking && !this->game_paused_by_player) Command<CMD_PAUSE>::Post(PauseMode::Normal, true);
174
175 /* Close all always on-top windows to get a clean screen */
176 if (_game_mode != GM_MENU) HideVitalWindows();
177
178 MarkWholeScreenDirty();
179 this->window_number = difficulty; // show highscore chart for difficulty...
180 this->background_img = SPR_HIGHSCORE_CHART_BEGIN; // which background to show
181 this->rank = ranking;
182 }
183
184 void Close([[maybe_unused]] int data = 0) override
185 {
186 if (_game_mode != GM_MENU && !_exit_game) ShowVitalWindows();
187
188 if (!_networking && !this->game_paused_by_player) Command<CMD_PAUSE>::Post(PauseMode::Normal, false); // unpause
189
190 this->EndGameHighScoreBaseWindow::Close();
191 }
192
193 void OnPaint() override
194 {
195 const auto &hs = _highscore_table[this->window_number];
196
197 this->SetupHighScoreEndWindow();
198 Point pt = this->GetTopLeft(ScaleSpriteTrad(640), ScaleSpriteTrad(480));
199
200 /* Draw the title. */
201 DrawStringMultiLine(pt.x + ScaleSpriteTrad(70), pt.x + ScaleSpriteTrad(570), pt.y, pt.y + ScaleSpriteTrad(140), STR_HIGHSCORE_TOP_COMPANIES, TC_FROMSTRING, SA_CENTER);
202
203 /* Draw Highscore peepz */
204 for (uint8_t i = 0; i < ClampTo<uint8_t>(hs.size()); i++) {
205 DrawString(pt.x + ScaleSpriteTrad(40), pt.x + ScaleSpriteTrad(600), pt.y + ScaleSpriteTrad(140 + i * 55),
206 GetString(STR_HIGHSCORE_POSITION, i + 1));
207
208 if (!hs[i].name.empty()) {
209 TextColour colour = (this->rank == i) ? TC_RED : TC_BLACK; // draw new highscore in red
210
211 DrawString(pt.x + ScaleSpriteTrad(71), pt.x + ScaleSpriteTrad(569), pt.y + ScaleSpriteTrad(140 + i * 55),
212 GetString(STR_JUST_BIG_RAW_STRING, hs[i].name), colour);
213 DrawString(pt.x + ScaleSpriteTrad(71), pt.x + ScaleSpriteTrad(569), pt.y + ScaleSpriteTrad(140) + GetCharacterHeight(FS_LARGE) + ScaleSpriteTrad(i * 55),
214 GetString(STR_HIGHSCORE_STATS, hs[i].title, hs[i].score), colour);
215 }
216 }
217 }
218};
219
220static constexpr std::initializer_list<NWidgetPart> _nested_highscore_widgets = {
221 NWidget(WWT_PANEL, COLOUR_BROWN, WID_H_BACKGROUND), SetResize(1, 1), EndContainer(),
222};
223
224static WindowDesc _highscore_desc(
225 WDP_MANUAL, {}, 0, 0,
226 WC_HIGHSCORE, WC_NONE,
227 {},
228 _nested_highscore_widgets
229);
230
231static WindowDesc _endgame_desc(
232 WDP_MANUAL, {}, 0, 0,
233 WC_ENDSCREEN, WC_NONE,
234 {},
235 _nested_highscore_widgets
236);
237
243 void ShowHighscoreTable(int difficulty, int8_t ranking)
244{
245 CloseWindowByClass(WC_HIGHSCORE);
246 new HighScoreWindow(_highscore_desc, difficulty, ranking);
247}
248
253 void ShowEndGameChart()
254{
255 /* Dedicated server doesn't need the highscore window and neither does -v null. */
256 if (_network_dedicated || (!_networking && !Company::IsValidID(_local_company))) return;
257
258 HideVitalWindows();
259 CloseWindowByClass(WC_ENDSCREEN);
260 new EndGameWindow(_endgame_desc);
261}
262
263static const IntervalTimer<TimerGameCalendar> _check_end_game({TimerGameCalendar::YEAR, TimerGameCalendar::Priority::NONE}, [](auto)
264{
265 /* 0 = never */
266 if (_settings_game.game_creation.ending_year == 0) return;
267
268 /* Show the end-game chart at the end of the ending year (hence the + 1). */
269 if (TimerGameCalendar::year == _settings_game.game_creation.ending_year + 1) {
270 ShowEndGameChart();
271 }
272});
BaseBitSet::Reset
constexpr Timpl & Reset()
Reset all bits.
Definition base_bitset_type.hpp:83
IntervalTimer
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition timer_game_calendar.h:31
command_func.h
Functions related to commands.
company_base.h
Definition of stuff that is very close to a company, like the company struct itself.
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition company_cmd.cpp:55
company_func.h
Functions related to companies.
COMPANY_SPECTATOR
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
Definition company_type.h:21
SCORE_MAX
static constexpr int SCORE_MAX
The max score that can be in the performance history.
Definition economy_type.h:83
GetCharacterHeight
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:87
GetSpriteSize
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:968
DrawString
int DrawString(int left, int right, int top, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:668
DrawSprite
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1034
_pause_mode
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:50
DrawStringMultiLine
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:785
GfxFillRect
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:115
gfx_func.h
Functions related to the gfx engine.
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
FS_LARGE
@ FS_LARGE
Index of the large font in the font tables.
Definition gfx_type.h:251
SA_CENTER
@ SA_CENTER
Center both horizontally and vertically.
Definition gfx_type.h:398
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:307
FILLRECT_OPAQUE
@ FILLRECT_OPAQUE
Fill rectangle with a single colour.
Definition gfx_type.h:345
EndContainer
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
Definition widget_type.h:1232
NWidget
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
Definition widget_type.h:1427
SetResize
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
Definition widget_type.h:1148
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1549
SaveHighScoreValueNetwork
int8_t SaveHighScoreValueNetwork()
Save the highscores in a network game when it has ended.
Definition highscore.cpp:88
_highscore_table
HighScoresTable _highscore_table
Table with all the high scores.
Definition highscore.cpp:24
SaveHighScoreValue
int8_t SaveHighScoreValue(const Company *c)
Save the highscore for the company.
Definition highscore.cpp:58
highscore.h
Declaration of functions and types defined in highscore.h and highscore_gui.h.
ShowHighscoreTable
void ShowHighscoreTable(int difficulty, int8_t ranking)
Show the highscore table for a given difficulty.
Definition highscore_gui.cpp:243
ShowEndGameChart
void ShowEndGameChart()
Show the endgame victory screen in 2050.
Definition highscore_gui.cpp:253
highscore_widget.h
Types related to the highscore widgets.
WID_H_BACKGROUND
@ WID_H_BACKGROUND
Background of the window.
Definition highscore_widget.h:15
hotkeys.h
Hotkey related functions.
IsQuitKey
bool IsQuitKey(uint16_t keycode)
Does the given keycode match one of the keycodes bound to 'quit game'?
Definition main_gui.cpp:541
ShowVitalWindows
void ShowVitalWindows()
Show the vital in-game windows.
Definition main_gui.cpp:582
misc_cmd.h
Miscellaneous command definitions.
_networking
bool _networking
are we in networking mode?
Definition network.cpp:67
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:70
network.h
Basic functions/variables used all over the place.
PauseMode::Normal
@ Normal
A game normally paused.
PC_BLACK
static constexpr PixelColour PC_BLACK
Black palette colour.
Definition palette_func.h:96
safeguards.h
A number of safeguards to prevent using unsafe methods.
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
SP_CUSTOM
@ SP_CUSTOM
No profile, special "custom" highscore.
Definition settings_type.h:47
SP_MULTIPLAYER
@ SP_MULTIPLAYER
Special "multiplayer" highscore. Not saved, always specific to the current game.
Definition settings_type.h:50
sprites.h
This file contains all sprite-related enums and defines.
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:424
strings_func.h
Functions related to OTTD's strings.
CommandHelper
Definition command_func.h:84
CompanyProperties::old_economy
std::array< CompanyEconomyEntry, MAX_HISTORY_QUARTERS > old_economy
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Definition company_base.h:118
Company
Definition company_base.h:127
Coord2D< int >
Coord2D::y
T y
Y coordinate.
Definition geometry_type.hpp:35
Coord2D::x
T x
X coordinate.
Definition geometry_type.hpp:34
Dimension
Dimensions (a width and height) of a rectangle in 2D.
Definition geometry_type.hpp:56
EndGameHighScoreBaseWindow
Definition highscore_gui.cpp:33
EndGameHighScoreBaseWindow::OnKeyPress
EventState OnKeyPress(char32_t key, uint16_t keycode) override
A key has been pressed.
Definition highscore_gui.cpp:82
EndGameHighScoreBaseWindow::GetTopLeft
Point GetTopLeft(int x, int y)
Return the coordinate of the screen such that a window of 640x480 is centered at the screen.
Definition highscore_gui.cpp:71
EndGameHighScoreBaseWindow::OnClick
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Definition highscore_gui.cpp:77
EndGameWindow
End game window shown at the end of the game.
Definition highscore_gui.cpp:107
EndGameWindow::Close
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
Definition highscore_gui.cpp:137
EndGameWindow::OnPaint
void OnPaint() override
The window must be repainted.
Definition highscore_gui.cpp:144
GameCreationSettings::ending_year
TimerGameCalendar::Year ending_year
scoring end date
Definition settings_type.h:381
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition settings_type.h:634
HighScoreWindow
Definition highscore_gui.cpp:166
HighScoreWindow::OnPaint
void OnPaint() override
The window must be repainted.
Definition highscore_gui.cpp:193
HighScoreWindow::Close
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
Definition highscore_gui.cpp:184
HighScoreWindow::game_paused_by_player
bool game_paused_by_player
True if the game was paused by the player when the highscore window was opened.
Definition highscore_gui.cpp:167
PixelColour
Colour for pixel/line drawing.
Definition gfx_type.h:405
Pool::PoolItem<&_company_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition pool_type.hpp:286
Pool::PoolItem<&_company_pool >::IsValidID
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition pool_type.hpp:376
Pool::PoolItem<&_company_pool >::GetIfValid
static Titem * GetIfValid(auto index)
Returns Titem with given index.
Definition pool_type.hpp:398
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition geometry_type.hpp:101
WindowDesc
High level window description.
Definition window_gui.h:168
Window
Data structure for an opened window.
Definition window_gui.h:274
Window::Close
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1104
Window::DrawWidgets
void DrawWidgets() const
Paint all widgets of a window.
Definition widget.cpp:784
Window::InitNested
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1823
Window::flags
WindowFlags flags
Window flags.
Definition window_gui.h:301
Window::height
int height
Height of the window (number of pixels down in y direction)
Definition window_gui.h:313
Window::width
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:312
Window::window_number
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:303
timer.h
Definition of Interval and OneShot timers.
timer_game_calendar.h
Definition of the game-calendar-timer.
WWT_PANEL
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
ResizeWindow
void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen, bool schedule_resize)
Resize the window.
Definition window.cpp:2099
CloseWindowByClass
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
Definition window.cpp:1207
HideVitalWindows
void HideVitalWindows()
Close all always on-top windows to get an empty screen.
Definition window.cpp:3396
window_func.h
Window functions not directly related to making/drawing windows.
window_gui.h
Functions, definitions and such used only by the GUI.
WindowFlag::WhiteBorder
@ WhiteBorder
Window white border counter bit mask.
WDP_MANUAL
@ WDP_MANUAL
Manually align the window (so no automatic location finding)
Definition window_gui.h:143
WidgetID
int WidgetID
Widget ID.
Definition window_type.h:20
EventState
EventState
State of handling an event.
Definition window_type.h:780
ES_HANDLED
@ ES_HANDLED
The passed event is handled.
Definition window_type.h:781
ES_NOT_HANDLED
@ ES_NOT_HANDLED
The passed event is not handled.
Definition window_type.h:782
WC_HIGHSCORE
@ WC_HIGHSCORE
Highscore; Window numbers:
Definition window_type.h:672
WC_ENDSCREEN
@ WC_ENDSCREEN
Endscreen; Window numbers:
Definition window_type.h:678
WC_NONE
@ WC_NONE
No window, redirects to WC_MAIN_WINDOW.
Definition window_type.h:50
zoom_func.h
Functions related to zooming.
ScaleSpriteTrad
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107