Remove ZeroedMemoryAllocator as a base class of Window
[openttd/fttd.git] / src / graph_gui.cpp
blob119e6f322f7f750e9d42cb1c53812de866ae4c21
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file graph_gui.cpp GUI that shows performance graphs. */
12 #include "stdafx.h"
13 #include "graph_gui.h"
14 #include "window_gui.h"
15 #include "company_base.h"
16 #include "company_gui.h"
17 #include "economy_func.h"
18 #include "cargotype.h"
19 #include "strings_func.h"
20 #include "window_func.h"
21 #include "date_func.h"
22 #include "gfx_func.h"
23 #include "sortlist_type.h"
24 #include "core/geometry_func.hpp"
25 #include "currency.h"
27 #include "widgets/graph_widget.h"
29 #include "table/strings.h"
30 #include "table/sprites.h"
31 #include <math.h>
33 /* Bitmasks of company and cargo indices that shouldn't be drawn. */
34 static uint _legend_excluded_companies;
35 static uint _legend_excluded_cargo;
37 /* Apparently these don't play well with enums. */
38 static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX); // Value used for a datapoint that shouldn't be drawn.
39 static const uint INVALID_DATAPOINT_POS = UINT_MAX; // Used to determine if the previous point was drawn.
41 /****************/
42 /* GRAPH LEGEND */
43 /****************/
45 struct GraphLegendWindow : Window {
46 GraphLegendWindow (const WindowDesc *desc, WindowNumber window_number) : Window(desc)
48 this->InitNested(window_number);
50 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
51 if (!HasBit(_legend_excluded_companies, c)) this->LowerWidget(c + WID_GL_FIRST_COMPANY);
53 this->OnInvalidateData(c);
57 virtual void DrawWidget(const Rect &r, int widget) const
59 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, MAX_COMPANIES + WID_GL_FIRST_COMPANY)) return;
61 CompanyID cid = (CompanyID)(widget - WID_GL_FIRST_COMPANY);
63 if (!Company::IsValidID(cid)) return;
65 bool rtl = _current_text_dir == TD_RTL;
67 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
68 DrawCompanyIcon(cid, rtl ? r.right - d.width - 2 : r.left + 2, r.top + (r.bottom - r.top - d.height) / 2);
70 SetDParam(0, cid);
71 SetDParam(1, cid);
72 DrawString(r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : (d.width + 4)), r.right - (rtl ? (d.width + 4) : (uint)WD_FRAMERECT_RIGHT), r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2, STR_COMPANY_NAME_COMPANY_NUM, HasBit(_legend_excluded_companies, cid) ? TC_BLACK : TC_WHITE);
75 virtual void OnClick(Point pt, int widget, int click_count)
77 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, MAX_COMPANIES + WID_GL_FIRST_COMPANY)) return;
79 ToggleBit(_legend_excluded_companies, widget - WID_GL_FIRST_COMPANY);
80 this->ToggleWidgetLoweredState(widget);
81 this->SetDirty();
82 InvalidateWindowData(WC_INCOME_GRAPH, 0);
83 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
84 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
85 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
86 InvalidateWindowData(WC_COMPANY_VALUE, 0);
89 /**
90 * Some data on this window has become invalid.
91 * @param data Information about the changed data.
92 * @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 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
96 if (!gui_scope) return;
97 if (Company::IsValidID(data)) return;
99 SetBit(_legend_excluded_companies, data);
100 this->RaiseWidget(data + WID_GL_FIRST_COMPANY);
105 * Construct a vertical list of buttons, one for each company.
106 * @param biggest_index Storage for collecting the biggest index used in the returned tree.
107 * @return Panel with company buttons.
108 * @post \c *biggest_index contains the largest used index in the tree.
110 static NWidgetBase *MakeNWidgetCompanyLines(int *biggest_index)
112 NWidgetVertical *vert = new NWidgetVertical();
113 uint line_height = max<uint>(GetSpriteSize(SPR_COMPANY_ICON).height, FONT_HEIGHT_NORMAL) + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
115 for (int widnum = WID_GL_FIRST_COMPANY; widnum <= WID_GL_LAST_COMPANY; widnum++) {
116 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, widnum);
117 panel->SetMinimalSize(246, line_height);
118 panel->SetFill(1, 0);
119 panel->SetDataTip(0x0, STR_GRAPH_KEY_COMPANY_SELECTION_TOOLTIP);
120 vert->Add(panel);
122 *biggest_index = WID_GL_LAST_COMPANY;
123 return vert;
126 static const NWidgetPart _nested_graph_legend_widgets[] = {
127 NWidget(NWID_HORIZONTAL),
128 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
129 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_KEY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
130 NWidget(WWT_SHADEBOX, COLOUR_GREY),
131 NWidget(WWT_STICKYBOX, COLOUR_GREY),
132 EndContainer(),
133 NWidget(WWT_PANEL, COLOUR_GREY, WID_GL_BACKGROUND),
134 NWidget(NWID_SPACER), SetMinimalSize(0, 2),
135 NWidget(NWID_HORIZONTAL),
136 NWidget(NWID_SPACER), SetMinimalSize(2, 0),
137 NWidgetFunction(MakeNWidgetCompanyLines),
138 NWidget(NWID_SPACER), SetMinimalSize(2, 0),
139 EndContainer(),
140 EndContainer(),
143 static WindowDesc::Prefs _graph_legend_prefs ("graph_legend");
145 static const WindowDesc _graph_legend_desc(
146 WDP_AUTO, 0, 0,
147 WC_GRAPH_LEGEND, WC_NONE,
149 _nested_graph_legend_widgets, lengthof(_nested_graph_legend_widgets),
150 &_graph_legend_prefs
153 static void ShowGraphLegend()
155 AllocateWindowDescFront<GraphLegendWindow>(&_graph_legend_desc, 0);
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.
164 /******************/
165 /* BASE OF GRAPHS */
166 /*****************/
168 struct BaseGraphWindow : Window {
169 protected:
170 static const int GRAPH_MAX_DATASETS = 32;
171 static const int GRAPH_AXIS_LINE_COLOUR = PC_BLACK;
172 static const int GRAPH_NUM_MONTHS = 24; ///< Number of months displayed in the graph.
174 static const int MIN_GRAPH_NUM_LINES_Y = 9; ///< Minimal number of horizontal lines to draw.
175 static const int MIN_GRID_PIXEL_SIZE = 20; ///< Minimum distance between graph lines.
177 uint excluded_data; ///< bitmask of the datasets that shouldn't be displayed.
178 byte num_dataset;
179 byte num_on_x_axis;
180 byte num_vert_lines;
181 static const TextColour graph_axis_label_colour = TC_BLACK; ///< colour of the graph axis label.
183 /* The starting month and year that values are plotted against. If month is
184 * 0xFF, use x_values_start and x_values_increment below instead. */
185 byte month;
186 Year year;
188 /* These values are used if the graph is being plotted against values
189 * rather than the dates specified by month and year. */
190 uint16 x_values_start;
191 uint16 x_values_increment;
193 int graph_widget;
194 StringID format_str_y_axis;
195 byte colours[GRAPH_MAX_DATASETS];
196 OverflowSafeInt64 cost[GRAPH_MAX_DATASETS][GRAPH_NUM_MONTHS]; ///< Stored costs for the last #GRAPH_NUM_MONTHS months
199 * Get the interval that contains the graph's data. Excluded data is ignored to show smaller values in
200 * better detail when disabling higher ones.
201 * @param num_hori_lines Number of horizontal lines to be drawn.
202 * @return Highest and lowest values of the graph (ignoring disabled data).
204 ValuesInterval GetValuesInterval(int num_hori_lines) const
206 assert(num_hori_lines > 0);
208 ValuesInterval current_interval;
209 current_interval.highest = INT64_MIN;
210 current_interval.lowest = INT64_MAX;
212 for (int i = 0; i < this->num_dataset; i++) {
213 if (HasBit(this->excluded_data, i)) continue;
214 for (int j = 0; j < this->num_on_x_axis; j++) {
215 OverflowSafeInt64 datapoint = this->cost[i][j];
217 if (datapoint != INVALID_DATAPOINT) {
218 current_interval.highest = max(current_interval.highest, datapoint);
219 current_interval.lowest = min(current_interval.lowest, datapoint);
224 /* Prevent showing values too close to the graph limits. */
225 current_interval.highest = (11 * current_interval.highest) / 10;
226 current_interval.lowest = (11 * current_interval.lowest) / 10;
228 /* Always include zero in the shown range. */
229 double abs_lower = (current_interval.lowest > 0) ? 0 : (double)abs(current_interval.lowest);
230 double abs_higher = (current_interval.highest < 0) ? 0 : (double)current_interval.highest;
232 int num_pos_grids;
233 int64 grid_size;
235 if (abs_lower != 0 || abs_higher != 0) {
236 /* The number of grids to reserve for the positive part is: */
237 num_pos_grids = (int)floor(0.5 + num_hori_lines * abs_higher / (abs_higher + abs_lower));
239 /* If there are any positive or negative values, force that they have at least one grid. */
240 if (num_pos_grids == 0 && abs_higher != 0) num_pos_grids++;
241 if (num_pos_grids == num_hori_lines && abs_lower != 0) num_pos_grids--;
243 /* Get the required grid size for each side and use the maximum one. */
244 int64 grid_size_higher = (abs_higher > 0) ? ((int64)abs_higher + num_pos_grids - 1) / num_pos_grids : 0;
245 int64 grid_size_lower = (abs_lower > 0) ? ((int64)abs_lower + num_hori_lines - num_pos_grids - 1) / (num_hori_lines - num_pos_grids) : 0;
246 grid_size = max(grid_size_higher, grid_size_lower);
247 } else {
248 /* If both values are zero, show an empty graph. */
249 num_pos_grids = num_hori_lines / 2;
250 grid_size = 1;
253 current_interval.highest = num_pos_grids * grid_size;
254 current_interval.lowest = -(num_hori_lines - num_pos_grids) * grid_size;
255 return current_interval;
259 * Get width for Y labels.
260 * @param current_interval Interval that contains all of the graph data.
261 * @param num_hori_lines Number of horizontal lines to be drawn.
263 uint GetYLabelWidth(ValuesInterval current_interval, int num_hori_lines) const
265 /* draw text strings on the y axis */
266 int64 y_label = current_interval.highest;
267 int64 y_label_separation = (current_interval.highest - current_interval.lowest) / num_hori_lines;
269 uint max_width = 0;
271 for (int i = 0; i < (num_hori_lines + 1); i++) {
272 SetDParam(0, this->format_str_y_axis);
273 SetDParam(1, y_label);
274 Dimension d = GetStringBoundingBox(STR_GRAPH_Y_LABEL);
275 if (d.width > max_width) max_width = d.width;
277 y_label -= y_label_separation;
280 return max_width;
284 * Actually draw the graph.
285 * @param r the rectangle of the data field of the graph
287 void DrawGraph(Rect r) const
289 uint x, y; ///< Reused whenever x and y coordinates are needed.
290 ValuesInterval interval; ///< Interval that contains all of the graph data.
291 int x_axis_offset; ///< Distance from the top of the graph to the x axis.
293 /* the colours and cost array of GraphDrawer must accommodate
294 * both values for cargo and companies. So if any are higher, quit */
295 assert_compile(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES);
296 assert(this->num_vert_lines > 0);
298 byte grid_colour = _colour_gradient[COLOUR_GREY][4];
300 /* Rect r will be adjusted to contain just the graph, with labels being
301 * placed outside the area. */
302 r.top += 5 + GetCharacterHeight(FS_SMALL) / 2;
303 r.bottom -= (this->month == 0xFF ? 1 : 3) * GetCharacterHeight(FS_SMALL) + 4;
304 r.left += 9;
305 r.right -= 5;
307 /* Initial number of horizontal lines. */
308 int num_hori_lines = 160 / MIN_GRID_PIXEL_SIZE;
309 /* For the rest of the height, the number of horizontal lines will increase more slowly. */
310 int resize = (r.bottom - r.top - 160) / (2 * MIN_GRID_PIXEL_SIZE);
311 if (resize > 0) num_hori_lines += resize;
313 interval = GetValuesInterval(num_hori_lines);
315 int label_width = GetYLabelWidth(interval, num_hori_lines);
317 r.left += label_width;
319 int x_sep = (r.right - r.left) / this->num_vert_lines;
320 int y_sep = (r.bottom - r.top) / num_hori_lines;
322 /* Redetermine right and bottom edge of graph to fit with the integer
323 * separation values. */
324 r.right = r.left + x_sep * this->num_vert_lines;
325 r.bottom = r.top + y_sep * num_hori_lines;
327 OverflowSafeInt64 interval_size = interval.highest + abs(interval.lowest);
328 /* Where to draw the X axis. Use floating point to avoid overflowing and results of zero. */
329 x_axis_offset = (int)((r.bottom - r.top) * (double)interval.highest / (double)interval_size);
331 /* Draw the vertical grid lines. */
333 /* Don't draw the first line, as that's where the axis will be. */
334 x = r.left + x_sep;
336 for (int i = 0; i < this->num_vert_lines; i++) {
337 GfxFillRect(x, r.top, x, r.bottom, grid_colour);
338 x += x_sep;
341 /* Draw the horizontal grid lines. */
342 y = r.bottom;
344 for (int i = 0; i < (num_hori_lines + 1); i++) {
345 GfxFillRect(r.left - 3, y, r.left - 1, y, GRAPH_AXIS_LINE_COLOUR);
346 GfxFillRect(r.left, y, r.right, y, grid_colour);
347 y -= y_sep;
350 /* Draw the y axis. */
351 GfxFillRect(r.left, r.top, r.left, r.bottom, GRAPH_AXIS_LINE_COLOUR);
353 /* Draw the x axis. */
354 y = x_axis_offset + r.top;
355 GfxFillRect(r.left, y, r.right, y, GRAPH_AXIS_LINE_COLOUR);
357 /* Find the largest value that will be drawn. */
358 if (this->num_on_x_axis == 0) return;
360 assert(this->num_on_x_axis > 0);
361 assert(this->num_dataset > 0);
363 /* draw text strings on the y axis */
364 int64 y_label = interval.highest;
365 int64 y_label_separation = abs(interval.highest - interval.lowest) / num_hori_lines;
367 y = r.top - GetCharacterHeight(FS_SMALL) / 2;
369 for (int i = 0; i < (num_hori_lines + 1); i++) {
370 SetDParam(0, this->format_str_y_axis);
371 SetDParam(1, y_label);
372 DrawString(r.left - label_width - 4, r.left - 4, y, STR_GRAPH_Y_LABEL, graph_axis_label_colour, SA_RIGHT);
374 y_label -= y_label_separation;
375 y += y_sep;
378 /* draw strings on the x axis */
379 if (this->month != 0xFF) {
380 x = r.left;
381 y = r.bottom + 2;
382 byte month = this->month;
383 Year year = this->year;
384 for (int i = 0; i < this->num_on_x_axis; i++) {
385 SetDParam(0, month + STR_MONTH_ABBREV_JAN);
386 SetDParam(1, month + STR_MONTH_ABBREV_JAN + 2);
387 SetDParam(2, year);
388 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);
390 month += 3;
391 if (month >= 12) {
392 month = 0;
393 year++;
395 x += x_sep;
397 } else {
398 /* Draw the label under the data point rather than on the grid line. */
399 x = r.left;
400 y = r.bottom + 2;
401 uint16 label = this->x_values_start;
403 for (int i = 0; i < this->num_on_x_axis; i++) {
404 SetDParam(0, label);
405 DrawString(x + 1, x + x_sep - 1, y, STR_GRAPH_Y_LABEL_NUMBER, graph_axis_label_colour, SA_HOR_CENTER);
407 label += this->x_values_increment;
408 x += x_sep;
412 /* draw lines and dots */
413 uint linewidth = _settings_client.gui.graph_line_thickness;
414 uint pointoffs1 = (linewidth + 1) / 2;
415 uint pointoffs2 = linewidth + 1 - pointoffs1;
416 for (int i = 0; i < this->num_dataset; i++) {
417 if (!HasBit(this->excluded_data, i)) {
418 /* Centre the dot between the grid lines. */
419 x = r.left + (x_sep / 2);
421 byte colour = this->colours[i];
422 uint prev_x = INVALID_DATAPOINT_POS;
423 uint prev_y = INVALID_DATAPOINT_POS;
425 for (int j = 0; j < this->num_on_x_axis; j++) {
426 OverflowSafeInt64 datapoint = this->cost[i][j];
428 if (datapoint != INVALID_DATAPOINT) {
430 * Check whether we need to reduce the 'accuracy' of the
431 * datapoint value and the highest value to split overflows.
432 * And when 'drawing' 'one million' or 'one million and one'
433 * there is no significant difference, so the least
434 * significant bits can just be removed.
436 * If there are more bits needed than would fit in a 32 bits
437 * integer, so at about 31 bits because of the sign bit, the
438 * least significant bits are removed.
440 int mult_range = FindLastBit(x_axis_offset) + FindLastBit(abs(datapoint));
441 int reduce_range = max(mult_range - 31, 0);
443 /* Handle negative values differently (don't shift sign) */
444 if (datapoint < 0) {
445 datapoint = -(abs(datapoint) >> reduce_range);
446 } else {
447 datapoint >>= reduce_range;
449 y = r.top + x_axis_offset - ((r.bottom - r.top) * datapoint) / (interval_size >> reduce_range);
451 /* Draw the point. */
452 GfxFillRect(x - pointoffs1, y - pointoffs1, x + pointoffs2, y + pointoffs2, colour);
454 /* Draw the line connected to the previous point. */
455 if (prev_x != INVALID_DATAPOINT_POS) GfxDrawLine(prev_x, prev_y, x, y, colour, linewidth);
457 prev_x = x;
458 prev_y = y;
459 } else {
460 prev_x = INVALID_DATAPOINT_POS;
461 prev_y = INVALID_DATAPOINT_POS;
464 x += x_sep;
471 BaseGraphWindow (const WindowDesc *desc, int widget, StringID format_str_y_axis) :
472 Window(desc),
473 excluded_data(0),
474 num_dataset(0),
475 num_on_x_axis(0),
476 num_vert_lines(24),
477 month(0),
478 year(0),
479 x_values_start(0),
480 x_values_increment(0),
481 graph_widget(widget),
482 format_str_y_axis(format_str_y_axis)
484 memset (this->colours, 0, sizeof(this->colours));
485 memset (this->cost, 0, sizeof(this->cost));
486 SetWindowDirty(WC_GRAPH_LEGEND, 0);
489 void InitializeWindow(WindowNumber number)
491 /* Initialise the dataset */
492 this->UpdateStatistics(true);
494 this->InitNested(number);
497 public:
498 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
500 if (widget != this->graph_widget) return;
502 uint x_label_width = 0;
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, month + STR_MONTH_ABBREV_JAN + 2);
510 SetDParam(2, year);
511 x_label_width = max(x_label_width, GetStringBoundingBox(month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH).width);
513 month += 3;
514 if (month >= 12) {
515 month = 0;
516 year++;
519 } else {
520 /* Draw the label under the data point rather than on the grid line. */
521 SetDParamMaxValue(0, this->x_values_start + this->num_on_x_axis * this->x_values_increment, 0, FS_SMALL);
522 x_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL_NUMBER).width;
525 SetDParam(0, this->format_str_y_axis);
526 SetDParam(1, INT64_MAX);
527 uint y_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL).width;
529 size->width = max<uint>(size->width, 5 + y_label_width + this->num_on_x_axis * (x_label_width + 5) + 9);
530 size->height = max<uint>(size->height, 5 + (1 + MIN_GRAPH_NUM_LINES_Y * 2 + (this->month != 0xFF ? 3 : 1)) * FONT_HEIGHT_SMALL + 4);
531 size->height = max<uint>(size->height, size->width / 3);
534 virtual void DrawWidget(const Rect &r, int widget) const
536 if (widget != this->graph_widget) return;
538 DrawGraph(r);
541 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
543 return INVALID_DATAPOINT;
546 virtual void OnClick(Point pt, int widget, int click_count)
548 /* Clicked on legend? */
549 if (widget == WID_CV_KEY_BUTTON) ShowGraphLegend();
552 virtual void OnTick()
554 this->UpdateStatistics(false);
558 * Some data on this window has become invalid.
559 * @param data Information about the changed data.
560 * @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.
562 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
564 if (!gui_scope) return;
565 this->UpdateStatistics(true);
569 * Update the statistics.
570 * @param initialize Initialize the data structure.
572 void UpdateStatistics(bool initialize)
574 uint excluded_companies = _legend_excluded_companies;
576 /* Exclude the companies which aren't valid */
577 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
578 if (!Company::IsValidID(c)) SetBit(excluded_companies, c);
581 byte nums = 0;
582 const Company *c;
583 FOR_ALL_COMPANIES(c) {
584 nums = min(this->num_vert_lines, max(nums, c->num_valid_stat_ent));
587 int mo = (_cur_month / 3 - nums) * 3;
588 int yr = _cur_year;
589 while (mo < 0) {
590 yr--;
591 mo += 12;
594 if (!initialize && this->excluded_data == excluded_companies && this->num_on_x_axis == nums &&
595 this->year == yr && this->month == mo) {
596 /* There's no reason to get new stats */
597 return;
600 this->excluded_data = excluded_companies;
601 this->num_on_x_axis = nums;
602 this->year = yr;
603 this->month = mo;
605 int numd = 0;
606 for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; k++) {
607 c = Company::GetIfValid(k);
608 if (c != NULL) {
609 this->colours[numd] = _colour_gradient[c->colour][6];
610 for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
611 this->cost[numd][i] = (j >= c->num_valid_stat_ent) ? INVALID_DATAPOINT : GetGraphData(c, j);
612 i++;
615 numd++;
618 this->num_dataset = numd;
623 /********************/
624 /* OPERATING PROFIT */
625 /********************/
627 struct OperatingProfitGraphWindow : BaseGraphWindow {
628 OperatingProfitGraphWindow (const WindowDesc *desc, WindowNumber window_number) :
629 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
631 this->InitializeWindow(window_number);
634 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
636 return c->old_economy[j].income + c->old_economy[j].expenses;
640 static const NWidgetPart _nested_operating_profit_widgets[] = {
641 NWidget(NWID_HORIZONTAL),
642 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
643 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_OPERATING_PROFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
644 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, 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),
645 NWidget(WWT_SHADEBOX, COLOUR_GREY),
646 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
647 NWidget(WWT_STICKYBOX, COLOUR_GREY),
648 EndContainer(),
649 NWidget(WWT_PANEL, COLOUR_GREY, WID_CV_BACKGROUND),
650 NWidget(NWID_HORIZONTAL),
651 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CV_GRAPH), SetMinimalSize(576, 160), SetFill(1, 1), SetResize(1, 1),
652 NWidget(NWID_VERTICAL),
653 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
654 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CV_RESIZE),
655 EndContainer(),
656 EndContainer(),
657 EndContainer(),
660 static WindowDesc::Prefs _operating_profit_prefs ("graph_operating_profit");
662 static const WindowDesc _operating_profit_desc(
663 WDP_AUTO, 0, 0,
664 WC_OPERATING_PROFIT, WC_NONE,
666 _nested_operating_profit_widgets, lengthof(_nested_operating_profit_widgets),
667 &_operating_profit_prefs
671 void ShowOperatingProfitGraph()
673 AllocateWindowDescFront<OperatingProfitGraphWindow>(&_operating_profit_desc, 0);
677 /****************/
678 /* INCOME GRAPH */
679 /****************/
681 struct IncomeGraphWindow : BaseGraphWindow {
682 IncomeGraphWindow (const WindowDesc *desc, WindowNumber window_number) :
683 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
685 this->InitializeWindow(window_number);
688 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
690 return c->old_economy[j].income;
694 static const NWidgetPart _nested_income_graph_widgets[] = {
695 NWidget(NWID_HORIZONTAL),
696 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
697 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_INCOME_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
698 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, 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),
699 NWidget(WWT_SHADEBOX, COLOUR_GREY),
700 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
701 NWidget(WWT_STICKYBOX, COLOUR_GREY),
702 EndContainer(),
703 NWidget(WWT_PANEL, COLOUR_GREY, WID_CV_BACKGROUND),
704 NWidget(NWID_HORIZONTAL),
705 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CV_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
706 NWidget(NWID_VERTICAL),
707 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
708 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CV_RESIZE),
709 EndContainer(),
710 EndContainer(),
711 EndContainer(),
714 static WindowDesc::Prefs _income_graph_prefs ("graph_income");
716 static const WindowDesc _income_graph_desc(
717 WDP_AUTO, 0, 0,
718 WC_INCOME_GRAPH, WC_NONE,
720 _nested_income_graph_widgets, lengthof(_nested_income_graph_widgets),
721 &_income_graph_prefs
724 void ShowIncomeGraph()
726 AllocateWindowDescFront<IncomeGraphWindow>(&_income_graph_desc, 0);
729 /*******************/
730 /* DELIVERED CARGO */
731 /*******************/
733 struct DeliveredCargoGraphWindow : BaseGraphWindow {
734 DeliveredCargoGraphWindow (const WindowDesc *desc, WindowNumber window_number) :
735 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_COMMA)
737 this->InitializeWindow(window_number);
740 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
742 return c->old_economy[j].delivered_cargo.GetSum<OverflowSafeInt64>();
746 static const NWidgetPart _nested_delivered_cargo_graph_widgets[] = {
747 NWidget(NWID_HORIZONTAL),
748 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
749 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_CARGO_DELIVERED_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
750 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, 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),
751 NWidget(WWT_SHADEBOX, COLOUR_GREY),
752 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
753 NWidget(WWT_STICKYBOX, COLOUR_GREY),
754 EndContainer(),
755 NWidget(WWT_PANEL, COLOUR_GREY, WID_CV_BACKGROUND),
756 NWidget(NWID_HORIZONTAL),
757 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CV_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
758 NWidget(NWID_VERTICAL),
759 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
760 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CV_RESIZE),
761 EndContainer(),
762 EndContainer(),
763 EndContainer(),
766 static WindowDesc::Prefs _delivered_cargo_graph_prefs ("graph_delivered_cargo");
768 static const WindowDesc _delivered_cargo_graph_desc(
769 WDP_AUTO, 0, 0,
770 WC_DELIVERED_CARGO, WC_NONE,
772 _nested_delivered_cargo_graph_widgets, lengthof(_nested_delivered_cargo_graph_widgets),
773 &_delivered_cargo_graph_prefs
776 void ShowDeliveredCargoGraph()
778 AllocateWindowDescFront<DeliveredCargoGraphWindow>(&_delivered_cargo_graph_desc, 0);
781 /***********************/
782 /* PERFORMANCE HISTORY */
783 /***********************/
785 struct PerformanceHistoryGraphWindow : BaseGraphWindow {
786 PerformanceHistoryGraphWindow (const WindowDesc *desc, WindowNumber window_number) :
787 BaseGraphWindow(desc, WID_PHG_GRAPH, STR_JUST_COMMA)
789 this->InitializeWindow(window_number);
792 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
794 return c->old_economy[j].performance_history;
797 virtual void OnClick(Point pt, int widget, int click_count)
799 if (widget == WID_PHG_DETAILED_PERFORMANCE) ShowPerformanceRatingDetail();
800 this->BaseGraphWindow::OnClick(pt, widget, click_count);
804 static const NWidgetPart _nested_performance_history_widgets[] = {
805 NWidget(NWID_HORIZONTAL),
806 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
807 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_COMPANY_PERFORMANCE_RATINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
808 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, 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),
809 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_PHG_KEY), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
810 NWidget(WWT_SHADEBOX, COLOUR_GREY),
811 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
812 NWidget(WWT_STICKYBOX, COLOUR_GREY),
813 EndContainer(),
814 NWidget(WWT_PANEL, COLOUR_GREY, WID_PHG_BACKGROUND),
815 NWidget(NWID_HORIZONTAL),
816 NWidget(WWT_EMPTY, COLOUR_GREY, WID_PHG_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
817 NWidget(NWID_VERTICAL),
818 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
819 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_PHG_RESIZE),
820 EndContainer(),
821 EndContainer(),
822 EndContainer(),
825 static WindowDesc::Prefs _performance_history_prefs ("graph_performance");
827 static const WindowDesc _performance_history_desc(
828 WDP_AUTO, 0, 0,
829 WC_PERFORMANCE_HISTORY, WC_NONE,
831 _nested_performance_history_widgets, lengthof(_nested_performance_history_widgets),
832 &_performance_history_prefs
835 void ShowPerformanceHistoryGraph()
837 AllocateWindowDescFront<PerformanceHistoryGraphWindow>(&_performance_history_desc, 0);
840 /*****************/
841 /* COMPANY VALUE */
842 /*****************/
844 struct CompanyValueGraphWindow : BaseGraphWindow {
845 CompanyValueGraphWindow (const WindowDesc *desc, WindowNumber window_number) :
846 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
848 this->InitializeWindow(window_number);
851 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
853 return c->old_economy[j].company_value;
857 static const NWidgetPart _nested_company_value_graph_widgets[] = {
858 NWidget(NWID_HORIZONTAL),
859 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
860 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_COMPANY_VALUES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
861 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, 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),
862 NWidget(WWT_SHADEBOX, COLOUR_GREY),
863 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
864 NWidget(WWT_STICKYBOX, COLOUR_GREY),
865 EndContainer(),
866 NWidget(WWT_PANEL, COLOUR_GREY, WID_CV_BACKGROUND),
867 NWidget(NWID_HORIZONTAL),
868 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CV_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
869 NWidget(NWID_VERTICAL),
870 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
871 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CV_RESIZE),
872 EndContainer(),
873 EndContainer(),
874 EndContainer(),
877 static WindowDesc::Prefs _company_value_graph_prefs ("graph_company_value");
879 static const WindowDesc _company_value_graph_desc(
880 WDP_AUTO, 0, 0,
881 WC_COMPANY_VALUE, WC_NONE,
883 _nested_company_value_graph_widgets, lengthof(_nested_company_value_graph_widgets),
884 &_company_value_graph_prefs
887 void ShowCompanyValueGraph()
889 AllocateWindowDescFront<CompanyValueGraphWindow>(&_company_value_graph_desc, 0);
892 /*****************/
893 /* PAYMENT RATES */
894 /*****************/
896 struct PaymentRatesGraphWindow : BaseGraphWindow {
897 bool first_init; ///< This value is true until the first initialization of the window has finished.
898 PaymentRatesGraphWindow (const WindowDesc *desc, WindowNumber window_number) :
899 BaseGraphWindow(desc, WID_CPR_GRAPH, STR_JUST_CURRENCY_SHORT)
901 this->first_init = true;
902 this->num_on_x_axis = 20;
903 this->num_vert_lines = 20;
904 this->month = 0xFF;
905 this->x_values_start = 10;
906 this->x_values_increment = 10;
908 /* Initialise the dataset */
909 this->OnHundredthTick();
911 this->InitNested(window_number);
913 this->UpdateLoweredWidgets();
916 virtual void OnInit()
918 /* UpdateLoweredWidgets needs to be called after a language or NewGRF change, but it can't be called before
919 * InitNested is done. On the first init these functions are called in the correct order by the constructor. */
920 if (!this->first_init) {
921 /* Initialise the dataset */
922 this->OnHundredthTick();
923 this->UpdateLoweredWidgets();
925 this->first_init = false;
928 void UpdateExcludedData()
930 this->excluded_data = 0;
932 int i = 0;
933 const CargoSpec *cs;
934 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
935 if (HasBit(_legend_excluded_cargo, cs->Index())) SetBit(this->excluded_data, i);
936 i++;
940 void UpdateLoweredWidgets()
942 for (int i = 0; i < _sorted_standard_cargo_specs_size; i++) {
943 this->SetWidgetLoweredState(WID_CPR_CARGO_FIRST + i, !HasBit(this->excluded_data, i));
947 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
949 if (widget < WID_CPR_CARGO_FIRST) {
950 BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
951 return;
954 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_CPR_CARGO_FIRST];
955 SetDParam(0, cs->name);
956 Dimension d = GetStringBoundingBox(STR_GRAPH_CARGO_PAYMENT_CARGO);
957 d.width += 14; // colour field
958 d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
959 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
960 *size = maxdim(d, *size);
963 virtual void DrawWidget(const Rect &r, int widget) const
965 if (widget < WID_CPR_CARGO_FIRST) {
966 BaseGraphWindow::DrawWidget(r, widget);
967 return;
970 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_CPR_CARGO_FIRST];
971 bool rtl = _current_text_dir == TD_RTL;
973 /* Since the buttons have no text, no images,
974 * both the text and the coloured box have to be manually painted.
975 * clk_dif will move one pixel down and one pixel to the right
976 * when the button is clicked */
977 byte clk_dif = this->IsWidgetLowered(widget) ? 1 : 0;
978 int x = r.left + WD_FRAMERECT_LEFT;
979 int y = r.top;
981 int rect_x = clk_dif + (rtl ? r.right - 12 : r.left + WD_FRAMERECT_LEFT);
983 GfxFillRect(rect_x, y + clk_dif, rect_x + 8, y + 5 + clk_dif, PC_BLACK);
984 GfxFillRect(rect_x + 1, y + 1 + clk_dif, rect_x + 7, y + 4 + clk_dif, cs->legend_colour);
985 SetDParam(0, cs->name);
986 DrawString(rtl ? r.left : x + 14 + clk_dif, (rtl ? r.right - 14 + clk_dif : r.right), y + clk_dif, STR_GRAPH_CARGO_PAYMENT_CARGO);
989 virtual void OnClick(Point pt, int widget, int click_count)
991 switch (widget) {
992 case WID_CPR_ENABLE_CARGOES:
993 /* Remove all cargoes from the excluded lists. */
994 _legend_excluded_cargo = 0;
995 this->excluded_data = 0;
996 this->UpdateLoweredWidgets();
997 this->SetDirty();
998 break;
1000 case WID_CPR_DISABLE_CARGOES: {
1001 /* Add all cargoes to the excluded lists. */
1002 int i = 0;
1003 const CargoSpec *cs;
1004 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1005 SetBit(_legend_excluded_cargo, cs->Index());
1006 SetBit(this->excluded_data, i);
1007 i++;
1009 this->UpdateLoweredWidgets();
1010 this->SetDirty();
1011 break;
1014 default:
1015 if (widget >= WID_CPR_CARGO_FIRST) {
1016 int i = widget - WID_CPR_CARGO_FIRST;
1017 ToggleBit(_legend_excluded_cargo, _sorted_cargo_specs[i]->Index());
1018 this->ToggleWidgetLoweredState(widget);
1019 this->UpdateExcludedData();
1020 this->SetDirty();
1022 break;
1026 virtual void OnTick()
1028 /* Override default OnTick */
1032 * Some data on this window has become invalid.
1033 * @param data Information about the changed data.
1034 * @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.
1036 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1038 if (!gui_scope) return;
1039 this->OnHundredthTick();
1042 virtual void OnHundredthTick()
1044 this->UpdateExcludedData();
1046 int i = 0;
1047 const CargoSpec *cs;
1048 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1049 this->colours[i] = cs->legend_colour;
1050 for (uint j = 0; j != 20; j++) {
1051 this->cost[i][j] = GetTransportedGoodsIncome(10, 20, j * 4 + 4, cs->Index());
1053 i++;
1055 this->num_dataset = i;
1059 /** Construct the row containing the digit keys. */
1060 static NWidgetBase *MakeCargoButtons(int *biggest_index)
1062 NWidgetVertical *ver = new NWidgetVertical;
1064 for (int i = 0; i < _sorted_standard_cargo_specs_size; i++) {
1065 NWidgetBackground *leaf = new NWidgetBackground(WWT_PANEL, COLOUR_ORANGE, WID_CPR_CARGO_FIRST + i, NULL);
1066 leaf->tool_tip = STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO;
1067 leaf->SetFill(1, 0);
1068 leaf->SetLowered(true);
1069 ver->Add(leaf);
1071 *biggest_index = WID_CPR_CARGO_FIRST + _sorted_standard_cargo_specs_size - 1;
1072 return ver;
1076 static const NWidgetPart _nested_cargo_payment_rates_widgets[] = {
1077 NWidget(NWID_HORIZONTAL),
1078 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1079 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1080 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1081 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1082 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1083 EndContainer(),
1084 NWidget(WWT_PANEL, COLOUR_GREY, WID_CPR_BACKGROUND), SetMinimalSize(568, 128),
1085 NWidget(NWID_HORIZONTAL),
1086 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1087 NWidget(WWT_TEXT, COLOUR_GREY, WID_CPR_HEADER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_TITLE, STR_NULL),
1088 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1089 EndContainer(),
1090 NWidget(NWID_HORIZONTAL),
1091 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CPR_GRAPH), SetMinimalSize(495, 0), SetFill(1, 1), SetResize(1, 1),
1092 NWidget(NWID_VERTICAL),
1093 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 0), SetResize(0, 1),
1094 NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_CPR_ENABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1095 NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_CPR_DISABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1096 NWidget(NWID_SPACER), SetMinimalSize(0, 4),
1097 NWidgetFunction(MakeCargoButtons),
1098 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1), SetResize(0, 1),
1099 EndContainer(),
1100 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1101 EndContainer(),
1102 NWidget(NWID_HORIZONTAL),
1103 NWidget(NWID_SPACER), SetMinimalSize(WD_RESIZEBOX_WIDTH, 0), SetFill(1, 0), SetResize(1, 0),
1104 NWidget(WWT_TEXT, COLOUR_GREY, WID_CPR_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_X_LABEL, STR_NULL),
1105 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1106 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CPR_RESIZE),
1107 EndContainer(),
1108 EndContainer(),
1111 static WindowDesc::Prefs _cargo_payment_rates_prefs ("graph_cargo_payment_rates");
1113 static const WindowDesc _cargo_payment_rates_desc(
1114 WDP_AUTO, 0, 0,
1115 WC_PAYMENT_RATES, WC_NONE,
1117 _nested_cargo_payment_rates_widgets, lengthof(_nested_cargo_payment_rates_widgets),
1118 &_cargo_payment_rates_prefs
1122 void ShowCargoPaymentRates()
1124 AllocateWindowDescFront<PaymentRatesGraphWindow>(&_cargo_payment_rates_desc, 0);
1127 /************************/
1128 /* COMPANY LEAGUE TABLE */
1129 /************************/
1131 static const StringID _performance_titles[] = {
1132 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ENGINEER,
1133 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ENGINEER,
1134 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRAFFIC_MANAGER,
1135 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRAFFIC_MANAGER,
1136 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRANSPORT_COORDINATOR,
1137 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRANSPORT_COORDINATOR,
1138 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ROUTE_SUPERVISOR,
1139 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ROUTE_SUPERVISOR,
1140 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_DIRECTOR,
1141 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_DIRECTOR,
1142 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHIEF_EXECUTIVE,
1143 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHIEF_EXECUTIVE,
1144 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHAIRMAN,
1145 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHAIRMAN,
1146 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_PRESIDENT,
1147 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TYCOON,
1150 static inline StringID GetPerformanceTitleFromValue(uint value)
1152 return _performance_titles[minu(value, 1000) >> 6];
1155 class CompanyLeagueWindow : public Window {
1156 private:
1157 GUIList<const Company*> companies;
1158 uint ordinal_width; ///< The width of the ordinal number
1159 uint text_width; ///< The width of the actual text
1160 uint icon_width; ///< The width of the company icon
1161 int line_height; ///< Height of the text lines
1164 * (Re)Build the company league list
1166 void BuildCompanyList()
1168 if (!this->companies.NeedRebuild()) return;
1170 this->companies.Clear();
1172 const Company *c;
1173 FOR_ALL_COMPANIES(c) {
1174 *this->companies.Append() = c;
1177 this->companies.Compact();
1178 this->companies.RebuildDone();
1181 /** Sort the company league by performance history */
1182 static int CDECL PerformanceSorter(const Company * const *c1, const Company * const *c2)
1184 return (*c2)->old_economy[0].performance_history - (*c1)->old_economy[0].performance_history;
1187 public:
1188 CompanyLeagueWindow (const WindowDesc *desc, WindowNumber window_number)
1189 : Window (desc), companies(), ordinal_width (0),
1190 text_width (0), icon_width (0), line_height (0)
1192 this->InitNested(window_number);
1193 this->companies.ForceRebuild();
1194 this->companies.NeedResort();
1197 virtual void OnPaint()
1199 this->BuildCompanyList();
1200 this->companies.Sort(&PerformanceSorter);
1202 this->DrawWidgets();
1205 virtual void DrawWidget(const Rect &r, int widget) const
1207 if (widget != WID_CL_BACKGROUND) return;
1209 int icon_y_offset = 1 + (FONT_HEIGHT_NORMAL - this->line_height) / 2;
1210 uint y = r.top + WD_FRAMERECT_TOP - icon_y_offset;
1212 bool rtl = _current_text_dir == TD_RTL;
1213 uint ordinal_left = rtl ? r.right - WD_FRAMERECT_LEFT - this->ordinal_width : r.left + WD_FRAMERECT_LEFT;
1214 uint ordinal_right = rtl ? r.right - WD_FRAMERECT_LEFT : r.left + WD_FRAMERECT_LEFT + this->ordinal_width;
1215 uint icon_left = r.left + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT + (rtl ? this->text_width : this->ordinal_width);
1216 uint text_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - WD_FRAMERECT_LEFT - this->text_width;
1217 uint text_right = rtl ? r.left + WD_FRAMERECT_LEFT + this->text_width : r.right - WD_FRAMERECT_LEFT;
1219 for (uint i = 0; i != this->companies.Length(); i++) {
1220 const Company *c = this->companies[i];
1221 DrawString(ordinal_left, ordinal_right, y, i + STR_ORDINAL_NUMBER_1ST, i == 0 ? TC_WHITE : TC_YELLOW);
1223 DrawCompanyIcon(c->index, icon_left, y + icon_y_offset);
1225 SetDParam(0, c->index);
1226 SetDParam(1, c->index);
1227 SetDParam(2, GetPerformanceTitleFromValue(c->old_economy[0].performance_history));
1228 DrawString(text_left, text_right, y, STR_COMPANY_LEAGUE_COMPANY_NAME);
1229 y += this->line_height;
1233 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1235 if (widget != WID_CL_BACKGROUND) return;
1237 this->ordinal_width = 0;
1238 for (uint i = 0; i < MAX_COMPANIES; i++) {
1239 this->ordinal_width = max(this->ordinal_width, GetStringBoundingBox(STR_ORDINAL_NUMBER_1ST + i).width);
1241 this->ordinal_width += 5; // Keep some extra spacing
1243 uint widest_width = 0;
1244 uint widest_title = 0;
1245 for (uint i = 0; i < lengthof(_performance_titles); i++) {
1246 uint width = GetStringBoundingBox(_performance_titles[i]).width;
1247 if (width > widest_width) {
1248 widest_title = i;
1249 widest_width = width;
1253 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
1254 this->icon_width = d.width + 2;
1255 this->line_height = max<int>(d.height + 2, FONT_HEIGHT_NORMAL);
1257 const Company *c;
1258 FOR_ALL_COMPANIES(c) {
1259 SetDParam(0, c->index);
1260 SetDParam(1, c->index);
1261 SetDParam(2, _performance_titles[widest_title]);
1262 widest_width = max(widest_width, GetStringBoundingBox(STR_COMPANY_LEAGUE_COMPANY_NAME).width);
1265 this->text_width = widest_width + 30; // Keep some extra spacing
1267 size->width = WD_FRAMERECT_LEFT + this->ordinal_width + WD_FRAMERECT_RIGHT + this->icon_width + WD_FRAMERECT_LEFT + this->text_width + WD_FRAMERECT_RIGHT;
1268 size->height = WD_FRAMERECT_TOP + this->line_height * MAX_COMPANIES + WD_FRAMERECT_BOTTOM;
1272 virtual void OnTick()
1274 if (this->companies.NeedResort()) {
1275 this->SetDirty();
1280 * Some data on this window has become invalid.
1281 * @param data Information about the changed data.
1282 * @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.
1284 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1286 if (data == 0) {
1287 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1288 this->companies.ForceRebuild();
1289 } else {
1290 this->companies.ForceResort();
1295 static const NWidgetPart _nested_company_league_widgets[] = {
1296 NWidget(NWID_HORIZONTAL),
1297 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1298 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_COMPANY_LEAGUE_TABLE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1299 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1300 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1301 EndContainer(),
1302 NWidget(WWT_PANEL, COLOUR_GREY, WID_CL_BACKGROUND), SetMinimalSize(400, 0), SetMinimalTextLines(15, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM),
1305 static WindowDesc::Prefs _company_league_prefs ("league");
1307 static const WindowDesc _company_league_desc(
1308 WDP_AUTO, 0, 0,
1309 WC_COMPANY_LEAGUE, WC_NONE,
1311 _nested_company_league_widgets, lengthof(_nested_company_league_widgets),
1312 &_company_league_prefs
1315 void ShowCompanyLeagueTable()
1317 AllocateWindowDescFront<CompanyLeagueWindow>(&_company_league_desc, 0);
1320 /*****************************/
1321 /* PERFORMANCE RATING DETAIL */
1322 /*****************************/
1324 struct PerformanceRatingDetailWindow : Window {
1325 static CompanyID company;
1326 int timeout;
1328 PerformanceRatingDetailWindow (const WindowDesc *desc, WindowNumber window_number)
1329 : Window (desc), timeout (0)
1331 this->UpdateCompanyStats();
1333 this->InitNested(window_number);
1334 this->OnInvalidateData(INVALID_COMPANY);
1337 void UpdateCompanyStats()
1339 /* Update all company stats with the current data
1340 * (this is because _score_info is not saved to a savegame) */
1341 Company *c;
1342 FOR_ALL_COMPANIES(c) {
1343 UpdateCompanyRatingAndValue(c, false);
1346 this->timeout = DAY_TICKS * 5;
1349 uint score_info_left;
1350 uint score_info_right;
1351 uint bar_left;
1352 uint bar_right;
1353 uint bar_width;
1354 uint bar_height;
1355 uint score_detail_left;
1356 uint score_detail_right;
1358 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1360 switch (widget) {
1361 case WID_PRD_SCORE_FIRST:
1362 this->bar_height = FONT_HEIGHT_NORMAL + 4;
1363 size->height = this->bar_height + 2 * WD_MATRIX_TOP;
1365 uint score_info_width = 0;
1366 for (uint i = SCORE_BEGIN; i < SCORE_END; i++) {
1367 score_info_width = max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + i).width);
1369 SetDParamMaxValue(0, 1000);
1370 score_info_width += GetStringBoundingBox(STR_BLACK_COMMA).width + WD_FRAMERECT_LEFT;
1372 SetDParamMaxValue(0, 100);
1373 this->bar_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_PERCENT).width + 20; // Wide bars!
1375 /* At this number we are roughly at the max; it can become wider,
1376 * but then you need at 1000 times more money. At that time you're
1377 * not that interested anymore in the last few digits anyway.
1378 * The 500 is because 999 999 500 to 999 999 999 are rounded to
1379 * 1 000 M, and not 999 999 k. Use negative numbers to account for
1380 * the negative income/amount of money etc. as well. */
1381 int max = -(999999999 - 500);
1383 /* Scale max for the display currency. Prior to rendering the value
1384 * is converted into the display currency, which may cause it to
1385 * raise significantly. We need to compensate for that since {{CURRCOMPACT}}
1386 * is used, which can produce quite short renderings of very large
1387 * values. Otherwise the calculated width could be too narrow.
1388 * Note that it doesn't work if there was a currency with an exchange
1389 * rate greater than max.
1390 * When the currency rate is more than 1000, the 999 999 k becomes at
1391 * least 999 999 M which roughly is equally long. Furthermore if the
1392 * exchange rate is that high, 999 999 k is usually not enough anymore
1393 * to show the different currency numbers. */
1394 if (_currency->rate < 1000) max /= _currency->rate;
1395 SetDParam(0, max);
1396 SetDParam(1, max);
1397 uint score_detail_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY).width;
1399 size->width = 7 + score_info_width + 5 + this->bar_width + 5 + score_detail_width + 7;
1400 uint left = 7;
1401 uint right = size->width - 7;
1403 bool rtl = _current_text_dir == TD_RTL;
1404 this->score_info_left = rtl ? right - score_info_width : left;
1405 this->score_info_right = rtl ? right : left + score_info_width;
1407 this->score_detail_left = rtl ? left : right - score_detail_width;
1408 this->score_detail_right = rtl ? left + score_detail_width : right;
1410 this->bar_left = left + (rtl ? score_detail_width : score_info_width) + 5;
1411 this->bar_right = this->bar_left + this->bar_width;
1412 break;
1416 virtual void DrawWidget(const Rect &r, int widget) const
1418 /* No need to draw when there's nothing to draw */
1419 if (this->company == INVALID_COMPANY) return;
1421 if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
1422 if (this->IsWidgetDisabled(widget)) return;
1423 CompanyID cid = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1424 int offset = (cid == this->company) ? 1 : 0;
1425 Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
1426 DrawCompanyIcon(cid, (r.left + r.right - sprite_size.width) / 2 + offset, (r.top + r.bottom - sprite_size.height) / 2 + offset);
1427 return;
1430 if (!IsInsideMM(widget, WID_PRD_SCORE_FIRST, WID_PRD_SCORE_LAST + 1)) return;
1432 ScoreID score_type = (ScoreID)(widget - WID_PRD_SCORE_FIRST);
1434 /* The colours used to show how the progress is going */
1435 int colour_done = _colour_gradient[COLOUR_GREEN][4];
1436 int colour_notdone = _colour_gradient[COLOUR_RED][4];
1438 /* Draw all the score parts */
1439 int val = _score_part[company][score_type];
1440 int needed = _score_info[score_type].needed;
1441 int score = _score_info[score_type].score;
1443 /* SCORE_TOTAL has his own rules ;) */
1444 if (score_type == SCORE_TOTAL) {
1445 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) score += _score_info[i].score;
1446 needed = SCORE_MAX;
1449 uint bar_top = r.top + WD_MATRIX_TOP;
1450 uint text_top = bar_top + 2;
1452 DrawString(this->score_info_left, this->score_info_right, text_top, STR_PERFORMANCE_DETAIL_VEHICLES + score_type);
1454 /* Draw the score */
1455 SetDParam(0, score);
1456 DrawString(this->score_info_left, this->score_info_right, text_top, STR_BLACK_COMMA, TC_FROMSTRING, SA_RIGHT);
1458 /* Calculate the %-bar */
1459 uint x = Clamp(val, 0, needed) * this->bar_width / needed;
1460 bool rtl = _current_text_dir == TD_RTL;
1461 if (rtl) {
1462 x = this->bar_right - x;
1463 } else {
1464 x = this->bar_left + x;
1467 /* Draw the bar */
1468 if (x != this->bar_left) GfxFillRect(this->bar_left, bar_top, x, bar_top + this->bar_height, rtl ? colour_notdone : colour_done);
1469 if (x != this->bar_right) GfxFillRect(x, bar_top, this->bar_right, bar_top + this->bar_height, rtl ? colour_done : colour_notdone);
1471 /* Draw it */
1472 SetDParam(0, Clamp(val, 0, needed) * 100 / needed);
1473 DrawString(this->bar_left, this->bar_right, text_top, STR_PERFORMANCE_DETAIL_PERCENT, TC_FROMSTRING, SA_HOR_CENTER);
1475 /* SCORE_LOAN is inversed */
1476 if (score_type == SCORE_LOAN) val = needed - val;
1478 /* Draw the amount we have against what is needed
1479 * For some of them it is in currency format */
1480 SetDParam(0, val);
1481 SetDParam(1, needed);
1482 switch (score_type) {
1483 case SCORE_MIN_PROFIT:
1484 case SCORE_MIN_INCOME:
1485 case SCORE_MAX_INCOME:
1486 case SCORE_MONEY:
1487 case SCORE_LOAN:
1488 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY);
1489 break;
1490 default:
1491 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_INT);
1495 virtual void OnClick(Point pt, int widget, int click_count)
1497 /* Check which button is clicked */
1498 if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
1499 /* Is it no on disable? */
1500 if (!this->IsWidgetDisabled(widget)) {
1501 this->RaiseWidget(this->company + WID_PRD_COMPANY_FIRST);
1502 this->company = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1503 this->LowerWidget(this->company + WID_PRD_COMPANY_FIRST);
1504 this->SetDirty();
1509 virtual void OnTick()
1511 if (_pause_mode != PM_UNPAUSED) return;
1513 /* Update the company score every 5 days */
1514 if (--this->timeout == 0) {
1515 this->UpdateCompanyStats();
1516 this->SetDirty();
1521 * Some data on this window has become invalid.
1522 * @param data the company ID of the company that is going to be removed
1523 * @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.
1525 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1527 if (!gui_scope) return;
1528 /* Disable the companies who are not active */
1529 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
1530 this->SetWidgetDisabledState(i + WID_PRD_COMPANY_FIRST, !Company::IsValidID(i));
1533 /* Check if the currently selected company is still active. */
1534 if (this->company != INVALID_COMPANY && !Company::IsValidID(this->company)) {
1535 /* Raise the widget for the previous selection. */
1536 this->RaiseWidget(this->company + WID_PRD_COMPANY_FIRST);
1537 this->company = INVALID_COMPANY;
1540 if (this->company == INVALID_COMPANY) {
1541 const Company *c;
1542 FOR_ALL_COMPANIES(c) {
1543 this->company = c->index;
1544 break;
1548 /* Make sure the widget is lowered */
1549 this->LowerWidget(this->company + WID_PRD_COMPANY_FIRST);
1553 CompanyID PerformanceRatingDetailWindow::company = INVALID_COMPANY;
1556 * Make a vertical list of panels for outputting score details.
1557 * @param biggest_index Storage for collecting the biggest index used in the returned tree.
1558 * @return Panel with performance details.
1559 * @post \c *biggest_index contains the largest used index in the tree.
1561 static NWidgetBase *MakePerformanceDetailPanels(int *biggest_index)
1563 const StringID performance_tips[] = {
1564 STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP,
1565 STR_PERFORMANCE_DETAIL_STATIONS_TOOLTIP,
1566 STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP,
1567 STR_PERFORMANCE_DETAIL_MIN_INCOME_TOOLTIP,
1568 STR_PERFORMANCE_DETAIL_MAX_INCOME_TOOLTIP,
1569 STR_PERFORMANCE_DETAIL_DELIVERED_TOOLTIP,
1570 STR_PERFORMANCE_DETAIL_CARGO_TOOLTIP,
1571 STR_PERFORMANCE_DETAIL_MONEY_TOOLTIP,
1572 STR_PERFORMANCE_DETAIL_LOAN_TOOLTIP,
1573 STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP,
1576 assert_compile(lengthof(performance_tips) == SCORE_END - SCORE_BEGIN);
1578 NWidgetVertical *vert = new NWidgetVertical(NC_EQUALSIZE);
1579 for (int widnum = WID_PRD_SCORE_FIRST; widnum <= WID_PRD_SCORE_LAST; widnum++) {
1580 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, widnum);
1581 panel->SetFill(1, 1);
1582 panel->SetDataTip(0x0, performance_tips[widnum - WID_PRD_SCORE_FIRST]);
1583 vert->Add(panel);
1585 *biggest_index = WID_PRD_SCORE_LAST;
1586 return vert;
1589 /** Make a number of rows with buttons for each company for the performance rating detail window. */
1590 NWidgetBase *MakeCompanyButtonRowsGraphGUI(int *biggest_index)
1592 return MakeCompanyButtonRows(biggest_index, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST, 8, STR_PERFORMANCE_DETAIL_SELECT_COMPANY_TOOLTIP);
1595 static const NWidgetPart _nested_performance_rating_detail_widgets[] = {
1596 NWidget(NWID_HORIZONTAL),
1597 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1598 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_PERFORMANCE_DETAIL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1599 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1600 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1601 EndContainer(),
1602 NWidget(WWT_PANEL, COLOUR_GREY),
1603 NWidgetFunction(MakeCompanyButtonRowsGraphGUI), SetPadding(0, 1, 1, 2),
1604 EndContainer(),
1605 NWidgetFunction(MakePerformanceDetailPanels),
1608 static WindowDesc::Prefs _performance_rating_detail_prefs ("league_details");
1610 static const WindowDesc _performance_rating_detail_desc(
1611 WDP_AUTO, 0, 0,
1612 WC_PERFORMANCE_DETAIL, WC_NONE,
1614 _nested_performance_rating_detail_widgets, lengthof(_nested_performance_rating_detail_widgets),
1615 &_performance_rating_detail_prefs
1618 void ShowPerformanceRatingDetail()
1620 AllocateWindowDescFront<PerformanceRatingDetailWindow>(&_performance_rating_detail_desc, 0);