OpenTTD Source 20261129-master-g72a8bdc861
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include <ranges>
12#include "misc/history_func.hpp"
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 "sound_func.h"
22#include "gfx_func.h"
24#include "currency_func.h"
25#include "timer/timer.h"
26#include "timer/timer_window.h"
29#include "zoom_func.h"
30#include "industry.h"
31#include "town.h"
32
34
35#include "table/strings.h"
36#include "table/sprites.h"
37
38#include "safeguards.h"
39
42
43/* Apparently these don't play well with enums. */
44static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX);
45static const uint INVALID_DATAPOINT_POS = UINT_MAX;
46
47constexpr double INT64_MAX_IN_DOUBLE = static_cast<double>(INT64_MAX - 512);
48static_assert(static_cast<int64_t>(INT64_MAX_IN_DOUBLE) < INT64_MAX);
49
50/****************/
51/* GRAPH LEGEND */
52/****************/
53
54struct GraphLegendWindow : Window {
55 GraphLegendWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc)
56 {
57 this->InitNested(window_number);
58
59 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
61
62 this->OnInvalidateData(c.base());
63 }
64 }
65
66 void DrawWidget(const Rect &r, WidgetID widget) const override
67 {
68 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, WID_GL_FIRST_COMPANY + MAX_COMPANIES)) return;
69
70 CompanyID cid = (CompanyID)(widget - WID_GL_FIRST_COMPANY);
71
72 if (!Company::IsValidID(cid)) return;
73
74 bool rtl = _current_text_dir == TD_RTL;
75
76 const Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
78 DrawCompanyIcon(cid, rtl ? ir.right - d.width : ir.left, CentreBounds(ir.top, ir.bottom, d.height));
79
80 const Rect tr = ir.Indent(d.width + WidgetDimensions::scaled.hsep_normal, rtl);
81 DrawString(tr.left, tr.right, CentreBounds(tr.top, tr.bottom, GetCharacterHeight(FontSize::Normal)), GetString(STR_COMPANY_NAME_COMPANY_NUM, cid, cid), _legend_excluded_companies.Test(cid) ? TextColour::Black : TextColour::White);
82 }
83
84 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
85 {
86 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, WID_GL_FIRST_COMPANY + MAX_COMPANIES)) return;
87
88 _legend_excluded_companies.Flip(static_cast<CompanyID>(widget - WID_GL_FIRST_COMPANY));
89 this->ToggleWidgetLoweredState(widget);
90 this->SetDirty();
91 InvalidateWindowData(WindowClass::IncomeGraph, 0);
92 InvalidateWindowData(WindowClass::OperatingProfitGraph, 0);
93 InvalidateWindowData(WindowClass::DeliveredCargoGraph, 0);
94 InvalidateWindowData(WindowClass::PerformanceGraph, 0);
95 InvalidateWindowData(WindowClass::CompanyValueGraph, 0);
96
98 }
99
105 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
106 {
107 if (!gui_scope) return;
108 if (Company::IsValidID(data)) return;
109
110 _legend_excluded_companies.Set(static_cast<CompanyID>(data));
111 this->RaiseWidget(data + WID_GL_FIRST_COMPANY);
112 }
113};
114
119static std::unique_ptr<NWidgetBase> MakeNWidgetCompanyLines()
120{
121 auto vert = std::make_unique<NWidgetVertical>(NWidContainerFlag::EqualSize);
122 vert->SetPadding(2, 2, 2, 2);
123 uint sprite_height = GetSpriteSize(SPR_COMPANY_ICON, nullptr, ZoomLevel::Normal).height;
124
125 for (WidgetID widnum = WID_GL_FIRST_COMPANY; widnum <= WID_GL_LAST_COMPANY; widnum++) {
126 auto panel = std::make_unique<NWidgetBackground>(WWT_PANEL, Colours::Brown, widnum);
127 panel->SetMinimalSize(246, sprite_height + WidgetDimensions::unscaled.framerect.Vertical());
128 panel->SetMinimalTextLines(1, WidgetDimensions::unscaled.framerect.Vertical(), FontSize::Normal);
129 panel->SetFill(1, 1);
130 panel->SetToolTip(STR_GRAPH_KEY_COMPANY_SELECTION_TOOLTIP);
131 vert->Add(std::move(panel));
132 }
133 return vert;
134}
135
136static constexpr std::initializer_list<NWidgetPart> _nested_graph_legend_widgets = {
139 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_GRAPH_KEY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
142 EndContainer(),
145 EndContainer(),
146};
147
150 WindowPosition::Automatic, "graph_legend", 0, 0,
151 WindowClass::GraphLegend, WindowClass::None,
152 {},
153 _nested_graph_legend_widgets
154);
155
156static void ShowGraphLegend()
157{
159}
160
166
167/******************/
168/* BASE OF GRAPHS */
169/*****************/
170
171struct BaseGraphWindow : Window {
172protected:
173 static const int GRAPH_MAX_DATASETS = 64;
174 static constexpr PixelColour GRAPH_BASE_COLOUR = GREY_SCALE(2);
175 static constexpr PixelColour GRAPH_GRID_COLOUR = GREY_SCALE(3);
176 static constexpr PixelColour GRAPH_AXIS_LINE_COLOUR = GREY_SCALE(1);
177 static constexpr PixelColour GRAPH_ZERO_LINE_COLOUR = GREY_SCALE(8);
178 static constexpr PixelColour GRAPH_YEAR_LINE_COLOUR = GREY_SCALE(5);
179 static const int GRAPH_NUM_MONTHS = 24;
180 static const int GRAPH_PAYMENT_RATE_STEPS = 20;
181 static const int PAYMENT_GRAPH_X_STEP_DAYS = 10;
182 static const int PAYMENT_GRAPH_X_STEP_SECONDS = 20;
183 static const int ECONOMY_YEAR_MINUTES = 12;
184 static const int ECONOMY_QUARTER_MINUTES = 3;
185 static const int ECONOMY_MONTH_MINUTES = 1;
186
188
189 static const int MIN_GRAPH_NUM_LINES_Y = 9;
190 static const int MIN_GRID_PIXEL_SIZE = 20;
191
192 struct GraphScale {
193 StringID label = STR_NULL;
194 uint8_t month_increment = 0;
195 int16_t x_values_increment = 0;
196 const HistoryRange *history_range = nullptr;
197 };
198
204
205 static constexpr GraphScale MONTHLY_SCALE_WALLCLOCK[] = {
206 {STR_GRAPH_LAST_24_MINUTES_TIME_LABEL, HISTORY_MONTH.total_division, ECONOMY_MONTH_MINUTES, &HISTORY_MONTH},
207 {STR_GRAPH_LAST_72_MINUTES_TIME_LABEL, HISTORY_QUARTER.total_division, ECONOMY_QUARTER_MINUTES, &HISTORY_QUARTER},
208 {STR_GRAPH_LAST_288_MINUTES_TIME_LABEL, HISTORY_YEAR.total_division, ECONOMY_YEAR_MINUTES, &HISTORY_YEAR},
209 };
210
211 static constexpr GraphScale MONTHLY_SCALE_CALENDAR[] = {
212 {STR_GRAPH_LAST_24_MONTHS, HISTORY_MONTH.total_division, ECONOMY_MONTH_MINUTES, &HISTORY_MONTH},
213 {STR_GRAPH_LAST_24_QUARTERS, HISTORY_QUARTER.total_division, ECONOMY_QUARTER_MINUTES, &HISTORY_QUARTER},
214 {STR_GRAPH_LAST_24_YEARS, HISTORY_YEAR.total_division, ECONOMY_YEAR_MINUTES, &HISTORY_YEAR},
215 };
216
217 uint64_t excluded_data = 0;
218 uint64_t excluded_range = 0;
219 uint64_t masked_range = 0;
220 uint8_t num_on_x_axis = 0;
221 uint8_t num_vert_lines = GRAPH_NUM_MONTHS;
222
225 uint8_t month_increment = 3;
226
227 bool draw_dates = true;
228
234 bool x_values_reversed = true;
237
238 StringID format_str_y_axis{};
239
240 struct DataSet {
241 std::array<OverflowSafeInt64, GRAPH_NUM_MONTHS> values;
242 PixelColour colour;
243 uint8_t exclude_bit;
244 uint8_t range_bit;
245 uint8_t dash;
246 };
247 std::vector<DataSet> data{};
248
249 std::span<const GraphRange> ranges{};
250 std::span<const GraphScale> scales{};
251 uint8_t selected_scale = 0;
252
253 uint8_t highlight_data = UINT8_MAX;
254 uint8_t highlight_range = UINT8_MAX;
255 bool highlight_state = false;
256
257 struct BaseFiller {
259
260 inline void MakeZero(uint i) const { this->dataset.values[i] = 0; }
261 inline void MakeInvalid(uint i) const { this->dataset.values[i] = INVALID_DATAPOINT; }
262 };
263
264 template <typename Tprojection>
266 Tprojection proj;
267
268 inline void Fill(uint i, const auto &data) const { this->dataset.values[i] = std::invoke(this->proj, data); }
269 };
270
276 template <typename Tprojection, typename Ttransformer>
278 Tprojection proj;
279 Ttransformer transformer;
280
286 inline void Fill(uint i, const auto &data) const { this->dataset.values[i] = transformer(std::invoke(this->proj, data)); }
287 };
288
294 std::span<const OverflowSafeInt64> GetDataSetRange(const DataSet &dataset) const
295 {
296 return {std::begin(dataset.values), std::begin(dataset.values) + this->num_on_x_axis};
297 }
298
305 ValuesInterval GetValuesInterval(int num_hori_lines) const
306 {
307 assert(num_hori_lines > 0);
308
309 ValuesInterval current_interval;
310 current_interval.highest = INT64_MIN;
311 current_interval.lowest = INT64_MAX;
312
313 for (const DataSet &dataset : this->data) {
314 if (HasBit(this->excluded_data, dataset.exclude_bit)) continue;
315 if (HasBit(this->excluded_range, dataset.range_bit)) continue;
316
317 for (const OverflowSafeInt64 &datapoint : this->GetDataSetRange(dataset)) {
318 if (datapoint != INVALID_DATAPOINT) {
319 current_interval.highest = std::max(current_interval.highest, datapoint);
320 current_interval.lowest = std::min(current_interval.lowest, datapoint);
321 }
322 }
323 }
324
325 /* Always include zero in the shown range. */
326 double abs_lower = (current_interval.lowest > 0) ? 0 : (double)abs(current_interval.lowest);
327 double abs_higher = (current_interval.highest < 0) ? 0 : (double)current_interval.highest;
328
329 /* Prevent showing values too close to the graph limits. */
330 abs_higher = (11.0 * abs_higher) / 10.0;
331 abs_lower = (11.0 * abs_lower) / 10.0;
332
333 int num_pos_grids;
334 OverflowSafeInt64 grid_size;
335
336 if (abs_lower != 0 || abs_higher != 0) {
337 /* The number of grids to reserve for the positive part is: */
338 num_pos_grids = (int)floor(0.5 + num_hori_lines * abs_higher / (abs_higher + abs_lower));
339
340 /* If there are any positive or negative values, force that they have at least one grid. */
341 if (num_pos_grids == 0 && abs_higher != 0) num_pos_grids++;
342 if (num_pos_grids == num_hori_lines && abs_lower != 0) num_pos_grids--;
343
344 /* Get the required grid size for each side and use the maximum one. */
345
346 OverflowSafeInt64 grid_size_higher = 0;
347 if (abs_higher > 0) {
348 grid_size_higher = abs_higher > INT64_MAX_IN_DOUBLE ? INT64_MAX : static_cast<int64_t>(abs_higher);
349 grid_size_higher = (grid_size_higher + num_pos_grids - 1) / num_pos_grids;
350 }
351
352 OverflowSafeInt64 grid_size_lower = 0;
353 if (abs_lower > 0) {
354 grid_size_lower = abs_lower > INT64_MAX_IN_DOUBLE ? INT64_MAX : static_cast<int64_t>(abs_lower);
355 grid_size_lower = (grid_size_lower + num_hori_lines - num_pos_grids - 1) / (num_hori_lines - num_pos_grids);
356 }
357
358 grid_size = std::max(grid_size_higher, grid_size_lower);
359 } else {
360 /* If both values are zero, show an empty graph. */
361 num_pos_grids = num_hori_lines / 2;
362 grid_size = 1;
363 }
364
365 current_interval.highest = num_pos_grids * grid_size;
366 current_interval.lowest = -(num_hori_lines - num_pos_grids) * grid_size;
367 return current_interval;
368 }
369
376 uint GetYLabelWidth(ValuesInterval current_interval, int num_hori_lines) const
377 {
378 /* draw text strings on the y axis */
379 int64_t y_label = current_interval.highest;
380 int64_t y_label_separation = (current_interval.highest - current_interval.lowest) / num_hori_lines;
381
382 uint max_width = 0;
383
384 for (int i = 0; i < (num_hori_lines + 1); i++) {
385 Dimension d = GetStringBoundingBox(GetString(STR_GRAPH_Y_LABEL, this->format_str_y_axis, y_label));
386 if (d.width > max_width) max_width = d.width;
387
388 y_label -= y_label_separation;
389 }
390
391 return max_width;
392 }
393
398 void DrawGraph(Rect r) const
399 {
400 uint x, y;
401 ValuesInterval interval;
402 int x_axis_offset;
403
404 /* the colours and cost array of GraphDrawer must accommodate
405 * both values for cargo and companies. So if any are higher, quit */
406 static_assert(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES);
407 assert(this->num_vert_lines > 0);
408
409 bool rtl = _current_text_dir == TD_RTL;
410
411 /* Rect r will be adjusted to contain just the graph, with labels being
412 * placed outside the area. */
414 r.bottom -= (this->draw_dates ? 2 : 1) * GetCharacterHeight(FontSize::Small) + ScaleGUITrad(4);
415 r.left += ScaleGUITrad(rtl ? 5 : 9);
416 r.right -= ScaleGUITrad(rtl ? 9 : 5);
417
418 /* Initial number of horizontal lines. */
419 int num_hori_lines = 160 / ScaleGUITrad(MIN_GRID_PIXEL_SIZE);
420 /* For the rest of the height, the number of horizontal lines will increase more slowly. */
421 int resize = (r.bottom - r.top - 160) / (2 * ScaleGUITrad(MIN_GRID_PIXEL_SIZE));
422 if (resize > 0) num_hori_lines += resize;
423
424 interval = GetValuesInterval(num_hori_lines);
425
426 int label_width = GetYLabelWidth(interval, num_hori_lines);
427
428 if (rtl) {
429 r.right -= label_width;
430 } else {
431 r.left += label_width;
432 }
433
434 int x_sep = (r.right - r.left) / this->num_vert_lines;
435 int y_sep = (r.bottom - r.top) / num_hori_lines;
436
437 /* Redetermine right and bottom edge of graph to fit with the integer
438 * separation values. */
439 if (rtl) {
440 r.left = r.right - x_sep * this->num_vert_lines;
441 } else {
442 r.right = r.left + x_sep * this->num_vert_lines;
443 }
444 r.bottom = r.top + y_sep * num_hori_lines;
445
446 OverflowSafeInt64 interval_size = interval.highest + abs(interval.lowest);
447 /* Where to draw the X axis. Use floating point to avoid overflowing and results of zero. */
448 x_axis_offset = (int)((r.bottom - r.top) * (double)interval.highest / (double)interval_size);
449
450 /* Draw the background of the graph itself. */
451 GfxFillRect(r.left, r.top, r.right, r.bottom, GRAPH_BASE_COLOUR);
452
453 /* Draw the grid lines. */
454 int gridline_width = WidgetDimensions::scaled.bevel.top;
455 PixelColour grid_colour = GRAPH_GRID_COLOUR;
456
457 /* Don't draw the first line, as that's where the axis will be. */
458 if (rtl) {
459 x_sep = -x_sep;
460 x = r.right + x_sep;
461 } else {
462 x = r.left + x_sep;
463 }
464
465 for (int i = 1; i < this->num_vert_lines + 1; i++) {
466 /* If using wallclock units, we separate periods with a lighter line. */
468 grid_colour = (i % 4 == 0) ? GRAPH_YEAR_LINE_COLOUR : GRAPH_GRID_COLOUR;
469 }
470 GfxFillRect(x, r.top, x + gridline_width - 1, r.bottom, grid_colour);
471 x += x_sep;
472 }
473
474 /* Draw the horizontal grid lines. */
475 y = r.bottom;
476
477 for (int i = 0; i < (num_hori_lines + 1); i++) {
478 if (rtl) {
479 GfxFillRect(r.right + 1, y, r.right + ScaleGUITrad(3), y + gridline_width - 1, GRAPH_AXIS_LINE_COLOUR);
480 } else {
481 GfxFillRect(r.left - ScaleGUITrad(3), y, r.left - 1, y + gridline_width - 1, GRAPH_AXIS_LINE_COLOUR);
482 }
483 GfxFillRect(r.left, y, r.right + gridline_width - 1, y + gridline_width - 1, GRAPH_GRID_COLOUR);
484 y -= y_sep;
485 }
486
487 /* Draw the y axis. */
488 GfxFillRect(r.left, r.top, r.left + gridline_width - 1, r.bottom + gridline_width - 1, GRAPH_AXIS_LINE_COLOUR);
489
490 /* Draw the x axis. */
491 y = x_axis_offset + r.top;
492 GfxFillRect(r.left, y, r.right + gridline_width - 1, y + gridline_width - 1, GRAPH_ZERO_LINE_COLOUR);
493
494 /* Find the largest value that will be drawn. */
495 if (this->num_on_x_axis == 0) return;
496
497 assert(this->num_on_x_axis > 0);
498
499 /* draw text strings on the y axis */
500 int64_t y_label = interval.highest;
501 int64_t y_label_separation = abs(interval.highest - interval.lowest) / num_hori_lines;
502
503 y = r.top - GetCharacterHeight(FontSize::Small) / 2;
504
505 for (int i = 0; i < (num_hori_lines + 1); i++) {
506 if (rtl) {
507 DrawString(r.right + ScaleGUITrad(4), r.right + label_width + ScaleGUITrad(4), y,
508 GetString(STR_GRAPH_Y_LABEL, this->format_str_y_axis, y_label),
510 } else {
511 DrawString(r.left - label_width - ScaleGUITrad(4), r.left - ScaleGUITrad(4), y,
512 GetString(STR_GRAPH_Y_LABEL, this->format_str_y_axis, y_label),
514 }
515
516 y_label -= y_label_separation;
517 y += y_sep;
518 }
519
520 x = rtl ? r.right : r.left;
521 y = r.bottom + ScaleGUITrad(2);
522
523 /* if there are not enough datapoints to fill the graph, align to the right */
524 x += (this->num_vert_lines - this->num_on_x_axis) * x_sep;
525
526 /* Draw x-axis labels and markings for graphs based on financial quarters and years. */
527 if (this->draw_dates) {
528 TimerGameEconomy::Month mo = this->month;
529 TimerGameEconomy::Year yr = this->year;
530 for (int i = 0; i < this->num_on_x_axis; i++) {
531 if (rtl) {
532 DrawStringMultiLineWithClipping(x + x_sep, x, y, this->height,
533 GetString(mo == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH, STR_MONTH_ABBREV_JAN + mo, yr),
535 } else {
536 DrawStringMultiLineWithClipping(x, x + x_sep, y, this->height,
537 GetString(mo == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH, STR_MONTH_ABBREV_JAN + mo, yr),
539 }
540
541 mo += this->month_increment;
542 if (mo >= 12) {
543 mo = 0;
544 yr++;
545
546 /* Draw a lighter grid line between years. Top and bottom adjustments ensure we don't draw over top and bottom horizontal grid lines. */
547 GfxFillRect(x + x_sep, r.top + gridline_width, x + x_sep + gridline_width - 1, r.bottom - 1, GRAPH_YEAR_LINE_COLOUR);
548 }
549 x += x_sep;
550 }
551 } else {
552 /* Draw x-axis labels for graphs not based on quarterly performance (cargo payment rates, and all graphs when using wallclock units). */
553 int16_t iterator;
554 uint16_t label;
555 if (this->x_values_reversed) {
556 label = this->x_values_increment * this->num_on_x_axis;
557 iterator = -this->x_values_increment;
558 } else {
559 label = this->x_values_increment;
560 iterator = this->x_values_increment;
561 }
562
563 for (int i = 0; i < this->num_on_x_axis; i++) {
564 if (rtl) {
565 DrawString(x + x_sep + 1, x - 1, y, GetString(STR_GRAPH_Y_LABEL_NUMBER, label), GRAPH_AXIS_LABEL_COLOUR, AlignmentH::Centre);
566 } else {
567 DrawString(x + 1, x + x_sep - 1, y, GetString(STR_GRAPH_Y_LABEL_NUMBER, label), GRAPH_AXIS_LABEL_COLOUR, AlignmentH::Centre);
568 }
569
570 label += iterator;
571 x += x_sep;
572 }
573 }
574
575 /* Draw lines and dots. */
576 uint linewidth = ScaleGUITrad(_settings_client.gui.graph_line_thickness);
577 uint pointwidth = ScaleGUITrad(_settings_client.gui.graph_line_thickness + 1);
578 uint pointoffs1 = pointwidth / 2;
579 uint pointoffs2 = pointwidth - pointoffs1;
580
581 auto draw_dataset = [&](const DataSet &dataset, PixelColour colour) {
582 if (HasBit(this->excluded_data, dataset.exclude_bit)) return;
583 if (HasBit(this->excluded_range, dataset.range_bit)) return;
584
585 /* Centre the dot between the grid lines. */
586 if (rtl) {
587 x = r.right + (x_sep / 2);
588 } else {
589 x = r.left + (x_sep / 2);
590 }
591
592 /* if there are not enough datapoints to fill the graph, align to the right */
593 x += (this->num_vert_lines - this->num_on_x_axis) * x_sep;
594
595 uint prev_x = INVALID_DATAPOINT_POS;
596 uint prev_y = INVALID_DATAPOINT_POS;
597
598 const uint dash = ScaleGUITrad(dataset.dash);
599 for (OverflowSafeInt64 datapoint : this->GetDataSetRange(dataset)) {
600 if (datapoint != INVALID_DATAPOINT) {
601 /*
602 * Check whether we need to reduce the 'accuracy' of the
603 * datapoint value and the highest value to split overflows.
604 * And when 'drawing' 'one million' or 'one million and one'
605 * there is no significant difference, so the least
606 * significant bits can just be removed.
607 *
608 * If there are more bits needed than would fit in a 32 bits
609 * integer, so at about 31 bits because of the sign bit, the
610 * least significant bits are removed.
611 */
612 int mult_range = FindLastBit<uint32_t>(x_axis_offset) + FindLastBit<uint64_t>(abs(datapoint));
613 int reduce_range = std::max(mult_range - 31, 0);
614
615 /* Handle negative values differently (don't shift sign) */
616 if (datapoint < 0) {
617 datapoint = -(abs(datapoint) >> reduce_range);
618 } else {
619 datapoint >>= reduce_range;
620 }
621 y = r.top + x_axis_offset - ((r.bottom - r.top) * datapoint) / (interval_size >> reduce_range);
622
623 /* Draw the point. */
624 GfxFillRect(x - pointoffs1, y - pointoffs1, x + pointoffs2, y + pointoffs2, colour);
625
626 /* Draw the line connected to the previous point. */
627 if (prev_x != INVALID_DATAPOINT_POS) GfxDrawLine(prev_x, prev_y, x, y, colour, linewidth, dash);
628
629 prev_x = x;
630 prev_y = y;
631 } else {
632 prev_x = INVALID_DATAPOINT_POS;
633 prev_y = INVALID_DATAPOINT_POS;
634 }
635
636 x += x_sep;
637 }
638 };
639
640 /* Draw unhighlighted datasets. */
641 for (const DataSet &dataset : this->data) {
642 if (dataset.exclude_bit != this->highlight_data && dataset.range_bit != this->highlight_range) {
643 draw_dataset(dataset, dataset.colour);
644 }
645 }
646
647 /* If any dataset or range is highlighted, draw separately after the rest so they appear on top of all other
648 * data. Highlighted data is only drawn when highlight_state is set, otherwise it is invisible. */
649 if (this->highlight_state && (this->highlight_data != UINT8_MAX || this->highlight_range != UINT8_MAX)) {
650 for (const DataSet &dataset : this->data) {
651 if (dataset.exclude_bit == this->highlight_data || dataset.range_bit == this->highlight_range) {
652 draw_dataset(dataset, PC_WHITE);
653 }
654 }
655 }
656 }
657
658 BaseGraphWindow(WindowDesc &desc, StringID format_str_y_axis) :
659 Window(desc),
660 format_str_y_axis(format_str_y_axis)
661 {
662 SetWindowDirty(WindowClass::GraphLegend, 0);
663 }
664
665 const IntervalTimer<TimerWindow> blink_interval = {TIMER_BLINK_INTERVAL, [this](auto) {
666 /* If nothing is highlighted then no redraw is needed. */
667 if (this->highlight_data == UINT8_MAX && this->highlight_range == UINT8_MAX) return;
668
669 /* Toggle the highlight state and redraw. */
670 this->highlight_state = !this->highlight_state;
671 this->SetDirty();
672 }};
673
674 void UpdateMatrixSize(WidgetID widget, Dimension &size, Dimension &resize, auto labels)
675 {
676 size = {};
677 for (const StringID &str : labels) {
678 size = maxdim(size, GetStringBoundingBox(str, FontSize::Small));
679 }
680
683
684 /* Set fixed height for number of ranges. */
685 size.height *= static_cast<uint>(std::size(labels));
686
687 resize.width = 0;
688 resize.height = 0;
689 this->GetWidget<NWidgetCore>(widget)->SetMatrixDimension(1, ClampTo<uint32_t>(std::size(labels)));
690 }
691
692public:
693 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
694 {
695 switch (widget) {
697 this->UpdateMatrixSize(widget, size, resize, this->ranges | std::views::transform(&GraphRange::label));
698 break;
699
701 this->UpdateMatrixSize(widget, size, resize, this->scales | std::views::transform(&GraphScale::label));
702 break;
703
704 case WID_GRAPH_GRAPH: {
705 uint x_label_width = 0;
706
707 /* Draw x-axis labels and markings for graphs based on financial quarters and years. */
708 if (this->draw_dates) {
709 uint yr = GetParamMaxValue(this->year.base(), 4, FontSize::Small);
710 for (uint mo = 0; mo < 12; ++mo) {
711 x_label_width = std::max(x_label_width, GetStringBoundingBox(GetString(mo == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH, STR_MONTH_ABBREV_JAN + mo, yr)).width);
712 }
713 } else {
714 /* Draw x-axis labels for graphs not based on quarterly performance (cargo payment rates). */
715 uint64_t max_value = GetParamMaxValue((this->num_on_x_axis + 1) * this->x_values_increment, 0, FontSize::Small);
716 x_label_width = GetStringBoundingBox(GetString(STR_GRAPH_Y_LABEL_NUMBER, max_value)).width;
717 }
718
719 uint y_label_width = GetStringBoundingBox(GetString(STR_GRAPH_Y_LABEL, this->format_str_y_axis, INT64_MAX)).width;
720
721 size.width = std::max<uint>(size.width, ScaleGUITrad(5) + y_label_width + this->num_vert_lines * (x_label_width + ScaleGUITrad(5)) + ScaleGUITrad(9));
722 size.height = std::max<uint>(size.height, ScaleGUITrad(5) + (1 + MIN_GRAPH_NUM_LINES_Y * 2 + (this->draw_dates ? 3 : 1)) * GetCharacterHeight(FontSize::Small) + ScaleGUITrad(4));
723 size.height = std::max<uint>(size.height, size.width / 3);
724 break;
725 }
726
727 default: break;
728 }
729 }
730
731 bool OnTooltip([[maybe_unused]] Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
732 {
733 if (widget != WID_GRAPH_RANGE_MATRIX) return false;
734
735 int row = GetRowFromWidget(pt.y, widget, 0, GetCharacterHeight(FontSize::Small) + WidgetDimensions::scaled.framerect.Vertical());
736 if (row == INT_MAX) return false;
737
738 GuiShowTooltips(this, GetEncodedString(this->ranges[row].tooltip), close_cond);
739 return true;
740 }
741
742 void DrawWidget(const Rect &r, WidgetID widget) const override
743 {
744 switch (widget) {
745 case WID_GRAPH_GRAPH:
746 this->DrawGraph(r);
747 break;
748
750 uint line_height = GetCharacterHeight(FontSize::Small) + WidgetDimensions::scaled.framerect.Vertical();
751 uint index = 0;
752 Rect line = r.WithHeight(line_height);
753 for (const auto &[label, tooltip] : this->ranges) {
754 bool lowered = !HasBit(this->excluded_range, index) && !HasBit(this->masked_range, index);
755
756 /* Redraw frame if lowered */
758
759 const Rect text = line.Shrink(WidgetDimensions::scaled.framerect);
760 DrawString(text, label, (this->highlight_state && this->highlight_range == index) ? TextColour::White : TextColour::Black, {AlignmentH::Centre, AlignmentV::Middle}, false, FontSize::Small);
761
762 if (HasBit(this->masked_range, index)) {
764 }
765
766 line = line.Translate(0, line_height);
767 ++index;
768 }
769 break;
770 }
771
773 uint line_height = GetCharacterHeight(FontSize::Small) + WidgetDimensions::scaled.framerect.Vertical();
774 uint8_t selected_month_increment = this->scales[this->selected_scale].month_increment;
775 Rect line = r.WithHeight(line_height);
776 for (const auto &scale : this->scales) {
777 /* Redraw frame if selected */
778 if (selected_month_increment == scale.month_increment) DrawFrameRect(line, Colours::Brown, FrameFlag::Lowered);
779
780 DrawString(line.Shrink(WidgetDimensions::scaled.framerect), scale.label, TextColour::Black, {AlignmentH::Centre, AlignmentV::Middle}, false, FontSize::Small);
781
782 line = line.Translate(0, line_height);
783 }
784 break;
785 }
786
787 default: break;
788 }
789 }
790
791 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
792 {
793 /* Clicked on legend? */
794 switch (widget) {
796 ShowGraphLegend();
797 break;
798
800 int row = GetRowFromWidget(pt.y, widget, 0, GetCharacterHeight(FontSize::Small) + WidgetDimensions::scaled.framerect.Vertical());
801
802 if (HasBit(this->masked_range, row)) break;
803 ToggleBit(this->excluded_range, row);
804 SndClickBeep();
805 this->SetDirty();
806 break;
807 }
808
810 int row = GetRowFromWidget(pt.y, widget, 0, GetCharacterHeight(FontSize::Small) + WidgetDimensions::scaled.framerect.Vertical());
811 const auto &scale = this->scales[row];
812 if (this->selected_scale != row) {
813 this->selected_scale = row;
814 this->month_increment = scale.month_increment;
815 this->x_values_increment = scale.x_values_increment;
816 this->InvalidateData();
817 }
818 break;
819 }
820
821 default: break;
822 }
823 }
824
825 void OnMouseOver(Point pt, WidgetID widget) override
826 {
827 /* Test if a range should be highlighted. */
828 uint8_t new_highlight_range = UINT8_MAX;
829 if (widget == WID_GRAPH_RANGE_MATRIX) {
830 int row = GetRowFromWidget(pt.y, widget, 0, GetCharacterHeight(FontSize::Small) + WidgetDimensions::scaled.framerect.Vertical());
831 if (!HasBit(this->excluded_range, row)) new_highlight_range = static_cast<uint8_t>(row);
832 }
833
834 /* Test if a dataset should be highlighted. */
835 uint8_t new_highlight_data = UINT8_MAX;
836 if (widget == WID_GRAPH_MATRIX) {
837 auto dataset_index = this->GetDatasetIndex(pt.y);
838 if (dataset_index.has_value() && !HasBit(this->excluded_data, *dataset_index)) new_highlight_data = *dataset_index;
839 }
840
841 if (this->highlight_data == new_highlight_data && this->highlight_range == new_highlight_range) return;
842
843 /* Range or data set highlight has changed, set and redraw. */
844 this->highlight_data = new_highlight_data;
845 this->highlight_range = new_highlight_range;
846 this->highlight_state = true;
847 this->SetDirty();
848 }
849
850 void OnGameTick() override
851 {
852 this->UpdateStatistics(false);
853 }
854
860 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
861 {
862 if (!gui_scope) return;
863 this->UpdateStatistics(true);
864 }
865
870 virtual void UpdateStatistics(bool initialize) = 0;
871
877 virtual std::optional<uint8_t> GetDatasetIndex([[maybe_unused]] int y) { return std::nullopt; }
878};
879
880class BaseCompanyGraphWindow : public BaseGraphWindow {
881public:
882 BaseCompanyGraphWindow(WindowDesc &desc, StringID format_str_y_axis) : BaseGraphWindow(desc, format_str_y_axis) {}
883
884 void InitializeWindow(WindowNumber number)
885 {
886 /* Initialise the dataset */
887 this->UpdateStatistics(true);
888
889 this->CreateNestedTree();
890
891 auto *wid = this->GetWidget<NWidgetCore>(WID_GRAPH_FOOTER);
892 wid->SetString(TimerGameEconomy::UsingWallclockUnits() ? STR_GRAPH_LAST_72_MINUTES_TIME_LABEL : STR_EMPTY);
893
894 this->FinishInitNested(number);
895 }
896
897 void UpdateStatistics(bool initialize) override
898 {
899 CompanyMask excluded_companies = _legend_excluded_companies;
900
901 /* Exclude the companies which aren't valid */
902 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
903 if (!Company::IsValidID(c)) excluded_companies.Set(c);
904 }
905
906 uint8_t nums = 0;
907 for (const Company *c : Company::Iterate()) {
908 nums = std::min(this->num_vert_lines, std::max(nums, c->num_valid_stat_ent));
909 }
910
911 int mo = (TimerGameEconomy::month / this->month_increment - nums) * this->month_increment;
912 auto yr = TimerGameEconomy::year;
913 while (mo < 0) {
914 yr--;
915 mo += 12;
916 }
917
918 if (!initialize && this->excluded_data == excluded_companies.base() && this->num_on_x_axis == nums &&
919 this->year == yr && this->month == mo) {
920 /* There's no reason to get new stats */
921 return;
922 }
923
924 this->excluded_data = excluded_companies.base();
925 this->num_on_x_axis = nums;
926 this->year = yr;
927 this->month = mo;
928
929 this->data.clear();
930 for (CompanyID k = CompanyID::Begin(); k < MAX_COMPANIES; ++k) {
931 const Company *c = Company::GetIfValid(k);
932 if (c == nullptr) continue;
933
934 DataSet &dataset = this->data.emplace_back();
935 dataset.colour = GetColourGradient(c->colour, Shade::Lighter);
936 dataset.exclude_bit = k.base();
937
938 for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
939 if (j >= c->num_valid_stat_ent) {
940 dataset.values[i] = INVALID_DATAPOINT;
941 } else {
942 /* Ensure we never assign INVALID_DATAPOINT, as that has another meaning.
943 * Instead, use the value just under it. Hopefully nobody will notice. */
944 dataset.values[i] = std::min(GetGraphData(c, j), INVALID_DATAPOINT - 1);
945 }
946 i++;
947 }
948 }
949 }
950
957 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j) = 0;
958};
959
960
961/********************/
962/* OPERATING PROFIT */
963/********************/
964
965struct OperatingProfitGraphWindow : BaseCompanyGraphWindow {
966 OperatingProfitGraphWindow(WindowDesc &desc, WindowNumber window_number) :
967 BaseCompanyGraphWindow(desc, STR_JUST_CURRENCY_SHORT)
968 {
969 this->num_on_x_axis = GRAPH_NUM_MONTHS;
970 this->num_vert_lines = GRAPH_NUM_MONTHS;
971 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
972
973 this->InitializeWindow(window_number);
974 }
975
976 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
977 {
978 return c->old_economy[j].income + c->old_economy[j].expenses;
979 }
980};
981
982static constexpr std::initializer_list<NWidgetPart> _nested_operating_profit_widgets = {
985 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_GRAPH_OPERATING_PROFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
986 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
990 EndContainer(),
996 EndContainer(),
997 EndContainer(),
998};
999
1002 WindowPosition::Automatic, "graph_operating_profit", 0, 0,
1003 WindowClass::OperatingProfitGraph, WindowClass::None,
1004 {},
1005 _nested_operating_profit_widgets
1006);
1007
1008
1009void ShowOperatingProfitGraph()
1010{
1012}
1013
1014
1015/****************/
1016/* INCOME GRAPH */
1017/****************/
1018
1019struct IncomeGraphWindow : BaseCompanyGraphWindow {
1020 IncomeGraphWindow(WindowDesc &desc, WindowNumber window_number) :
1021 BaseCompanyGraphWindow(desc, STR_JUST_CURRENCY_SHORT)
1022 {
1023 this->num_on_x_axis = GRAPH_NUM_MONTHS;
1024 this->num_vert_lines = GRAPH_NUM_MONTHS;
1025 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
1026
1027 this->InitializeWindow(window_number);
1028 }
1029
1030 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
1031 {
1032 return c->old_economy[j].income;
1033 }
1034};
1035
1036static constexpr std::initializer_list<NWidgetPart> _nested_income_graph_widgets = {
1039 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_GRAPH_INCOME_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1040 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
1044 EndContainer(),
1050 EndContainer(),
1051 EndContainer(),
1052};
1053
1056 WindowPosition::Automatic, "graph_income", 0, 0,
1057 WindowClass::IncomeGraph, WindowClass::None,
1058 {},
1059 _nested_income_graph_widgets
1060);
1061
1062void ShowIncomeGraph()
1063{
1065}
1066
1067/*******************/
1068/* DELIVERED CARGO */
1069/*******************/
1070
1071struct DeliveredCargoGraphWindow : BaseCompanyGraphWindow {
1072 DeliveredCargoGraphWindow(WindowDesc &desc, WindowNumber window_number) :
1073 BaseCompanyGraphWindow(desc, STR_JUST_COMMA)
1074 {
1075 this->num_on_x_axis = GRAPH_NUM_MONTHS;
1076 this->num_vert_lines = GRAPH_NUM_MONTHS;
1077 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
1078
1079 this->InitializeWindow(window_number);
1080 }
1081
1082 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
1083 {
1084 return c->old_economy[j].delivered_cargo.GetSum<OverflowSafeInt64>();
1085 }
1086};
1087
1088static constexpr std::initializer_list<NWidgetPart> _nested_delivered_cargo_graph_widgets = {
1091 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_GRAPH_CARGO_DELIVERED_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1092 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
1096 EndContainer(),
1102 EndContainer(),
1103 EndContainer(),
1104};
1105
1108 WindowPosition::Automatic, "graph_delivered_cargo", 0, 0,
1109 WindowClass::DeliveredCargoGraph, WindowClass::None,
1110 {},
1111 _nested_delivered_cargo_graph_widgets
1112);
1113
1114void ShowDeliveredCargoGraph()
1115{
1117}
1118
1119/***********************/
1120/* PERFORMANCE HISTORY */
1121/***********************/
1122
1123struct PerformanceHistoryGraphWindow : BaseCompanyGraphWindow {
1124 PerformanceHistoryGraphWindow(WindowDesc &desc, WindowNumber window_number) :
1125 BaseCompanyGraphWindow(desc, STR_JUST_COMMA)
1126 {
1127 this->num_on_x_axis = GRAPH_NUM_MONTHS;
1128 this->num_vert_lines = GRAPH_NUM_MONTHS;
1129 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
1130
1131 this->InitializeWindow(window_number);
1132 }
1133
1134 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
1135 {
1136 return c->old_economy[j].performance_history;
1137 }
1138
1139 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1140 {
1141 if (widget == WID_PHG_DETAILED_PERFORMANCE) ShowPerformanceRatingDetail();
1142 this->BaseGraphWindow::OnClick(pt, widget, click_count);
1143 }
1144};
1145
1146static constexpr std::initializer_list<NWidgetPart> _nested_performance_history_widgets = {
1149 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_GRAPH_COMPANY_PERFORMANCE_RATINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1150 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_PHG_DETAILED_PERFORMANCE), SetMinimalSize(50, 0), SetStringTip(STR_PERFORMANCE_DETAIL_KEY, STR_GRAPH_PERFORMANCE_DETAIL_TOOLTIP),
1151 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
1155 EndContainer(),
1161 EndContainer(),
1162 EndContainer(),
1163};
1164
1167 WindowPosition::Automatic, "graph_performance", 0, 0,
1168 WindowClass::PerformanceGraph, WindowClass::None,
1169 {},
1170 _nested_performance_history_widgets
1171);
1172
1173void ShowPerformanceHistoryGraph()
1174{
1176}
1177
1178/*****************/
1179/* COMPANY VALUE */
1180/*****************/
1181
1182struct CompanyValueGraphWindow : BaseCompanyGraphWindow {
1183 CompanyValueGraphWindow(WindowDesc &desc, WindowNumber window_number) :
1184 BaseCompanyGraphWindow(desc, STR_JUST_CURRENCY_SHORT)
1185 {
1186 this->num_on_x_axis = GRAPH_NUM_MONTHS;
1187 this->num_vert_lines = GRAPH_NUM_MONTHS;
1188 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
1189
1190 this->InitializeWindow(window_number);
1191 }
1192
1193 OverflowSafeInt64 GetGraphData(const Company *c, int j) override
1194 {
1195 return c->old_economy[j].company_value;
1196 }
1197};
1198
1199static constexpr std::initializer_list<NWidgetPart> _nested_company_value_graph_widgets = {
1202 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_GRAPH_COMPANY_VALUES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1203 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_KEY_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
1207 EndContainer(),
1213 EndContainer(),
1214 EndContainer(),
1215};
1216
1219 WindowPosition::Automatic, "graph_company_value", 0, 0,
1220 WindowClass::CompanyValueGraph, WindowClass::None,
1221 {},
1222 _nested_company_value_graph_widgets
1223);
1224
1225void ShowCompanyValueGraph()
1226{
1228}
1229
1230struct BaseCargoGraphWindow : BaseGraphWindow {
1231 Scrollbar *vscroll = nullptr;
1232 uint line_height = 0;
1233 uint legend_width = 0;
1234
1236
1237 BaseCargoGraphWindow(WindowDesc &desc, StringID format_str_y_axis) : BaseGraphWindow(desc, format_str_y_axis) {}
1238
1239 void InitializeWindow(WindowNumber number, StringID footer_wallclock = STR_NULL, StringID footer_calendar = STR_NULL)
1240 {
1241 this->CreateNestedTree();
1242
1243 this->excluded_range = this->masked_range;
1244 this->cargo_types = this->GetCargoTypes(number);
1245
1247 this->vscroll->SetCount(this->cargo_types.Count());
1248
1249 auto *wid = this->GetWidget<NWidgetCore>(WID_GRAPH_FOOTER);
1250 wid->SetString(TimerGameEconomy::UsingWallclockUnits() ? footer_wallclock : footer_calendar);
1251
1252 this->FinishInitNested(number);
1253
1254 /* Initialise the dataset */
1255 this->InvalidateData();
1256 }
1257
1263 virtual CargoTypes GetCargoTypes(WindowNumber number) const = 0;
1264
1269 virtual CargoTypes &GetExcludedCargoTypes() const = 0;
1270
1271 std::optional<uint8_t> GetDatasetIndex(int y) override
1272 {
1273 int row = this->vscroll->GetScrolledRowFromWidget(y, this, WID_GRAPH_MATRIX);
1274 if (row >= this->vscroll->GetCount()) return std::nullopt;
1275
1276 for (const CargoSpec *cs : _sorted_cargo_specs) {
1277 if (!this->cargo_types.Test(cs->Index())) continue;
1278 if (row-- > 0) continue;
1279
1280 return cs->Index();
1281 }
1282
1283 return std::nullopt;
1284 }
1285
1286 void OnInit() override
1287 {
1288 /* Width of the legend blob. */
1289 this->legend_width = GetCharacterHeight(FontSize::Small) * 9 / 6;
1290 }
1291
1292 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1293 {
1294 if (widget != WID_GRAPH_MATRIX) {
1295 BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
1296 return;
1297 }
1298
1300
1301 for (CargoType cargo_type : this->cargo_types) {
1302 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1303
1304 Dimension d = GetStringBoundingBox(GetString(STR_GRAPH_CARGO_PAYMENT_CARGO, cs->name));
1305 d.width += this->legend_width + WidgetDimensions::scaled.hsep_normal; // colour field
1306 d.width += WidgetDimensions::scaled.framerect.Horizontal();
1307 d.height += WidgetDimensions::scaled.framerect.Vertical();
1308 size = maxdim(d, size);
1309 }
1310
1311 this->line_height = size.height;
1312 size.height = this->line_height * 11; /* Default number of cargo types in most climates. */
1313 resize.width = 0;
1314 fill.height = resize.height = this->line_height;
1315 }
1316
1317 void DrawWidget(const Rect &r, WidgetID widget) const override
1318 {
1319 if (widget != WID_GRAPH_MATRIX) {
1320 BaseGraphWindow::DrawWidget(r, widget);
1321 return;
1322 }
1323
1324 bool rtl = _current_text_dir == TD_RTL;
1325
1326 int pos = this->vscroll->GetPosition();
1327 int max = pos + this->vscroll->GetCapacity();
1328
1329 Rect line = r.WithHeight(this->line_height);
1330
1331 for (const CargoSpec *cs : _sorted_cargo_specs) {
1332 if (!this->cargo_types.Test(cs->Index())) continue;
1333
1334 if (pos-- > 0) continue;
1335 if (--max < 0) break;
1336
1337 bool lowered = !CargoTypes{this->excluded_data}.Test(cs->Index());
1338
1339 /* Redraw frame if lowered */
1340 if (lowered) DrawFrameRect(line, Colours::Brown, FrameFlag::Lowered);
1341
1342 const Rect text = line.Shrink(WidgetDimensions::scaled.framerect);
1343
1344 /* Cargo-colour box with outline */
1345 const Rect cargo = text.WithWidth(this->legend_width, rtl);
1346 GfxFillRect(cargo, PC_BLACK);
1347 PixelColour pc = cs->legend_colour;
1348 if (this->highlight_data == cs->Index()) pc = this->highlight_state ? PC_WHITE : PC_BLACK;
1350
1351 /* Cargo name */
1352 DrawString(text.Indent(this->legend_width + WidgetDimensions::scaled.hsep_normal, rtl), GetString(STR_GRAPH_CARGO_PAYMENT_CARGO, cs->name));
1353
1354 line = line.Translate(0, this->line_height);
1355 }
1356 }
1357
1358 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1359 {
1360 switch (widget) {
1362 /* Remove all cargoes from the excluded lists. */
1363 this->GetExcludedCargoTypes() = {};
1364 this->excluded_data = this->GetExcludedCargoTypes().base();
1365 this->SetDirty();
1366 break;
1367
1369 /* Add all cargoes to the excluded lists. */
1370 this->GetExcludedCargoTypes() = this->cargo_types;
1371 this->excluded_data = this->GetExcludedCargoTypes().base();
1372 this->SetDirty();
1373 break;
1374 }
1375
1376 case WID_GRAPH_MATRIX: {
1377 int row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_GRAPH_MATRIX);
1378 if (row >= this->vscroll->GetCount()) return;
1379
1380 SndClickBeep();
1381
1382 for (const CargoSpec *cs : _sorted_cargo_specs) {
1383 if (!this->cargo_types.Test(cs->Index())) continue;
1384 if (row-- > 0) continue;
1385
1386 this->GetExcludedCargoTypes().Flip(cs->Index());
1387 this->excluded_data = this->GetExcludedCargoTypes().base();
1388 this->SetDirty();
1389 break;
1390 }
1391 break;
1392 }
1393
1394 default:
1395 this->BaseGraphWindow::OnClick(pt, widget, click_count);
1396 break;
1397 }
1398 }
1399
1400 void OnResize() override
1401 {
1402 this->vscroll->SetCapacityFromWidget(this, WID_GRAPH_MATRIX);
1403 }
1404
1406 const IntervalTimer<TimerGameCalendar> update_cargo_types_interval = {{TimerGameCalendar::Trigger::Day, TimerGameCalendar::Priority::None}, [this](auto) {
1407 CargoTypes new_cargo_types = this->GetCargoTypes(this->window_number);
1408 if (new_cargo_types == this->cargo_types) return;
1409
1410 this->cargo_types = new_cargo_types;
1411 this->vscroll->SetCount(this->cargo_types.Count());
1412
1413 this->InvalidateData(0, false);
1414 }};
1415};
1416
1417/*****************/
1418/* PAYMENT RATES */
1419/*****************/
1420
1421struct PaymentRatesGraphWindow : BaseCargoGraphWindow {
1422 static inline CargoTypes excluded_cargo_types{};
1423
1424 PaymentRatesGraphWindow(WindowDesc &desc, WindowNumber window_number) : BaseCargoGraphWindow(desc, STR_JUST_CURRENCY_SHORT)
1425 {
1426 this->num_on_x_axis = GRAPH_PAYMENT_RATE_STEPS;
1427 this->num_vert_lines = GRAPH_PAYMENT_RATE_STEPS;
1428 this->draw_dates = false;
1429
1430 this->x_values_reversed = false;
1431 /* The x-axis is labeled in either seconds or days. A day is two seconds, so we adjust the label if needed. */
1433
1434 this->InitializeWindow(window_number, STR_GRAPH_CARGO_PAYMENT_RATES_SECONDS, STR_GRAPH_CARGO_PAYMENT_RATES_DAYS);
1435 }
1436
1438 {
1439 return _standard_cargo_mask;
1440 }
1441
1443 {
1444 return PaymentRatesGraphWindow::excluded_cargo_types;
1445 }
1446
1452 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1453 {
1454 if (!gui_scope) return;
1455 this->UpdatePaymentRates();
1456 }
1457
1459 const IntervalTimer<TimerWindow> update_payment_interval = {std::chrono::seconds(3), [this](auto) {
1460 this->UpdatePaymentRates();
1461 }};
1462
1463 void UpdateStatistics(bool) override {}
1464
1469 {
1470 this->excluded_data = this->GetExcludedCargoTypes().base();
1471
1472 this->data.clear();
1473 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1474 DataSet &dataset = this->data.emplace_back();
1475 dataset.colour = cs->legend_colour;
1476 dataset.exclude_bit = cs->Index();
1477
1478 for (uint j = 0; j != this->num_on_x_axis; j++) {
1479 dataset.values[j] = GetTransportedGoodsIncome(10, 20, j * 4 + 4, cs->Index());
1480 }
1481 }
1482 }
1483};
1484
1485static constexpr std::initializer_list<NWidgetPart> _nested_cargo_payment_rates_widgets = {
1488 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_GRAPH_CARGO_PAYMENT_RATES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1492 EndContainer(),
1498 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1499 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_ENABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1500 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_DISABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1503 NWidget(WWT_MATRIX, Colours::Brown, WID_GRAPH_MATRIX), SetFill(1, 0), SetResize(0, 2), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO), SetScrollbar(WID_GRAPH_MATRIX_SCROLLBAR),
1505 EndContainer(),
1506 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1507 EndContainer(),
1508 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1509 EndContainer(),
1513 EndContainer(),
1514 EndContainer(),
1515};
1516
1519 WindowPosition::Automatic, "graph_cargo_payment_rates", 0, 0,
1520 WindowClass::CargoPaymentRatesGraph, WindowClass::None,
1521 {},
1522 _nested_cargo_payment_rates_widgets
1523);
1524
1525
1526void ShowCargoPaymentRates()
1527{
1529}
1530
1531/*****************************/
1532/* PERFORMANCE RATING DETAIL */
1533/*****************************/
1534
1535struct PerformanceRatingDetailWindow : Window {
1536 static CompanyID company;
1537 int timeout = 0;
1538 uint score_info_left = 0;
1539 uint score_info_right = 0;
1540 uint bar_left = 0;
1541 uint bar_right = 0;
1542 uint bar_width = 0;
1543 uint bar_height = 0;
1544 uint score_detail_left = 0;
1545 uint score_detail_right = 0;
1546
1547 PerformanceRatingDetailWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc)
1548 {
1549 this->UpdateCompanyStats();
1550
1551 this->InitNested(window_number);
1552 this->OnInvalidateData(CompanyID::Invalid().base());
1553 }
1554
1555 void UpdateCompanyStats()
1556 {
1557 /* Update all company stats with the current data
1558 * (this is because _score_info is not saved to a savegame) */
1559 for (Company *c : Company::Iterate()) {
1561 }
1562
1563 this->timeout = Ticks::DAY_TICKS * 5;
1564 }
1565
1566 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1567 {
1568 switch (widget) {
1570 this->bar_height = GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.fullbevel.Vertical();
1571 size.height = this->bar_height + WidgetDimensions::scaled.matrix.Vertical();
1572
1573 uint score_info_width = 0;
1574 for (ScoreID i : EnumRange(ScoreID::End)) {
1575 score_info_width = std::max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + to_underlying(i)).width);
1576 }
1577 score_info_width += GetStringBoundingBox(GetString(STR_JUST_COMMA, GetParamMaxValue(1000))).width + WidgetDimensions::scaled.hsep_wide;
1578
1579 this->bar_width = GetStringBoundingBox(GetString(STR_PERFORMANCE_DETAIL_PERCENT, GetParamMaxValue(100))).width + WidgetDimensions::scaled.hsep_indent * 2; // Wide bars!
1580
1581 /* At this number we are roughly at the max; it can become wider,
1582 * but then you need at 1000 times more money. At that time you're
1583 * not that interested anymore in the last few digits anyway.
1584 * The 500 is because 999 999 500 to 999 999 999 are rounded to
1585 * 1 000 M, and not 999 999 k. Use negative numbers to account for
1586 * the negative income/amount of money etc. as well. */
1587 int max = -(999999999 - 500);
1588
1589 /* Scale max for the display currency. Prior to rendering the value
1590 * is converted into the display currency, which may cause it to
1591 * raise significantly. We need to compensate for that since {{CURRCOMPACT}}
1592 * is used, which can produce quite short renderings of very large
1593 * values. Otherwise the calculated width could be too narrow.
1594 * Note that it doesn't work if there was a currency with an exchange
1595 * rate greater than max.
1596 * When the currency rate is more than 1000, the 999 999 k becomes at
1597 * least 999 999 M which roughly is equally long. Furthermore if the
1598 * exchange rate is that high, 999 999 k is usually not enough anymore
1599 * to show the different currency numbers. */
1600 if (GetCurrency().rate < 1000) max /= GetCurrency().rate;
1601 uint score_detail_width = GetStringBoundingBox(GetString(STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY, max, max)).width;
1602
1603 size.width = WidgetDimensions::scaled.frametext.Horizontal() + score_info_width + WidgetDimensions::scaled.hsep_wide + this->bar_width + WidgetDimensions::scaled.hsep_wide + score_detail_width;
1604 uint left = WidgetDimensions::scaled.frametext.left;
1605 uint right = size.width - WidgetDimensions::scaled.frametext.right;
1606
1607 bool rtl = _current_text_dir == TD_RTL;
1608 this->score_info_left = rtl ? right - score_info_width : left;
1609 this->score_info_right = rtl ? right : left + score_info_width;
1610
1611 this->score_detail_left = rtl ? left : right - score_detail_width;
1612 this->score_detail_right = rtl ? left + score_detail_width : right;
1613
1614 this->bar_left = left + (rtl ? score_detail_width : score_info_width) + WidgetDimensions::scaled.hsep_wide;
1615 this->bar_right = this->bar_left + this->bar_width - 1;
1616 break;
1617 }
1618 }
1619
1620 void DrawWidget(const Rect &r, WidgetID widget) const override
1621 {
1622 /* No need to draw when there's nothing to draw */
1623 if (this->company == CompanyID::Invalid()) return;
1624
1626 if (this->IsWidgetDisabled(widget)) return;
1627 CompanyID cid = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1629 DrawCompanyIcon(cid, CentreBounds(r.left, r.right, sprite_size.width), CentreBounds(r.top, r.bottom, sprite_size.height));
1630 return;
1631 }
1632
1633 if (!IsInsideMM(widget, WID_PRD_SCORE_FIRST, WID_PRD_SCORE_LAST + 1)) return;
1634
1635 ScoreID score_type = (ScoreID)(widget - WID_PRD_SCORE_FIRST);
1636
1637 /* The colours used to show how the progress is going */
1640
1641 /* Draw all the score parts */
1642 int64_t val = _score_part[company][score_type];
1643 int64_t needed = _score_info[score_type].needed;
1644 int score = _score_info[score_type].score;
1645
1646 /* ScoreID::Total has its own rules ;) */
1647 if (score_type == ScoreID::Total) {
1648 for (ScoreID i : EnumRange(ScoreID::End)) score += _score_info[i].score;
1649 needed = SCORE_MAX;
1650 }
1651
1652 uint bar_top = CentreBounds(r.top, r.bottom, this->bar_height);
1653 uint text_top = CentreBounds(r.top, r.bottom, GetCharacterHeight(FontSize::Normal));
1654
1655 DrawString(this->score_info_left, this->score_info_right, text_top, STR_PERFORMANCE_DETAIL_VEHICLES + to_underlying(score_type));
1656
1657 /* Draw the score */
1658 DrawString(this->score_info_left, this->score_info_right, text_top, GetString(STR_JUST_COMMA, score), TextColour::Black, AlignmentH::End);
1659
1660 /* Calculate the %-bar */
1661 uint x = Clamp<int64_t>(val, 0, needed) * this->bar_width / needed;
1662 bool rtl = _current_text_dir == TD_RTL;
1663 if (rtl) {
1664 x = this->bar_right - x;
1665 } else {
1666 x = this->bar_left + x;
1667 }
1668
1669 /* Draw the bar */
1670 if (x != this->bar_left) GfxFillRect(this->bar_left, bar_top, x, bar_top + this->bar_height - 1, rtl ? colour_notdone : colour_done);
1671 if (x != this->bar_right) GfxFillRect(x, bar_top, this->bar_right, bar_top + this->bar_height - 1, rtl ? colour_done : colour_notdone);
1672
1673 /* Draw it */
1674 DrawString(this->bar_left, this->bar_right, text_top, GetString(STR_PERFORMANCE_DETAIL_PERCENT, Clamp<int64_t>(val, 0, needed) * 100 / needed), TextColour::FromString, AlignmentH::Centre);
1675
1676 /* ScoreID::Loan is inverted */
1677 if (score_type == ScoreID::Loan) val = needed - val;
1678
1679 /* Draw the amount we have against what is needed
1680 * For some of them it is in currency format */
1681 switch (score_type) {
1682 case ScoreID::MinProfit:
1683 case ScoreID::MinIncome:
1684 case ScoreID::MaxIncome:
1685 case ScoreID::Money:
1686 case ScoreID::Loan:
1687 DrawString(this->score_detail_left, this->score_detail_right, text_top, GetString(STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY, val, needed));
1688 break;
1689 default:
1690 DrawString(this->score_detail_left, this->score_detail_right, text_top, GetString(STR_PERFORMANCE_DETAIL_AMOUNT_INT, val, needed));
1691 break;
1692 }
1693 }
1694
1695 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1696 {
1697 /* Check which button is clicked */
1699 /* Is it no on disable? */
1700 if (!this->IsWidgetDisabled(widget)) {
1701 this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company);
1702 this->company = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1703 this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company);
1704 this->SetDirty();
1705 }
1706 }
1707 }
1708
1709 void OnGameTick() override
1710 {
1711 /* Update the company score every 5 days */
1712 if (--this->timeout == 0) {
1713 this->UpdateCompanyStats();
1714 this->SetDirty();
1715 }
1716 }
1717
1723 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1724 {
1725 if (!gui_scope) return;
1726 /* Disable the companies who are not active */
1727 for (CompanyID i = CompanyID::Begin(); i < MAX_COMPANIES; ++i) {
1729 }
1730
1731 /* Check if the currently selected company is still active. */
1732 if (this->company != CompanyID::Invalid() && !Company::IsValidID(this->company)) {
1733 /* Raise the widget for the previous selection. */
1734 this->RaiseWidget(WID_PRD_COMPANY_FIRST + this->company);
1735 this->company = CompanyID::Invalid();
1736 }
1737
1738 if (this->company == CompanyID::Invalid()) {
1739 for (const Company *c : Company::Iterate()) {
1740 this->company = c->index;
1741 break;
1742 }
1743 }
1744
1745 /* Make sure the widget is lowered */
1746 if (this->company != CompanyID::Invalid()) {
1747 this->LowerWidget(WID_PRD_COMPANY_FIRST + this->company);
1748 }
1749 }
1750};
1751
1752CompanyID PerformanceRatingDetailWindow::company = CompanyID::Invalid();
1753
1754/*******************************/
1755/* INDUSTRY PRODUCTION HISTORY */
1756/*******************************/
1757
1758struct IndustryProductionGraphWindow : BaseCargoGraphWindow {
1759 static constexpr GraphRange RANGE_LABELS[] = {
1760 {STR_GRAPH_INDUSTRY_RANGE_PRODUCED, STR_GRAPH_INDUSTRY_RANGE_PRODUCED_TOOLTIP},
1761 {STR_GRAPH_INDUSTRY_RANGE_TRANSPORTED, STR_GRAPH_INDUSTRY_RANGE_TRANSPORTED_TOOLTIP},
1762 {STR_GRAPH_INDUSTRY_RANGE_DELIVERED, STR_GRAPH_INDUSTRY_RANGE_DELIVERED_TOOLTIP},
1763 {STR_GRAPH_INDUSTRY_RANGE_WAITING, STR_GRAPH_INDUSTRY_RANGE_WAITING_TOOLTIP},
1764 };
1765
1766 static inline CargoTypes excluded_cargo_types{};
1767
1768 IndustryProductionGraphWindow(WindowDesc &desc, WindowNumber window_number) :
1769 BaseCargoGraphWindow(desc, STR_JUST_COMMA)
1770 {
1771 this->num_on_x_axis = GRAPH_NUM_MONTHS;
1772 this->num_vert_lines = GRAPH_NUM_MONTHS;
1773 this->month_increment = 1;
1774 this->x_values_increment = ECONOMY_MONTH_MINUTES;
1775 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
1776 this->ranges = RANGE_LABELS;
1777
1779 if (!i->IsCargoProduced()) this->masked_range = (1U << 0) | (1U << 1);
1780 if (!i->IsCargoAccepted()) this->masked_range = (1U << 2) | (1U << 3);
1781
1782 this->InitializeWindow(window_number);
1783 }
1784
1785 void OnInit() override
1786 {
1788
1789 this->scales = TimerGameEconomy::UsingWallclockUnits() ? MONTHLY_SCALE_WALLCLOCK : MONTHLY_SCALE_CALENDAR;
1790 }
1791
1793 {
1796 for (const auto &a : i->accepted) {
1797 if (IsValidCargoType(a.cargo)) cargo_types.Set(a.cargo);
1798 }
1799 for (const auto &p : i->produced) {
1800 if (IsValidCargoType(p.cargo)) cargo_types.Set(p.cargo);
1801 }
1802 return cargo_types;
1803 }
1804
1806 {
1807 return IndustryProductionGraphWindow::excluded_cargo_types;
1808 }
1809
1810 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
1811 {
1812 if (widget == WID_GRAPH_CAPTION) return GetString(STR_GRAPH_INDUSTRY_CAPTION, this->window_number);
1813
1814 return this->Window::GetWidgetString(widget, stringid);
1815 }
1816
1817 void UpdateStatistics(bool initialize) override
1818 {
1819 int mo = (TimerGameEconomy::month / this->month_increment - this->num_vert_lines) * this->month_increment;
1820 auto yr = TimerGameEconomy::year;
1821 while (mo < 0) {
1822 yr--;
1823 mo += 12;
1824 }
1825
1826 if (!initialize && this->excluded_data == this->GetExcludedCargoTypes().base() && this->num_on_x_axis == this->num_vert_lines && this->year == yr && this->month == mo) {
1827 /* There's no reason to get new stats */
1828 return;
1829 }
1830
1831 this->excluded_data = this->GetExcludedCargoTypes().base();
1832 this->year = yr;
1833 this->month = mo;
1834
1835 const Industry *i = Industry::Get(this->window_number);
1836
1837 this->data.clear();
1838 this->data.reserve(
1839 2 * std::ranges::count_if(i->produced, &IsValidCargoType, &Industry::ProducedCargo::cargo) +
1840 2 * std::ranges::count_if(i->accepted, &IsValidCargoType, &Industry::AcceptedCargo::cargo));
1841
1842 for (const auto &p : i->produced) {
1843 if (!IsValidCargoType(p.cargo)) continue;
1844 const CargoSpec *cs = CargoSpec::Get(p.cargo);
1845
1846 DataSet &produced = this->data.emplace_back();
1847 produced.colour = cs->legend_colour;
1848 produced.exclude_bit = cs->Index();
1849 produced.range_bit = 0;
1850
1851 DataSet &transported = this->data.emplace_back();
1852 transported.colour = cs->legend_colour;
1853 transported.exclude_bit = cs->Index();
1854 transported.range_bit = 1;
1855 transported.dash = 2;
1856
1857 FillFromHistory<GRAPH_NUM_MONTHS>(p.history, i->valid_history, *this->scales[this->selected_scale].history_range,
1860 }
1861
1862 for (const auto &a : i->accepted) {
1863 if (!IsValidCargoType(a.cargo)) continue;
1864 const CargoSpec *cs = CargoSpec::Get(a.cargo);
1865
1866 DataSet &accepted = this->data.emplace_back();
1867 accepted.colour = cs->legend_colour;
1868 accepted.exclude_bit = cs->Index();
1869 accepted.range_bit = 2;
1870 accepted.dash = 1;
1871
1872 DataSet &waiting = this->data.emplace_back();
1873 waiting.colour = cs->legend_colour;
1874 waiting.exclude_bit = cs->Index();
1875 waiting.range_bit = 3;
1876 waiting.dash = 4;
1877
1878 FillFromHistory<GRAPH_NUM_MONTHS>(a.history.get(), i->valid_history, *this->scales[this->selected_scale].history_range,
1879 Filler{{accepted}, &Industry::AcceptedHistory::accepted},
1881 }
1882
1883 this->SetDirty();
1884 }
1885};
1886
1887static constexpr std::initializer_list<NWidgetPart> _nested_industry_production_widgets = {
1894 EndContainer(),
1899 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1902 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_ENABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1903 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_DISABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1906 NWidget(WWT_MATRIX, Colours::Brown, WID_GRAPH_MATRIX), SetFill(1, 0), SetResize(0, 2), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO), SetScrollbar(WID_GRAPH_MATRIX_SCROLLBAR),
1908 EndContainer(),
1910 NWidget(WWT_MATRIX, Colours::Brown, WID_GRAPH_SCALE_MATRIX), SetFill(1, 0), SetResize(0, 0), SetMatrixDataTip(1, 0, STR_GRAPH_SELECT_SCALE),
1911 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
1912 EndContainer(),
1913 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1914 EndContainer(),
1918 EndContainer(),
1919 EndContainer(),
1920};
1921
1924 WindowPosition::Automatic, "graph_industry_production", 0, 0,
1925 WindowClass::IndustryProductionGraph, WindowClass::IndustryView,
1926 {},
1927 _nested_industry_production_widgets
1928);
1929
1930void ShowIndustryProductionGraph(WindowNumber window_number)
1931{
1933}
1934
1935struct TownCargoGraphWindow : BaseCargoGraphWindow {
1936 static constexpr GraphRange RANGE_LABELS[] = {
1937 {STR_GRAPH_TOWN_RANGE_PRODUCED, STR_GRAPH_TOWN_RANGE_PRODUCED_TOOLTIP},
1938 {STR_GRAPH_TOWN_RANGE_TRANSPORTED, STR_GRAPH_TOWN_RANGE_TRANSPORTED_TOOLTIP},
1939 {STR_GRAPH_TOWN_RANGE_DELIVERED, STR_GRAPH_TOWN_RANGE_DELIVERED_TOOLTIP},
1940 };
1941
1942 static inline CargoTypes excluded_cargo_types{};
1943
1944 TownCargoGraphWindow(WindowDesc &desc, WindowNumber window_number) : BaseCargoGraphWindow(desc, STR_JUST_COMMA)
1945 {
1946 this->num_on_x_axis = GRAPH_NUM_MONTHS;
1947 this->num_vert_lines = GRAPH_NUM_MONTHS;
1948 this->month_increment = 1;
1949 this->x_values_increment = ECONOMY_MONTH_MINUTES;
1950 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
1951 this->ranges = RANGE_LABELS;
1952
1953 this->InitializeWindow(window_number);
1954 }
1955
1956 void OnInit() override
1957 {
1959
1960 this->scales = TimerGameEconomy::UsingWallclockUnits() ? MONTHLY_SCALE_WALLCLOCK : MONTHLY_SCALE_CALENDAR;
1961 }
1962
1964 {
1966 const Town *t = Town::Get(window_number);
1967 for (const auto &s : t->supplied) {
1968 if (IsValidCargoType(s.cargo)) cargo_types.Set(s.cargo);
1969 }
1970 for (const auto &a : t->accepted) {
1971 if (IsValidCargoType(a.cargo)) cargo_types.Set(a.cargo);
1972 }
1973 return cargo_types;
1974 }
1975
1977 {
1978 return TownCargoGraphWindow::excluded_cargo_types;
1979 }
1980
1981 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
1982 {
1983 if (widget == WID_GRAPH_CAPTION) return GetString(STR_GRAPH_TOWN_CARGO_CAPTION, this->window_number);
1984
1985 return this->Window::GetWidgetString(widget, stringid);
1986 }
1987
1988 void UpdateStatistics(bool initialize) override
1989 {
1990 int mo = (TimerGameEconomy::month / this->month_increment - this->num_vert_lines) * this->month_increment;
1991 auto yr = TimerGameEconomy::year;
1992 while (mo < 0) {
1993 yr--;
1994 mo += 12;
1995 }
1996
1997 if (!initialize && this->excluded_data == this->GetExcludedCargoTypes().base() && this->num_on_x_axis == this->num_vert_lines && this->year == yr && this->month == mo) {
1998 /* There's no reason to get new stats */
1999 return;
2000 }
2001
2002 this->excluded_data = this->GetExcludedCargoTypes().base();
2003 this->year = yr;
2004 this->month = mo;
2005
2006 const Town *t = Town::Get(this->window_number);
2007
2008 this->data.clear();
2009 this->data.reserve(
2010 2 * std::ranges::count_if(t->supplied, &IsValidCargoType, &Town::SuppliedCargo::cargo) +
2011 1 * std::ranges::count_if(t->accepted, &IsValidCargoType, &Town::AcceptedCargo::cargo));
2012
2013 for (const auto &s : t->supplied) {
2014 if (!IsValidCargoType(s.cargo)) continue;
2015 const CargoSpec *cs = CargoSpec::Get(s.cargo);
2016
2017 DataSet &produced = this->data.emplace_back();
2018 produced.colour = cs->legend_colour;
2019 produced.exclude_bit = cs->Index();
2020 produced.range_bit = 0;
2021
2022 DataSet &transported = this->data.emplace_back();
2023 transported.colour = cs->legend_colour;
2024 transported.exclude_bit = cs->Index();
2025 transported.range_bit = 1;
2026 transported.dash = 2;
2027
2028 FillFromHistory<GRAPH_NUM_MONTHS>(s.history, t->valid_history, *this->scales[this->selected_scale].history_range,
2031 }
2032
2033 for (const auto &a : t->accepted) {
2034 if (!IsValidCargoType(a.cargo)) continue;
2035 const CargoSpec *cs = CargoSpec::Get(a.cargo);
2036
2037 DataSet &accepted = this->data.emplace_back();
2038 accepted.colour = cs->legend_colour;
2039 accepted.exclude_bit = cs->Index();
2040 accepted.range_bit = 2;
2041 accepted.dash = 1;
2042
2043 FillFromHistory<GRAPH_NUM_MONTHS>(a.history, t->valid_history, *this->scales[this->selected_scale].history_range,
2044 Filler{{accepted}, &Town::AcceptedHistory::accepted});
2045 }
2046
2047 this->SetDirty();
2048 }
2049};
2050
2051static constexpr std::initializer_list<NWidgetPart> _nested_town_cargo_graph_widgets = {
2058 EndContainer(),
2063 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
2066 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_ENABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
2067 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_DISABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
2070 NWidget(WWT_MATRIX, Colours::Brown, WID_GRAPH_MATRIX), SetFill(1, 0), SetResize(0, 2), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO), SetScrollbar(WID_GRAPH_MATRIX_SCROLLBAR),
2072 EndContainer(),
2074 NWidget(WWT_MATRIX, Colours::Brown, WID_GRAPH_SCALE_MATRIX), SetFill(1, 0), SetResize(0, 0), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO),
2075 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
2076 EndContainer(),
2077 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
2078 EndContainer(),
2082 EndContainer(),
2083 EndContainer(),
2084};
2085
2088 WindowPosition::Automatic, "graph_town_cargo", 0, 0,
2089 WindowClass::TownCargoGraph, WindowClass::TownView,
2090 {},
2091 _nested_town_cargo_graph_widgets
2092);
2093
2094void ShowTownCargoGraph(WindowNumber window_number)
2095{
2097}
2098
2100struct StationGraphWindow : BaseCargoGraphWindow {
2102 static inline constexpr GraphRange RANGE_LABELS[] = {
2103 {STR_GRAPH_STATION_RANGE_ACCEPTED, STR_GRAPH_STATION_RANGE_ACCEPTED_TOOLTIP},
2104 {STR_GRAPH_STATION_RANGE_WAITING, STR_GRAPH_STATION_RANGE_WAITING_TOOLTIP},
2105 {STR_GRAPH_STATION_RANGE_SUPPLY, STR_GRAPH_STATION_RANGE_SUPPLY_TOOLTIP},
2106 {STR_GRAPH_STATION_RANGE_LOST, STR_GRAPH_STATION_RANGE_LOST_TOOLTIP},
2107 };
2108
2111
2118 BaseCargoGraphWindow(desc, STR_JUST_COMMA)
2119 {
2120 this->num_on_x_axis = GRAPH_NUM_MONTHS;
2121 this->num_vert_lines = GRAPH_NUM_MONTHS;
2122 this->month_increment = 1;
2123 this->x_values_reversed = true;
2124 this->x_values_increment = ECONOMY_MONTH_MINUTES;
2125 this->draw_dates = !TimerGameEconomy::UsingWallclockUnits();
2126 this->ranges = RANGE_LABELS;
2127
2128 this->InitializeWindow(window_number, STR_GRAPH_LAST_24_MINUTES_TIME_LABEL);
2129 }
2130
2131 void OnInit() override
2132 {
2134
2135 this->scales = TimerGameEconomy::UsingWallclockUnits() ? MONTHLY_SCALE_WALLCLOCK : MONTHLY_SCALE_CALENDAR;
2136 }
2137
2139 {
2141 const Station *st = Station::Get(window_number);
2142 for (CargoType cargo_type : _cargo_mask) {
2143 if (st->goods[cargo_type].HasRating() || st->goods[cargo_type].HasHistory()) cargo_types.Set(cargo_type);
2144 }
2145 return cargo_types;
2146 }
2147
2152
2153 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
2154 {
2155 if (widget == WID_GRAPH_CAPTION) return GetString(STR_GRAPH_STATION_CAPTION, this->window_number);
2156
2157 return this->Window::GetWidgetString(widget, stringid);
2158 }
2159
2160 void UpdateStatistics(bool initialize) override
2161 {
2162 int mo = TimerGameEconomy::month - this->num_vert_lines;
2163 auto yr = TimerGameEconomy::year;
2164 while (mo < 0) {
2165 yr--;
2166 mo += 12;
2167 }
2168
2169 if (!initialize && this->excluded_data == this->GetExcludedCargoTypes().base() && this->num_on_x_axis == this->num_vert_lines && this->year == yr && this->month == mo) {
2170 /* There's no reason to get new stats */
2171 return;
2172 }
2173
2174 this->excluded_data = this->GetExcludedCargoTypes().base();
2175 this->year = yr;
2176 this->month = mo;
2177
2178 const Station *st = Station::Get(this->window_number);
2179
2180 /* Reserve space for the 4 series of data for each cargo type. */
2181 this->data.clear();
2182 this->data.reserve(4 * std::ranges::count_if(st->goods, &GoodsEntry::HasHistory));
2183
2184 for (CargoType cargo_type : this->cargo_types) {
2185 const GoodsEntry &ge = st->goods[cargo_type];
2186 if (!ge.HasHistory()) continue;
2187
2188 const CargoSpec *cs = CargoSpec::Get(cargo_type);
2189
2190 DataSet &accepted = this->data.emplace_back();
2191 accepted.colour = cs->legend_colour;
2192 accepted.exclude_bit = cs->Index();
2193 accepted.range_bit = 0;
2194
2195 DataSet &waiting = this->data.emplace_back();
2196 waiting.colour = cs->legend_colour;
2197 waiting.exclude_bit = cs->Index();
2198 waiting.range_bit = 1;
2199 waiting.dash = 1;
2200
2201 DataSet &supply = this->data.emplace_back();
2202 supply.colour = cs->legend_colour;
2203 supply.exclude_bit = cs->Index();
2204 supply.range_bit = 2;
2205 supply.dash = 2;
2206
2207 DataSet &lost = this->data.emplace_back();
2208 lost.colour = cs->legend_colour;
2209 lost.exclude_bit = cs->Index();
2210 lost.range_bit = 3;
2211 lost.dash = 3;
2212
2213 FillFromHistory<GRAPH_NUM_MONTHS>(ge.GetHistory().history, st->valid_cargo_history, *this->scales[this->selected_scale].history_range,
2218 }
2219
2220 this->SetDirty();
2221 }
2222};
2223
2232 EndContainer(),
2237 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
2238 NWidget(WWT_MATRIX, Colours::Brown, WID_GRAPH_RANGE_MATRIX), SetFill(1, 0), SetResize(0, 0), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO),
2240 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_ENABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
2241 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_GRAPH_DISABLE_CARGOES), SetStringTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
2244 NWidget(WWT_MATRIX, Colours::Brown, WID_GRAPH_MATRIX), SetFill(1, 0), SetResize(0, 2), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO), SetScrollbar(WID_GRAPH_MATRIX_SCROLLBAR),
2246 EndContainer(),
2248 NWidget(WWT_MATRIX, Colours::Brown, WID_GRAPH_SCALE_MATRIX), SetFill(1, 0), SetResize(0, 0), SetMatrixDataTip(1, 0, STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO),
2249 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
2250 EndContainer(),
2251 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
2252 EndContainer(),
2256 EndContainer(),
2257 EndContainer(),
2258};
2259
2262 WindowPosition::Automatic, "graph_station", 0, 0,
2263 WindowClass::StationCargoGraph, WindowClass::StationView,
2264 {},
2266);
2267
2276
2281static std::unique_ptr<NWidgetBase> MakePerformanceDetailPanels()
2282{
2283 auto realtime = TimerGameEconomy::UsingWallclockUnits();
2284 const StringID performance_tips[] = {
2285 realtime ? STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP_PERIODS : STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP_YEARS,
2286 STR_PERFORMANCE_DETAIL_STATIONS_TOOLTIP,
2287 realtime ? STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP_PERIODS : STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP_YEARS,
2288 STR_PERFORMANCE_DETAIL_MIN_INCOME_TOOLTIP,
2289 STR_PERFORMANCE_DETAIL_MAX_INCOME_TOOLTIP,
2290 STR_PERFORMANCE_DETAIL_DELIVERED_TOOLTIP,
2291 STR_PERFORMANCE_DETAIL_CARGO_TOOLTIP,
2292 STR_PERFORMANCE_DETAIL_MONEY_TOOLTIP,
2293 STR_PERFORMANCE_DETAIL_LOAN_TOOLTIP,
2294 STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP,
2295 };
2296
2297 static_assert(lengthof(performance_tips) == to_underlying(ScoreID::End));
2298
2299 auto vert = std::make_unique<NWidgetVertical>(NWidContainerFlag::EqualSize);
2300 for (WidgetID widnum = WID_PRD_SCORE_FIRST; widnum <= WID_PRD_SCORE_LAST; widnum++) {
2301 auto panel = std::make_unique<NWidgetBackground>(WWT_PANEL, Colours::Brown, widnum);
2302 panel->SetFill(1, 1);
2303 panel->SetToolTip(performance_tips[widnum - WID_PRD_SCORE_FIRST]);
2304 vert->Add(std::move(panel));
2305 }
2306 return vert;
2307}
2308
2310std::unique_ptr<NWidgetBase> MakeCompanyButtonRowsGraphGUI()
2311{
2312 return MakeCompanyButtonRows(WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST, Colours::Brown, 8, STR_PERFORMANCE_DETAIL_SELECT_COMPANY_TOOLTIP);
2313}
2314
2315static constexpr std::initializer_list<NWidgetPart> _nested_performance_rating_detail_widgets = {
2318 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_PERFORMANCE_DETAIL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2321 EndContainer(),
2324 EndContainer(),
2326};
2327
2330 WindowPosition::Automatic, "league_details", 0, 0,
2331 WindowClass::PerformanceDetail, WindowClass::None,
2332 {},
2333 _nested_performance_rating_detail_widgets
2334);
2335
2336void ShowPerformanceRatingDetail()
2337{
2339}
2340
2341void InitializeGraphGui()
2342{
2344 PaymentRatesGraphWindow::excluded_cargo_types = {};
2345 IndustryProductionGraphWindow::excluded_cargo_types = {};
2346}
constexpr uint8_t FindLastBit(T x)
Search the last set bit in a value.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T ToggleBit(T &x, const uint8_t y)
Toggles a bit in a variable.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
static constexpr CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:77
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
std::span< const CargoSpec * > _sorted_standard_cargo_specs
Standard cargo specifications sorted alphabetically by name.
CargoTypes _standard_cargo_mask
Bitmask of real cargo types available.
Definition cargotype.cpp:35
std::vector< const CargoSpec * > _sorted_cargo_specs
Cargo specifications sorted alphabetically by name.
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition cargotype.cpp:30
Types/functions related to cargoes.
uint Count() const
Count the number of set bits.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr Timpl & Flip()
Flip all bits.
constexpr Timpl & Set()
Set all bits.
void UpdateStatistics(bool initialize) override
Update the statistics.
virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)=0
Get the data to show in the graph for a given company at a location along the X-axis.
Iterate a range of enum values.
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.
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:2474
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:2548
size_type GetCount() const
Gets the number of elements in the list.
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.
StrongType::Typedef< int32_t, struct YearTag< struct Economy >, StrongType::Compare, StrongType::Integer > Year
RectPadding framerect
Standard padding inside many panels.
Definition window_gui.h:41
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
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.
Functions to handle different currencies.
const CurrencySpec & GetCurrency()
Get the currently selected currency.
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:190
const EnumIndexArray< ScoreInfo, ScoreID, ScoreID::End > _score_info
Score info, values used for computing the detailed performance rating.
Definition economy.cpp:79
Functions related to the economy.
ScoreID
Score categories in the detailed performance rating.
@ MinIncome
Income in the quarter with the lowest profit of the last 12 quarters.
@ End
Score ID end marker.
@ Total
Total points out of possible points ,must always be the last entry.
@ Loan
The amount of money company can take as a loan.
@ MaxIncome
Income in the quarter with the highest profit of the last 12 quarters.
@ MinProfit
The profit of the vehicle with the lowest income.
@ Money
Amount of money company has in the bank.
static constexpr int SCORE_MAX
The max score that can be in the performance history.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
@ ForceRight
Force align to the right.
@ Centre
Align to the centre.
@ End
Align to the end, LTR/RTL aware.
@ Start
Align to the start, LTR/RTL aware.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
@ Middle
Align to the middle.
bool DrawStringMultiLineWithClipping(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw a multiline string, possibly over multiple lines, if the region is within the current display cl...
Definition gfx.cpp:867
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:966
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:111
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
Functions related to the gfx engine.
@ Small
Index of the small font in the font tables.
Definition gfx_type.h:250
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Green
Green.
Definition gfx_type.h:291
@ Brown
Brown.
Definition gfx_type.h:298
@ Red
Red.
Definition gfx_type.h:289
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:315
@ White
White colour.
Definition gfx_type.h:330
@ FromString
Marker for telling to use the colour from the string.
Definition gfx_type.h:317
@ Black
Black colour.
Definition gfx_type.h:334
@ Checker
Draw only every second pixel, used for greying-out.
Definition gfx_type.h:393
static WindowDesc _station_graph_desc(WindowPosition::Automatic, "graph_station", 0, 0, WindowClass::StationCargoGraph, WindowClass::StationView, {}, _nested_station_graph_widgets)
Window definition for the station graph window.
static WindowDesc _operating_profit_desc(WindowPosition::Automatic, "graph_operating_profit", 0, 0, WindowClass::OperatingProfitGraph, WindowClass::None, {}, _nested_operating_profit_widgets)
Window definition for the operating profit graph window.
static WindowDesc _graph_legend_desc(WindowPosition::Automatic, "graph_legend", 0, 0, WindowClass::GraphLegend, WindowClass::None, {}, _nested_graph_legend_widgets)
Window definition for the graph legend window.
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:47
static std::unique_ptr< NWidgetBase > MakeNWidgetCompanyLines()
Construct a vertical list of buttons, one for each company.
void ShowStationGraph(WindowNumber window_number)
Create a station graph window for a station.
static CompanyMask _legend_excluded_companies
Bitmasks of company and cargo indices that shouldn't be drawn.
Definition graph_gui.cpp:41
std::unique_ptr< NWidgetBase > MakeCompanyButtonRowsGraphGUI()
Make a number of rows with buttons for each company for the performance rating detail window.
static WindowDesc _industry_production_desc(WindowPosition::Automatic, "graph_industry_production", 0, 0, WindowClass::IndustryProductionGraph, WindowClass::IndustryView, {}, _nested_industry_production_widgets)
Window definition for the industry production graph window.
static WindowDesc _performance_history_desc(WindowPosition::Automatic, "graph_performance", 0, 0, WindowClass::PerformanceGraph, WindowClass::None, {}, _nested_performance_history_widgets)
Window definition for the performance history graph window.
static WindowDesc _town_cargo_graph_desc(WindowPosition::Automatic, "graph_town_cargo", 0, 0, WindowClass::TownCargoGraph, WindowClass::TownView, {}, _nested_town_cargo_graph_widgets)
Window definition for the town cargo graph window.
static WindowDesc _delivered_cargo_graph_desc(WindowPosition::Automatic, "graph_delivered_cargo", 0, 0, WindowClass::DeliveredCargoGraph, WindowClass::None, {}, _nested_delivered_cargo_graph_widgets)
Window definition for the delivered cargo graph window.
static WindowDesc _cargo_payment_rates_desc(WindowPosition::Automatic, "graph_cargo_payment_rates", 0, 0, WindowClass::CargoPaymentRatesGraph, WindowClass::None, {}, _nested_cargo_payment_rates_widgets)
Window definition for the cargo payment rates graph window.
static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX)
Value used for a datapoint that shouldn't be drawn.
static const uint INVALID_DATAPOINT_POS
Used to determine if the previous point was drawn.
Definition graph_gui.cpp:45
static std::unique_ptr< NWidgetBase > MakePerformanceDetailPanels()
Make a vertical list of panels for outputting score details.
static constexpr NWidgetPart _nested_station_graph_widgets[]
Widgets of the station graph window.
static WindowDesc _performance_rating_detail_desc(WindowPosition::Automatic, "league_details", 0, 0, WindowClass::PerformanceDetail, WindowClass::None, {}, _nested_performance_rating_detail_widgets)
Window definition for the performance rating details window.
static WindowDesc _income_graph_desc(WindowPosition::Automatic, "graph_income", 0, 0, WindowClass::IncomeGraph, WindowClass::None, {}, _nested_income_graph_widgets)
Window definition for the income graph window.
static WindowDesc _company_value_graph_desc(WindowPosition::Automatic, "graph_company_value", 0, 0, WindowClass::CompanyValueGraph, WindowClass::None, {}, _nested_company_value_graph_widgets)
Window definition for the company value graph window.
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_SCALE_MATRIX
Horizontal axis scale list.
@ 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 SetResizeWidgetTypeTip(ResizeWidgetType widget_type, StringID tip)
Widget part function for setting the resize widget type and tooltip.
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 EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart SetTextStyle(TextColour colour, FontSize size=FontSize::Normal)
Widget part function for setting the text style.
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetAlignment(Alignment align)
Widget part function for setting the alignment of text/images.
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:1013
Functions for storing historical data.
uint32_t RxDecompress(uint16_t num)
Decompress a range-compressed integer.
void FillFromHistory(const HistoryData< T > &history, ValidHistoryMask valid_history, const HistoryRange &hr, Tfillers &&... fillers)
Fill some data with historical data.
Base of all industries.
#define Point
Macro that prevents name conflicts between included headers.
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
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
void GuiShowTooltips(Window *parent, EncodedString &&text, TooltipCloseCondition close_tooltip)
Shows a tooltip.
Definition misc_gui.cpp:690
OverflowSafeInt< int64_t > OverflowSafeInt64
A 64-bit overflow safe type.
PixelColour GetColourGradient(Colours colour, Shade shade)
Get colour gradient palette index.
Definition palette.cpp:393
@ Darker
Darker colour shade.
@ Lighter
Lighter colour shade.
@ Normal
Normal colour shade.
constexpr PixelColour GREY_SCALE(uint8_t level)
Return the colour for a particular greyscale level.
static constexpr PixelColour PC_BLACK
Black palette colour.
static constexpr PixelColour PC_WHITE
White palette colour.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
void SndClickBeep()
Play a beep sound for a click event if enabled in settings.
Definition sound.cpp:252
Functions related to sound.
This file contains all sprite-related enums and defines.
static const SpriteID SPR_COMPANY_ICON
Icon showing company colour.
Definition sprites.h:386
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:261
uint64_t GetParamMaxValue(uint64_t max_value, uint min_count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:235
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
uint legend_width
Width of legend 'blob'.
virtual CargoTypes & GetExcludedCargoTypes() const =0
Get a reference to the cargo types that should not be shown.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnInit() override
Notification that the nested widget tree gets initialized.
std::optional< uint8_t > GetDatasetIndex(int y) override
Get the dataset associated with a given Y-location within WID_GRAPH_MATRIX.
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.
virtual CargoTypes GetCargoTypes(WindowNumber number) const =0
Get the CargoTypes to show in this window.
const IntervalTimer< TimerGameCalendar > update_cargo_types_interval
Timer to periodically refresh the available cargo types.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
CargoTypes cargo_types
Cargo types that can be selected.
void OnResize() override
Called after the window got resized.
Scrollbar * vscroll
Cargo list scrollbar.
uint line_height
Pixel height of each cargo type row.
DataSet & dataset
Dataset to fill.
Tprojection proj
Projection to apply.
Label and tooltip for a graph range.
StringID label
Label for this range.
StringID tooltip
Tooltip for this range.
Fill graph dataset with transformed data.
Tprojection proj
Projection to apply.
void Fill(uint i, const auto &data) const
Fill graph dataset with transform data.
Ttransformer transformer
Transformer to apply.
uint GetYLabelWidth(ValuesInterval current_interval, int num_hori_lines) const
Get width for Y labels.
TimerGameEconomy::Year year
The starting year that values are plotted against.
bool OnTooltip(Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
Event to display a custom tooltip.
void OnGameTick() override
Called once per (game) tick.
virtual void UpdateStatistics(bool initialize)=0
Update the statistics.
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.
static const int GRAPH_PAYMENT_RATE_STEPS
Number of steps on Payment rate graph.
void OnMouseOver(Point pt, WidgetID widget) override
The mouse is currently moving over the window or has just moved outside of the window.
std::span< const OverflowSafeInt64 > GetDataSetRange(const DataSet &dataset) const
Get appropriate part of dataset values for the current number of horizontal points.
TimerGameEconomy::Month month
The starting month that values are plotted against.
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 datasets hidden by the player.
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 hidden by the player.
uint8_t highlight_range
Data range that should be highlighted, or UINT8_MAX for none.
bool highlight_state
Current state of highlight, toggled every TIMER_BLINK_INTERVAL period.
uint8_t month_increment
month increment between vertical lines. must be divisor of 12.
virtual std::optional< uint8_t > GetDatasetIndex(int y)
Get the dataset associated with a given Y-location within WID_GRAPH_MATRIX.
static const int PAYMENT_GRAPH_X_STEP_DAYS
X-axis step label for cargo payment rates "Days in transit".
static const int ECONOMY_YEAR_MINUTES
Minutes per economic year.
ValuesInterval GetValuesInterval(int num_hori_lines) const
Get the interval that contains the graph's data.
uint64_t masked_range
bitmask of ranges that are not available for the current data.
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.
bool x_values_reversed
These values are used if the graph is being plotted against values rather than the dates specified by...
int16_t x_values_increment
These values are used if the graph is being plotted against values rather than the dates specified by...
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.
uint8_t highlight_data
Data set that should be highlighted, or UINT8_MAX for none.
Specification of a cargo type.
Definition cargotype.h:76
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:110
PixelColour legend_colour
Colour in legends and graphs.
Definition cargotype.h:79
StringID name
Name of this type of cargo.
Definition cargotype.h:93
Colours colour
Company colour.
std::array< CompanyEconomyEntry, MAX_HISTORY_QUARTERS > old_economy
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
uint8_t num_valid_stat_ent
Number of valid statistical entries in old_economy.
OverflowSafeInt64 GetGraphData(const Company *c, int j) override
Get the data to show in the graph for a given company at a location along the X-axis.
T y
Y coordinate.
uint16_t rate
The conversion rate compared to the base currency.
OverflowSafeInt64 GetGraphData(const Company *c, int j) override
Get the data to show in the graph for a given company at a location along the X-axis.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
HistoryData< CargoHistory > history
Historical cargo data.
uint16_t rx_waiting
Compressed cargo waiting.
uint16_t rx_lost
Compressed cargo lost.
uint16_t rx_accepted
Compressed cargo accepted.
uint16_t rx_supply
Compressed cargo supply.
Stores station stats for a single cargo.
const CargoHistoryData & GetHistory() const
Get the cargo history data.
bool HasHistory() const
Test if cargo history is present.
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:66
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
OverflowSafeInt64 GetGraphData(const Company *c, int j) override
Get the data to show in the graph for a given company at a location along the X-axis.
void UpdateStatistics(bool initialize) override
Update the statistics.
CargoTypes GetCargoTypes(WindowNumber window_number) const override
Get the CargoTypes to show in this window.
CargoTypes & GetExcludedCargoTypes() const override
Get a reference to the cargo types that should not be shown.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnInit() override
Notification that the nested widget tree gets initialized.
CargoType cargo
Cargo type.
Definition industry.h:88
uint16_t accepted
Total accepted.
Definition industry.h:83
uint16_t waiting
Average waiting.
Definition industry.h:84
CargoType cargo
Cargo type.
Definition industry.h:76
uint16_t transported
Total transported.
Definition industry.h:67
uint16_t production
Total produced.
Definition industry.h:66
Defines the internal data of a functional industry.
Definition industry.h:64
bool IsCargoAccepted() const
Test if this industry accepts any cargo.
Definition industry.h:225
ValidHistoryMask valid_history
Mask of valid history records.
Definition industry.h:111
ProducedCargoes produced
produced cargo slots
Definition industry.h:112
AcceptedCargoes accepted
accepted cargo slots
Definition industry.h:113
bool IsCargoProduced() const
Test if this industry produces any cargo.
Definition industry.h:231
Partial widget specification to allow NWidgets to be written nested.
OverflowSafeInt64 GetGraphData(const Company *c, int j) override
Get the data to show in the graph for a given company at a location along the X-axis.
void UpdateStatistics(bool) override
Update the statistics.
void UpdatePaymentRates()
Update the payment rates according to the latest information.
CargoTypes & GetExcludedCargoTypes() const override
Get a reference to the cargo types that should not be shown.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
const IntervalTimer< TimerWindow > update_payment_interval
Update the payment rates on a regular interval.
CargoTypes GetCargoTypes(WindowNumber) const override
Get the CargoTypes to show in this window.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
OverflowSafeInt64 GetGraphData(const Company *c, int j) override
Get the data to show in the graph for a given company at a location along the X-axis.
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.
Colour for pixel/line drawing.
Definition gfx_type.h:307
static Pool::IterateWrapper< Company > Iterate(size_t from=0)
static Industry * Get(auto index)
static Company * GetIfValid(auto 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.
static Station * Get(auto index)
CargoTypes & GetExcludedCargoTypes() const override
Get a reference to the cargo types that should not be shown.
static constexpr GraphRange RANGE_LABELS[]
List of range label strings.
StationGraphWindow(WindowDesc &desc, WindowNumber window_number)
Construct this station graph window.
void OnInit() override
Notification that the nested widget tree gets initialized.
void UpdateStatistics(bool initialize) override
Update the statistics.
CargoTypes GetCargoTypes(WindowNumber window_number) const override
Get the CargoTypes to show in this window.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
static CargoTypes excluded_cargo_types
Cargo types to filter out.
Station data structure.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
ValidHistoryMask valid_cargo_history
Mask of valid cargo history records.
CargoTypes & GetExcludedCargoTypes() const override
Get a reference to the cargo types that should not be shown.
CargoTypes GetCargoTypes(WindowNumber window_number) const override
Get the CargoTypes to show in this window.
void UpdateStatistics(bool initialize) override
Update the statistics.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnInit() override
Notification that the nested widget tree gets initialized.
CargoType cargo
Cargo type of accepted cargo.
Definition town.h:117
uint32_t accepted
Total accepted.
Definition town.h:112
uint32_t transported
Total transported.
Definition town.h:93
uint32_t production
Total produced.
Definition town.h:92
Town data structure.
Definition town.h:64
SuppliedCargoes supplied
Cargo statistics about supplied cargo.
Definition town.h:131
ValidHistoryMask valid_history
Mask of valid history records.
Definition town.h:135
AcceptedCargoes accepted
Cargo statistics about accepted cargo.
Definition town.h:132
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:171
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:1855
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
void RaiseWidget(WidgetID widget_index)
Marks a widget as raised.
Definition window_gui.h:468
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
ResizeInfo resize
Resize information.
Definition window_gui.h:313
int scale
Scale of this window – used to determine how to resize.
Definition window_gui.h:303
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
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
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
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:218
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
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:1869
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
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.
static constexpr std::chrono::milliseconds TIMER_BLINK_INTERVAL
Interval used by blinking interface elements.
Base of the town class.
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
Draw frame rectangle.
Definition widget.cpp:308
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
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:3492
@ 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:39
@ 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:37
@ 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
@ EqualSize
Containers should keep all their (resizing) children equally large.
@ HideBevel
Bevel of resize box is hidden.
Definition widget_type.h:29
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:3377
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
TooltipCloseCondition
Definition window_gui.h:262
@ Lowered
If set the frame is lowered and the background colour brighter (ie. buttons when pressed).
Definition window_gui.h:26
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ Automatic
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:21
Functions related to zooming.
@ Normal
The normal zoom level.
Definition zoom_type.h:26