Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / graph_gui.cpp
blobda5ba21c53251fd6571a176669429ea5d2482561
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 <http://www.gnu.org/licenses/>.
6 */
8 /** @file graph_gui.cpp GUI that shows performance graphs. */
10 #include "stdafx.h"
11 #include "graph_gui.h"
12 #include "window_gui.h"
13 #include "company_base.h"
14 #include "company_gui.h"
15 #include "economy_func.h"
16 #include "cargotype.h"
17 #include "strings_func.h"
18 #include "window_func.h"
19 #include "gfx_func.h"
20 #include "core/geometry_func.hpp"
21 #include "currency.h"
22 #include "timer/timer.h"
23 #include "timer/timer_window.h"
24 #include "timer/timer_game_tick.h"
25 #include "timer/timer_game_calendar.h"
26 #include "timer/timer_game_economy.h"
27 #include "zoom_func.h"
29 #include "widgets/graph_widget.h"
31 #include "table/strings.h"
32 #include "table/sprites.h"
34 #include "safeguards.h"
36 /* Bitmasks of company and cargo indices that shouldn't be drawn. */
37 static CompanyMask _legend_excluded_companies;
38 static CargoTypes _legend_excluded_cargo;
40 /* Apparently these don't play well with enums. */
41 static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX); // Value used for a datapoint that shouldn't be drawn.
42 static const uint INVALID_DATAPOINT_POS = UINT_MAX; // Used to determine if the previous point was drawn.
44 constexpr double INT64_MAX_IN_DOUBLE = static_cast<double>(INT64_MAX - 512); ///< The biggest double that when cast to int64_t still fits in a int64_t.
45 static_assert(static_cast<int64_t>(INT64_MAX_IN_DOUBLE) < INT64_MAX);
47 /****************/
48 /* GRAPH LEGEND */
49 /****************/
51 struct GraphLegendWindow : Window {
52 GraphLegendWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
54 this->InitNested(window_number);
56 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
57 if (!HasBit(_legend_excluded_companies, c)) this->LowerWidget(WID_GL_FIRST_COMPANY + c);
59 this->OnInvalidateData(c);
63 void DrawWidget(const Rect &r, WidgetID widget) const override
65 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, WID_GL_FIRST_COMPANY + MAX_COMPANIES)) return;
67 CompanyID cid = (CompanyID)(widget - WID_GL_FIRST_COMPANY);
69 if (!Company::IsValidID(cid)) return;
71 bool rtl = _current_text_dir == TD_RTL;
73 const Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
74 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
75 DrawCompanyIcon(cid, rtl ? ir.right - d.width : ir.left, CenterBounds(ir.top, ir.bottom, d.height));
77 const Rect tr = ir.Indent(d.width + WidgetDimensions::scaled.hsep_normal, rtl);
78 SetDParam(0, cid);
79 SetDParam(1, cid);
80 DrawString(tr.left, tr.right, CenterBounds(tr.top, tr.bottom, GetCharacterHeight(FS_NORMAL)), STR_COMPANY_NAME_COMPANY_NUM, HasBit(_legend_excluded_companies, cid) ? TC_BLACK : TC_WHITE);
83 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
85 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, WID_GL_FIRST_COMPANY + MAX_COMPANIES)) return;
87 ToggleBit(_legend_excluded_companies, widget - WID_GL_FIRST_COMPANY);
88 this->ToggleWidgetLoweredState(widget);
89 this->SetDirty();
90 InvalidateWindowData(WC_INCOME_GRAPH, 0);
91 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
92 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
93 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
94 InvalidateWindowData(WC_COMPANY_VALUE, 0);
97 /**
98 * Some data on this window has become invalid.
99 * @param data Information about the changed data.
100 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
102 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
104 if (!gui_scope) return;
105 if (Company::IsValidID(data)) return;
107 SetBit(_legend_excluded_companies, data);
108 this->RaiseWidget(data + WID_GL_FIRST_COMPANY);
113 * Construct a vertical list of buttons, one for each company.
114 * @return Panel with company buttons.
116 static std::unique_ptr<NWidgetBase> MakeNWidgetCompanyLines()
118 auto vert = std::make_unique<NWidgetVertical>(NC_EQUALSIZE);
119 vert->SetPadding(2, 2, 2, 2);
120 uint sprite_height = GetSpriteSize(SPR_COMPANY_ICON, nullptr, ZOOM_LVL_OUT_4X).height;
122 for (WidgetID widnum = WID_GL_FIRST_COMPANY; widnum <= WID_GL_LAST_COMPANY; widnum++) {
123 auto panel = std::make_unique<NWidgetBackground>(WWT_PANEL, COLOUR_BROWN, widnum);
124 panel->SetMinimalSize(246, sprite_height + WidgetDimensions::unscaled.framerect.Vertical());
125 panel->SetMinimalTextLines(1, WidgetDimensions::unscaled.framerect.Vertical(), FS_NORMAL);
126 panel->SetFill(1, 1);
127 panel->SetDataTip(0x0, STR_GRAPH_KEY_COMPANY_SELECTION_TOOLTIP);
128 vert->Add(std::move(panel));
130 return vert;
133 static constexpr NWidgetPart _nested_graph_legend_widgets[] = {
134 NWidget(NWID_HORIZONTAL),
135 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
136 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_KEY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
137 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
138 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
139 EndContainer(),
140 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GL_BACKGROUND),
141 NWidgetFunction(MakeNWidgetCompanyLines),
142 EndContainer(),
145 static WindowDesc _graph_legend_desc(__FILE__, __LINE__,
146 WDP_AUTO, "graph_legend", 0, 0,
147 WC_GRAPH_LEGEND, WC_NONE,
149 std::begin(_nested_graph_legend_widgets), std::end(_nested_graph_legend_widgets)
152 static void ShowGraphLegend()
154 AllocateWindowDescFront<GraphLegendWindow>(&_graph_legend_desc, 0);
157 /** Contains the interval of a graph's data. */
158 struct ValuesInterval {
159 OverflowSafeInt64 highest; ///< Highest value of this interval. Must be zero or greater.
160 OverflowSafeInt64 lowest; ///< Lowest value of this interval. Must be zero or less.
163 /******************/
164 /* BASE OF GRAPHS */
165 /*****************/
167 struct BaseGraphWindow : Window {
168 protected:
169 static const int GRAPH_MAX_DATASETS = 64;
170 static const int GRAPH_BASE_COLOUR = GREY_SCALE(2);
171 static const int GRAPH_GRID_COLOUR = GREY_SCALE(3);
172 static const int GRAPH_AXIS_LINE_COLOUR = GREY_SCALE(1);
173 static const int GRAPH_ZERO_LINE_COLOUR = GREY_SCALE(8);
174 static const int GRAPH_YEAR_LINE_COLOUR = GREY_SCALE(5);
175 static const int GRAPH_NUM_MONTHS = 24; ///< Number of months displayed in the graph.
176 static const int PAYMENT_GRAPH_X_STEP_DAYS = 20; ///< X-axis step label for cargo payment rates "Days in transit".
177 static const int PAYMENT_GRAPH_X_STEP_SECONDS = 10; ///< X-axis step label for cargo payment rates "Seconds in transit".
178 static const int ECONOMY_QUARTER_MINUTES = 3; ///< Minutes per economic quarter.
180 static const TextColour GRAPH_AXIS_LABEL_COLOUR = TC_BLACK; ///< colour of the graph axis label.
182 static const int MIN_GRAPH_NUM_LINES_Y = 9; ///< Minimal number of horizontal lines to draw.
183 static const int MIN_GRID_PIXEL_SIZE = 20; ///< Minimum distance between graph lines.
185 uint64_t excluded_data; ///< bitmask of the datasets that shouldn't be displayed.
186 byte num_dataset;
187 byte num_on_x_axis;
188 byte num_vert_lines;
190 /* The starting month and year that values are plotted against. */
191 TimerGameEconomy::Month month;
192 TimerGameEconomy::Year year;
194 bool draw_dates = true; ///< Should we draw months and years on the time axis?
196 /* These values are used if the graph is being plotted against values
197 * rather than the dates specified by month and year. */
198 uint16_t x_values_start;
199 uint16_t x_values_increment;
201 StringID format_str_y_axis;
202 byte colours[GRAPH_MAX_DATASETS];
203 OverflowSafeInt64 cost[GRAPH_MAX_DATASETS][GRAPH_NUM_MONTHS]; ///< Stored costs for the last #GRAPH_NUM_MONTHS months
206 * Get the interval that contains the graph's data. Excluded data is ignored to show smaller values in
207 * better detail when disabling higher ones.
208 * @param num_hori_lines Number of horizontal lines to be drawn.
209 * @return Highest and lowest values of the graph (ignoring disabled data).
211 ValuesInterval GetValuesInterval(int num_hori_lines) const
213 assert(num_hori_lines > 0);
215 ValuesInterval current_interval;
216 current_interval.highest = INT64_MIN;
217 current_interval.lowest = INT64_MAX;
219 for (int i = 0; i < this->num_dataset; i++) {
220 if (HasBit(this->excluded_data, i)) continue;
221 for (int j = 0; j < this->num_on_x_axis; j++) {
222 OverflowSafeInt64 datapoint = this->cost[i][j];
224 if (datapoint != INVALID_DATAPOINT) {
225 current_interval.highest = std::max(current_interval.highest, datapoint);
226 current_interval.lowest = std::min(current_interval.lowest, datapoint);
231 /* Always include zero in the shown range. */
232 double abs_lower = (current_interval.lowest > 0) ? 0 : (double)abs(current_interval.lowest);
233 double abs_higher = (current_interval.highest < 0) ? 0 : (double)current_interval.highest;
235 /* Prevent showing values too close to the graph limits. */
236 abs_higher = (11.0 * abs_higher) / 10.0;
237 abs_lower = (11.0 * abs_lower) / 10.0;
239 int num_pos_grids;
240 OverflowSafeInt64 grid_size;
242 if (abs_lower != 0 || abs_higher != 0) {
243 /* The number of grids to reserve for the positive part is: */
244 num_pos_grids = (int)floor(0.5 + num_hori_lines * abs_higher / (abs_higher + abs_lower));
246 /* If there are any positive or negative values, force that they have at least one grid. */
247 if (num_pos_grids == 0 && abs_higher != 0) num_pos_grids++;
248 if (num_pos_grids == num_hori_lines && abs_lower != 0) num_pos_grids--;
250 /* Get the required grid size for each side and use the maximum one. */
252 OverflowSafeInt64 grid_size_higher = 0;
253 if (abs_higher > 0) {
254 grid_size_higher = abs_higher > INT64_MAX_IN_DOUBLE ? INT64_MAX : static_cast<int64_t>(abs_higher);
255 grid_size_higher = (grid_size_higher + num_pos_grids - 1) / num_pos_grids;
258 OverflowSafeInt64 grid_size_lower = 0;
259 if (abs_lower > 0) {
260 grid_size_lower = abs_lower > INT64_MAX_IN_DOUBLE ? INT64_MAX : static_cast<int64_t>(abs_lower);
261 grid_size_lower = (grid_size_lower + num_hori_lines - num_pos_grids - 1) / (num_hori_lines - num_pos_grids);
264 grid_size = std::max(grid_size_higher, grid_size_lower);
265 } else {
266 /* If both values are zero, show an empty graph. */
267 num_pos_grids = num_hori_lines / 2;
268 grid_size = 1;
271 current_interval.highest = num_pos_grids * grid_size;
272 current_interval.lowest = -(num_hori_lines - num_pos_grids) * grid_size;
273 return current_interval;
277 * Get width for Y labels.
278 * @param current_interval Interval that contains all of the graph data.
279 * @param num_hori_lines Number of horizontal lines to be drawn.
281 uint GetYLabelWidth(ValuesInterval current_interval, int num_hori_lines) const
283 /* draw text strings on the y axis */
284 int64_t y_label = current_interval.highest;
285 int64_t y_label_separation = (current_interval.highest - current_interval.lowest) / num_hori_lines;
287 uint max_width = 0;
289 for (int i = 0; i < (num_hori_lines + 1); i++) {
290 SetDParam(0, this->format_str_y_axis);
291 SetDParam(1, y_label);
292 Dimension d = GetStringBoundingBox(STR_GRAPH_Y_LABEL);
293 if (d.width > max_width) max_width = d.width;
295 y_label -= y_label_separation;
298 return max_width;
302 * Actually draw the graph.
303 * @param r the rectangle of the data field of the graph
305 void DrawGraph(Rect r) const
307 uint x, y; ///< Reused whenever x and y coordinates are needed.
308 ValuesInterval interval; ///< Interval that contains all of the graph data.
309 int x_axis_offset; ///< Distance from the top of the graph to the x axis.
311 /* the colours and cost array of GraphDrawer must accommodate
312 * both values for cargo and companies. So if any are higher, quit */
313 static_assert(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES);
314 assert(this->num_vert_lines > 0);
316 /* Rect r will be adjusted to contain just the graph, with labels being
317 * placed outside the area. */
318 r.top += ScaleGUITrad(5) + GetCharacterHeight(FS_SMALL) / 2;
319 r.bottom -= (this->draw_dates ? 2 : 1) * GetCharacterHeight(FS_SMALL) + ScaleGUITrad(4);
320 r.left += ScaleGUITrad(9);
321 r.right -= ScaleGUITrad(5);
323 /* Initial number of horizontal lines. */
324 int num_hori_lines = 160 / ScaleGUITrad(MIN_GRID_PIXEL_SIZE);
325 /* For the rest of the height, the number of horizontal lines will increase more slowly. */
326 int resize = (r.bottom - r.top - 160) / (2 * ScaleGUITrad(MIN_GRID_PIXEL_SIZE));
327 if (resize > 0) num_hori_lines += resize;
329 interval = GetValuesInterval(num_hori_lines);
331 int label_width = GetYLabelWidth(interval, num_hori_lines);
333 r.left += label_width;
335 int x_sep = (r.right - r.left) / this->num_vert_lines;
336 int y_sep = (r.bottom - r.top) / num_hori_lines;
338 /* Redetermine right and bottom edge of graph to fit with the integer
339 * separation values. */
340 r.right = r.left + x_sep * this->num_vert_lines;
341 r.bottom = r.top + y_sep * num_hori_lines;
343 OverflowSafeInt64 interval_size = interval.highest + abs(interval.lowest);
344 /* Where to draw the X axis. Use floating point to avoid overflowing and results of zero. */
345 x_axis_offset = (int)((r.bottom - r.top) * (double)interval.highest / (double)interval_size);
347 /* Draw the background of the graph itself. */
348 GfxFillRect(r.left, r.top, r.right, r.bottom, GRAPH_BASE_COLOUR);
350 /* Draw the vertical grid lines. */
352 /* Don't draw the first line, as that's where the axis will be. */
353 x = r.left + x_sep;
355 int grid_colour = GRAPH_GRID_COLOUR;
356 for (int i = 1; i < this->num_vert_lines + 1; i++) {
357 /* If using wallclock units, we separate periods with a lighter line. */
358 if (TimerGameEconomy::UsingWallclockUnits()) {
359 grid_colour = (i % 4 == 0) ? GRAPH_YEAR_LINE_COLOUR : GRAPH_GRID_COLOUR;
361 GfxFillRect(x, r.top, x, r.bottom, grid_colour);
362 x += x_sep;
365 /* Draw the horizontal grid lines. */
366 y = r.bottom;
368 for (int i = 0; i < (num_hori_lines + 1); i++) {
369 GfxFillRect(r.left - ScaleGUITrad(3), y, r.left - 1, y, GRAPH_AXIS_LINE_COLOUR);
370 GfxFillRect(r.left, y, r.right, y, GRAPH_GRID_COLOUR);
371 y -= y_sep;
374 /* Draw the y axis. */
375 GfxFillRect(r.left, r.top, r.left, r.bottom, GRAPH_AXIS_LINE_COLOUR);
377 /* Draw the x axis. */
378 y = x_axis_offset + r.top;
379 GfxFillRect(r.left, y, r.right, y, GRAPH_ZERO_LINE_COLOUR);
381 /* Find the largest value that will be drawn. */
382 if (this->num_on_x_axis == 0) return;
384 assert(this->num_on_x_axis > 0);
386 /* draw text strings on the y axis */
387 int64_t y_label = interval.highest;
388 int64_t y_label_separation = abs(interval.highest - interval.lowest) / num_hori_lines;
390 y = r.top - GetCharacterHeight(FS_SMALL) / 2;
392 for (int i = 0; i < (num_hori_lines + 1); i++) {
393 SetDParam(0, this->format_str_y_axis);
394 SetDParam(1, y_label);
395 DrawString(r.left - label_width - ScaleGUITrad(4), r.left - ScaleGUITrad(4), y, STR_GRAPH_Y_LABEL, GRAPH_AXIS_LABEL_COLOUR, SA_RIGHT);
397 y_label -= y_label_separation;
398 y += y_sep;
401 /* Draw x-axis labels and markings for graphs based on financial quarters and years. */
402 if (this->draw_dates) {
403 x = r.left;
404 y = r.bottom + ScaleGUITrad(2);
405 TimerGameEconomy::Month month = this->month;
406 TimerGameEconomy::Year year = this->year;
407 for (int i = 0; i < this->num_on_x_axis; i++) {
408 SetDParam(0, month + STR_MONTH_ABBREV_JAN);
409 SetDParam(1, year);
410 DrawStringMultiLine(x, x + x_sep, y, this->height, month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH, GRAPH_AXIS_LABEL_COLOUR, SA_LEFT);
412 month += 3;
413 if (month >= 12) {
414 month = 0;
415 year++;
417 /* Draw a lighter grid line between years. Top and bottom adjustments ensure we don't draw over top and bottom horizontal grid lines. */
418 GfxFillRect(x + x_sep, r.top + 1, x + x_sep, r.bottom - 1, GRAPH_YEAR_LINE_COLOUR);
420 x += x_sep;
422 } else {
423 /* Draw x-axis labels for graphs not based on quarterly performance (cargo payment rates, and all graphs when using wallclock units). */
424 x = r.left;
425 y = r.bottom + ScaleGUITrad(2);
426 uint16_t label = this->x_values_start;
428 for (int i = 0; i < this->num_on_x_axis; i++) {
429 SetDParam(0, label);
430 DrawString(x + 1, x + x_sep - 1, y, STR_GRAPH_Y_LABEL_NUMBER, GRAPH_AXIS_LABEL_COLOUR, SA_HOR_CENTER);
432 label += this->x_values_increment;
433 x += x_sep;
437 /* draw lines and dots */
438 uint linewidth = _settings_client.gui.graph_line_thickness;
439 uint pointoffs1 = (linewidth + 1) / 2;
440 uint pointoffs2 = linewidth + 1 - pointoffs1;
441 for (int i = 0; i < this->num_dataset; i++) {
442 if (!HasBit(this->excluded_data, i)) {
443 /* Centre the dot between the grid lines. */
444 x = r.left + (x_sep / 2);
446 byte colour = this->colours[i];
447 uint prev_x = INVALID_DATAPOINT_POS;
448 uint prev_y = INVALID_DATAPOINT_POS;
450 for (int j = 0; j < this->num_on_x_axis; j++) {
451 OverflowSafeInt64 datapoint = this->cost[i][j];
453 if (datapoint != INVALID_DATAPOINT) {
455 * Check whether we need to reduce the 'accuracy' of the
456 * datapoint value and the highest value to split overflows.
457 * And when 'drawing' 'one million' or 'one million and one'
458 * there is no significant difference, so the least
459 * significant bits can just be removed.
461 * If there are more bits needed than would fit in a 32 bits
462 * integer, so at about 31 bits because of the sign bit, the
463 * least significant bits are removed.
465 int mult_range = FindLastBit<uint32_t>(x_axis_offset) + FindLastBit<uint64_t>(abs(datapoint));
466 int reduce_range = std::max(mult_range - 31, 0);
468 /* Handle negative values differently (don't shift sign) */
469 if (datapoint < 0) {
470 datapoint = -(abs(datapoint) >> reduce_range);
471 } else {
472 datapoint >>= reduce_range;
474 y = r.top + x_axis_offset - ((r.bottom - r.top) * datapoint) / (interval_size >> reduce_range);
476 /* Draw the point. */
477 GfxFillRect(x - pointoffs1, y - pointoffs1, x + pointoffs2, y + pointoffs2, colour);
479 /* Draw the line connected to the previous point. */
480 if (prev_x != INVALID_DATAPOINT_POS) GfxDrawLine(prev_x, prev_y, x, y, colour, linewidth);
482 prev_x = x;
483 prev_y = y;
484 } else {
485 prev_x = INVALID_DATAPOINT_POS;
486 prev_y = INVALID_DATAPOINT_POS;
489 x += x_sep;
496 BaseGraphWindow(WindowDesc *desc, StringID format_str_y_axis) :
497 Window(desc),
498 format_str_y_axis(format_str_y_axis)
500 SetWindowDirty(WC_GRAPH_LEGEND, 0);
501 this->num_vert_lines = 24;
504 void InitializeWindow(WindowNumber number)
506 /* Initialise the dataset */
507 this->UpdateStatistics(true);
509 this->CreateNestedTree();
511 auto *wid = this->GetWidget<NWidgetCore>(WID_GRAPH_FOOTER);
512 if (wid != nullptr && TimerGameEconomy::UsingWallclockUnits()) {
513 wid->SetDataTip(STR_GRAPH_LAST_72_MINUTES_TIME_LABEL, STR_NULL);
516 this->FinishInitNested(number);
519 public:
520 void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
522 if (widget != WID_GRAPH_GRAPH) return;
524 uint x_label_width = 0;
526 /* Draw x-axis labels and markings for graphs based on financial quarters and years. */
527 if (this->draw_dates) {
528 TimerGameEconomy::Month month = this->month;
529 TimerGameEconomy::Year year = this->year;
530 for (int i = 0; i < this->num_on_x_axis; i++) {
531 SetDParam(0, month + STR_MONTH_ABBREV_JAN);
532 SetDParam(1, year);
533 x_label_width = std::max(x_label_width, GetStringBoundingBox(month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH).width);
535 month += 3;
536 if (month >= 12) {
537 month = 0;
538 year++;
541 } else {
542 /* Draw x-axis labels for graphs not based on quarterly performance (cargo payment rates). */
543 SetDParamMaxValue(0, this->x_values_start + this->num_on_x_axis * this->x_values_increment, 0, FS_SMALL);
544 x_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL_NUMBER).width;
547 SetDParam(0, this->format_str_y_axis);
548 SetDParam(1, INT64_MAX);
549 uint y_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL).width;
551 size->width = std::max<uint>(size->width, ScaleGUITrad(5) + y_label_width + this->num_vert_lines * (x_label_width + ScaleGUITrad(5)) + ScaleGUITrad(9));
552 size->height = std::max<uint>(size->height, ScaleGUITrad(5) + (1 + MIN_GRAPH_NUM_LINES_Y * 2 + (this->draw_dates ? 3 : 1)) * GetCharacterHeight(FS_SMALL) + ScaleGUITrad(4));
553 size->height = std::max<uint>(size->height, size->width / 3);
556 void DrawWidget(const Rect &r, WidgetID widget) const override
558 if (widget != WID_GRAPH_GRAPH) return;
560 DrawGraph(r);
563 virtual OverflowSafeInt64 GetGraphData(const Company *, int)
565 return INVALID_DATAPOINT;
568 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
570 /* Clicked on legend? */
571 if (widget == WID_GRAPH_KEY_BUTTON) ShowGraphLegend();
574 void OnGameTick() override
576 this->UpdateStatistics(false);
580 * Some data on this window has become invalid.
581 * @param data Information about the changed data.
582 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
584 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
586 if (!gui_scope) return;
587 this->UpdateStatistics(true);
591 * Update the statistics.
592 * @param initialize Initialize the data structure.
594 void UpdateStatistics(bool initialize)
596 CompanyMask excluded_companies = _legend_excluded_companies;
598 /* Exclude the companies which aren't valid */
599 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
600 if (!Company::IsValidID(c)) SetBit(excluded_companies, c);
603 byte nums = 0;
604 for (const Company *c : Company::Iterate()) {
605 nums = std::min(this->num_vert_lines, std::max(nums, c->num_valid_stat_ent));
608 int mo = (TimerGameEconomy::month / 3 - nums) * 3;
609 auto yr = TimerGameEconomy::year;
610 while (mo < 0) {
611 yr--;
612 mo += 12;
615 if (!initialize && this->excluded_data == excluded_companies && this->num_on_x_axis == nums &&
616 this->year == yr && this->month == mo) {
617 /* There's no reason to get new stats */
618 return;
621 this->excluded_data = excluded_companies;
622 this->num_on_x_axis = nums;
623 this->year = yr;
624 this->month = mo;
626 int numd = 0;
627 for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; k++) {
628 const Company *c = Company::GetIfValid(k);
629 if (c != nullptr) {
630 this->colours[numd] = _colour_gradient[c->colour][6];
631 for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
632 if (j >= c->num_valid_stat_ent) {
633 this->cost[numd][i] = INVALID_DATAPOINT;
634 } else {
635 /* Ensure we never assign INVALID_DATAPOINT, as that has another meaning.
636 * Instead, use the value just under it. Hopefully nobody will notice. */
637 this->cost[numd][i] = std::min(GetGraphData(c, j), INVALID_DATAPOINT - 1);
639 i++;
642 numd++;
645 this->num_dataset = numd;
650 /********************/
651 /* OPERATING PROFIT */
652 /********************/
654 struct OperatingProfitGraphWindow : BaseGraphWindow {
655 OperatingProfitGraphWindow(WindowDesc *desc, WindowNumber window_number) :
656 BaseGraphWindow(desc, STR_JUST_CURRENCY_SHORT)
658 this->num_on_x_axis = GRAPH_NUM_MONTHS;
659 this->num_vert_lines = GRAPH_NUM_MONTHS;
660 this->x_values_start = ECONOMY_QUARTER_MINUTES;
661 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
662 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
664 this->InitializeWindow(window_number);
667 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
669 return c->old_economy[j].income + c->old_economy[j].expenses;
673 static constexpr NWidgetPart _nested_operating_profit_widgets[] = {
674 NWidget(NWID_HORIZONTAL),
675 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
676 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_OPERATING_PROFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
677 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
678 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
679 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
680 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
681 EndContainer(),
682 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
683 NWidget(NWID_VERTICAL),
684 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_GRAPH_GRAPH), SetMinimalSize(576, 160), SetFill(1, 1), SetResize(1, 1),
685 NWidget(NWID_HORIZONTAL),
686 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
687 NWidget(WWT_TEXT, COLOUR_BROWN, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_EMPTY, STR_NULL),
688 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
689 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetDataTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
690 EndContainer(),
691 EndContainer(),
692 EndContainer(),
695 static WindowDesc _operating_profit_desc(__FILE__, __LINE__,
696 WDP_AUTO, "graph_operating_profit", 0, 0,
697 WC_OPERATING_PROFIT, WC_NONE,
699 std::begin(_nested_operating_profit_widgets), std::end(_nested_operating_profit_widgets)
703 void ShowOperatingProfitGraph()
705 AllocateWindowDescFront<OperatingProfitGraphWindow>(&_operating_profit_desc, 0);
709 /****************/
710 /* INCOME GRAPH */
711 /****************/
713 struct IncomeGraphWindow : BaseGraphWindow {
714 IncomeGraphWindow(WindowDesc *desc, WindowNumber window_number) :
715 BaseGraphWindow(desc, STR_JUST_CURRENCY_SHORT)
717 this->num_on_x_axis = GRAPH_NUM_MONTHS;
718 this->num_vert_lines = GRAPH_NUM_MONTHS;
719 this->x_values_start = ECONOMY_QUARTER_MINUTES;
720 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
721 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
723 this->InitializeWindow(window_number);
726 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
728 return c->old_economy[j].income;
732 static constexpr NWidgetPart _nested_income_graph_widgets[] = {
733 NWidget(NWID_HORIZONTAL),
734 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
735 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_INCOME_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
736 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
737 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
738 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
739 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
740 EndContainer(),
741 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
742 NWidget(NWID_VERTICAL),
743 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_GRAPH_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
744 NWidget(NWID_HORIZONTAL),
745 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
746 NWidget(WWT_TEXT, COLOUR_BROWN, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_EMPTY, STR_NULL),
747 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
748 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetDataTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
749 EndContainer(),
750 EndContainer(),
751 EndContainer(),
754 static WindowDesc _income_graph_desc(__FILE__, __LINE__,
755 WDP_AUTO, "graph_income", 0, 0,
756 WC_INCOME_GRAPH, WC_NONE,
758 std::begin(_nested_income_graph_widgets), std::end(_nested_income_graph_widgets)
761 void ShowIncomeGraph()
763 AllocateWindowDescFront<IncomeGraphWindow>(&_income_graph_desc, 0);
766 /*******************/
767 /* DELIVERED CARGO */
768 /*******************/
770 struct DeliveredCargoGraphWindow : BaseGraphWindow {
771 DeliveredCargoGraphWindow(WindowDesc *desc, WindowNumber window_number) :
772 BaseGraphWindow(desc, STR_JUST_COMMA)
774 this->num_on_x_axis = GRAPH_NUM_MONTHS;
775 this->num_vert_lines = GRAPH_NUM_MONTHS;
776 this->x_values_start = ECONOMY_QUARTER_MINUTES;
777 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
778 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
780 this->InitializeWindow(window_number);
783 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
785 return c->old_economy[j].delivered_cargo.GetSum<OverflowSafeInt64>();
789 static constexpr NWidgetPart _nested_delivered_cargo_graph_widgets[] = {
790 NWidget(NWID_HORIZONTAL),
791 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
792 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_CARGO_DELIVERED_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
793 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
794 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
795 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
796 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
797 EndContainer(),
798 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
799 NWidget(NWID_VERTICAL),
800 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_GRAPH_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
801 NWidget(NWID_HORIZONTAL),
802 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
803 NWidget(WWT_TEXT, COLOUR_BROWN, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_EMPTY, STR_NULL),
804 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
805 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetDataTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
806 EndContainer(),
807 EndContainer(),
808 EndContainer(),
811 static WindowDesc _delivered_cargo_graph_desc(__FILE__, __LINE__,
812 WDP_AUTO, "graph_delivered_cargo", 0, 0,
813 WC_DELIVERED_CARGO, WC_NONE,
815 std::begin(_nested_delivered_cargo_graph_widgets), std::end(_nested_delivered_cargo_graph_widgets)
818 void ShowDeliveredCargoGraph()
820 AllocateWindowDescFront<DeliveredCargoGraphWindow>(&_delivered_cargo_graph_desc, 0);
823 /***********************/
824 /* PERFORMANCE HISTORY */
825 /***********************/
827 struct PerformanceHistoryGraphWindow : BaseGraphWindow {
828 PerformanceHistoryGraphWindow(WindowDesc *desc, WindowNumber window_number) :
829 BaseGraphWindow(desc, STR_JUST_COMMA)
831 this->num_on_x_axis = GRAPH_NUM_MONTHS;
832 this->num_vert_lines = GRAPH_NUM_MONTHS;
833 this->x_values_start = ECONOMY_QUARTER_MINUTES;
834 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
835 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
837 this->InitializeWindow(window_number);
840 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
842 return c->old_economy[j].performance_history;
845 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
847 if (widget == WID_PHG_DETAILED_PERFORMANCE) ShowPerformanceRatingDetail();
848 this->BaseGraphWindow::OnClick(pt, widget, click_count);
852 static constexpr NWidgetPart _nested_performance_history_widgets[] = {
853 NWidget(NWID_HORIZONTAL),
854 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
855 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_COMPANY_PERFORMANCE_RATINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
856 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_PHG_DETAILED_PERFORMANCE), SetMinimalSize(50, 0), SetDataTip(STR_PERFORMANCE_DETAIL_KEY, STR_GRAPH_PERFORMANCE_DETAIL_TOOLTIP),
857 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
858 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
859 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
860 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
861 EndContainer(),
862 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
863 NWidget(NWID_VERTICAL),
864 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_GRAPH_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
865 NWidget(NWID_HORIZONTAL),
866 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
867 NWidget(WWT_TEXT, COLOUR_BROWN, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_EMPTY, STR_NULL),
868 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
869 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetDataTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
870 EndContainer(),
871 EndContainer(),
872 EndContainer(),
875 static WindowDesc _performance_history_desc(__FILE__, __LINE__,
876 WDP_AUTO, "graph_performance", 0, 0,
877 WC_PERFORMANCE_HISTORY, WC_NONE,
879 std::begin(_nested_performance_history_widgets), std::end(_nested_performance_history_widgets)
882 void ShowPerformanceHistoryGraph()
884 AllocateWindowDescFront<PerformanceHistoryGraphWindow>(&_performance_history_desc, 0);
887 /*****************/
888 /* COMPANY VALUE */
889 /*****************/
891 struct CompanyValueGraphWindow : BaseGraphWindow {
892 CompanyValueGraphWindow(WindowDesc *desc, WindowNumber window_number) :
893 BaseGraphWindow(desc, STR_JUST_CURRENCY_SHORT)
895 this->num_on_x_axis = GRAPH_NUM_MONTHS;
896 this->num_vert_lines = GRAPH_NUM_MONTHS;
897 this->x_values_start = ECONOMY_QUARTER_MINUTES;
898 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
899 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
901 this->InitializeWindow(window_number);
904 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
906 return c->old_economy[j].company_value;
910 static constexpr NWidgetPart _nested_company_value_graph_widgets[] = {
911 NWidget(NWID_HORIZONTAL),
912 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
913 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_COMPANY_VALUES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
914 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
915 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
916 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
917 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
918 EndContainer(),
919 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
920 NWidget(NWID_VERTICAL),
921 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_GRAPH_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
922 NWidget(NWID_HORIZONTAL),
923 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
924 NWidget(WWT_TEXT, COLOUR_BROWN, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_EMPTY, STR_NULL),
925 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
926 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetDataTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
927 EndContainer(),
928 EndContainer(),
929 EndContainer(),
932 static WindowDesc _company_value_graph_desc(__FILE__, __LINE__,
933 WDP_AUTO, "graph_company_value", 0, 0,
934 WC_COMPANY_VALUE, WC_NONE,
936 std::begin(_nested_company_value_graph_widgets), std::end(_nested_company_value_graph_widgets)
939 void ShowCompanyValueGraph()
941 AllocateWindowDescFront<CompanyValueGraphWindow>(&_company_value_graph_desc, 0);
944 /*****************/
945 /* PAYMENT RATES */
946 /*****************/
948 struct PaymentRatesGraphWindow : BaseGraphWindow {
949 uint line_height; ///< Pixel height of each cargo type row.
950 Scrollbar *vscroll; ///< Cargo list scrollbar.
951 uint legend_width; ///< Width of legend 'blob'.
953 PaymentRatesGraphWindow(WindowDesc *desc, WindowNumber window_number) :
954 BaseGraphWindow(desc, STR_JUST_CURRENCY_SHORT)
956 this->num_on_x_axis = 20;
957 this->num_vert_lines = 20;
958 this->draw_dates = false;
959 /* The x-axis is labeled in either seconds or days. A day is two seconds, so we adjust the label if needed. */
960 this->x_values_start = (TimerGameEconomy::UsingWallclockUnits() ? PAYMENT_GRAPH_X_STEP_SECONDS : PAYMENT_GRAPH_X_STEP_DAYS);
961 this->x_values_increment = (TimerGameEconomy::UsingWallclockUnits() ? PAYMENT_GRAPH_X_STEP_SECONDS : PAYMENT_GRAPH_X_STEP_DAYS);
963 this->CreateNestedTree();
964 this->vscroll = this->GetScrollbar(WID_CPR_MATRIX_SCROLLBAR);
965 this->vscroll->SetCount(_sorted_standard_cargo_specs.size());
967 auto *wid = this->GetWidget<NWidgetCore>(WID_GRAPH_FOOTER);
968 wid->SetDataTip(TimerGameEconomy::UsingWallclockUnits() ? STR_GRAPH_CARGO_PAYMENT_RATES_SECONDS: STR_GRAPH_CARGO_PAYMENT_RATES_DAYS, STR_NULL);
970 /* Initialise the dataset */
971 this->UpdatePaymentRates();
973 this->FinishInitNested(window_number);
976 void OnInit() override
978 /* Width of the legend blob. */
979 this->legend_width = GetCharacterHeight(FS_SMALL) * 9 / 6;
982 void UpdateExcludedData()
984 this->excluded_data = 0;
986 int i = 0;
987 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
988 if (HasBit(_legend_excluded_cargo, cs->Index())) SetBit(this->excluded_data, i);
989 i++;
993 void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
995 if (widget != WID_CPR_MATRIX) {
996 BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
997 return;
1000 size->height = GetCharacterHeight(FS_SMALL) + WidgetDimensions::scaled.framerect.Vertical();
1002 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1003 SetDParam(0, cs->name);
1004 Dimension d = GetStringBoundingBox(STR_GRAPH_CARGO_PAYMENT_CARGO);
1005 d.width += this->legend_width + WidgetDimensions::scaled.hsep_normal; // colour field
1006 d.width += WidgetDimensions::scaled.framerect.Horizontal();
1007 d.height += WidgetDimensions::scaled.framerect.Vertical();
1008 *size = maxdim(d, *size);
1011 this->line_height = size->height;
1012 size->height = this->line_height * 11; /* Default number of cargo types in most climates. */
1013 resize->width = 0;
1014 resize->height = this->line_height;
1017 void DrawWidget(const Rect &r, WidgetID widget) const override
1019 if (widget != WID_CPR_MATRIX) {
1020 BaseGraphWindow::DrawWidget(r, widget);
1021 return;
1024 bool rtl = _current_text_dir == TD_RTL;
1026 int pos = this->vscroll->GetPosition();
1027 int max = pos + this->vscroll->GetCapacity();
1029 Rect line = r.WithHeight(this->line_height);
1030 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1031 if (pos-- > 0) continue;
1032 if (--max < 0) break;
1034 bool lowered = !HasBit(_legend_excluded_cargo, cs->Index());
1036 /* Redraw frame if lowered */
1037 if (lowered) DrawFrameRect(line, COLOUR_BROWN, FR_LOWERED);
1039 const Rect text = line.Shrink(WidgetDimensions::scaled.framerect);
1041 /* Cargo-colour box with outline */
1042 const Rect cargo = text.WithWidth(this->legend_width, rtl);
1043 GfxFillRect(cargo, PC_BLACK);
1044 GfxFillRect(cargo.Shrink(WidgetDimensions::scaled.bevel), cs->legend_colour);
1046 /* Cargo name */
1047 SetDParam(0, cs->name);
1048 DrawString(text.Indent(this->legend_width + WidgetDimensions::scaled.hsep_normal, rtl), STR_GRAPH_CARGO_PAYMENT_CARGO);
1050 line = line.Translate(0, this->line_height);
1054 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1056 switch (widget) {
1057 case WID_CPR_ENABLE_CARGOES:
1058 /* Remove all cargoes from the excluded lists. */
1059 _legend_excluded_cargo = 0;
1060 this->excluded_data = 0;
1061 this->SetDirty();
1062 break;
1064 case WID_CPR_DISABLE_CARGOES: {
1065 /* Add all cargoes to the excluded lists. */
1066 int i = 0;
1067 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1068 SetBit(_legend_excluded_cargo, cs->Index());
1069 SetBit(this->excluded_data, i);
1070 i++;
1072 this->SetDirty();
1073 break;
1076 case WID_CPR_MATRIX: {
1077 auto it = this->vscroll->GetScrolledItemFromWidget(_sorted_standard_cargo_specs, pt.y, this, WID_CPR_MATRIX);
1078 if (it != _sorted_standard_cargo_specs.end()) {
1079 ToggleBit(_legend_excluded_cargo, (*it)->Index());
1080 this->UpdateExcludedData();
1081 this->SetDirty();
1082 break;
1084 break;
1089 void OnResize() override
1091 this->vscroll->SetCapacityFromWidget(this, WID_CPR_MATRIX);
1094 void OnGameTick() override
1096 /* Override default OnGameTick */
1100 * Some data on this window has become invalid.
1101 * @param data Information about the changed data.
1102 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1104 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1106 if (!gui_scope) return;
1107 this->UpdatePaymentRates();
1110 /** Update the payment rates on a regular interval. */
1111 IntervalTimer<TimerWindow> update_payment_interval = {std::chrono::seconds(3), [this](auto) {
1112 this->UpdatePaymentRates();
1116 * Update the payment rates according to the latest information.
1118 void UpdatePaymentRates()
1120 this->UpdateExcludedData();
1122 int i = 0;
1123 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1124 this->colours[i] = cs->legend_colour;
1125 for (uint j = 0; j != this->num_on_x_axis; j++) {
1126 this->cost[i][j] = GetTransportedGoodsIncome(10, 20, j * 4 + 4, cs->Index());
1128 i++;
1130 this->num_dataset = i;
1134 static constexpr NWidgetPart _nested_cargo_payment_rates_widgets[] = {
1135 NWidget(NWID_HORIZONTAL),
1136 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1137 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1138 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1139 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1140 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1141 EndContainer(),
1142 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND), SetMinimalSize(568, 128),
1143 NWidget(NWID_HORIZONTAL),
1144 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1145 NWidget(WWT_TEXT, COLOUR_BROWN, WID_GRAPH_HEADER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_TITLE, STR_NULL),
1146 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1147 EndContainer(),
1148 NWidget(NWID_HORIZONTAL),
1149 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_GRAPH_GRAPH), SetMinimalSize(495, 0), SetFill(1, 1), SetResize(1, 1),
1150 NWidget(NWID_VERTICAL),
1151 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1152 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_CPR_ENABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1153 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_CPR_DISABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1154 NWidget(NWID_SPACER), SetMinimalSize(0, 4),
1155 NWidget(NWID_HORIZONTAL),
1156 NWidget(WWT_MATRIX, COLOUR_BROWN, WID_CPR_MATRIX), SetFill(1, 0), SetResize(0, 2), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO), SetScrollbar(WID_CPR_MATRIX_SCROLLBAR),
1157 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_CPR_MATRIX_SCROLLBAR),
1158 EndContainer(),
1159 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1160 EndContainer(),
1161 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1162 EndContainer(),
1163 NWidget(NWID_HORIZONTAL),
1164 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
1165 NWidget(WWT_TEXT, COLOUR_BROWN, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_NULL, STR_NULL),
1166 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1167 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetDataTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
1168 EndContainer(),
1169 EndContainer(),
1172 static WindowDesc _cargo_payment_rates_desc(__FILE__, __LINE__,
1173 WDP_AUTO, "graph_cargo_payment_rates", 0, 0,
1174 WC_PAYMENT_RATES, WC_NONE,
1176 std::begin(_nested_cargo_payment_rates_widgets), std::end(_nested_cargo_payment_rates_widgets)
1180 void ShowCargoPaymentRates()
1182 AllocateWindowDescFront<PaymentRatesGraphWindow>(&_cargo_payment_rates_desc, 0);
1185 /*****************************/
1186 /* PERFORMANCE RATING DETAIL */
1187 /*****************************/
1189 struct PerformanceRatingDetailWindow : Window {
1190 static CompanyID company;
1191 int timeout;
1193 PerformanceRatingDetailWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
1195 this->UpdateCompanyStats();
1197 this->InitNested(window_number);
1198 this->OnInvalidateData(INVALID_COMPANY);
1201 void UpdateCompanyStats()
1203 /* Update all company stats with the current data
1204 * (this is because _score_info is not saved to a savegame) */
1205 for (Company *c : Company::Iterate()) {
1206 UpdateCompanyRatingAndValue(c, false);
1209 this->timeout = Ticks::DAY_TICKS * 5;
1212 uint score_info_left;
1213 uint score_info_right;
1214 uint bar_left;
1215 uint bar_right;
1216 uint bar_width;
1217 uint bar_height;
1218 uint score_detail_left;
1219 uint score_detail_right;
1221 void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
1223 switch (widget) {
1224 case WID_PRD_SCORE_FIRST:
1225 this->bar_height = GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.fullbevel.Vertical();
1226 size->height = this->bar_height + WidgetDimensions::scaled.matrix.Vertical();
1228 uint score_info_width = 0;
1229 for (uint i = SCORE_BEGIN; i < SCORE_END; i++) {
1230 score_info_width = std::max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + i).width);
1232 SetDParamMaxValue(0, 1000);
1233 score_info_width += GetStringBoundingBox(STR_JUST_COMMA).width + WidgetDimensions::scaled.hsep_wide;
1235 SetDParamMaxValue(0, 100);
1236 this->bar_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_PERCENT).width + WidgetDimensions::scaled.hsep_indent * 2; // Wide bars!
1238 /* At this number we are roughly at the max; it can become wider,
1239 * but then you need at 1000 times more money. At that time you're
1240 * not that interested anymore in the last few digits anyway.
1241 * The 500 is because 999 999 500 to 999 999 999 are rounded to
1242 * 1 000 M, and not 999 999 k. Use negative numbers to account for
1243 * the negative income/amount of money etc. as well. */
1244 int max = -(999999999 - 500);
1246 /* Scale max for the display currency. Prior to rendering the value
1247 * is converted into the display currency, which may cause it to
1248 * raise significantly. We need to compensate for that since {{CURRCOMPACT}}
1249 * is used, which can produce quite short renderings of very large
1250 * values. Otherwise the calculated width could be too narrow.
1251 * Note that it doesn't work if there was a currency with an exchange
1252 * rate greater than max.
1253 * When the currency rate is more than 1000, the 999 999 k becomes at
1254 * least 999 999 M which roughly is equally long. Furthermore if the
1255 * exchange rate is that high, 999 999 k is usually not enough anymore
1256 * to show the different currency numbers. */
1257 if (_currency->rate < 1000) max /= _currency->rate;
1258 SetDParam(0, max);
1259 SetDParam(1, max);
1260 uint score_detail_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY).width;
1262 size->width = WidgetDimensions::scaled.frametext.Horizontal() + score_info_width + WidgetDimensions::scaled.hsep_wide + this->bar_width + WidgetDimensions::scaled.hsep_wide + score_detail_width;
1263 uint left = WidgetDimensions::scaled.frametext.left;
1264 uint right = size->width - WidgetDimensions::scaled.frametext.right;
1266 bool rtl = _current_text_dir == TD_RTL;
1267 this->score_info_left = rtl ? right - score_info_width : left;
1268 this->score_info_right = rtl ? right : left + score_info_width;
1270 this->score_detail_left = rtl ? left : right - score_detail_width;
1271 this->score_detail_right = rtl ? left + score_detail_width : right;
1273 this->bar_left = left + (rtl ? score_detail_width : score_info_width) + WidgetDimensions::scaled.hsep_wide;
1274 this->bar_right = this->bar_left + this->bar_width - 1;
1275 break;
1279 void DrawWidget(const Rect &r, WidgetID widget) const override
1281 /* No need to draw when there's nothing to draw */
1282 if (this->company == INVALID_COMPANY) return;
1284 if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
1285 if (this->IsWidgetDisabled(widget)) return;
1286 CompanyID cid = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1287 Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
1288 DrawCompanyIcon(cid, CenterBounds(r.left, r.right, sprite_size.width), CenterBounds(r.top, r.bottom, sprite_size.height));
1289 return;
1292 if (!IsInsideMM(widget, WID_PRD_SCORE_FIRST, WID_PRD_SCORE_LAST + 1)) return;
1294 ScoreID score_type = (ScoreID)(widget - WID_PRD_SCORE_FIRST);
1296 /* The colours used to show how the progress is going */
1297 int colour_done = _colour_gradient[COLOUR_GREEN][4];
1298 int colour_notdone = _colour_gradient[COLOUR_RED][4];
1300 /* Draw all the score parts */
1301 int64_t val = _score_part[company][score_type];
1302 int64_t needed = _score_info[score_type].needed;
1303 int score = _score_info[score_type].score;
1305 /* SCORE_TOTAL has its own rules ;) */
1306 if (score_type == SCORE_TOTAL) {
1307 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) score += _score_info[i].score;
1308 needed = SCORE_MAX;
1311 uint bar_top = CenterBounds(r.top, r.bottom, this->bar_height);
1312 uint text_top = CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL));
1314 DrawString(this->score_info_left, this->score_info_right, text_top, STR_PERFORMANCE_DETAIL_VEHICLES + score_type);
1316 /* Draw the score */
1317 SetDParam(0, score);
1318 DrawString(this->score_info_left, this->score_info_right, text_top, STR_JUST_COMMA, TC_BLACK, SA_RIGHT);
1320 /* Calculate the %-bar */
1321 uint x = Clamp<int64_t>(val, 0, needed) * this->bar_width / needed;
1322 bool rtl = _current_text_dir == TD_RTL;
1323 if (rtl) {
1324 x = this->bar_right - x;
1325 } else {
1326 x = this->bar_left + x;
1329 /* Draw the bar */
1330 if (x != this->bar_left) GfxFillRect(this->bar_left, bar_top, x, bar_top + this->bar_height - 1, rtl ? colour_notdone : colour_done);
1331 if (x != this->bar_right) GfxFillRect(x, bar_top, this->bar_right, bar_top + this->bar_height - 1, rtl ? colour_done : colour_notdone);
1333 /* Draw it */
1334 SetDParam(0, Clamp<int64_t>(val, 0, needed) * 100 / needed);
1335 DrawString(this->bar_left, this->bar_right, text_top, STR_PERFORMANCE_DETAIL_PERCENT, TC_FROMSTRING, SA_HOR_CENTER);
1337 /* SCORE_LOAN is inversed */
1338 if (score_type == SCORE_LOAN) val = needed - val;
1340 /* Draw the amount we have against what is needed
1341 * For some of them it is in currency format */
1342 SetDParam(0, val);
1343 SetDParam(1, needed);
1344 switch (score_type) {
1345 case SCORE_MIN_PROFIT:
1346 case SCORE_MIN_INCOME:
1347 case SCORE_MAX_INCOME:
1348 case SCORE_MONEY:
1349 case SCORE_LOAN:
1350 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY);
1351 break;
1352 default:
1353 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_INT);
1357 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1359 /* Check which button is clicked */
1360 if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
1361 /* Is it no on disable? */
1362 if (!this->IsWidgetDisabled(widget)) {
1363 this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company);
1364 this->company = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1365 this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company);
1366 this->SetDirty();
1371 void OnGameTick() override
1373 /* Update the company score every 5 days */
1374 if (--this->timeout == 0) {
1375 this->UpdateCompanyStats();
1376 this->SetDirty();
1381 * Some data on this window has become invalid.
1382 * @param data the company ID of the company that is going to be removed
1383 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1385 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1387 if (!gui_scope) return;
1388 /* Disable the companies who are not active */
1389 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
1390 this->SetWidgetDisabledState(WID_PRD_COMPANY_FIRST + i, !Company::IsValidID(i));
1393 /* Check if the currently selected company is still active. */
1394 if (this->company != INVALID_COMPANY && !Company::IsValidID(this->company)) {
1395 /* Raise the widget for the previous selection. */
1396 this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company);
1397 this->company = INVALID_COMPANY;
1400 if (this->company == INVALID_COMPANY) {
1401 for (const Company *c : Company::Iterate()) {
1402 this->company = c->index;
1403 break;
1407 /* Make sure the widget is lowered */
1408 this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company);
1412 CompanyID PerformanceRatingDetailWindow::company = INVALID_COMPANY;
1415 * Make a vertical list of panels for outputting score details.
1416 * @return Panel with performance details.
1418 static std::unique_ptr<NWidgetBase> MakePerformanceDetailPanels()
1420 auto realtime = TimerGameEconomy::UsingWallclockUnits();
1421 const StringID performance_tips[] = {
1422 realtime ? STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP_PERIODS : STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP_YEARS,
1423 STR_PERFORMANCE_DETAIL_STATIONS_TOOLTIP,
1424 realtime ? STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP_PERIODS : STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP_YEARS,
1425 STR_PERFORMANCE_DETAIL_MIN_INCOME_TOOLTIP,
1426 STR_PERFORMANCE_DETAIL_MAX_INCOME_TOOLTIP,
1427 STR_PERFORMANCE_DETAIL_DELIVERED_TOOLTIP,
1428 STR_PERFORMANCE_DETAIL_CARGO_TOOLTIP,
1429 STR_PERFORMANCE_DETAIL_MONEY_TOOLTIP,
1430 STR_PERFORMANCE_DETAIL_LOAN_TOOLTIP,
1431 STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP,
1434 static_assert(lengthof(performance_tips) == SCORE_END - SCORE_BEGIN);
1436 auto vert = std::make_unique<NWidgetVertical>(NC_EQUALSIZE);
1437 for (WidgetID widnum = WID_PRD_SCORE_FIRST; widnum <= WID_PRD_SCORE_LAST; widnum++) {
1438 auto panel = std::make_unique<NWidgetBackground>(WWT_PANEL, COLOUR_BROWN, widnum);
1439 panel->SetFill(1, 1);
1440 panel->SetDataTip(0x0, performance_tips[widnum - WID_PRD_SCORE_FIRST]);
1441 vert->Add(std::move(panel));
1443 return vert;
1446 /** Make a number of rows with buttons for each company for the performance rating detail window. */
1447 std::unique_ptr<NWidgetBase> MakeCompanyButtonRowsGraphGUI()
1449 return MakeCompanyButtonRows(WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST, COLOUR_BROWN, 8, STR_PERFORMANCE_DETAIL_SELECT_COMPANY_TOOLTIP);
1452 static constexpr NWidgetPart _nested_performance_rating_detail_widgets[] = {
1453 NWidget(NWID_HORIZONTAL),
1454 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1455 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_PERFORMANCE_DETAIL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1456 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1457 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1458 EndContainer(),
1459 NWidget(WWT_PANEL, COLOUR_BROWN),
1460 NWidgetFunction(MakeCompanyButtonRowsGraphGUI), SetPadding(2),
1461 EndContainer(),
1462 NWidgetFunction(MakePerformanceDetailPanels),
1465 static WindowDesc _performance_rating_detail_desc(__FILE__, __LINE__,
1466 WDP_AUTO, "league_details", 0, 0,
1467 WC_PERFORMANCE_DETAIL, WC_NONE,
1469 std::begin(_nested_performance_rating_detail_widgets), std::end(_nested_performance_rating_detail_widgets)
1472 void ShowPerformanceRatingDetail()
1474 AllocateWindowDescFront<PerformanceRatingDetailWindow>(&_performance_rating_detail_desc, 0);
1477 void InitializeGraphGui()
1479 _legend_excluded_companies = 0;
1480 _legend_excluded_cargo = 0;