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 */
7
8 /** @file graph_gui.cpp GUI that shows performance graphs. */
9
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 "date_func.h"
20 #include "gfx_func.h"
21 #include "sortlist_type.h"
22 #include "core/geometry_func.hpp"
23 #include "currency.h"
24 #include "zoom_func.h"
25
26 #include "widgets/graph_widget.h"
27
28 #include "table/strings.h"
29 #include "table/sprites.h"
30 #include <math.h>
31
32 #include "safeguards.h"
33
34 /* Bitmasks of company and cargo indices that shouldn't be drawn. */
35 static CompanyMask _legend_excluded_companies;
36 static CargoTypes _legend_excluded_cargo;
37
38 /* Apparently these don't play well with enums. */
39 static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX); // Value used for a datapoint that shouldn't be drawn.
40 static const uint INVALID_DATAPOINT_POS = UINT_MAX; // Used to determine if the previous point was drawn.
41
42 /****************/
43 /* GRAPH LEGEND */
44 /****************/
45
46 struct GraphLegendWindow : Window {
GraphLegendWindowGraphLegendWindow47 GraphLegendWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
48 {
49 this->InitNested(window_number);
50
51 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
52 if (!HasBit(_legend_excluded_companies, c)) this->LowerWidget(c + WID_GL_FIRST_COMPANY);
53
54 this->OnInvalidateData(c);
55 }
56 }
57
DrawWidgetGraphLegendWindow58 void DrawWidget(const Rect &r, int widget) const override
59 {
60 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, MAX_COMPANIES + WID_GL_FIRST_COMPANY)) return;
61
62 CompanyID cid = (CompanyID)(widget - WID_GL_FIRST_COMPANY);
63
64 if (!Company::IsValidID(cid)) return;
65
66 bool rtl = _current_text_dir == TD_RTL;
67
68 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
69 DrawCompanyIcon(cid, rtl ? r.right - d.width - ScaleGUITrad(2) : r.left + ScaleGUITrad(2), CenterBounds(r.top, r.bottom, d.height));
70
71 SetDParam(0, cid);
72 SetDParam(1, cid);
73 DrawString(r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : (d.width + ScaleGUITrad(4))), r.right - (rtl ? (d.width + ScaleGUITrad(4)) : (uint)WD_FRAMERECT_RIGHT), CenterBounds(r.top, r.bottom, FONT_HEIGHT_NORMAL), STR_COMPANY_NAME_COMPANY_NUM, HasBit(_legend_excluded_companies, cid) ? TC_BLACK : TC_WHITE);
74 }
75
OnClickGraphLegendWindow76 void OnClick(Point pt, int widget, int click_count) override
77 {
78 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, MAX_COMPANIES + WID_GL_FIRST_COMPANY)) return;
79
80 ToggleBit(_legend_excluded_companies, widget - WID_GL_FIRST_COMPANY);
81 this->ToggleWidgetLoweredState(widget);
82 this->SetDirty();
83 InvalidateWindowData(WC_INCOME_GRAPH, 0);
84 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
85 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
86 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
87 InvalidateWindowData(WC_COMPANY_VALUE, 0);
88 }
89
90 /**
91 * Some data on this window has become invalid.
92 * @param data Information about the changed data.
93 * @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.
94 */
OnInvalidateDataGraphLegendWindow95 void OnInvalidateData(int data = 0, bool gui_scope = true) override
96 {
97 if (!gui_scope) return;
98 if (Company::IsValidID(data)) return;
99
100 SetBit(_legend_excluded_companies, data);
101 this->RaiseWidget(data + WID_GL_FIRST_COMPANY);
102 }
103 };
104
105 /**
106 * Construct a vertical list of buttons, one for each company.
107 * @param biggest_index Storage for collecting the biggest index used in the returned tree.
108 * @return Panel with company buttons.
109 * @post \c *biggest_index contains the largest used index in the tree.
110 */
MakeNWidgetCompanyLines(int * biggest_index)111 static NWidgetBase *MakeNWidgetCompanyLines(int *biggest_index)
112 {
113 NWidgetVertical *vert = new NWidgetVertical();
114 uint sprite_height = GetSpriteSize(SPR_COMPANY_ICON, nullptr, ZOOM_LVL_OUT_4X).height;
115
116 for (int widnum = WID_GL_FIRST_COMPANY; widnum <= WID_GL_LAST_COMPANY; widnum++) {
117 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_BROWN, widnum);
118 panel->SetMinimalSize(246, sprite_height);
119 panel->SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM, FS_NORMAL);
120 panel->SetFill(1, 0);
121 panel->SetDataTip(0x0, STR_GRAPH_KEY_COMPANY_SELECTION_TOOLTIP);
122 vert->Add(panel);
123 }
124 *biggest_index = WID_GL_LAST_COMPANY;
125 return vert;
126 }
127
128 static const NWidgetPart _nested_graph_legend_widgets[] = {
129 NWidget(NWID_HORIZONTAL),
130 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
131 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_KEY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
132 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
133 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
134 EndContainer(),
135 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GL_BACKGROUND),
136 NWidget(NWID_SPACER), SetMinimalSize(0, 2),
137 NWidget(NWID_HORIZONTAL),
138 NWidget(NWID_SPACER), SetMinimalSize(2, 0),
139 NWidgetFunction(MakeNWidgetCompanyLines),
140 NWidget(NWID_SPACER), SetMinimalSize(2, 0),
141 EndContainer(),
142 NWidget(NWID_SPACER), SetMinimalSize(0, 2),
143 EndContainer(),
144 };
145
146 static WindowDesc _graph_legend_desc(
147 WDP_AUTO, "graph_legend", 0, 0,
148 WC_GRAPH_LEGEND, WC_NONE,
149 0,
150 _nested_graph_legend_widgets, lengthof(_nested_graph_legend_widgets)
151 );
152
ShowGraphLegend()153 static void ShowGraphLegend()
154 {
155 AllocateWindowDescFront<GraphLegendWindow>(&_graph_legend_desc, 0);
156 }
157
158 /** Contains the interval of a graph's data. */
159 struct ValuesInterval {
160 OverflowSafeInt64 highest; ///< Highest value of this interval. Must be zero or greater.
161 OverflowSafeInt64 lowest; ///< Lowest value of this interval. Must be zero or less.
162 };
163
164 /******************/
165 /* BASE OF GRAPHS */
166 /*****************/
167
168 struct BaseGraphWindow : Window {
169 protected:
170 static const int GRAPH_MAX_DATASETS = 64;
171 static const int GRAPH_BASE_COLOUR = GREY_SCALE(2);
172 static const int GRAPH_GRID_COLOUR = GREY_SCALE(3);
173 static const int GRAPH_AXIS_LINE_COLOUR = GREY_SCALE(1);
174 static const int GRAPH_ZERO_LINE_COLOUR = GREY_SCALE(8);
175 static const int GRAPH_YEAR_LINE_COLOUR = GREY_SCALE(5);
176 static const int GRAPH_NUM_MONTHS = 24; ///< Number of months displayed in the graph.
177
178 static const TextColour GRAPH_AXIS_LABEL_COLOUR = TC_BLACK; ///< colour of the graph axis label.
179
180 static const int MIN_GRAPH_NUM_LINES_Y = 9; ///< Minimal number of horizontal lines to draw.
181 static const int MIN_GRID_PIXEL_SIZE = 20; ///< Minimum distance between graph lines.
182
183 uint64 excluded_data; ///< bitmask of the datasets that shouldn't be displayed.
184 byte num_dataset;
185 byte num_on_x_axis;
186 byte num_vert_lines;
187
188 /* The starting month and year that values are plotted against. If month is
189 * 0xFF, use x_values_start and x_values_increment below instead. */
190 byte month;
191 Year year;
192
193 /* These values are used if the graph is being plotted against values
194 * rather than the dates specified by month and year. */
195 uint16 x_values_start;
196 uint16 x_values_increment;
197
198 int graph_widget;
199 StringID format_str_y_axis;
200 byte colours[GRAPH_MAX_DATASETS];
201 OverflowSafeInt64 cost[GRAPH_MAX_DATASETS][GRAPH_NUM_MONTHS]; ///< Stored costs for the last #GRAPH_NUM_MONTHS months
202
203 /**
204 * Get the interval that contains the graph's data. Excluded data is ignored to show smaller values in
205 * better detail when disabling higher ones.
206 * @param num_hori_lines Number of horizontal lines to be drawn.
207 * @return Highest and lowest values of the graph (ignoring disabled data).
208 */
GetValuesIntervalBaseGraphWindow209 ValuesInterval GetValuesInterval(int num_hori_lines) const
210 {
211 assert(num_hori_lines > 0);
212
213 ValuesInterval current_interval;
214 current_interval.highest = INT64_MIN;
215 current_interval.lowest = INT64_MAX;
216
217 for (int i = 0; i < this->num_dataset; i++) {
218 if (HasBit(this->excluded_data, i)) continue;
219 for (int j = 0; j < this->num_on_x_axis; j++) {
220 OverflowSafeInt64 datapoint = this->cost[i][j];
221
222 if (datapoint != INVALID_DATAPOINT) {
223 current_interval.highest = std::max(current_interval.highest, datapoint);
224 current_interval.lowest = std::min(current_interval.lowest, datapoint);
225 }
226 }
227 }
228
229 /* Prevent showing values too close to the graph limits. */
230 current_interval.highest = (11 * current_interval.highest) / 10;
231 current_interval.lowest = (11 * current_interval.lowest) / 10;
232
233 /* Always include zero in the shown range. */
234 double abs_lower = (current_interval.lowest > 0) ? 0 : (double)abs(current_interval.lowest);
235 double abs_higher = (current_interval.highest < 0) ? 0 : (double)current_interval.highest;
236
237 int num_pos_grids;
238 int64 grid_size;
239
240 if (abs_lower != 0 || abs_higher != 0) {
241 /* The number of grids to reserve for the positive part is: */
242 num_pos_grids = (int)floor(0.5 + num_hori_lines * abs_higher / (abs_higher + abs_lower));
243
244 /* If there are any positive or negative values, force that they have at least one grid. */
245 if (num_pos_grids == 0 && abs_higher != 0) num_pos_grids++;
246 if (num_pos_grids == num_hori_lines && abs_lower != 0) num_pos_grids--;
247
248 /* Get the required grid size for each side and use the maximum one. */
249 int64 grid_size_higher = (abs_higher > 0) ? ((int64)abs_higher + num_pos_grids - 1) / num_pos_grids : 0;
250 int64 grid_size_lower = (abs_lower > 0) ? ((int64)abs_lower + num_hori_lines - num_pos_grids - 1) / (num_hori_lines - num_pos_grids) : 0;
251 grid_size = std::max(grid_size_higher, grid_size_lower);
252 } else {
253 /* If both values are zero, show an empty graph. */
254 num_pos_grids = num_hori_lines / 2;
255 grid_size = 1;
256 }
257
258 current_interval.highest = num_pos_grids * grid_size;
259 current_interval.lowest = -(num_hori_lines - num_pos_grids) * grid_size;
260 return current_interval;
261 }
262
263 /**
264 * Get width for Y labels.
265 * @param current_interval Interval that contains all of the graph data.
266 * @param num_hori_lines Number of horizontal lines to be drawn.
267 */
GetYLabelWidthBaseGraphWindow268 uint GetYLabelWidth(ValuesInterval current_interval, int num_hori_lines) const
269 {
270 /* draw text strings on the y axis */
271 int64 y_label = current_interval.highest;
272 int64 y_label_separation = (current_interval.highest - current_interval.lowest) / num_hori_lines;
273
274 uint max_width = 0;
275
276 for (int i = 0; i < (num_hori_lines + 1); i++) {
277 SetDParam(0, this->format_str_y_axis);
278 SetDParam(1, y_label);
279 Dimension d = GetStringBoundingBox(STR_GRAPH_Y_LABEL);
280 if (d.width > max_width) max_width = d.width;
281
282 y_label -= y_label_separation;
283 }
284
285 return max_width;
286 }
287
288 /**
289 * Actually draw the graph.
290 * @param r the rectangle of the data field of the graph
291 */
DrawGraphBaseGraphWindow292 void DrawGraph(Rect r) const
293 {
294 uint x, y; ///< Reused whenever x and y coordinates are needed.
295 ValuesInterval interval; ///< Interval that contains all of the graph data.
296 int x_axis_offset; ///< Distance from the top of the graph to the x axis.
297
298 /* the colours and cost array of GraphDrawer must accommodate
299 * both values for cargo and companies. So if any are higher, quit */
300 static_assert(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES);
301 assert(this->num_vert_lines > 0);
302
303 /* Rect r will be adjusted to contain just the graph, with labels being
304 * placed outside the area. */
305 r.top += 5 + GetCharacterHeight(FS_SMALL) / 2;
306 r.bottom -= (this->month == 0xFF ? 1 : 2) * GetCharacterHeight(FS_SMALL) + 4;
307 r.left += 9;
308 r.right -= 5;
309
310 /* Initial number of horizontal lines. */
311 int num_hori_lines = 160 / MIN_GRID_PIXEL_SIZE;
312 /* For the rest of the height, the number of horizontal lines will increase more slowly. */
313 int resize = (r.bottom - r.top - 160) / (2 * MIN_GRID_PIXEL_SIZE);
314 if (resize > 0) num_hori_lines += resize;
315
316 interval = GetValuesInterval(num_hori_lines);
317
318 int label_width = GetYLabelWidth(interval, num_hori_lines);
319
320 r.left += label_width;
321
322 int x_sep = (r.right - r.left) / this->num_vert_lines;
323 int y_sep = (r.bottom - r.top) / num_hori_lines;
324
325 /* Redetermine right and bottom edge of graph to fit with the integer
326 * separation values. */
327 r.right = r.left + x_sep * this->num_vert_lines;
328 r.bottom = r.top + y_sep * num_hori_lines;
329
330 OverflowSafeInt64 interval_size = interval.highest + abs(interval.lowest);
331 /* Where to draw the X axis. Use floating point to avoid overflowing and results of zero. */
332 x_axis_offset = (int)((r.bottom - r.top) * (double)interval.highest / (double)interval_size);
333
334 /* Draw the background of the graph itself. */
335 GfxFillRect(r.left, r.top, r.right, r.bottom, GRAPH_BASE_COLOUR);
336
337 /* Draw the vertical grid lines. */
338
339 /* Don't draw the first line, as that's where the axis will be. */
340 x = r.left + x_sep;
341
342 for (int i = 0; i < this->num_vert_lines; i++) {
343 GfxFillRect(x, r.top, x, r.bottom, GRAPH_GRID_COLOUR);
344 x += x_sep;
345 }
346
347 /* Draw the horizontal grid lines. */
348 y = r.bottom;
349
350 for (int i = 0; i < (num_hori_lines + 1); i++) {
351 GfxFillRect(r.left - 3, y, r.left - 1, y, GRAPH_AXIS_LINE_COLOUR);
352 GfxFillRect(r.left, y, r.right, y, GRAPH_GRID_COLOUR);
353 y -= y_sep;
354 }
355
356 /* Draw the y axis. */
357 GfxFillRect(r.left, r.top, r.left, r.bottom, GRAPH_AXIS_LINE_COLOUR);
358
359 /* Draw the x axis. */
360 y = x_axis_offset + r.top;
361 GfxFillRect(r.left, y, r.right, y, GRAPH_ZERO_LINE_COLOUR);
362
363 /* Find the largest value that will be drawn. */
364 if (this->num_on_x_axis == 0) return;
365
366 assert(this->num_on_x_axis > 0);
367 assert(this->num_dataset > 0);
368
369 /* draw text strings on the y axis */
370 int64 y_label = interval.highest;
371 int64 y_label_separation = abs(interval.highest - interval.lowest) / num_hori_lines;
372
373 y = r.top - GetCharacterHeight(FS_SMALL) / 2;
374
375 for (int i = 0; i < (num_hori_lines + 1); i++) {
376 SetDParam(0, this->format_str_y_axis);
377 SetDParam(1, y_label);
378 DrawString(r.left - label_width - 4, r.left - 4, y, STR_GRAPH_Y_LABEL, GRAPH_AXIS_LABEL_COLOUR, SA_RIGHT);
379
380 y_label -= y_label_separation;
381 y += y_sep;
382 }
383
384 /* Draw x-axis labels and markings for graphs based on financial quarters and years. */
385 if (this->month != 0xFF) {
386 x = r.left;
387 y = r.bottom + 2;
388 byte month = this->month;
389 Year year = this->year;
390 for (int i = 0; i < this->num_on_x_axis; i++) {
391 SetDParam(0, month + STR_MONTH_ABBREV_JAN);
392 SetDParam(1, year);
393 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);
394
395 month += 3;
396 if (month >= 12) {
397 month = 0;
398 year++;
399
400 /* Draw a lighter grid line between years. Top and bottom adjustments ensure we don't draw over top and bottom horizontal grid lines. */
401 GfxFillRect(x + x_sep, r.top + 1, x + x_sep, r.bottom - 1, GRAPH_YEAR_LINE_COLOUR);
402 }
403 x += x_sep;
404 }
405 } else {
406 /* Draw x-axis labels for graphs not based on quarterly performance (cargo payment rates). */
407 x = r.left;
408 y = r.bottom + 2;
409 uint16 label = this->x_values_start;
410
411 for (int i = 0; i < this->num_on_x_axis; i++) {
412 SetDParam(0, label);
413 DrawString(x + 1, x + x_sep - 1, y, STR_GRAPH_Y_LABEL_NUMBER, GRAPH_AXIS_LABEL_COLOUR, SA_HOR_CENTER);
414
415 label += this->x_values_increment;
416 x += x_sep;
417 }
418 }
419
420 /* draw lines and dots */
421 uint linewidth = _settings_client.gui.graph_line_thickness;
422 uint pointoffs1 = (linewidth + 1) / 2;
423 uint pointoffs2 = linewidth + 1 - pointoffs1;
424 for (int i = 0; i < this->num_dataset; i++) {
425 if (!HasBit(this->excluded_data, i)) {
426 /* Centre the dot between the grid lines. */
427 x = r.left + (x_sep / 2);
428
429 byte colour = this->colours[i];
430 uint prev_x = INVALID_DATAPOINT_POS;
431 uint prev_y = INVALID_DATAPOINT_POS;
432
433 for (int j = 0; j < this->num_on_x_axis; j++) {
434 OverflowSafeInt64 datapoint = this->cost[i][j];
435
436 if (datapoint != INVALID_DATAPOINT) {
437 /*
438 * Check whether we need to reduce the 'accuracy' of the
439 * datapoint value and the highest value to split overflows.
440 * And when 'drawing' 'one million' or 'one million and one'
441 * there is no significant difference, so the least
442 * significant bits can just be removed.
443 *
444 * If there are more bits needed than would fit in a 32 bits
445 * integer, so at about 31 bits because of the sign bit, the
446 * least significant bits are removed.
447 */
448 int mult_range = FindLastBit(x_axis_offset) + FindLastBit(abs(datapoint));
449 int reduce_range = std::max(mult_range - 31, 0);
450
451 /* Handle negative values differently (don't shift sign) */
452 if (datapoint < 0) {
453 datapoint = -(abs(datapoint) >> reduce_range);
454 } else {
455 datapoint >>= reduce_range;
456 }
457 y = r.top + x_axis_offset - ((r.bottom - r.top) * datapoint) / (interval_size >> reduce_range);
458
459 /* Draw the point. */
460 GfxFillRect(x - pointoffs1, y - pointoffs1, x + pointoffs2, y + pointoffs2, colour);
461
462 /* Draw the line connected to the previous point. */
463 if (prev_x != INVALID_DATAPOINT_POS) GfxDrawLine(prev_x, prev_y, x, y, colour, linewidth);
464
465 prev_x = x;
466 prev_y = y;
467 } else {
468 prev_x = INVALID_DATAPOINT_POS;
469 prev_y = INVALID_DATAPOINT_POS;
470 }
471
472 x += x_sep;
473 }
474 }
475 }
476 }
477
478
BaseGraphWindowBaseGraphWindow479 BaseGraphWindow(WindowDesc *desc, int widget, StringID format_str_y_axis) :
480 Window(desc),
481 format_str_y_axis(format_str_y_axis)
482 {
483 SetWindowDirty(WC_GRAPH_LEGEND, 0);
484 this->num_vert_lines = 24;
485 this->graph_widget = widget;
486 }
487
InitializeWindowBaseGraphWindow488 void InitializeWindow(WindowNumber number)
489 {
490 /* Initialise the dataset */
491 this->UpdateStatistics(true);
492
493 this->InitNested(number);
494 }
495
496 public:
UpdateWidgetSizeBaseGraphWindow497 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
498 {
499 if (widget != this->graph_widget) return;
500
501 uint x_label_width = 0;
502
503 /* Draw x-axis labels and markings for graphs based on financial quarters and years. */
504 if (this->month != 0xFF) {
505 byte month = this->month;
506 Year year = this->year;
507 for (int i = 0; i < this->num_on_x_axis; i++) {
508 SetDParam(0, month + STR_MONTH_ABBREV_JAN);
509 SetDParam(1, year);
510 x_label_width = std::max(x_label_width, GetStringBoundingBox(month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH).width);
511
512 month += 3;
513 if (month >= 12) {
514 month = 0;
515 year++;
516 }
517 }
518 } else {
519 /* Draw x-axis labels for graphs not based on quarterly performance (cargo payment rates). */
520 SetDParamMaxValue(0, this->x_values_start + this->num_on_x_axis * this->x_values_increment, 0, FS_SMALL);
521 x_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL_NUMBER).width;
522 }
523
524 SetDParam(0, this->format_str_y_axis);
525 SetDParam(1, INT64_MAX);
526 uint y_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL).width;
527
528 size->width = std::max<uint>(size->width, 5 + y_label_width + this->num_on_x_axis * (x_label_width + 5) + 9);
529 size->height = std::max<uint>(size->height, 5 + (1 + MIN_GRAPH_NUM_LINES_Y * 2 + (this->month != 0xFF ? 3 : 1)) * FONT_HEIGHT_SMALL + 4);
530 size->height = std::max<uint>(size->height, size->width / 3);
531 }
532
DrawWidgetBaseGraphWindow533 void DrawWidget(const Rect &r, int widget) const override
534 {
535 if (widget != this->graph_widget) return;
536
537 DrawGraph(r);
538 }
539
GetGraphDataBaseGraphWindow540 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
541 {
542 return INVALID_DATAPOINT;
543 }
544
OnClickBaseGraphWindow545 void OnClick(Point pt, int widget, int click_count) override
546 {
547 /* Clicked on legend? */
548 if (widget == WID_CV_KEY_BUTTON) ShowGraphLegend();
549 }
550
OnGameTickBaseGraphWindow551 void OnGameTick() override
552 {
553 this->UpdateStatistics(false);
554 }
555
556 /**
557 * Some data on this window has become invalid.
558 * @param data Information about the changed data.
559 * @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.
560 */
OnInvalidateDataBaseGraphWindow561 void OnInvalidateData(int data = 0, bool gui_scope = true) override
562 {
563 if (!gui_scope) return;
564 this->UpdateStatistics(true);
565 }
566
567 /**
568 * Update the statistics.
569 * @param initialize Initialize the data structure.
570 */
UpdateStatisticsBaseGraphWindow571 void UpdateStatistics(bool initialize)
572 {
573 CompanyMask excluded_companies = _legend_excluded_companies;
574
575 /* Exclude the companies which aren't valid */
576 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
577 if (!Company::IsValidID(c)) SetBit(excluded_companies, c);
578 }
579
580 byte nums = 0;
581 for (const Company *c : Company::Iterate()) {
582 nums = std::min(this->num_vert_lines, std::max(nums, c->num_valid_stat_ent));
583 }
584
585 int mo = (_cur_month / 3 - nums) * 3;
586 int yr = _cur_year;
587 while (mo < 0) {
588 yr--;
589 mo += 12;
590 }
591
592 if (!initialize && this->excluded_data == excluded_companies && this->num_on_x_axis == nums &&
593 this->year == yr && this->month == mo) {
594 /* There's no reason to get new stats */
595 return;
596 }
597
598 this->excluded_data = excluded_companies;
599 this->num_on_x_axis = nums;
600 this->year = yr;
601 this->month = mo;
602
603 int numd = 0;
604 for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; k++) {
605 const Company *c = Company::GetIfValid(k);
606 if (c != nullptr) {
607 this->colours[numd] = _colour_gradient[c->colour][6];
608 for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
609 this->cost[numd][i] = (j >= c->num_valid_stat_ent) ? INVALID_DATAPOINT : GetGraphData(c, j);
610 i++;
611 }
612 }
613 numd++;
614 }
615
616 this->num_dataset = numd;
617 }
618 };
619
620
621 /********************/
622 /* OPERATING PROFIT */
623 /********************/
624
625 struct OperatingProfitGraphWindow : BaseGraphWindow {
OperatingProfitGraphWindowOperatingProfitGraphWindow626 OperatingProfitGraphWindow(WindowDesc *desc, WindowNumber window_number) :
627 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
628 {
629 this->InitializeWindow(window_number);
630 }
631
GetGraphDataOperatingProfitGraphWindow632 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
633 {
634 return c->old_economy[j].income + c->old_economy[j].expenses;
635 }
636 };
637
638 static const NWidgetPart _nested_operating_profit_widgets[] = {
639 NWidget(NWID_HORIZONTAL),
640 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
641 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_OPERATING_PROFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
642 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_CV_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
643 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
644 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
645 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
646 EndContainer(),
647 NWidget(WWT_PANEL, COLOUR_BROWN, WID_CV_BACKGROUND),
648 NWidget(NWID_HORIZONTAL),
649 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_CV_GRAPH), SetMinimalSize(576, 160), SetFill(1, 1), SetResize(1, 1),
650 NWidget(NWID_VERTICAL),
651 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
652 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_CV_RESIZE),
653 EndContainer(),
654 EndContainer(),
655 EndContainer(),
656 };
657
658 static WindowDesc _operating_profit_desc(
659 WDP_AUTO, "graph_operating_profit", 0, 0,
660 WC_OPERATING_PROFIT, WC_NONE,
661 0,
662 _nested_operating_profit_widgets, lengthof(_nested_operating_profit_widgets)
663 );
664
665
ShowOperatingProfitGraph()666 void ShowOperatingProfitGraph()
667 {
668 AllocateWindowDescFront<OperatingProfitGraphWindow>(&_operating_profit_desc, 0);
669 }
670
671
672 /****************/
673 /* INCOME GRAPH */
674 /****************/
675
676 struct IncomeGraphWindow : BaseGraphWindow {
IncomeGraphWindowIncomeGraphWindow677 IncomeGraphWindow(WindowDesc *desc, WindowNumber window_number) :
678 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
679 {
680 this->InitializeWindow(window_number);
681 }
682
GetGraphDataIncomeGraphWindow683 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
684 {
685 return c->old_economy[j].income;
686 }
687 };
688
689 static const NWidgetPart _nested_income_graph_widgets[] = {
690 NWidget(NWID_HORIZONTAL),
691 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
692 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_INCOME_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
693 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_CV_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
694 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
695 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
696 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
697 EndContainer(),
698 NWidget(WWT_PANEL, COLOUR_BROWN, WID_CV_BACKGROUND),
699 NWidget(NWID_HORIZONTAL),
700 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_CV_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
701 NWidget(NWID_VERTICAL),
702 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
703 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_CV_RESIZE),
704 EndContainer(),
705 EndContainer(),
706 EndContainer(),
707 };
708
709 static WindowDesc _income_graph_desc(
710 WDP_AUTO, "graph_income", 0, 0,
711 WC_INCOME_GRAPH, WC_NONE,
712 0,
713 _nested_income_graph_widgets, lengthof(_nested_income_graph_widgets)
714 );
715
ShowIncomeGraph()716 void ShowIncomeGraph()
717 {
718 AllocateWindowDescFront<IncomeGraphWindow>(&_income_graph_desc, 0);
719 }
720
721 /*******************/
722 /* DELIVERED CARGO */
723 /*******************/
724
725 struct DeliveredCargoGraphWindow : BaseGraphWindow {
DeliveredCargoGraphWindowDeliveredCargoGraphWindow726 DeliveredCargoGraphWindow(WindowDesc *desc, WindowNumber window_number) :
727 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_COMMA)
728 {
729 this->InitializeWindow(window_number);
730 }
731
GetGraphDataDeliveredCargoGraphWindow732 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
733 {
734 return c->old_economy[j].delivered_cargo.GetSum<OverflowSafeInt64>();
735 }
736 };
737
738 static const NWidgetPart _nested_delivered_cargo_graph_widgets[] = {
739 NWidget(NWID_HORIZONTAL),
740 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
741 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_CARGO_DELIVERED_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
742 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_CV_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
743 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
744 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
745 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
746 EndContainer(),
747 NWidget(WWT_PANEL, COLOUR_BROWN, WID_CV_BACKGROUND),
748 NWidget(NWID_HORIZONTAL),
749 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_CV_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
750 NWidget(NWID_VERTICAL),
751 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
752 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_CV_RESIZE),
753 EndContainer(),
754 EndContainer(),
755 EndContainer(),
756 };
757
758 static WindowDesc _delivered_cargo_graph_desc(
759 WDP_AUTO, "graph_delivered_cargo", 0, 0,
760 WC_DELIVERED_CARGO, WC_NONE,
761 0,
762 _nested_delivered_cargo_graph_widgets, lengthof(_nested_delivered_cargo_graph_widgets)
763 );
764
ShowDeliveredCargoGraph()765 void ShowDeliveredCargoGraph()
766 {
767 AllocateWindowDescFront<DeliveredCargoGraphWindow>(&_delivered_cargo_graph_desc, 0);
768 }
769
770 /***********************/
771 /* PERFORMANCE HISTORY */
772 /***********************/
773
774 struct PerformanceHistoryGraphWindow : BaseGraphWindow {
PerformanceHistoryGraphWindowPerformanceHistoryGraphWindow775 PerformanceHistoryGraphWindow(WindowDesc *desc, WindowNumber window_number) :
776 BaseGraphWindow(desc, WID_PHG_GRAPH, STR_JUST_COMMA)
777 {
778 this->InitializeWindow(window_number);
779 }
780
GetGraphDataPerformanceHistoryGraphWindow781 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
782 {
783 return c->old_economy[j].performance_history;
784 }
785
OnClickPerformanceHistoryGraphWindow786 void OnClick(Point pt, int widget, int click_count) override
787 {
788 if (widget == WID_PHG_DETAILED_PERFORMANCE) ShowPerformanceRatingDetail();
789 this->BaseGraphWindow::OnClick(pt, widget, click_count);
790 }
791 };
792
793 static const NWidgetPart _nested_performance_history_widgets[] = {
794 NWidget(NWID_HORIZONTAL),
795 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
796 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_COMPANY_PERFORMANCE_RATINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
797 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_PHG_DETAILED_PERFORMANCE), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_PERFORMANCE_DETAIL_KEY, STR_GRAPH_PERFORMANCE_DETAIL_TOOLTIP),
798 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_PHG_KEY), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
799 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
800 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
801 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
802 EndContainer(),
803 NWidget(WWT_PANEL, COLOUR_BROWN, WID_PHG_BACKGROUND),
804 NWidget(NWID_HORIZONTAL),
805 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_PHG_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
806 NWidget(NWID_VERTICAL),
807 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
808 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_PHG_RESIZE),
809 EndContainer(),
810 EndContainer(),
811 EndContainer(),
812 };
813
814 static WindowDesc _performance_history_desc(
815 WDP_AUTO, "graph_performance", 0, 0,
816 WC_PERFORMANCE_HISTORY, WC_NONE,
817 0,
818 _nested_performance_history_widgets, lengthof(_nested_performance_history_widgets)
819 );
820
ShowPerformanceHistoryGraph()821 void ShowPerformanceHistoryGraph()
822 {
823 AllocateWindowDescFront<PerformanceHistoryGraphWindow>(&_performance_history_desc, 0);
824 }
825
826 /*****************/
827 /* COMPANY VALUE */
828 /*****************/
829
830 struct CompanyValueGraphWindow : BaseGraphWindow {
CompanyValueGraphWindowCompanyValueGraphWindow831 CompanyValueGraphWindow(WindowDesc *desc, WindowNumber window_number) :
832 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
833 {
834 this->InitializeWindow(window_number);
835 }
836
GetGraphDataCompanyValueGraphWindow837 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
838 {
839 return c->old_economy[j].company_value;
840 }
841 };
842
843 static const NWidgetPart _nested_company_value_graph_widgets[] = {
844 NWidget(NWID_HORIZONTAL),
845 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
846 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_COMPANY_VALUES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
847 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_CV_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
848 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
849 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
850 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
851 EndContainer(),
852 NWidget(WWT_PANEL, COLOUR_BROWN, WID_CV_BACKGROUND),
853 NWidget(NWID_HORIZONTAL),
854 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_CV_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
855 NWidget(NWID_VERTICAL),
856 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
857 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_CV_RESIZE),
858 EndContainer(),
859 EndContainer(),
860 EndContainer(),
861 };
862
863 static WindowDesc _company_value_graph_desc(
864 WDP_AUTO, "graph_company_value", 0, 0,
865 WC_COMPANY_VALUE, WC_NONE,
866 0,
867 _nested_company_value_graph_widgets, lengthof(_nested_company_value_graph_widgets)
868 );
869
ShowCompanyValueGraph()870 void ShowCompanyValueGraph()
871 {
872 AllocateWindowDescFront<CompanyValueGraphWindow>(&_company_value_graph_desc, 0);
873 }
874
875 /*****************/
876 /* PAYMENT RATES */
877 /*****************/
878
879 struct PaymentRatesGraphWindow : BaseGraphWindow {
880 uint line_height; ///< Pixel height of each cargo type row.
881 Scrollbar *vscroll; ///< Cargo list scrollbar.
882 uint legend_width; ///< Width of legend 'blob'.
883
PaymentRatesGraphWindowPaymentRatesGraphWindow884 PaymentRatesGraphWindow(WindowDesc *desc, WindowNumber window_number) :
885 BaseGraphWindow(desc, WID_CPR_GRAPH, STR_JUST_CURRENCY_SHORT)
886 {
887 this->num_on_x_axis = 20;
888 this->num_vert_lines = 20;
889 this->month = 0xFF;
890 this->x_values_start = 10;
891 this->x_values_increment = 10;
892
893 this->CreateNestedTree();
894 this->vscroll = this->GetScrollbar(WID_CPR_MATRIX_SCROLLBAR);
895 this->vscroll->SetCount(static_cast<int>(_sorted_standard_cargo_specs.size()));
896
897 /* Initialise the dataset */
898 this->OnHundredthTick();
899
900 this->FinishInitNested(window_number);
901 }
902
OnInitPaymentRatesGraphWindow903 void OnInit() override
904 {
905 /* Width of the legend blob. */
906 this->legend_width = (FONT_HEIGHT_SMALL - ScaleFontTrad(1)) * 8 / 5;
907 }
908
UpdateExcludedDataPaymentRatesGraphWindow909 void UpdateExcludedData()
910 {
911 this->excluded_data = 0;
912
913 int i = 0;
914 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
915 if (HasBit(_legend_excluded_cargo, cs->Index())) SetBit(this->excluded_data, i);
916 i++;
917 }
918 }
919
UpdateWidgetSizePaymentRatesGraphWindow920 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
921 {
922 if (widget != WID_CPR_MATRIX) {
923 BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
924 return;
925 }
926
927 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
928 SetDParam(0, cs->name);
929 Dimension d = GetStringBoundingBox(STR_GRAPH_CARGO_PAYMENT_CARGO);
930 d.width += this->legend_width + 4; // colour field
931 d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
932 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
933 *size = maxdim(d, *size);
934 }
935
936 this->line_height = size->height;
937 size->height = this->line_height * 11; /* Default number of cargo types in most climates. */
938 resize->width = 0;
939 resize->height = this->line_height;
940 }
941
DrawWidgetPaymentRatesGraphWindow942 void DrawWidget(const Rect &r, int widget) const override
943 {
944 if (widget != WID_CPR_MATRIX) {
945 BaseGraphWindow::DrawWidget(r, widget);
946 return;
947 }
948
949 bool rtl = _current_text_dir == TD_RTL;
950
951 int x = r.left + WD_FRAMERECT_LEFT;
952 int y = r.top;
953 uint row_height = FONT_HEIGHT_SMALL;
954 int padding = ScaleFontTrad(1);
955
956 int pos = this->vscroll->GetPosition();
957 int max = pos + this->vscroll->GetCapacity();
958
959 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
960 if (pos-- > 0) continue;
961 if (--max < 0) break;
962
963 bool lowered = !HasBit(_legend_excluded_cargo, cs->Index());
964
965 /* Redraw box if lowered */
966 if (lowered) DrawFrameRect(r.left, y, r.right, y + this->line_height - 1, COLOUR_BROWN, FR_LOWERED);
967
968 byte clk_dif = lowered ? 1 : 0;
969 int rect_x = clk_dif + (rtl ? r.right - this->legend_width - WD_FRAMERECT_RIGHT : r.left + WD_FRAMERECT_LEFT);
970
971 GfxFillRect(rect_x, y + padding + clk_dif, rect_x + this->legend_width, y + row_height - 1 + clk_dif, PC_BLACK);
972 GfxFillRect(rect_x + 1, y + padding + 1 + clk_dif, rect_x + this->legend_width - 1, y + row_height - 2 + clk_dif, cs->legend_colour);
973 SetDParam(0, cs->name);
974 DrawString(rtl ? r.left : x + this->legend_width + 4 + clk_dif, (rtl ? r.right - this->legend_width - 4 + clk_dif : r.right), y + clk_dif, STR_GRAPH_CARGO_PAYMENT_CARGO);
975
976 y += this->line_height;
977 }
978 }
979
OnClickPaymentRatesGraphWindow980 void OnClick(Point pt, int widget, int click_count) override
981 {
982 switch (widget) {
983 case WID_CPR_ENABLE_CARGOES:
984 /* Remove all cargoes from the excluded lists. */
985 _legend_excluded_cargo = 0;
986 this->excluded_data = 0;
987 this->SetDirty();
988 break;
989
990 case WID_CPR_DISABLE_CARGOES: {
991 /* Add all cargoes to the excluded lists. */
992 int i = 0;
993 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
994 SetBit(_legend_excluded_cargo, cs->Index());
995 SetBit(this->excluded_data, i);
996 i++;
997 }
998 this->SetDirty();
999 break;
1000 }
1001
1002 case WID_CPR_MATRIX: {
1003 uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_CPR_MATRIX);
1004 if (row >= this->vscroll->GetCount()) return;
1005
1006 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1007 if (row-- > 0) continue;
1008
1009 ToggleBit(_legend_excluded_cargo, cs->Index());
1010 this->UpdateExcludedData();
1011 this->SetDirty();
1012 break;
1013 }
1014 break;
1015 }
1016 }
1017 }
1018
OnResizePaymentRatesGraphWindow1019 void OnResize() override
1020 {
1021 this->vscroll->SetCapacityFromWidget(this, WID_CPR_MATRIX);
1022 }
1023
OnGameTickPaymentRatesGraphWindow1024 void OnGameTick() override
1025 {
1026 /* Override default OnGameTick */
1027 }
1028
1029 /**
1030 * Some data on this window has become invalid.
1031 * @param data Information about the changed data.
1032 * @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.
1033 */
OnInvalidateDataPaymentRatesGraphWindow1034 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1035 {
1036 if (!gui_scope) return;
1037 this->OnHundredthTick();
1038 }
1039
OnHundredthTickPaymentRatesGraphWindow1040 void OnHundredthTick() override
1041 {
1042 this->UpdateExcludedData();
1043
1044 int i = 0;
1045 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1046 this->colours[i] = cs->legend_colour;
1047 for (uint j = 0; j != 20; j++) {
1048 this->cost[i][j] = GetTransportedGoodsIncome(10, 20, j * 4 + 4, cs->Index());
1049 }
1050 i++;
1051 }
1052 this->num_dataset = i;
1053 }
1054 };
1055
1056 static const NWidgetPart _nested_cargo_payment_rates_widgets[] = {
1057 NWidget(NWID_HORIZONTAL),
1058 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1059 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1060 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1061 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1062 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1063 EndContainer(),
1064 NWidget(WWT_PANEL, COLOUR_BROWN, WID_CPR_BACKGROUND), SetMinimalSize(568, 128),
1065 NWidget(NWID_HORIZONTAL),
1066 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1067 NWidget(WWT_TEXT, COLOUR_BROWN, WID_CPR_HEADER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_TITLE, STR_NULL),
1068 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1069 EndContainer(),
1070 NWidget(NWID_HORIZONTAL),
1071 NWidget(WWT_EMPTY, COLOUR_BROWN, WID_CPR_GRAPH), SetMinimalSize(495, 0), SetFill(1, 1), SetResize(1, 1),
1072 NWidget(NWID_VERTICAL),
1073 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1074 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_CPR_ENABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1075 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_CPR_DISABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1076 NWidget(NWID_SPACER), SetMinimalSize(0, 4),
1077 NWidget(NWID_HORIZONTAL),
1078 NWidget(WWT_MATRIX, COLOUR_BROWN, WID_CPR_MATRIX), SetResize(0, 2), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO), SetScrollbar(WID_CPR_MATRIX_SCROLLBAR),
1079 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_CPR_MATRIX_SCROLLBAR),
1080 EndContainer(),
1081 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1082 EndContainer(),
1083 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1084 EndContainer(),
1085 NWidget(NWID_HORIZONTAL),
1086 NWidget(NWID_SPACER), SetMinimalSize(WD_RESIZEBOX_WIDTH, 0), SetFill(1, 0), SetResize(1, 0),
1087 NWidget(WWT_TEXT, COLOUR_BROWN, WID_CPR_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_X_LABEL, STR_NULL),
1088 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1089 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_CPR_RESIZE),
1090 EndContainer(),
1091 EndContainer(),
1092 };
1093
1094 static WindowDesc _cargo_payment_rates_desc(
1095 WDP_AUTO, "graph_cargo_payment_rates", 0, 0,
1096 WC_PAYMENT_RATES, WC_NONE,
1097 0,
1098 _nested_cargo_payment_rates_widgets, lengthof(_nested_cargo_payment_rates_widgets)
1099 );
1100
1101
ShowCargoPaymentRates()1102 void ShowCargoPaymentRates()
1103 {
1104 AllocateWindowDescFront<PaymentRatesGraphWindow>(&_cargo_payment_rates_desc, 0);
1105 }
1106
1107 /************************/
1108 /* COMPANY LEAGUE TABLE */
1109 /************************/
1110
1111 static const StringID _performance_titles[] = {
1112 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ENGINEER,
1113 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ENGINEER,
1114 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRAFFIC_MANAGER,
1115 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRAFFIC_MANAGER,
1116 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRANSPORT_COORDINATOR,
1117 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRANSPORT_COORDINATOR,
1118 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ROUTE_SUPERVISOR,
1119 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ROUTE_SUPERVISOR,
1120 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_DIRECTOR,
1121 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_DIRECTOR,
1122 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHIEF_EXECUTIVE,
1123 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHIEF_EXECUTIVE,
1124 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHAIRMAN,
1125 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHAIRMAN,
1126 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_PRESIDENT,
1127 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TYCOON,
1128 };
1129
GetPerformanceTitleFromValue(uint value)1130 static inline StringID GetPerformanceTitleFromValue(uint value)
1131 {
1132 return _performance_titles[std::min(value, 1000u) >> 6];
1133 }
1134
1135 class CompanyLeagueWindow : public Window {
1136 private:
1137 GUIList<const Company*> companies;
1138 uint ordinal_width; ///< The width of the ordinal number
1139 uint text_width; ///< The width of the actual text
1140 uint icon_width; ///< The width of the company icon
1141 int line_height; ///< Height of the text lines
1142
1143 /**
1144 * (Re)Build the company league list
1145 */
BuildCompanyList()1146 void BuildCompanyList()
1147 {
1148 if (!this->companies.NeedRebuild()) return;
1149
1150 this->companies.clear();
1151
1152 for (const Company *c : Company::Iterate()) {
1153 this->companies.push_back(c);
1154 }
1155
1156 this->companies.shrink_to_fit();
1157 this->companies.RebuildDone();
1158 }
1159
1160 /** Sort the company league by performance history */
PerformanceSorter(const Company * const & c1,const Company * const & c2)1161 static bool PerformanceSorter(const Company * const &c1, const Company * const &c2)
1162 {
1163 return c2->old_economy[0].performance_history < c1->old_economy[0].performance_history;
1164 }
1165
1166 public:
CompanyLeagueWindow(WindowDesc * desc,WindowNumber window_number)1167 CompanyLeagueWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
1168 {
1169 this->InitNested(window_number);
1170 this->companies.ForceRebuild();
1171 this->companies.NeedResort();
1172 }
1173
OnPaint()1174 void OnPaint() override
1175 {
1176 this->BuildCompanyList();
1177 this->companies.Sort(&PerformanceSorter);
1178
1179 this->DrawWidgets();
1180 }
1181
DrawWidget(const Rect & r,int widget) const1182 void DrawWidget(const Rect &r, int widget) const override
1183 {
1184 if (widget != WID_CL_BACKGROUND) return;
1185
1186 int icon_y_offset = 1 + (FONT_HEIGHT_NORMAL - this->line_height) / 2;
1187 uint y = r.top + WD_FRAMERECT_TOP - icon_y_offset;
1188
1189 bool rtl = _current_text_dir == TD_RTL;
1190 uint ordinal_left = rtl ? r.right - WD_FRAMERECT_LEFT - this->ordinal_width : r.left + WD_FRAMERECT_LEFT;
1191 uint ordinal_right = rtl ? r.right - WD_FRAMERECT_LEFT : r.left + WD_FRAMERECT_LEFT + this->ordinal_width;
1192 uint icon_left = r.left + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT + (rtl ? this->text_width : this->ordinal_width);
1193 uint text_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - WD_FRAMERECT_LEFT - this->text_width;
1194 uint text_right = rtl ? r.left + WD_FRAMERECT_LEFT + this->text_width : r.right - WD_FRAMERECT_LEFT;
1195
1196 for (uint i = 0; i != this->companies.size(); i++) {
1197 const Company *c = this->companies[i];
1198 DrawString(ordinal_left, ordinal_right, y, i + STR_ORDINAL_NUMBER_1ST, i == 0 ? TC_WHITE : TC_YELLOW);
1199
1200 DrawCompanyIcon(c->index, icon_left, y + icon_y_offset);
1201
1202 SetDParam(0, c->index);
1203 SetDParam(1, c->index);
1204 SetDParam(2, GetPerformanceTitleFromValue(c->old_economy[0].performance_history));
1205 DrawString(text_left, text_right, y, STR_COMPANY_LEAGUE_COMPANY_NAME);
1206 y += this->line_height;
1207 }
1208 }
1209
UpdateWidgetSize(int widget,Dimension * size,const Dimension & padding,Dimension * fill,Dimension * resize)1210 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1211 {
1212 if (widget != WID_CL_BACKGROUND) return;
1213
1214 this->ordinal_width = 0;
1215 for (uint i = 0; i < MAX_COMPANIES; i++) {
1216 this->ordinal_width = std::max(this->ordinal_width, GetStringBoundingBox(STR_ORDINAL_NUMBER_1ST + i).width);
1217 }
1218 this->ordinal_width += 5; // Keep some extra spacing
1219
1220 uint widest_width = 0;
1221 uint widest_title = 0;
1222 for (uint i = 0; i < lengthof(_performance_titles); i++) {
1223 uint width = GetStringBoundingBox(_performance_titles[i]).width;
1224 if (width > widest_width) {
1225 widest_title = i;
1226 widest_width = width;
1227 }
1228 }
1229
1230 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
1231 this->icon_width = d.width + 2;
1232 this->line_height = std::max<int>(d.height + 2, FONT_HEIGHT_NORMAL);
1233
1234 for (const Company *c : Company::Iterate()) {
1235 SetDParam(0, c->index);
1236 SetDParam(1, c->index);
1237 SetDParam(2, _performance_titles[widest_title]);
1238 widest_width = std::max(widest_width, GetStringBoundingBox(STR_COMPANY_LEAGUE_COMPANY_NAME).width);
1239 }
1240
1241 this->text_width = widest_width + 30; // Keep some extra spacing
1242
1243 size->width = WD_FRAMERECT_LEFT + this->ordinal_width + WD_FRAMERECT_RIGHT + this->icon_width + WD_FRAMERECT_LEFT + this->text_width + WD_FRAMERECT_RIGHT;
1244 size->height = WD_FRAMERECT_TOP + this->line_height * MAX_COMPANIES + WD_FRAMERECT_BOTTOM;
1245 }
1246
1247
OnGameTick()1248 void OnGameTick() override
1249 {
1250 if (this->companies.NeedResort()) {
1251 this->SetDirty();
1252 }
1253 }
1254
1255 /**
1256 * Some data on this window has become invalid.
1257 * @param data Information about the changed data.
1258 * @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.
1259 */
OnInvalidateData(int data=0,bool gui_scope=true)1260 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1261 {
1262 if (data == 0) {
1263 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1264 this->companies.ForceRebuild();
1265 } else {
1266 this->companies.ForceResort();
1267 }
1268 }
1269 };
1270
1271 static const NWidgetPart _nested_company_league_widgets[] = {
1272 NWidget(NWID_HORIZONTAL),
1273 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1274 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_COMPANY_LEAGUE_TABLE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1275 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1276 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1277 EndContainer(),
1278 NWidget(WWT_PANEL, COLOUR_BROWN, WID_CL_BACKGROUND), SetMinimalSize(400, 0), SetMinimalTextLines(15, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM),
1279 };
1280
1281 static WindowDesc _company_league_desc(
1282 WDP_AUTO, "league", 0, 0,
1283 WC_COMPANY_LEAGUE, WC_NONE,
1284 0,
1285 _nested_company_league_widgets, lengthof(_nested_company_league_widgets)
1286 );
1287
ShowCompanyLeagueTable()1288 void ShowCompanyLeagueTable()
1289 {
1290 AllocateWindowDescFront<CompanyLeagueWindow>(&_company_league_desc, 0);
1291 }
1292
1293 /*****************************/
1294 /* PERFORMANCE RATING DETAIL */
1295 /*****************************/
1296
1297 struct PerformanceRatingDetailWindow : Window {
1298 static CompanyID company;
1299 int timeout;
1300
PerformanceRatingDetailWindowPerformanceRatingDetailWindow1301 PerformanceRatingDetailWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
1302 {
1303 this->UpdateCompanyStats();
1304
1305 this->InitNested(window_number);
1306 this->OnInvalidateData(INVALID_COMPANY);
1307 }
1308
UpdateCompanyStatsPerformanceRatingDetailWindow1309 void UpdateCompanyStats()
1310 {
1311 /* Update all company stats with the current data
1312 * (this is because _score_info is not saved to a savegame) */
1313 for (Company *c : Company::Iterate()) {
1314 UpdateCompanyRatingAndValue(c, false);
1315 }
1316
1317 this->timeout = DAY_TICKS * 5;
1318 }
1319
1320 uint score_info_left;
1321 uint score_info_right;
1322 uint bar_left;
1323 uint bar_right;
1324 uint bar_width;
1325 uint bar_height;
1326 uint score_detail_left;
1327 uint score_detail_right;
1328
UpdateWidgetSizePerformanceRatingDetailWindow1329 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1330 {
1331 switch (widget) {
1332 case WID_PRD_SCORE_FIRST:
1333 this->bar_height = FONT_HEIGHT_NORMAL + 4;
1334 size->height = this->bar_height + 2 * WD_MATRIX_TOP;
1335
1336 uint score_info_width = 0;
1337 for (uint i = SCORE_BEGIN; i < SCORE_END; i++) {
1338 score_info_width = std::max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + i).width);
1339 }
1340 SetDParamMaxValue(0, 1000);
1341 score_info_width += GetStringBoundingBox(STR_BLACK_COMMA).width + WD_FRAMERECT_LEFT;
1342
1343 SetDParamMaxValue(0, 100);
1344 this->bar_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_PERCENT).width + 20; // Wide bars!
1345
1346 /* At this number we are roughly at the max; it can become wider,
1347 * but then you need at 1000 times more money. At that time you're
1348 * not that interested anymore in the last few digits anyway.
1349 * The 500 is because 999 999 500 to 999 999 999 are rounded to
1350 * 1 000 M, and not 999 999 k. Use negative numbers to account for
1351 * the negative income/amount of money etc. as well. */
1352 int max = -(999999999 - 500);
1353
1354 /* Scale max for the display currency. Prior to rendering the value
1355 * is converted into the display currency, which may cause it to
1356 * raise significantly. We need to compensate for that since {{CURRCOMPACT}}
1357 * is used, which can produce quite short renderings of very large
1358 * values. Otherwise the calculated width could be too narrow.
1359 * Note that it doesn't work if there was a currency with an exchange
1360 * rate greater than max.
1361 * When the currency rate is more than 1000, the 999 999 k becomes at
1362 * least 999 999 M which roughly is equally long. Furthermore if the
1363 * exchange rate is that high, 999 999 k is usually not enough anymore
1364 * to show the different currency numbers. */
1365 if (_currency->rate < 1000) max /= _currency->rate;
1366 SetDParam(0, max);
1367 SetDParam(1, max);
1368 uint score_detail_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY).width;
1369
1370 size->width = 7 + score_info_width + 5 + this->bar_width + 5 + score_detail_width + 7;
1371 uint left = 7;
1372 uint right = size->width - 7;
1373
1374 bool rtl = _current_text_dir == TD_RTL;
1375 this->score_info_left = rtl ? right - score_info_width : left;
1376 this->score_info_right = rtl ? right : left + score_info_width;
1377
1378 this->score_detail_left = rtl ? left : right - score_detail_width;
1379 this->score_detail_right = rtl ? left + score_detail_width : right;
1380
1381 this->bar_left = left + (rtl ? score_detail_width : score_info_width) + 5;
1382 this->bar_right = this->bar_left + this->bar_width;
1383 break;
1384 }
1385 }
1386
DrawWidgetPerformanceRatingDetailWindow1387 void DrawWidget(const Rect &r, int widget) const override
1388 {
1389 /* No need to draw when there's nothing to draw */
1390 if (this->company == INVALID_COMPANY) return;
1391
1392 if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
1393 if (this->IsWidgetDisabled(widget)) return;
1394 CompanyID cid = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1395 int offset = (cid == this->company) ? 1 : 0;
1396 Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
1397 DrawCompanyIcon(cid, (r.left + r.right - sprite_size.width) / 2 + offset, (r.top + r.bottom - sprite_size.height) / 2 + offset);
1398 return;
1399 }
1400
1401 if (!IsInsideMM(widget, WID_PRD_SCORE_FIRST, WID_PRD_SCORE_LAST + 1)) return;
1402
1403 ScoreID score_type = (ScoreID)(widget - WID_PRD_SCORE_FIRST);
1404
1405 /* The colours used to show how the progress is going */
1406 int colour_done = _colour_gradient[COLOUR_GREEN][4];
1407 int colour_notdone = _colour_gradient[COLOUR_RED][4];
1408
1409 /* Draw all the score parts */
1410 int64 val = _score_part[company][score_type];
1411 int64 needed = _score_info[score_type].needed;
1412 int score = _score_info[score_type].score;
1413
1414 /* SCORE_TOTAL has its own rules ;) */
1415 if (score_type == SCORE_TOTAL) {
1416 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) score += _score_info[i].score;
1417 needed = SCORE_MAX;
1418 }
1419
1420 uint bar_top = r.top + WD_MATRIX_TOP;
1421 uint text_top = bar_top + 2;
1422
1423 DrawString(this->score_info_left, this->score_info_right, text_top, STR_PERFORMANCE_DETAIL_VEHICLES + score_type);
1424
1425 /* Draw the score */
1426 SetDParam(0, score);
1427 DrawString(this->score_info_left, this->score_info_right, text_top, STR_BLACK_COMMA, TC_FROMSTRING, SA_RIGHT);
1428
1429 /* Calculate the %-bar */
1430 uint x = Clamp<int64>(val, 0, needed) * this->bar_width / needed;
1431 bool rtl = _current_text_dir == TD_RTL;
1432 if (rtl) {
1433 x = this->bar_right - x;
1434 } else {
1435 x = this->bar_left + x;
1436 }
1437
1438 /* Draw the bar */
1439 if (x != this->bar_left) GfxFillRect(this->bar_left, bar_top, x, bar_top + this->bar_height, rtl ? colour_notdone : colour_done);
1440 if (x != this->bar_right) GfxFillRect(x, bar_top, this->bar_right, bar_top + this->bar_height, rtl ? colour_done : colour_notdone);
1441
1442 /* Draw it */
1443 SetDParam(0, Clamp<int64>(val, 0, needed) * 100 / needed);
1444 DrawString(this->bar_left, this->bar_right, text_top, STR_PERFORMANCE_DETAIL_PERCENT, TC_FROMSTRING, SA_HOR_CENTER);
1445
1446 /* SCORE_LOAN is inversed */
1447 if (score_type == SCORE_LOAN) val = needed - val;
1448
1449 /* Draw the amount we have against what is needed
1450 * For some of them it is in currency format */
1451 SetDParam(0, val);
1452 SetDParam(1, needed);
1453 switch (score_type) {
1454 case SCORE_MIN_PROFIT:
1455 case SCORE_MIN_INCOME:
1456 case SCORE_MAX_INCOME:
1457 case SCORE_MONEY:
1458 case SCORE_LOAN:
1459 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY);
1460 break;
1461 default:
1462 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_INT);
1463 }
1464 }
1465
OnClickPerformanceRatingDetailWindow1466 void OnClick(Point pt, int widget, int click_count) override
1467 {
1468 /* Check which button is clicked */
1469 if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
1470 /* Is it no on disable? */
1471 if (!this->IsWidgetDisabled(widget)) {
1472 this->RaiseWidget(this->company + WID_PRD_COMPANY_FIRST);
1473 this->company = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1474 this->LowerWidget(this->company + WID_PRD_COMPANY_FIRST);
1475 this->SetDirty();
1476 }
1477 }
1478 }
1479
OnGameTickPerformanceRatingDetailWindow1480 void OnGameTick() override
1481 {
1482 /* Update the company score every 5 days */
1483 if (--this->timeout == 0) {
1484 this->UpdateCompanyStats();
1485 this->SetDirty();
1486 }
1487 }
1488
1489 /**
1490 * Some data on this window has become invalid.
1491 * @param data the company ID of the company that is going to be removed
1492 * @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.
1493 */
OnInvalidateDataPerformanceRatingDetailWindow1494 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1495 {
1496 if (!gui_scope) return;
1497 /* Disable the companies who are not active */
1498 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
1499 this->SetWidgetDisabledState(i + WID_PRD_COMPANY_FIRST, !Company::IsValidID(i));
1500 }
1501
1502 /* Check if the currently selected company is still active. */
1503 if (this->company != INVALID_COMPANY && !Company::IsValidID(this->company)) {
1504 /* Raise the widget for the previous selection. */
1505 this->RaiseWidget(this->company + WID_PRD_COMPANY_FIRST);
1506 this->company = INVALID_COMPANY;
1507 }
1508
1509 if (this->company == INVALID_COMPANY) {
1510 for (const Company *c : Company::Iterate()) {
1511 this->company = c->index;
1512 break;
1513 }
1514 }
1515
1516 /* Make sure the widget is lowered */
1517 this->LowerWidget(this->company + WID_PRD_COMPANY_FIRST);
1518 }
1519 };
1520
1521 CompanyID PerformanceRatingDetailWindow::company = INVALID_COMPANY;
1522
1523 /**
1524 * Make a vertical list of panels for outputting score details.
1525 * @param biggest_index Storage for collecting the biggest index used in the returned tree.
1526 * @return Panel with performance details.
1527 * @post \c *biggest_index contains the largest used index in the tree.
1528 */
MakePerformanceDetailPanels(int * biggest_index)1529 static NWidgetBase *MakePerformanceDetailPanels(int *biggest_index)
1530 {
1531 const StringID performance_tips[] = {
1532 STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP,
1533 STR_PERFORMANCE_DETAIL_STATIONS_TOOLTIP,
1534 STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP,
1535 STR_PERFORMANCE_DETAIL_MIN_INCOME_TOOLTIP,
1536 STR_PERFORMANCE_DETAIL_MAX_INCOME_TOOLTIP,
1537 STR_PERFORMANCE_DETAIL_DELIVERED_TOOLTIP,
1538 STR_PERFORMANCE_DETAIL_CARGO_TOOLTIP,
1539 STR_PERFORMANCE_DETAIL_MONEY_TOOLTIP,
1540 STR_PERFORMANCE_DETAIL_LOAN_TOOLTIP,
1541 STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP,
1542 };
1543
1544 static_assert(lengthof(performance_tips) == SCORE_END - SCORE_BEGIN);
1545
1546 NWidgetVertical *vert = new NWidgetVertical(NC_EQUALSIZE);
1547 for (int widnum = WID_PRD_SCORE_FIRST; widnum <= WID_PRD_SCORE_LAST; widnum++) {
1548 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_BROWN, widnum);
1549 panel->SetFill(1, 1);
1550 panel->SetDataTip(0x0, performance_tips[widnum - WID_PRD_SCORE_FIRST]);
1551 vert->Add(panel);
1552 }
1553 *biggest_index = WID_PRD_SCORE_LAST;
1554 return vert;
1555 }
1556
1557 /** Make a number of rows with buttons for each company for the performance rating detail window. */
MakeCompanyButtonRowsGraphGUI(int * biggest_index)1558 NWidgetBase *MakeCompanyButtonRowsGraphGUI(int *biggest_index)
1559 {
1560 return MakeCompanyButtonRows(biggest_index, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST, COLOUR_BROWN, 8, STR_PERFORMANCE_DETAIL_SELECT_COMPANY_TOOLTIP);
1561 }
1562
1563 static const NWidgetPart _nested_performance_rating_detail_widgets[] = {
1564 NWidget(NWID_HORIZONTAL),
1565 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1566 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_PERFORMANCE_DETAIL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1567 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1568 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1569 EndContainer(),
1570 NWidget(WWT_PANEL, COLOUR_BROWN),
1571 NWidgetFunction(MakeCompanyButtonRowsGraphGUI), SetPadding(0, 1, 1, 2),
1572 EndContainer(),
1573 NWidgetFunction(MakePerformanceDetailPanels),
1574 };
1575
1576 static WindowDesc _performance_rating_detail_desc(
1577 WDP_AUTO, "league_details", 0, 0,
1578 WC_PERFORMANCE_DETAIL, WC_NONE,
1579 0,
1580 _nested_performance_rating_detail_widgets, lengthof(_nested_performance_rating_detail_widgets)
1581 );
1582
ShowPerformanceRatingDetail()1583 void ShowPerformanceRatingDetail()
1584 {
1585 AllocateWindowDescFront<PerformanceRatingDetailWindow>(&_performance_rating_detail_desc, 0);
1586 }
1587
InitializeGraphGui()1588 void InitializeGraphGui()
1589 {
1590 _legend_excluded_companies = 0;
1591 _legend_excluded_cargo = 0;
1592 }
1593