OpenTTD Source 20250205-master-gfd85ab1e2c
graph_gui.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#include "stdafx.h"
11#include "graph_gui.h"
12#include "window_gui.h"
13#include "company_base.h"
14#include "company_gui.h"
15#include "economy_func.h"
16#include "cargotype.h"
17#include "strings_func.h"
18#include "window_func.h"
19#include "gfx_func.h"
21#include "currency.h"
22#include "timer/timer.h"
23#include "timer/timer_window.h"
26#include "zoom_func.h"
27#include "industry.h"
28
30
31#include "table/strings.h"
32#include "table/sprites.h"
33
34#include "safeguards.h"
35
36/* Bitmasks of company and cargo indices that shouldn't be drawn. */
37static CompanyMask _legend_excluded_companies;
38static CargoTypes _legend_excluded_cargo_payment_rates;
39static CargoTypes _legend_excluded_cargo_production_history;
40
41/* Apparently these don't play well with enums. */
42static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX); // Value used for a datapoint that shouldn't be drawn.
43static const uint INVALID_DATAPOINT_POS = UINT_MAX; // Used to determine if the previous point was drawn.
44
45constexpr double INT64_MAX_IN_DOUBLE = static_cast<double>(INT64_MAX - 512);
46static_assert(static_cast<int64_t>(INT64_MAX_IN_DOUBLE) < INT64_MAX);
47
48/****************/
49/* GRAPH LEGEND */
50/****************/
51
54 {
55 this->InitNested(window_number);
56
57 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
58 if (!HasBit(_legend_excluded_companies, c)) this->LowerWidget(WID_GL_FIRST_COMPANY + c);
59
60 this->OnInvalidateData(c);
61 }
62 }
63
64 void DrawWidget(const Rect &r, WidgetID widget) const override
65 {
67
69
70 if (!Company::IsValidID(cid)) return;
71
73
74 const Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
75 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
76 DrawCompanyIcon(cid, rtl ? ir.right - d.width : ir.left, CenterBounds(ir.top, ir.bottom, d.height));
77
79 SetDParam(0, cid);
80 SetDParam(1, cid);
81 DrawString(tr.left, tr.right, CenterBounds(tr.top, tr.bottom, GetCharacterHeight(FS_NORMAL)), STR_COMPANY_NAME_COMPANY_NUM, HasBit(_legend_excluded_companies, cid) ? TC_BLACK : TC_WHITE);
82 }
83
97
103 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
104 {
105 if (!gui_scope) return;
106 if (Company::IsValidID(data)) return;
107
108 SetBit(_legend_excluded_companies, data);
109 this->RaiseWidget(data + WID_GL_FIRST_COMPANY);
110 }
111};
112
117static std::unique_ptr<NWidgetBase> MakeNWidgetCompanyLines()
118{
119 auto vert = std::make_unique<NWidgetVertical>(NC_EQUALSIZE);
120 vert->SetPadding(2, 2, 2, 2);
121 uint sprite_height = GetSpriteSize(SPR_COMPANY_ICON, nullptr, ZOOM_LVL_NORMAL).height;
122
123 for (WidgetID widnum = WID_GL_FIRST_COMPANY; widnum <= WID_GL_LAST_COMPANY; widnum++) {
124 auto panel = std::make_unique<NWidgetBackground>(WWT_PANEL, COLOUR_BROWN, widnum);
125 panel->SetMinimalSize(246, sprite_height + WidgetDimensions::unscaled.framerect.Vertical());
126 panel->SetMinimalTextLines(1, WidgetDimensions::unscaled.framerect.Vertical(), FS_NORMAL);
127 panel->SetFill(1, 1);
128 panel->SetToolTip(STR_GRAPH_KEY_COMPANY_SELECTION_TOOLTIP);
129 vert->Add(std::move(panel));
130 }
131 return vert;
132}
133
134static constexpr NWidgetPart _nested_graph_legend_widgets[] = {
136 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
137 NWidget(WWT_CAPTION, COLOUR_BROWN), SetStringTip(STR_GRAPH_KEY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
138 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
139 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
140 EndContainer(),
141 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GL_BACKGROUND),
143 EndContainer(),
144};
145
146static WindowDesc _graph_legend_desc(
147 WDP_AUTO, "graph_legend", 0, 0,
149 {},
150 _nested_graph_legend_widgets
151);
152
153static void ShowGraphLegend()
154{
155 AllocateWindowDescFront<GraphLegendWindow>(_graph_legend_desc, 0);
156}
157
163
164/******************/
165/* BASE OF GRAPHS */
166/*****************/
167
169protected:
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;
177 static const int PAYMENT_GRAPH_X_STEP_DAYS = 10;
178 static const int PAYMENT_GRAPH_X_STEP_SECONDS = 20;
179 static const int ECONOMY_QUARTER_MINUTES = 3;
180 static const int ECONOMY_MONTH_MINUTES = 1;
181
182 static const TextColour GRAPH_AXIS_LABEL_COLOUR = TC_BLACK;
183
184 static const int MIN_GRAPH_NUM_LINES_Y = 9;
185 static const int MIN_GRID_PIXEL_SIZE = 20;
186
189 uint8_t num_on_x_axis;
190 uint8_t num_vert_lines;
191
192 /* The starting month and year that values are plotted against. */
196
197 bool draw_dates = true;
198
199 /* These values are used if the graph is being plotted against values
200 * rather than the dates specified by month and year. */
201 uint16_t x_values_start;
202 uint16_t x_values_increment;
203
204 StringID format_str_y_axis;
205
206 struct DataSet {
207 std::array<OverflowSafeInt64, GRAPH_NUM_MONTHS> values;
208 uint8_t colour;
209 uint8_t exclude_bit;
210 uint8_t range_bit;
211 uint8_t dash;
212 };
213 std::vector<DataSet> data;
214
215 std::span<const StringID> ranges = {};
216
222 std::span<const OverflowSafeInt64> GetDataSetRange(const DataSet &dataset) const
223 {
224 return {std::begin(dataset.values), std::begin(dataset.values) + this->num_on_x_axis};
225 }
226
234 {
236
240
241 for (const DataSet &dataset : this->data) {
242 if (HasBit(this->excluded_data, dataset.exclude_bit)) continue;
243 if (HasBit(this->excluded_range, dataset.range_bit)) continue;
244
245 for (const OverflowSafeInt64 &datapoint : this->GetDataSetRange(dataset)) {
246 if (datapoint != INVALID_DATAPOINT) {
247 current_interval.highest = std::max(current_interval.highest, datapoint);
248 current_interval.lowest = std::min(current_interval.lowest, datapoint);
249 }
250 }
251 }
252
253 /* Always include zero in the shown range. */
254 double abs_lower = (current_interval.lowest > 0) ? 0 : (double)abs(current_interval.lowest);
255 double abs_higher = (current_interval.highest < 0) ? 0 : (double)current_interval.highest;
256
257 /* Prevent showing values too close to the graph limits. */
258 abs_higher = (11.0 * abs_higher) / 10.0;
259 abs_lower = (11.0 * abs_lower) / 10.0;
260
261 int num_pos_grids;
263
264 if (abs_lower != 0 || abs_higher != 0) {
265 /* The number of grids to reserve for the positive part is: */
267
268 /* If there are any positive or negative values, force that they have at least one grid. */
269 if (num_pos_grids == 0 && abs_higher != 0) num_pos_grids++;
271
272 /* Get the required grid size for each side and use the maximum one. */
273
275 if (abs_higher > 0) {
278 }
279
281 if (abs_lower > 0) {
284 }
285
287 } else {
288 /* If both values are zero, show an empty graph. */
290 grid_size = 1;
291 }
292
295 return current_interval;
296 }
297
304 {
305 /* draw text strings on the y axis */
308
309 uint max_width = 0;
310
311 for (int i = 0; i < (num_hori_lines + 1); i++) {
312 SetDParam(0, this->format_str_y_axis);
313 SetDParam(1, y_label);
315 if (d.width > max_width) max_width = d.width;
316
318 }
319
320 return max_width;
321 }
322
327 void DrawGraph(Rect r) const
328 {
329 uint x, y;
330 ValuesInterval interval;
331 int x_axis_offset;
332
333 /* the colours and cost array of GraphDrawer must accommodate
334 * both values for cargo and companies. So if any are higher, quit */
335 static_assert(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES);
336 assert(this->num_vert_lines > 0);
337
338 /* Rect r will be adjusted to contain just the graph, with labels being
339 * placed outside the area. */
340 r.top += ScaleGUITrad(5) + GetCharacterHeight(FS_SMALL) / 2;
341 r.bottom -= (this->draw_dates ? 2 : 1) * GetCharacterHeight(FS_SMALL) + ScaleGUITrad(4);
342 r.left += ScaleGUITrad(9);
343 r.right -= ScaleGUITrad(5);
344
345 /* Initial number of horizontal lines. */
347 /* For the rest of the height, the number of horizontal lines will increase more slowly. */
348 int resize = (r.bottom - r.top - 160) / (2 * ScaleGUITrad(MIN_GRID_PIXEL_SIZE));
349 if (resize > 0) num_hori_lines += resize;
350
352
354
355 r.left += label_width;
356
357 int x_sep = (r.right - r.left) / this->num_vert_lines;
358 int y_sep = (r.bottom - r.top) / num_hori_lines;
359
360 /* Redetermine right and bottom edge of graph to fit with the integer
361 * separation values. */
362 r.right = r.left + x_sep * this->num_vert_lines;
363 r.bottom = r.top + y_sep * num_hori_lines;
364
365 OverflowSafeInt64 interval_size = interval.highest + abs(interval.lowest);
366 /* Where to draw the X axis. Use floating point to avoid overflowing and results of zero. */
367 x_axis_offset = (int)((r.bottom - r.top) * (double)interval.highest / (double)interval_size);
368
369 /* Draw the background of the graph itself. */
370 GfxFillRect(r.left, r.top, r.right, r.bottom, GRAPH_BASE_COLOUR);
371
372 /* Draw the vertical grid lines. */
373
374 /* Don't draw the first line, as that's where the axis will be. */
375 x = r.left + x_sep;
376
377 int grid_colour = GRAPH_GRID_COLOUR;
378 for (int i = 1; i < this->num_vert_lines + 1; i++) {
379 /* If using wallclock units, we separate periods with a lighter line. */
381 grid_colour = (i % 4 == 0) ? GRAPH_YEAR_LINE_COLOUR : GRAPH_GRID_COLOUR;
382 }
383 GfxFillRect(x, r.top, x, r.bottom, grid_colour);
384 x += x_sep;
385 }
386
387 /* Draw the horizontal grid lines. */
388 y = r.bottom;
389
390 for (int i = 0; i < (num_hori_lines + 1); i++) {
391 GfxFillRect(r.left - ScaleGUITrad(3), y, r.left - 1, y, GRAPH_AXIS_LINE_COLOUR);
392 GfxFillRect(r.left, y, r.right, y, GRAPH_GRID_COLOUR);
393 y -= y_sep;
394 }
395
396 /* Draw the y axis. */
397 GfxFillRect(r.left, r.top, r.left, r.bottom, GRAPH_AXIS_LINE_COLOUR);
398
399 /* Draw the x axis. */
400 y = x_axis_offset + r.top;
401 GfxFillRect(r.left, y, r.right, y, GRAPH_ZERO_LINE_COLOUR);
402
403 /* Find the largest value that will be drawn. */
404 if (this->num_on_x_axis == 0) return;
405
406 assert(this->num_on_x_axis > 0);
407
408 /* draw text strings on the y axis */
409 int64_t y_label = interval.highest;
411
412 y = r.top - GetCharacterHeight(FS_SMALL) / 2;
413
414 for (int i = 0; i < (num_hori_lines + 1); i++) {
415 SetDParam(0, this->format_str_y_axis);
416 SetDParam(1, y_label);
418
420 y += y_sep;
421 }
422
423 /* Draw x-axis labels and markings for graphs based on financial quarters and years. */
424 if (this->draw_dates) {
425 x = r.left;
426 y = r.bottom + ScaleGUITrad(2);
427 TimerGameEconomy::Month month = this->month;
428 TimerGameEconomy::Year year = this->year;
429 for (int i = 0; i < this->num_on_x_axis; i++) {
431 SetDParam(1, year);
433
434 month += this->month_increment;
435 if (month >= 12) {
436 month = 0;
437 year++;
438
439 /* Draw a lighter grid line between years. Top and bottom adjustments ensure we don't draw over top and bottom horizontal grid lines. */
440 GfxFillRect(x + x_sep, r.top + 1, x + x_sep, r.bottom - 1, GRAPH_YEAR_LINE_COLOUR);
441 }
442 x += x_sep;
443 }
444 } else {
445 /* Draw x-axis labels for graphs not based on quarterly performance (cargo payment rates, and all graphs when using wallclock units). */
446 x = r.left;
447 y = r.bottom + ScaleGUITrad(2);
448 uint16_t label = this->x_values_start;
449
450 for (int i = 0; i < this->num_on_x_axis; i++) {
451 SetDParam(0, label);
453
454 label += this->x_values_increment;
455 x += x_sep;
456 }
457 }
458
459 /* draw lines and dots */
461 uint pointoffs1 = (linewidth + 1) / 2;
462 uint pointoffs2 = linewidth + 1 - pointoffs1;
463
464 for (const DataSet &dataset : this->data) {
465 if (HasBit(this->excluded_data, dataset.exclude_bit)) continue;
466 if (HasBit(this->excluded_range, dataset.range_bit)) continue;
467
468 /* Centre the dot between the grid lines. */
469 x = r.left + (x_sep / 2);
470
471 uint prev_x = INVALID_DATAPOINT_POS;
472 uint prev_y = INVALID_DATAPOINT_POS;
473
474 const uint dash = ScaleGUITrad(dataset.dash);
476 if (datapoint != INVALID_DATAPOINT) {
477 /*
478 * Check whether we need to reduce the 'accuracy' of the
479 * datapoint value and the highest value to split overflows.
480 * And when 'drawing' 'one million' or 'one million and one'
481 * there is no significant difference, so the least
482 * significant bits can just be removed.
483 *
484 * If there are more bits needed than would fit in a 32 bits
485 * integer, so at about 31 bits because of the sign bit, the
486 * least significant bits are removed.
487 */
489 int reduce_range = std::max(mult_range - 31, 0);
490
491 /* Handle negative values differently (don't shift sign) */
492 if (datapoint < 0) {
494 } else {
496 }
497 y = r.top + x_axis_offset - ((r.bottom - r.top) * datapoint) / (interval_size >> reduce_range);
498
499 /* Draw the point. */
500 GfxFillRect(x - pointoffs1, y - pointoffs1, x + pointoffs2, y + pointoffs2, dataset.colour);
501
502 /* Draw the line connected to the previous point. */
503 if (prev_x != INVALID_DATAPOINT_POS) GfxDrawLine(prev_x, prev_y, x, y, dataset.colour, linewidth, dash);
504
505 prev_x = x;
506 prev_y = y;
507 } else {
508 prev_x = INVALID_DATAPOINT_POS;
509 prev_y = INVALID_DATAPOINT_POS;
510 }
511
512 x += x_sep;
513 }
514 }
515 }
516
517 BaseGraphWindow(WindowDesc &desc, StringID format_str_y_axis) :
518 Window(desc),
519 format_str_y_axis(format_str_y_axis)
520 {
522 this->num_vert_lines = GRAPH_NUM_MONTHS;
523 this->month_increment = 3;
524 }
525
526 void InitializeWindow(WindowNumber number)
527 {
528 /* Initialise the dataset */
529 this->UpdateStatistics(true);
530
531 this->CreateNestedTree();
532
534 if (wid != nullptr && TimerGameEconomy::UsingWallclockUnits()) {
536 }
537
538 this->FinishInitNested(number);
539 }
540
541public:
543 {
544 switch (widget) {
546 for (const StringID &str : this->ranges) {
547 size = maxdim(size, GetStringBoundingBox(str, FS_SMALL));
548 }
549
552
553 /* Set fixed height for number of ranges. */
554 size.height *= static_cast<uint>(std::size(this->ranges));
555
556 resize.width = 0;
557 resize.height = 0;
558 this->GetWidget<NWidgetCore>(WID_GRAPH_RANGE_MATRIX)->SetMatrixDimension(1, ClampTo<uint32_t>(std::size(this->ranges)));
559 break;
560
561 case WID_GRAPH_GRAPH: {
562 uint x_label_width = 0;
563
564 /* Draw x-axis labels and markings for graphs based on financial quarters and years. */
565 if (this->draw_dates) {
566 TimerGameEconomy::Month month = this->month;
567 TimerGameEconomy::Year year = this->year;
568 for (int i = 0; i < this->num_on_x_axis; i++) {
570 SetDParam(1, year);
572
573 month += this->month_increment;
574 if (month >= 12) {
575 month = 0;
576 year++;
577 }
578 }
579 } else {
580 /* Draw x-axis labels for graphs not based on quarterly performance (cargo payment rates). */
581 SetDParamMaxValue(0, this->x_values_start + this->num_on_x_axis * this->x_values_increment, 0, FS_SMALL);
583 }
584
585 SetDParam(0, this->format_str_y_axis);
588
589 size.width = std::max<uint>(size.width, ScaleGUITrad(5) + y_label_width + this->num_vert_lines * (x_label_width + ScaleGUITrad(5)) + ScaleGUITrad(9));
590 size.height = std::max<uint>(size.height, ScaleGUITrad(5) + (1 + MIN_GRAPH_NUM_LINES_Y * 2 + (this->draw_dates ? 3 : 1)) * GetCharacterHeight(FS_SMALL) + ScaleGUITrad(4));
591 size.height = std::max<uint>(size.height, size.width / 3);
592 break;
593 }
594
595 default: break;
596 }
597 }
598
599 void DrawWidget(const Rect &r, WidgetID widget) const override
600 {
601 switch (widget) {
602 case WID_GRAPH_GRAPH:
603 this->DrawGraph(r);
604 break;
605
608 uint index = 0;
609 Rect line = r.WithHeight(line_height);
610 for (const auto &str : this->ranges) {
611 bool lowered = !HasBit(this->excluded_range, index);
612
613 /* Redraw frame if lowered */
614 if (lowered) DrawFrameRect(line, COLOUR_BROWN, FrameFlag::Lowered);
615
616 const Rect text = line.Shrink(WidgetDimensions::scaled.framerect);
617 DrawString(text, str, TC_BLACK, SA_CENTER, false, FS_SMALL);
618
619 line = line.Translate(0, line_height);
620 ++index;
621 }
622 break;
623 }
624
625 default: break;
626 }
627 }
628
629 virtual OverflowSafeInt64 GetGraphData(const Company *, int)
630 {
631 return INVALID_DATAPOINT;
632 }
633
634 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
635 {
636 /* Clicked on legend? */
637 switch (widget) {
639 ShowGraphLegend();
640 break;
641
643 int row = GetRowFromWidget(pt.y, widget, 0, GetCharacterHeight(FS_SMALL) + WidgetDimensions::scaled.framerect.Vertical());
644
645 ToggleBit(this->excluded_range, row);
646 this->SetDirty();
647 break;
648 }
649
650 default: break;
651 }
652 }
653
654 void OnGameTick() override
655 {
656 this->UpdateStatistics(false);
657 }
658
664 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
665 {
666 if (!gui_scope) return;
667 this->UpdateStatistics(true);
668 }
669
674 virtual void UpdateStatistics(bool initialize)
675 {
676 CompanyMask excluded_companies = _legend_excluded_companies;
677
678 /* Exclude the companies which aren't valid */
679 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
681 }
682
683 uint8_t nums = 0;
684 for (const Company *c : Company::Iterate()) {
685 nums = std::min(this->num_vert_lines, std::max(nums, c->num_valid_stat_ent));
686 }
687
688 int mo = (TimerGameEconomy::month / this->month_increment - nums) * this->month_increment;
690 while (mo < 0) {
691 yr--;
692 mo += 12;
693 }
694
695 if (!initialize && this->excluded_data == excluded_companies && this->num_on_x_axis == nums &&
696 this->year == yr && this->month == mo) {
697 /* There's no reason to get new stats */
698 return;
699 }
700
701 this->excluded_data = excluded_companies;
702 this->num_on_x_axis = nums;
703 this->year = yr;
704 this->month = mo;
705
706 this->data.clear();
707 for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; k++) {
708 const Company *c = Company::GetIfValid(k);
709 if (c == nullptr) continue;
710
711 DataSet &dataset = this->data.emplace_back();
712 dataset.colour = GetColourGradient(c->colour, SHADE_LIGHTER);
713 dataset.exclude_bit = k;
714
715 for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
716 if (j >= c->num_valid_stat_ent) {
717 dataset.values[i] = INVALID_DATAPOINT;
718 } else {
719 /* Ensure we never assign INVALID_DATAPOINT, as that has another meaning.
720 * Instead, use the value just under it. Hopefully nobody will notice. */
721 dataset.values[i] = std::min(GetGraphData(c, j), INVALID_DATAPOINT - 1);
722 }
723 i++;
724 }
725 }
726 }
727};
728
729
730/********************/
731/* OPERATING PROFIT */
732/********************/
733
737 {
738 this->num_on_x_axis = GRAPH_NUM_MONTHS;
739 this->num_vert_lines = GRAPH_NUM_MONTHS;
740 this->x_values_start = ECONOMY_QUARTER_MINUTES;
741 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
742 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
743
744 this->InitializeWindow(window_number);
745 }
746
747 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
748 {
749 return c->old_economy[j].income + c->old_economy[j].expenses;
750 }
751};
752
753static constexpr NWidgetPart _nested_operating_profit_widgets[] = {
755 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
756 NWidget(WWT_CAPTION, COLOUR_BROWN), SetStringTip(STR_GRAPH_OPERATING_PROFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
757 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
758 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
759 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
760 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
761 EndContainer(),
762 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
764 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GRAPH_GRAPH), SetMinimalSize(576, 160), SetFill(1, 1), SetResize(1, 1),
766 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
767 NWidget(WWT_TEXT, INVALID_COLOUR, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetStringTip(STR_EMPTY),
768 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
769 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetResizeWidgetTypeTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
770 EndContainer(),
771 EndContainer(),
772 EndContainer(),
773};
774
775static WindowDesc _operating_profit_desc(
776 WDP_AUTO, "graph_operating_profit", 0, 0,
778 {},
779 _nested_operating_profit_widgets
780);
781
782
783void ShowOperatingProfitGraph()
784{
785 AllocateWindowDescFront<OperatingProfitGraphWindow>(_operating_profit_desc, 0);
786}
787
788
789/****************/
790/* INCOME GRAPH */
791/****************/
792
796 {
797 this->num_on_x_axis = GRAPH_NUM_MONTHS;
798 this->num_vert_lines = GRAPH_NUM_MONTHS;
799 this->x_values_start = ECONOMY_QUARTER_MINUTES;
800 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
801 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
802
803 this->InitializeWindow(window_number);
804 }
805
806 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
807 {
808 return c->old_economy[j].income;
809 }
810};
811
812static constexpr NWidgetPart _nested_income_graph_widgets[] = {
814 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
815 NWidget(WWT_CAPTION, COLOUR_BROWN), SetStringTip(STR_GRAPH_INCOME_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
816 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
817 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
818 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
819 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
820 EndContainer(),
821 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
823 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GRAPH_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
825 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
826 NWidget(WWT_TEXT, INVALID_COLOUR, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetStringTip(STR_EMPTY),
827 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
828 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetResizeWidgetTypeTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
829 EndContainer(),
830 EndContainer(),
831 EndContainer(),
832};
833
834static WindowDesc _income_graph_desc(
835 WDP_AUTO, "graph_income", 0, 0,
837 {},
838 _nested_income_graph_widgets
839);
840
841void ShowIncomeGraph()
842{
843 AllocateWindowDescFront<IncomeGraphWindow>(_income_graph_desc, 0);
844}
845
846/*******************/
847/* DELIVERED CARGO */
848/*******************/
849
853 {
854 this->num_on_x_axis = GRAPH_NUM_MONTHS;
855 this->num_vert_lines = GRAPH_NUM_MONTHS;
856 this->x_values_start = ECONOMY_QUARTER_MINUTES;
857 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
858 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
859
860 this->InitializeWindow(window_number);
861 }
862
863 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
864 {
866 }
867};
868
869static constexpr NWidgetPart _nested_delivered_cargo_graph_widgets[] = {
871 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
872 NWidget(WWT_CAPTION, COLOUR_BROWN), SetStringTip(STR_GRAPH_CARGO_DELIVERED_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
873 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
874 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
875 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
876 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
877 EndContainer(),
878 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
880 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GRAPH_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
882 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
883 NWidget(WWT_TEXT, INVALID_COLOUR, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetStringTip(STR_EMPTY),
884 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
885 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetResizeWidgetTypeTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
886 EndContainer(),
887 EndContainer(),
888 EndContainer(),
889};
890
891static WindowDesc _delivered_cargo_graph_desc(
892 WDP_AUTO, "graph_delivered_cargo", 0, 0,
894 {},
895 _nested_delivered_cargo_graph_widgets
896);
897
898void ShowDeliveredCargoGraph()
899{
900 AllocateWindowDescFront<DeliveredCargoGraphWindow>(_delivered_cargo_graph_desc, 0);
901}
902
903/***********************/
904/* PERFORMANCE HISTORY */
905/***********************/
906
910 {
911 this->num_on_x_axis = GRAPH_NUM_MONTHS;
912 this->num_vert_lines = GRAPH_NUM_MONTHS;
913 this->x_values_start = ECONOMY_QUARTER_MINUTES;
914 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
915 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
916
917 this->InitializeWindow(window_number);
918 }
919
920 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
921 {
922 return c->old_economy[j].performance_history;
923 }
924
925 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
926 {
927 if (widget == WID_PHG_DETAILED_PERFORMANCE) ShowPerformanceRatingDetail();
928 this->BaseGraphWindow::OnClick(pt, widget, click_count);
929 }
930};
931
932static constexpr NWidgetPart _nested_performance_history_widgets[] = {
934 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
935 NWidget(WWT_CAPTION, COLOUR_BROWN), SetStringTip(STR_GRAPH_COMPANY_PERFORMANCE_RATINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
936 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_PHG_DETAILED_PERFORMANCE), SetMinimalSize(50, 0), SetStringTip(STR_PERFORMANCE_DETAIL_KEY, STR_GRAPH_PERFORMANCE_DETAIL_TOOLTIP),
937 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
938 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
939 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
940 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
941 EndContainer(),
942 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
944 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GRAPH_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
946 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
947 NWidget(WWT_TEXT, INVALID_COLOUR, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetStringTip(STR_EMPTY),
948 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
949 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetResizeWidgetTypeTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
950 EndContainer(),
951 EndContainer(),
952 EndContainer(),
953};
954
955static WindowDesc _performance_history_desc(
956 WDP_AUTO, "graph_performance", 0, 0,
958 {},
959 _nested_performance_history_widgets
960);
961
962void ShowPerformanceHistoryGraph()
963{
964 AllocateWindowDescFront<PerformanceHistoryGraphWindow>(_performance_history_desc, 0);
965}
966
967/*****************/
968/* COMPANY VALUE */
969/*****************/
970
974 {
975 this->num_on_x_axis = GRAPH_NUM_MONTHS;
976 this->num_vert_lines = GRAPH_NUM_MONTHS;
977 this->x_values_start = ECONOMY_QUARTER_MINUTES;
978 this->x_values_increment = ECONOMY_QUARTER_MINUTES;
979 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
980
981 this->InitializeWindow(window_number);
982 }
983
984 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
985 {
986 return c->old_economy[j].company_value;
987 }
988};
989
990static constexpr NWidgetPart _nested_company_value_graph_widgets[] = {
992 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
993 NWidget(WWT_CAPTION, COLOUR_BROWN), SetStringTip(STR_GRAPH_COMPANY_VALUES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
994 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
995 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
996 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
997 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
998 EndContainer(),
999 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND),
1001 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GRAPH_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
1003 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
1004 NWidget(WWT_TEXT, INVALID_COLOUR, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetStringTip(STR_EMPTY),
1005 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1006 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetResizeWidgetTypeTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
1007 EndContainer(),
1008 EndContainer(),
1009 EndContainer(),
1010};
1011
1012static WindowDesc _company_value_graph_desc(
1013 WDP_AUTO, "graph_company_value", 0, 0,
1015 {},
1016 _nested_company_value_graph_widgets
1017);
1018
1019void ShowCompanyValueGraph()
1020{
1021 AllocateWindowDescFront<CompanyValueGraphWindow>(_company_value_graph_desc, 0);
1022}
1023
1024/*****************/
1025/* PAYMENT RATES */
1026/*****************/
1027
1032
1035 {
1036 this->num_on_x_axis = 20;
1037 this->num_vert_lines = 20;
1038 this->draw_dates = false;
1039 /* The x-axis is labeled in either seconds or days. A day is two seconds, so we adjust the label if needed. */
1042
1043 this->CreateNestedTree();
1044 this->vscroll = this->GetScrollbar(WID_GRAPH_MATRIX_SCROLLBAR);
1045 this->vscroll->SetCount(_sorted_standard_cargo_specs.size());
1046
1049
1050 /* Initialise the dataset */
1051 this->UpdatePaymentRates();
1052
1053 this->FinishInitNested(window_number);
1054 }
1055
1056 void OnInit() override
1057 {
1058 /* Width of the legend blob. */
1059 this->legend_width = GetCharacterHeight(FS_SMALL) * 9 / 6;
1060 }
1061
1062 void UpdateExcludedData()
1063 {
1064 this->excluded_data = _legend_excluded_cargo_payment_rates;
1065 }
1066
1068 {
1069 if (widget != WID_GRAPH_MATRIX) {
1070 BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
1071 return;
1072 }
1073
1075
1076 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1077 SetDParam(0, cs->name);
1079 d.width += this->legend_width + WidgetDimensions::scaled.hsep_normal; // colour field
1082 size = maxdim(d, size);
1083 }
1084
1085 this->line_height = size.height;
1086 size.height = this->line_height * 11; /* Default number of cargo types in most climates. */
1087 resize.width = 0;
1088 resize.height = this->line_height;
1089 }
1090
1091 void DrawWidget(const Rect &r, WidgetID widget) const override
1092 {
1093 if (widget != WID_GRAPH_MATRIX) {
1094 BaseGraphWindow::DrawWidget(r, widget);
1095 return;
1096 }
1097
1098 bool rtl = _current_text_dir == TD_RTL;
1099
1100 auto [first, last] = this->vscroll->GetVisibleRangeIterators(_sorted_standard_cargo_specs);
1101
1102 Rect line = r.WithHeight(this->line_height);
1103 for (auto it = first; it != last; ++it) {
1104 const CargoSpec *cs = *it;
1105
1106 bool lowered = !HasBit(_legend_excluded_cargo_payment_rates, cs->Index());
1107
1108 /* Redraw frame if lowered */
1109 if (lowered) DrawFrameRect(line, COLOUR_BROWN, FrameFlag::Lowered);
1110
1111 const Rect text = line.Shrink(WidgetDimensions::scaled.framerect);
1112
1113 /* Cargo-colour box with outline */
1114 const Rect cargo = text.WithWidth(this->legend_width, rtl);
1115 GfxFillRect(cargo, PC_BLACK);
1116 GfxFillRect(cargo.Shrink(WidgetDimensions::scaled.bevel), cs->legend_colour);
1117
1118 /* Cargo name */
1119 SetDParam(0, cs->name);
1121
1122 line = line.Translate(0, this->line_height);
1123 }
1124 }
1125
1126 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1127 {
1128 switch (widget) {
1130 /* Remove all cargoes from the excluded lists. */
1131 _legend_excluded_cargo_payment_rates = 0;
1132 this->excluded_data = 0;
1133 this->SetDirty();
1134 break;
1135
1137 /* Add all cargoes to the excluded lists. */
1138 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1139 SetBit(_legend_excluded_cargo_payment_rates, cs->Index());
1140 SetBit(this->excluded_data, cs->Index());
1141 }
1142 this->SetDirty();
1143 break;
1144 }
1145
1146 case WID_GRAPH_MATRIX: {
1148 if (it != _sorted_standard_cargo_specs.end()) {
1149 ToggleBit(_legend_excluded_cargo_payment_rates, (*it)->Index());
1150 this->UpdateExcludedData();
1151 this->SetDirty();
1152 }
1153 break;
1154 }
1155
1156 default:
1157 this->BaseGraphWindow::OnClick(pt, widget, click_count);
1158 break;
1159 }
1160 }
1161
1162 void OnResize() override
1163 {
1164 this->vscroll->SetCapacityFromWidget(this, WID_GRAPH_MATRIX);
1165 }
1166
1167 void OnGameTick() override
1168 {
1169 /* Override default OnGameTick */
1170 }
1171
1177 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1178 {
1179 if (!gui_scope) return;
1180 this->UpdatePaymentRates();
1181 }
1182
1184 IntervalTimer<TimerWindow> update_payment_interval = {std::chrono::seconds(3), [this](auto) {
1185 this->UpdatePaymentRates();
1186 }};
1187
1192 {
1193 this->UpdateExcludedData();
1194
1195 this->data.clear();
1196 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1197 DataSet &dataset = this->data.emplace_back();
1198 dataset.colour = cs->legend_colour;
1199 dataset.exclude_bit = cs->Index();
1200
1201 for (uint j = 0; j != this->num_on_x_axis; j++) {
1202 dataset.values[j] = GetTransportedGoodsIncome(10, 20, j * 4 + 4, cs->Index());
1203 }
1204 }
1205 }
1206};
1207
1208static constexpr NWidgetPart _nested_cargo_payment_rates_widgets[] = {
1210 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1211 NWidget(WWT_CAPTION, COLOUR_BROWN), SetStringTip(STR_GRAPH_CARGO_PAYMENT_RATES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1212 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1213 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1214 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1215 EndContainer(),
1216 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND), SetMinimalSize(568, 128),
1218 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1219 NWidget(WWT_TEXT, INVALID_COLOUR, WID_GRAPH_HEADER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetStringTip(STR_GRAPH_CARGO_PAYMENT_RATES_TITLE),
1220 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1221 EndContainer(),
1223 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GRAPH_GRAPH), SetMinimalSize(495, 0), SetFill(1, 1), SetResize(1, 1),
1225 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1226 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_ENABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1227 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_DISABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1230 NWidget(WWT_MATRIX, COLOUR_BROWN, WID_GRAPH_MATRIX), SetFill(1, 0), SetResize(0, 2), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO), SetScrollbar(WID_GRAPH_MATRIX_SCROLLBAR),
1232 EndContainer(),
1233 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1234 EndContainer(),
1235 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1236 EndContainer(),
1238 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
1239 NWidget(WWT_TEXT, INVALID_COLOUR, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0),
1240 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1241 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetResizeWidgetTypeTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
1242 EndContainer(),
1243 EndContainer(),
1244};
1245
1246static WindowDesc _cargo_payment_rates_desc(
1247 WDP_AUTO, "graph_cargo_payment_rates", 0, 0,
1249 {},
1250 _nested_cargo_payment_rates_widgets
1251);
1252
1253
1254void ShowCargoPaymentRates()
1255{
1256 AllocateWindowDescFront<PaymentRatesGraphWindow>(_cargo_payment_rates_desc, 0);
1257}
1258
1259/*****************************/
1260/* PERFORMANCE RATING DETAIL */
1261/*****************************/
1262
1264 static CompanyID company;
1265 int timeout;
1266
1268 {
1269 this->UpdateCompanyStats();
1270
1271 this->InitNested(window_number);
1273 }
1274
1275 void UpdateCompanyStats()
1276 {
1277 /* Update all company stats with the current data
1278 * (this is because _score_info is not saved to a savegame) */
1279 for (Company *c : Company::Iterate()) {
1281 }
1282
1283 this->timeout = Ticks::DAY_TICKS * 5;
1284 }
1285
1286 uint score_info_left;
1287 uint score_info_right;
1288 uint bar_left;
1289 uint bar_right;
1290 uint bar_width;
1291 uint bar_height;
1292 uint score_detail_left;
1293 uint score_detail_right;
1294
1296 {
1297 switch (widget) {
1300 size.height = this->bar_height + WidgetDimensions::scaled.matrix.Vertical();
1301
1302 uint score_info_width = 0;
1303 for (uint i = SCORE_BEGIN; i < SCORE_END; i++) {
1305 }
1306 SetDParamMaxValue(0, 1000);
1308
1309 SetDParamMaxValue(0, 100);
1311
1312 /* At this number we are roughly at the max; it can become wider,
1313 * but then you need at 1000 times more money. At that time you're
1314 * not that interested anymore in the last few digits anyway.
1315 * The 500 is because 999 999 500 to 999 999 999 are rounded to
1316 * 1 000 M, and not 999 999 k. Use negative numbers to account for
1317 * the negative income/amount of money etc. as well. */
1318 int max = -(999999999 - 500);
1319
1320 /* Scale max for the display currency. Prior to rendering the value
1321 * is converted into the display currency, which may cause it to
1322 * raise significantly. We need to compensate for that since {{CURRCOMPACT}}
1323 * is used, which can produce quite short renderings of very large
1324 * values. Otherwise the calculated width could be too narrow.
1325 * Note that it doesn't work if there was a currency with an exchange
1326 * rate greater than max.
1327 * When the currency rate is more than 1000, the 999 999 k becomes at
1328 * least 999 999 M which roughly is equally long. Furthermore if the
1329 * exchange rate is that high, 999 999 k is usually not enough anymore
1330 * to show the different currency numbers. */
1331 if (GetCurrency().rate < 1000) max /= GetCurrency().rate;
1332 SetDParam(0, max);
1333 SetDParam(1, max);
1335
1338 uint right = size.width - WidgetDimensions::scaled.frametext.right;
1339
1340 bool rtl = _current_text_dir == TD_RTL;
1341 this->score_info_left = rtl ? right - score_info_width : left;
1342 this->score_info_right = rtl ? right : left + score_info_width;
1343
1344 this->score_detail_left = rtl ? left : right - score_detail_width;
1345 this->score_detail_right = rtl ? left + score_detail_width : right;
1346
1347 this->bar_left = left + (rtl ? score_detail_width : score_info_width) + WidgetDimensions::scaled.hsep_wide;
1348 this->bar_right = this->bar_left + this->bar_width - 1;
1349 break;
1350 }
1351 }
1352
1353 void DrawWidget(const Rect &r, WidgetID widget) const override
1354 {
1355 /* No need to draw when there's nothing to draw */
1356 if (this->company == INVALID_COMPANY) return;
1357
1359 if (this->IsWidgetDisabled(widget)) return;
1361 Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
1362 DrawCompanyIcon(cid, CenterBounds(r.left, r.right, sprite_size.width), CenterBounds(r.top, r.bottom, sprite_size.height));
1363 return;
1364 }
1365
1366 if (!IsInsideMM(widget, WID_PRD_SCORE_FIRST, WID_PRD_SCORE_LAST + 1)) return;
1367
1369
1370 /* The colours used to show how the progress is going */
1371 int colour_done = GetColourGradient(COLOUR_GREEN, SHADE_NORMAL);
1372 int colour_notdone = GetColourGradient(COLOUR_RED, SHADE_NORMAL);
1373
1374 /* Draw all the score parts */
1375 int64_t val = _score_part[company][score_type];
1377 int score = _score_info[score_type].score;
1378
1379 /* SCORE_TOTAL has its own rules ;) */
1380 if (score_type == SCORE_TOTAL) {
1381 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) score += _score_info[i].score;
1382 needed = SCORE_MAX;
1383 }
1384
1385 uint bar_top = CenterBounds(r.top, r.bottom, this->bar_height);
1386 uint text_top = CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL));
1387
1388 DrawString(this->score_info_left, this->score_info_right, text_top, STR_PERFORMANCE_DETAIL_VEHICLES + score_type);
1389
1390 /* Draw the score */
1391 SetDParam(0, score);
1392 DrawString(this->score_info_left, this->score_info_right, text_top, STR_JUST_COMMA, TC_BLACK, SA_RIGHT);
1393
1394 /* Calculate the %-bar */
1395 uint x = Clamp<int64_t>(val, 0, needed) * this->bar_width / needed;
1396 bool rtl = _current_text_dir == TD_RTL;
1397 if (rtl) {
1398 x = this->bar_right - x;
1399 } else {
1400 x = this->bar_left + x;
1401 }
1402
1403 /* Draw the bar */
1404 if (x != this->bar_left) GfxFillRect(this->bar_left, bar_top, x, bar_top + this->bar_height - 1, rtl ? colour_notdone : colour_done);
1405 if (x != this->bar_right) GfxFillRect(x, bar_top, this->bar_right, bar_top + this->bar_height - 1, rtl ? colour_done : colour_notdone);
1406
1407 /* Draw it */
1408 SetDParam(0, Clamp<int64_t>(val, 0, needed) * 100 / needed);
1409 DrawString(this->bar_left, this->bar_right, text_top, STR_PERFORMANCE_DETAIL_PERCENT, TC_FROMSTRING, SA_HOR_CENTER);
1410
1411 /* SCORE_LOAN is inversed */
1412 if (score_type == SCORE_LOAN) val = needed - val;
1413
1414 /* Draw the amount we have against what is needed
1415 * For some of them it is in currency format */
1416 SetDParam(0, val);
1417 SetDParam(1, needed);
1418 switch (score_type) {
1419 case SCORE_MIN_PROFIT:
1420 case SCORE_MIN_INCOME:
1421 case SCORE_MAX_INCOME:
1422 case SCORE_MONEY:
1423 case SCORE_LOAN:
1424 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY);
1425 break;
1426 default:
1427 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_INT);
1428 }
1429 }
1430
1431 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1432 {
1433 /* Check which button is clicked */
1435 /* Is it no on disable? */
1436 if (!this->IsWidgetDisabled(widget)) {
1437 this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company);
1438 this->company = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1439 this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company);
1440 this->SetDirty();
1441 }
1442 }
1443 }
1444
1445 void OnGameTick() override
1446 {
1447 /* Update the company score every 5 days */
1448 if (--this->timeout == 0) {
1449 this->UpdateCompanyStats();
1450 this->SetDirty();
1451 }
1452 }
1453
1459 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1460 {
1461 if (!gui_scope) return;
1462 /* Disable the companies who are not active */
1463 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
1465 }
1466
1467 /* Check if the currently selected company is still active. */
1468 if (this->company != INVALID_COMPANY && !Company::IsValidID(this->company)) {
1469 /* Raise the widget for the previous selection. */
1470 this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company);
1471 this->company = INVALID_COMPANY;
1472 }
1473
1474 if (this->company == INVALID_COMPANY) {
1475 for (const Company *c : Company::Iterate()) {
1476 this->company = c->index;
1477 break;
1478 }
1479 }
1480
1481 /* Make sure the widget is lowered */
1482 if (this->company != INVALID_COMPANY) {
1483 this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company);
1484 }
1485 }
1486};
1487
1488CompanyID PerformanceRatingDetailWindow::company = INVALID_COMPANY;
1489
1490/*******************************/
1491/* INDUSTRY PRODUCTION HISTORY */
1492/*******************************/
1493
1498
1499 static inline constexpr StringID RANGE_LABELS[] = {
1502 };
1503
1506 {
1507 this->num_on_x_axis = GRAPH_NUM_MONTHS;
1508 this->num_vert_lines = GRAPH_NUM_MONTHS;
1509 this->month_increment = 1;
1510 this->x_values_start = ECONOMY_MONTH_MINUTES;
1511 this->x_values_increment = ECONOMY_MONTH_MINUTES;
1512 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
1513 this->ranges = RANGE_LABELS;
1514
1515 this->CreateNestedTree();
1516 this->vscroll = this->GetScrollbar(WID_GRAPH_MATRIX_SCROLLBAR);
1517
1518 int count = 0;
1520 for (const auto &p : i->produced) {
1521 if (!IsValidCargoType(p.cargo)) continue;
1522 count++;
1523 }
1524 this->vscroll->SetCount(count);
1525
1528
1529 this->FinishInitNested(window_number);
1530
1531 /* Initialise the dataset */
1532 this->UpdateStatistics(true);
1533 }
1534
1535 void OnInit() override
1536 {
1537 /* Width of the legend blob. */
1538 this->legend_width = GetCharacterHeight(FS_SMALL) * 9 / 6;
1539 }
1540
1541 void UpdateExcludedData()
1542 {
1543 this->excluded_data = 0;
1544
1545 const Industry *i = Industry::Get(this->window_number);
1546 for (const auto &p : i->produced) {
1547 if (!IsValidCargoType(p.cargo)) continue;
1548 if (HasBit(_legend_excluded_cargo_production_history, p.cargo)) SetBit(this->excluded_data, p.cargo);
1549 }
1550 }
1551
1553 {
1554 if (widget != WID_GRAPH_MATRIX) {
1555 BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
1556 return;
1557 }
1558
1559 const Industry *i = Industry::Get(this->window_number);
1560 const CargoSpec *cs;
1561 for (const auto &p : i->produced) {
1562 if (!IsValidCargoType(p.cargo)) continue;
1563
1564 cs = CargoSpec::Get(p.cargo);
1565 SetDParam(0, cs->name);
1567 d.width += this->legend_width + WidgetDimensions::scaled.hsep_normal; // colour field
1570 size = maxdim(d, size);
1571 }
1572
1573 this->line_height = size.height;
1574 size.height = this->line_height * 11; /* Default number of cargo types in most climates. */
1575 resize.width = 0;
1576 resize.height = this->line_height;
1577 }
1578
1579 void DrawWidget(const Rect &r, WidgetID widget) const override
1580 {
1581 if (widget != WID_GRAPH_MATRIX) {
1582 BaseGraphWindow::DrawWidget(r, widget);
1583 return;
1584 }
1585
1586 bool rtl = _current_text_dir == TD_RTL;
1587
1588 int pos = this->vscroll->GetPosition();
1589 int max = pos + this->vscroll->GetCapacity();
1590
1591 Rect line = r.WithHeight(this->line_height);
1592 const Industry *i = Industry::Get(this->window_number);
1593 const CargoSpec *cs;
1594
1595 for (const auto &p : i->produced) {
1596 if (!IsValidCargoType(p.cargo)) continue;
1597
1598 if (pos-- > 0) continue;
1599 if (--max < 0) break;
1600
1601 cs = CargoSpec::Get(p.cargo);
1602
1603 bool lowered = !HasBit(_legend_excluded_cargo_production_history, p.cargo);
1604
1605 /* Redraw frame if lowered */
1606 if (lowered) DrawFrameRect(line, COLOUR_BROWN, FrameFlag::Lowered);
1607
1608 const Rect text = line.Shrink(WidgetDimensions::scaled.framerect);
1609
1610 /* Cargo-colour box with outline */
1611 const Rect cargo = text.WithWidth(this->legend_width, rtl);
1612 GfxFillRect(cargo, PC_BLACK);
1613 GfxFillRect(cargo.Shrink(WidgetDimensions::scaled.bevel), cs->legend_colour);
1614
1615 /* Cargo name */
1616 SetDParam(0, cs->name);
1618
1619 line = line.Translate(0, this->line_height);
1620 }
1621 }
1622
1623 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1624 {
1625 switch (widget) {
1627 /* Remove all cargoes from the excluded lists. */
1628 _legend_excluded_cargo_production_history = 0;
1629 this->excluded_data = 0;
1630 this->SetDirty();
1631 break;
1632
1634 /* Add all cargoes to the excluded lists. */
1635 const Industry *i = Industry::Get(this->window_number);
1636 for (const auto &p : i->produced) {
1637 if (!IsValidCargoType(p.cargo)) continue;
1638
1639 SetBit(_legend_excluded_cargo_production_history, p.cargo);
1640 SetBit(this->excluded_data, p.cargo);
1641 }
1642 this->SetDirty();
1643 break;
1644 }
1645
1646 case WID_GRAPH_MATRIX: {
1647 int row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_GRAPH_MATRIX);
1648 if (row >= this->vscroll->GetCount()) return;
1649
1650 const Industry *i = Industry::Get(this->window_number);
1651 for (const auto &p : i->produced) {
1652 if (!IsValidCargoType(p.cargo)) continue;
1653 if (row-- > 0) continue;
1654
1655 ToggleBit(_legend_excluded_cargo_production_history, p.cargo);
1656 this->UpdateExcludedData();
1657 this->SetDirty();
1658 break;
1659 }
1660 break;
1661 }
1662
1663 default:
1664 this->BaseGraphWindow::OnClick(pt, widget, click_count);
1665 break;
1666 }
1667 }
1668
1669 void SetStringParameters(WidgetID widget) const override
1670 {
1671 if (widget == WID_GRAPH_CAPTION) SetDParam(0, this->window_number);
1672 }
1673
1674 void OnResize() override
1675 {
1676 this->vscroll->SetCapacityFromWidget(this, WID_GRAPH_MATRIX);
1677 }
1678
1679 void UpdateStatistics(bool initialize) override
1680 {
1681 CargoTypes excluded_cargo = this->excluded_data;
1682 this->UpdateExcludedData();
1683
1684 int mo = TimerGameEconomy::month - this->num_vert_lines;
1686 while (mo < 0) {
1687 yr--;
1688 mo += 12;
1689 }
1690
1691 if (!initialize && this->excluded_data == excluded_cargo && this->num_on_x_axis == this->num_vert_lines && this->year == yr && this->month == mo) {
1692 /* There's no reason to get new stats */
1693 return;
1694 }
1695
1696 this->year = yr;
1697 this->month = mo;
1698
1699 const Industry *i = Industry::Get(this->window_number);
1700
1701 this->data.clear();
1702 for (const auto &p : i->produced) {
1703 if (!IsValidCargoType(p.cargo)) continue;
1704 const CargoSpec *cs = CargoSpec::Get(p.cargo);
1705
1706 DataSet &produced = this->data.emplace_back();
1707 produced.colour = cs->legend_colour;
1708 produced.exclude_bit = cs->Index();
1709 produced.range_bit = 0;
1710
1711 for (uint j = 0; j < GRAPH_NUM_MONTHS; j++) {
1712 produced.values[j] = p.history[GRAPH_NUM_MONTHS - j].production;
1713 }
1714
1715 DataSet &transported = this->data.emplace_back();
1716 transported.colour = cs->legend_colour;
1717 transported.exclude_bit = cs->Index();
1718 transported.range_bit = 1;
1719 transported.dash = 2;
1720
1721 for (uint j = 0; j < GRAPH_NUM_MONTHS; j++) {
1722 transported.values[j] = p.history[GRAPH_NUM_MONTHS - j].transported;
1723 }
1724 }
1725
1726 this->vscroll->SetCount(std::size(this->data));
1727
1728 this->SetDirty();
1729 }
1730};
1731
1732static constexpr NWidgetPart _nested_industry_production_widgets[] = {
1734 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1735 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_GRAPH_CAPTION), SetStringTip(STR_GRAPH_INDUSTRY_PRODUCTION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1736 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1737 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1738 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1739 EndContainer(),
1740 NWidget(WWT_PANEL, COLOUR_BROWN, WID_GRAPH_BACKGROUND), SetMinimalSize(568, 128),
1742 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_GRAPH_GRAPH), SetMinimalSize(495, 0), SetFill(1, 1), SetResize(1, 1),
1744 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1745 NWidget(WWT_MATRIX, COLOUR_BROWN, WID_GRAPH_RANGE_MATRIX), SetFill(1, 0), SetResize(0, 0), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO),
1747 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_ENABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1748 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_GRAPH_DISABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1751 NWidget(WWT_MATRIX, COLOUR_BROWN, WID_GRAPH_MATRIX), SetFill(1, 0), SetResize(0, 2), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO), SetScrollbar(WID_GRAPH_MATRIX_SCROLLBAR),
1753 EndContainer(),
1754 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1755 EndContainer(),
1756 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1757 EndContainer(),
1759 NWidget(NWID_SPACER), SetMinimalSize(12, 0), SetFill(1, 0), SetResize(1, 0),
1760 NWidget(WWT_TEXT, INVALID_COLOUR, WID_GRAPH_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetStringTip(STR_EMPTY),
1761 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1762 NWidget(WWT_RESIZEBOX, COLOUR_BROWN, WID_GRAPH_RESIZE), SetResizeWidgetTypeTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
1763 EndContainer(),
1764 EndContainer(),
1765};
1766
1767static WindowDesc _industry_production_desc(
1768 WDP_AUTO, "graph_industry_production", 0, 0,
1770 {},
1771 _nested_industry_production_widgets
1772);
1773
1774void ShowIndustryProductionGraph(WindowNumber window_number)
1775{
1776 AllocateWindowDescFront<IndustryProductionGraphWindow>(_industry_production_desc, window_number);
1777}
1778
1783static std::unique_ptr<NWidgetBase> MakePerformanceDetailPanels()
1784{
1785 auto realtime = TimerGameEconomy::UsingWallclockUnits();
1786 const StringID performance_tips[] = {
1787 realtime ? STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP_PERIODS : STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP_YEARS,
1788 STR_PERFORMANCE_DETAIL_STATIONS_TOOLTIP,
1789 realtime ? STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP_PERIODS : STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP_YEARS,
1790 STR_PERFORMANCE_DETAIL_MIN_INCOME_TOOLTIP,
1791 STR_PERFORMANCE_DETAIL_MAX_INCOME_TOOLTIP,
1792 STR_PERFORMANCE_DETAIL_DELIVERED_TOOLTIP,
1793 STR_PERFORMANCE_DETAIL_CARGO_TOOLTIP,
1794 STR_PERFORMANCE_DETAIL_MONEY_TOOLTIP,
1795 STR_PERFORMANCE_DETAIL_LOAN_TOOLTIP,
1796 STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP,
1797 };
1798
1799 static_assert(lengthof(performance_tips) == SCORE_END - SCORE_BEGIN);
1800
1801 auto vert = std::make_unique<NWidgetVertical>(NC_EQUALSIZE);
1802 for (WidgetID widnum = WID_PRD_SCORE_FIRST; widnum <= WID_PRD_SCORE_LAST; widnum++) {
1803 auto panel = std::make_unique<NWidgetBackground>(WWT_PANEL, COLOUR_BROWN, widnum);
1804 panel->SetFill(1, 1);
1805 panel->SetToolTip(performance_tips[widnum - WID_PRD_SCORE_FIRST]);
1806 vert->Add(std::move(panel));
1807 }
1808 return vert;
1809}
1810
1812std::unique_ptr<NWidgetBase> MakeCompanyButtonRowsGraphGUI()
1813{
1814 return MakeCompanyButtonRows(WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST, COLOUR_BROWN, 8, STR_PERFORMANCE_DETAIL_SELECT_COMPANY_TOOLTIP);
1815}
1816
1817static constexpr NWidgetPart _nested_performance_rating_detail_widgets[] = {
1819 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1820 NWidget(WWT_CAPTION, COLOUR_BROWN), SetStringTip(STR_PERFORMANCE_DETAIL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1821 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1822 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1823 EndContainer(),
1824 NWidget(WWT_PANEL, COLOUR_BROWN),
1826 EndContainer(),
1828};
1829
1830static WindowDesc _performance_rating_detail_desc(
1831 WDP_AUTO, "league_details", 0, 0,
1833 {},
1834 _nested_performance_rating_detail_widgets
1835);
1836
1837void ShowPerformanceRatingDetail()
1838{
1839 AllocateWindowDescFront<PerformanceRatingDetailWindow>(_performance_rating_detail_desc, 0);
1840}
1841
1842void InitializeGraphGui()
1843{
1844 _legend_excluded_companies = 0;
1845 _legend_excluded_cargo_payment_rates = 0;
1846 _legend_excluded_cargo_production_history = 0;
1847}
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr T ToggleBit(T &x, const uint8_t y)
Toggles a bit in a variable.
bool IsValidCargoType(CargoType t)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:105
static const CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:74
std::span< const CargoSpec * > _sorted_standard_cargo_specs
Standard cargo specifications sorted alphabetically by name.
Types/functions related to cargoes.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
Scrollbar data structure.
size_type GetCapacity() const
Gets the number of visible elements of the scrollbar.
void SetCount(size_t num)
Sets the number of elements in the list.
auto GetScrolledItemFromWidget(Tcontainer &container, int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Return an iterator pointing to the element of a scrolled widget that a user clicked in.
size_type GetScrolledRowFromWidget(int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Compute the row of a scrolled widget that a user clicked in.
Definition widget.cpp:2459
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2533
size_type GetCount() const
Gets the number of elements in the list.
auto GetVisibleRangeIterators(Tcontainer &container) const
Get a pair of iterators for the range of visible elements in a container.
size_type GetPosition() const
Gets the position of the first visible element in the list.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Year year
Current year, starting at 0.
static Month month
Current month (0..11).
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
uint8_t Month
Type for the month, note: 0 based, i.e.
RectPadding framerect
Standard padding inside many panels.
Definition window_gui.h:40
RectPadding frametext
Padding inside frame with text.
Definition window_gui.h:41
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:28
int hsep_wide
Wide horizontal spacing.
Definition window_gui.h:62
RectPadding fullbevel
Always-scaled bevel thickness.
Definition window_gui.h:39
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
RectPadding matrix
Padding of WWT_MATRIX items.
Definition window_gui.h:42
int hsep_normal
Normal horizontal spacing.
Definition window_gui.h:61
RectPadding bevel
Bevel thickness, affected by "scaled bevels" game option.
Definition window_gui.h:38
int hsep_indent
Width of identation for tree layouts.
Definition window_gui.h:63
Definition of stuff that is very close to a company, like the company struct itself.
void DrawCompanyIcon(CompanyID c, int x, int y)
Draw the icon of a company.
GUI Functions related to companies.
Owner
Enum for all companies/owners.
@ INVALID_COMPANY
An invalid company.
@ COMPANY_FIRST
First company, same as owner.
@ MAX_COMPANIES
Maximum number of companies.
Functions to handle different currencies.
const CurrencySpec & GetCurrency()
Get the currently selected currency.
Definition currency.h:118
int UpdateCompanyRatingAndValue(Company *c, bool update)
if update is set to true, the economy is updated with this score (also the house is updated,...
Definition economy.cpp:201
const ScoreInfo _score_info[]
Score info, values used for computing the detailed performance rating.
Definition economy.cpp:90
Functions related to the economy.
ScoreID
Score categories in the detailed performance rating.
@ SCORE_END
How many scores are there..
@ SCORE_TOTAL
This must always be the last entry.
static constexpr int SCORE_MAX
The max score that can be in the performance history.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:77
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:922
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:851
int DrawString(int left, int right, int top, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:657
void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:114
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:774
Functions related to the gfx engine.
int CenterBounds(int min, int max, int size)
Determine where to draw a centred object inside a widget.
Definition gfx_func.h:166
@ FS_SMALL
Index of the small font in the font tables.
Definition gfx_type.h:244
@ FS_NORMAL
Index of the normal font in the font tables.
Definition gfx_type.h:243
@ SA_LEFT
Left align the text.
Definition gfx_type.h:375
@ SA_RIGHT
Right align the text (must be a single bit).
Definition gfx_type.h:377
@ SA_HOR_CENTER
Horizontally center the text.
Definition gfx_type.h:376
@ SA_CENTER
Center both horizontally and vertically.
Definition gfx_type.h:385
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:294
constexpr double INT64_MAX_IN_DOUBLE
The biggest double that when cast to int64_t still fits in a int64_t.
Definition graph_gui.cpp:45
static std::unique_ptr< NWidgetBase > MakeNWidgetCompanyLines()
Construct a vertical list of buttons, one for each company.
std::unique_ptr< NWidgetBase > MakeCompanyButtonRowsGraphGUI()
Make a number of rows with buttons for each company for the performance rating detail window.
static std::unique_ptr< NWidgetBase > MakePerformanceDetailPanels()
Make a vertical list of panels for outputting score details.
Graph GUI functions.
Types related to the graph widgets.
@ WID_GRAPH_FOOTER
Footer.
@ WID_GRAPH_RESIZE
Resize button.
@ WID_GRAPH_BACKGROUND
Background of the window.
@ WID_GRAPH_GRAPH
Graph itself.
@ WID_PHG_DETAILED_PERFORMANCE
Detailed performance.
@ WID_GRAPH_HEADER
Header.
@ WID_GRAPH_MATRIX_SCROLLBAR
Cargo list scrollbar.
@ WID_GRAPH_DISABLE_CARGOES
Disable cargoes button.
@ WID_GRAPH_CAPTION
Caption.
@ WID_GRAPH_KEY_BUTTON
Key button.
@ WID_GRAPH_MATRIX
Cargo list.
@ WID_GRAPH_ENABLE_CARGOES
Enable cargoes button.
@ WID_GRAPH_RANGE_MATRIX
Range list.
@ WID_GL_FIRST_COMPANY
First company in the legend.
@ WID_GL_LAST_COMPANY
Last company in the legend.
@ WID_GL_BACKGROUND
Background of the window.
@ WID_PRD_COMPANY_FIRST
First company.
@ WID_PRD_SCORE_FIRST
First entry in the score list.
@ WID_PRD_SCORE_LAST
Last entry in the score list.
@ WID_PRD_COMPANY_LAST
Last company.
constexpr NWidgetPart SetMatrixDataTip(uint32_t cols, uint32_t rows, StringID tip={})
Widget part function for setting the data and tooltip of WWT_MATRIX widgets.
constexpr NWidgetPart NWidgetFunction(NWidgetFunctionType *func_ptr)
Obtain a nested widget (sub)tree from an external source.
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetPadding(uint8_t top, uint8_t right, uint8_t bottom, uint8_t left)
Widget part function for setting additional space around a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetResizeWidgetTypeTip(ResizeWidgetValues widget_type, StringID tip)
Widget part function for setting the resize widget type and tooltip.
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=-1)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
void SetDirty() const
Mark entire window as dirty (in need of re-paint)
Definition window.cpp:937
Base of all industries.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
uint8_t GetColourGradient(Colours colour, ColourShade shade)
Get colour gradient palette index.
Definition palette.cpp:387
static const uint8_t PC_BLACK
Black palette colour.
#define GREY_SCALE(level)
Return the colour for a particular greyscale level.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:56
This file contains all sprite-related enums and defines.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:277
void SetDParamMaxValue(size_t n, uint64_t max_value, uint min_count, FontSize size)
Set DParam n to some number that is suitable for string size computations.
Definition strings.cpp:127
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Definition strings.cpp:104
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:56
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
uint GetYLabelWidth(ValuesInterval current_interval, int num_hori_lines) const
Get width for Y labels.
void OnGameTick() override
Called once per (game) tick.
static const int MIN_GRID_PIXEL_SIZE
Minimum distance between graph lines.
static const int GRAPH_NUM_MONTHS
Number of months displayed in the graph.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
static const int ECONOMY_QUARTER_MINUTES
Minutes per economic quarter.
std::span< const OverflowSafeInt64 > GetDataSetRange(const DataSet &dataset) const
Get appropriate part of dataset values for the current number of horizontal points.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
static const int ECONOMY_MONTH_MINUTES
Minutes per economic month.
uint64_t excluded_data
bitmask of the datasets that shouldn't be displayed.
bool draw_dates
Should we draw months and years on the time axis?
static const int MIN_GRAPH_NUM_LINES_Y
Minimal number of horizontal lines to draw.
uint64_t excluded_range
bitmask of ranges that should not be displayed.
uint8_t month_increment
month increment between vertical lines. must be divisor of 12.
static const int PAYMENT_GRAPH_X_STEP_DAYS
X-axis step label for cargo payment rates "Days in transit".
ValuesInterval GetValuesInterval(int num_hori_lines) const
Get the interval that contains the graph's data.
virtual void UpdateStatistics(bool initialize)
Update the statistics.
static const TextColour GRAPH_AXIS_LABEL_COLOUR
colour of the graph axis label.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void DrawGraph(Rect r) const
Actually draw the graph.
static const int PAYMENT_GRAPH_X_STEP_SECONDS
X-axis step label for cargo payment rates "Seconds in transit".
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
const T GetSum() const
Get the sum of all cargo amounts.
Definition cargo_type.h:118
Specification of a cargo type.
Definition cargotype.h:77
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
CargoType Index() const
Determines index of this cargospec.
Definition cargotype.h:111
StringID name
Name of this type of cargo.
Definition cargotype.h:94
GUISettings gui
settings related to the GUI
Money income
The amount of income.
Money expenses
The amount of expenses.
Money company_value
The value of the company.
CargoArray delivered_cargo
The amount of delivered cargo.
int32_t performance_history
Company score (scale 0-1000)
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Colours colour
Company colour.
uint8_t num_valid_stat_ent
Number of valid statistical entries in old_economy.
uint16_t rate
The conversion rate compared to the base currency.
Definition currency.h:77
Dimensions (a width and height) of a rectangle in 2D.
uint8_t graph_line_thickness
the thickness of the lines in the various graph guis
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Definition graph_gui.cpp:84
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
Definition graph_gui.cpp:64
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void UpdateStatistics(bool initialize) override
Update the statistics.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnResize() override
Called after the window got resized.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
uint line_height
Pixel height of each cargo type row.
uint legend_width
Width of legend 'blob'.
void OnInit() override
Notification that the nested widget tree gets initialized.
void SetStringParameters(WidgetID widget) const override
Initialize string parameters for a widget.
Scrollbar * vscroll
Cargo list scrollbar.
Defines the internal data of a functional industry.
Definition industry.h:66
ProducedCargoes produced
produced cargo slots
Definition industry.h:97
Partial widget specification to allow NWidgets to be written nested.
uint line_height
Pixel height of each cargo type row.
void OnResize() override
Called after the window got resized.
void OnInit() override
Notification that the nested widget tree gets initialized.
void OnGameTick() override
Called once per (game) tick.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void UpdatePaymentRates()
Update the payment rates according to the latest information.
IntervalTimer< TimerWindow > update_payment_interval
Update the payment rates on a regular interval.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
uint legend_width
Width of legend 'blob'.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
Scrollbar * vscroll
Cargo list scrollbar.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnGameTick() override
Called once per (game) tick.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Coordinates of a point in 2D.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
static Titem * Get(size_t index)
Returns Titem with given index.
constexpr uint Horizontal() const
Get total horizontal padding of RectPadding.
constexpr uint Vertical() const
Get total vertical padding of RectPadding.
Specification of a rectangle with absolute coordinates of all edges.
Rect WithWidth(int width, bool end) const
Copy Rect and set its width.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Rect WithHeight(int height, bool end=false) const
Copy Rect and set its height.
Rect Indent(int indent, bool end) const
Copy Rect and indent it from its position.
Rect Translate(int x, int y) const
Copy and translate Rect by x,y pixels.
int needed
How much you need to get the perfect score.
int score
How much score it will give.
Templated helper to make a type-safe 'typedef' representing a single POD value.
Contains the interval of a graph's data.
OverflowSafeInt64 lowest
Lowest value of this interval. Must be zero or less.
OverflowSafeInt64 highest
Highest value of this interval. Must be zero or greater.
High level window description.
Definition window_gui.h:168
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1730
void RaiseWidget(WidgetID widget_index)
Marks a widget as raised.
Definition window_gui.h:468
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1720
bool IsWidgetDisabled(WidgetID widget_index) const
Gets the enabled/disabled status of a widget.
Definition window_gui.h:409
int left
x position of left edge of the window
Definition window_gui.h:308
int GetRowFromWidget(int clickpos, WidgetID widget, int padding, int line_height=-1) const
Compute the row of a widget that a user clicked in.
Definition window.cpp:210
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
Definition window_gui.h:970
void LowerWidget(WidgetID widget_index)
Marks a widget as lowered.
Definition window_gui.h:459
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1743
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:311
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
int height
Height of the window (number of pixels down in y direction)
Definition window_gui.h:311
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
void ToggleWidgetLoweredState(WidgetID widget_index)
Invert the lowered/raised status of a widget.
Definition window_gui.h:449
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Definition of Interval and OneShot timers.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Definition of the Window system.
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
Draw frame rectangle.
Definition widget.cpp:283
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:35
std::unique_ptr< NWidgetBase > MakeCompanyButtonRows(WidgetID widget_first, WidgetID widget_last, Colours button_colour, int max_length, StringID button_tooltip, bool resizable)
Make a number of rows with button-like graphics, for enabling/disabling each company.
Definition widget.cpp:3442
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ NWID_SPACER
Invisible widget that takes some space.
Definition widget_type.h:70
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:41
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX)
Definition widget_type.h:57
@ WWT_MATRIX
Grid of rows and columns.
Definition widget_type.h:50
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX)
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox)
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window)
Definition widget_type.h:60
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:39
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window)
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX)
Definition widget_type.h:56
@ WWT_TEXT
Pure simple text.
Definition widget_type.h:49
@ NC_EQUALSIZE
Value of the NCB_EQUALSIZE flag.
@ RWV_HIDE_BEVEL
Bevel of resize box is hidden.
Definition widget_type.h:31
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3217
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3099
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
@ Lowered
If set the frame is lowered and the background colour brighter (ie. buttons when pressed)
@ WDP_AUTO
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:20
@ WC_PERFORMANCE_HISTORY
Performance history graph; Window numbers:
@ WC_PERFORMANCE_DETAIL
Performance detail window; Window numbers:
@ WC_PAYMENT_RATES
Payment rates graph; Window numbers:
@ WC_GRAPH_LEGEND
Legend for graphs; Window numbers:
@ WC_NONE
No window, redirects to WC_MAIN_WINDOW.
Definition window_type.h:47
@ WC_OPERATING_PROFIT
Operating profit graph; Window numbers:
@ WC_INDUSTRY_PRODUCTION
Industry production history graph; Window numbers:
@ WC_INDUSTRY_VIEW
Industry view; Window numbers:
@ WC_INCOME_GRAPH
Income graph; Window numbers:
@ WC_DELIVERED_CARGO
Delivered cargo graph; Window numbers:
@ WC_COMPANY_VALUE
Company value graph; Window numbers:
Functions related to zooming.
@ ZOOM_LVL_NORMAL
The normal zoom level.
Definition zoom_type.h:21