OpenTTD Source 20261112-master-gbcbec5e63f
industry_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 "error.h"
13#include "gui.h"
14#include "settings_gui.h"
15#include "sound_func.h"
16#include "window_func.h"
17#include "textbuf_gui.h"
18#include "command_func.h"
19#include "viewport_func.h"
20#include "industry.h"
21#include "town.h"
22#include "cargo_type.h"
23#include "cheat_type.h"
24#include "newgrf_badge_gui.h"
25#include "newgrf_industries.h"
26#include "newgrf_text.h"
27#include "newgrf_debug.h"
28#include "network/network.h"
29#include "strings_func.h"
30#include "company_func.h"
31#include "tilehighlight_func.h"
32#include "string_func.h"
33#include "sortlist_type.h"
34#include "dropdown_func.h"
35#include "company_base.h"
37#include "core/random_func.hpp"
38#include "core/backup_type.hpp"
39#include "genworld.h"
40#include "smallmap_gui.h"
41#include "dropdown_type.h"
42#include "clear_map.h"
43#include "zoom_func.h"
44#include "industry_cmd.h"
45#include "graph_gui.h"
46#include "querystring_gui.h"
47#include "stringfilter_type.h"
48#include "timer/timer.h"
49#include "timer/timer_window.h"
50#include "hotkeys.h"
52
54
55#include "table/strings.h"
56
57#include <bitset>
58
59#include "safeguards.h"
60
61bool _ignore_industry_restrictions;
62std::bitset<NUM_INDUSTRYTYPES> _displayed_industries;
63
65enum class CargoSuffixType : uint8_t {
66 Fund = 0,
67 View = 1,
69};
70
78
84
85extern void GenerateIndustries();
86static void ShowIndustryCargoesWindow(IndustryType id);
87
97static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, CargoSuffix &suffix)
98{
99 suffix.text.clear();
101
104 std::array<int32_t, 16> regs100;
105 uint16_t callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (to_underlying(cst) << 8) | cargo, const_cast<Industry *>(ind), ind_type, t, regs100);
106 if (callback == CALLBACK_FAILED) return;
107
108 if (indspec->grf_prop.grffile->grf_version < 8) {
109 if (GB(callback, 0, 8) == 0xFF) return;
110 if (callback < 0x400) {
111 suffix.text = GetGRFStringWithTextStack(indspec->grf_prop.grffile, GRFSTR_MISC_GRF_TEXT + callback, regs100);
113 return;
114 }
116 return;
117
118 } else { // GRF version 8 or higher.
119 switch (callback) {
120 case 0x400:
121 return;
122 case 0x401:
124 return;
125 case 0x40E:
127 suffix.text = GetGRFStringWithTextStack(indspec->grf_prop.grffile, static_cast<GRFStringID>(regs100[0]), std::span{regs100}.subspan(1));
128 return;
129 case 0x40F:
131 suffix.text = GetGRFStringWithTextStack(indspec->grf_prop.grffile, static_cast<GRFStringID>(regs100[0]), std::span{regs100}.subspan(1));
132 return;
133 default:
134 break;
135 }
136 if (callback < 0x400) {
137 suffix.text = GetGRFStringWithTextStack(indspec->grf_prop.grffile, GRFSTR_MISC_GRF_TEXT + callback, regs100);
139 return;
140 }
141 if (callback >= 0x800 && callback < 0xC00) {
142 suffix.text = GetGRFStringWithTextStack(indspec->grf_prop.grffile, GRFSTR_MISC_GRF_TEXT + callback - 0x800, regs100);
144 return;
145 }
147 return;
148 }
149 }
150}
151
153enum class CargoSuffixDirection : uint8_t {
154 Out = 0,
155 In = 1,
156};
157
168template <typename TC, typename TS>
169static inline void GetAllCargoSuffixes(CargoSuffixDirection use_input, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
170{
171 static_assert(std::tuple_size_v<std::remove_reference_t<decltype(cargoes)>> <= lengthof(suffixes));
172
174 /* Reworked behaviour with new many-in-many-out scheme */
175 for (uint j = 0; j < lengthof(suffixes); j++) {
176 if (IsValidCargoType(cargoes[j])) {
177 uint8_t local_id = indspec->grf_prop.grffile->cargo_map[cargoes[j]]; // should we check the value for valid?
178 uint cargotype = local_id << 16 | to_underlying(use_input);
179 GetCargoSuffix(cargotype, cst, ind, ind_type, indspec, suffixes[j]);
180 } else {
181 suffixes[j].text.clear();
182 suffixes[j].display = CargoSuffixDisplay::None;
183 }
184 }
185 } else {
186 /* Compatible behaviour with old 3-in-2-out scheme */
187 for (uint j = 0; j < lengthof(suffixes); j++) {
188 suffixes[j].text.clear();
189 suffixes[j].display = CargoSuffixDisplay::None;
190 }
191 switch (use_input) {
193 /* Handle INDUSTRY_ORIGINAL_NUM_OUTPUTS cargoes */
194 if (IsValidCargoType(cargoes[0])) GetCargoSuffix(3, cst, ind, ind_type, indspec, suffixes[0]);
195 if (IsValidCargoType(cargoes[1])) GetCargoSuffix(4, cst, ind, ind_type, indspec, suffixes[1]);
196 break;
198 /* Handle INDUSTRY_ORIGINAL_NUM_INPUTS cargoes */
199 if (IsValidCargoType(cargoes[0])) GetCargoSuffix(0, cst, ind, ind_type, indspec, suffixes[0]);
200 if (IsValidCargoType(cargoes[1])) GetCargoSuffix(1, cst, ind, ind_type, indspec, suffixes[1]);
201 if (IsValidCargoType(cargoes[2])) GetCargoSuffix(2, cst, ind, ind_type, indspec, suffixes[2]);
202 break;
203 default:
204 NOT_REACHED();
205 }
206 }
207}
208
220void GetCargoSuffix(CargoSuffixDirection use_input, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, CargoType cargo, uint8_t slot, CargoSuffix &suffix)
221{
222 suffix.text.clear();
224 if (!IsValidCargoType(cargo)) return;
226 uint8_t local_id = indspec->grf_prop.grffile->cargo_map[cargo]; // should we check the value for valid?
227 uint cargotype = local_id << 16 | to_underlying(use_input);
228 GetCargoSuffix(cargotype, cst, ind, ind_type, indspec, suffix);
229 } else if (use_input == CargoSuffixDirection::In) {
230 if (slot < INDUSTRY_ORIGINAL_NUM_INPUTS) GetCargoSuffix(slot, cst, ind, ind_type, indspec, suffix);
231 } else if (use_input == CargoSuffixDirection::Out) {
232 if (slot < INDUSTRY_ORIGINAL_NUM_OUTPUTS) GetCargoSuffix(slot + INDUSTRY_ORIGINAL_NUM_INPUTS, cst, ind, ind_type, indspec, suffix);
233 }
234}
235
236std::array<IndustryType, NUM_INDUSTRYTYPES> _sorted_industry_types;
237
239static bool IndustryTypeNameSorter(const IndustryType &a, const IndustryType &b)
240{
241 int r = StrNaturalCompare(GetString(GetIndustrySpec(a)->name), GetString(GetIndustrySpec(b)->name)); // Sort by name (natural sorting).
242
243 /* If the names are equal, sort by industry type. */
244 return (r != 0) ? r < 0 : (a < b);
245}
246
251{
252 /* Add each industry type to the list. */
253 for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
255 }
256
257 /* Sort industry types by name. */
259}
260
261static constexpr std::initializer_list<NWidgetPart> _nested_build_industry_widgets = {
264 NWidget(WWT_CAPTION, Colours::DarkGreen), SetStringTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
268 EndContainer(),
272 SetStringTip(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP),
274 SetStringTip(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES, STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_TOOLTIP),
275 EndContainer(),
276 EndContainer(),
280 EndContainer(),
282 EndContainer(),
285 SetStringTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
288 EndContainer(),
289};
290
293 WindowPosition::Automatic, "build_industry", 170, 212,
294 WindowClass::BuildIndustry, WindowClass::None,
296 _nested_build_industry_widgets
297);
298
300class BuildIndustryWindow : public Window {
301 IndustryType selected_type = IT_INVALID;
302 std::vector<IndustryType> list{};
303 bool enabled = false;
304 Scrollbar *vscroll = nullptr;
306 GUIBadgeClasses badge_classes{};
307
309 static const int MAX_MINWIDTH_LINEHEIGHTS = 20;
310
311 void UpdateAvailability()
312 {
313 this->enabled = this->selected_type != IT_INVALID && (_game_mode == GameMode::Editor || GetIndustryProbabilityCallback(this->selected_type, IndustryAvailabilityCallType::UserCreation, 1) > 0);
314 }
315
316 void SetupArrays()
317 {
318 this->list.clear();
319
320 /* Fill the arrays with industries.
321 * The tests performed after the enabled allow to load the industries
322 * In the same way they are inserted by grf (if any)
323 */
324 for (IndustryType ind : _sorted_industry_types) {
325 const IndustrySpec *indsp = GetIndustrySpec(ind);
326 if (indsp->enabled) {
327 /* Rule is that editor mode loads all industries.
328 * In game mode, all non raw industries are loaded too
329 * and raw ones are loaded only when setting allows it */
330 if (_game_mode != GameMode::Editor && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
331 /* Unselect if the industry is no longer in the list */
332 if (this->selected_type == ind) this->selected_type = IT_INVALID;
333 continue;
334 }
335
336 this->list.push_back(ind);
337 }
338 }
339
340 /* First industry type is selected if the current selection is invalid. */
341 if (this->selected_type == IT_INVALID && !this->list.empty()) this->selected_type = this->list[0];
342
343 this->UpdateAvailability();
344
345 this->vscroll->SetCount(this->list.size());
346 }
347
350 {
351 this->SetWidgetDisabledState(WID_DPI_FUND_WIDGET, this->selected_type != IT_INVALID && !this->enabled);
352 this->SetWidgetDisabledState(WID_DPI_DISPLAY_WIDGET, this->selected_type == IT_INVALID && this->enabled);
353 }
354
366 std::string MakeCargoListString(const std::span<const CargoType> cargolist, const std::span<const CargoSuffix> cargo_suffix, StringID prefixstr) const
367 {
368 assert(cargolist.size() == cargo_suffix.size());
369
370 std::string cargostring;
371 std::string_view list_separator = GetListSeparator();
372
373 for (size_t j = 0; j < cargolist.size(); j++) {
374 if (!IsValidCargoType(cargolist[j])) continue;
375
376 if (!cargostring.empty()) cargostring += list_separator;
377 auto params = MakeParameters(CargoSpec::Get(cargolist[j])->name, cargo_suffix[j].text);
378 AppendStringWithArgsInPlace(cargostring, STR_INDUSTRY_VIEW_CARGO_LIST_EXTENSION, params);
379 }
380
381 if (cargostring.empty()) AppendStringInPlace(cargostring, STR_JUST_NOTHING);
382 return GetString(prefixstr, cargostring);
383 }
384
385public:
387 {
388 this->CreateNestedTree();
389 this->vscroll = this->GetScrollbar(WID_DPI_SCROLLBAR);
390 /* Show scenario editor tools in editor. */
391 if (_game_mode != GameMode::Editor) {
393 }
394 this->FinishInitNested(0);
395
396 this->SetButtons();
397 }
398
399 void OnInit() override
400 {
401 this->badge_classes = GUIBadgeClasses{GrfSpecFeature::Industries};
402
403 /* Width of the legend blob -- slightly larger than the smallmap legend blob. */
405 this->legend.width = this->legend.height * 9 / 6;
406
407 this->SetupArrays();
408 }
409
410 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
411 {
412 switch (widget) {
415 Dimension d{};
416 for (const auto &indtype : this->list) {
417 d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(indtype)->name));
418 }
419 fill.height = resize.height = std::max<uint>({this->legend.height, d.height, count.height}) + padding.height;
420 d.width += this->badge_classes.GetTotalColumnsWidth() + this->legend.width + WidgetDimensions::scaled.hsep_wide + WidgetDimensions::scaled.hsep_normal + count.width + padding.width;
421 d.height = 5 * resize.height;
422 size = maxdim(size, d);
423 break;
424 }
425
426 case WID_DPI_INFOPANEL: {
427 /* Extra line for cost outside of editor. */
428 int height = 2 + (_game_mode == GameMode::Editor ? 0 : 1);
429 uint extra_lines_req = 0;
430 uint extra_lines_prd = 0;
431 uint extra_lines_newgrf = 0;
433 Dimension d = {0, 0};
434 for (const auto &indtype : this->list) {
435 const IndustrySpec *indsp = GetIndustrySpec(indtype);
436 CargoSuffix cargo_suffix[std::tuple_size_v<decltype(indsp->accepts_cargo)>];
437
438 /* Measure the accepted cargoes, if any. */
439 GetAllCargoSuffixes(CargoSuffixDirection::In, CargoSuffixType::Fund, nullptr, indtype, indsp, indsp->accepts_cargo, cargo_suffix);
440 std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
441 Dimension strdim = GetStringBoundingBox(cargostring);
442 if (strdim.width > max_minwidth) {
443 extra_lines_req = std::max(extra_lines_req, strdim.width / max_minwidth + 1);
444 strdim.width = max_minwidth;
445 }
446 d = maxdim(d, strdim);
447
448 /* Measure the produced cargoes, if any. */
449 GetAllCargoSuffixes(CargoSuffixDirection::Out, CargoSuffixType::Fund, nullptr, indtype, indsp, indsp->produced_cargo, cargo_suffix);
450 cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
451 strdim = GetStringBoundingBox(cargostring);
452 if (strdim.width > max_minwidth) {
453 extra_lines_prd = std::max(extra_lines_prd, strdim.width / max_minwidth + 1);
454 strdim.width = max_minwidth;
455 }
456 d = maxdim(d, strdim);
457
458 if (indsp->grf_prop.HasGrfFile()) {
459 /* Reserve a few extra lines for text from an industry NewGRF. */
460 extra_lines_newgrf = 4;
461 }
462 }
463
464 /* Set it to something more sane :) */
465 height += extra_lines_prd + extra_lines_req + extra_lines_newgrf;
466 size.height = height * GetCharacterHeight(FontSize::Normal) + padding.height;
467 size.width = d.width + padding.width;
468 break;
469 }
470
471 case WID_DPI_FUND_WIDGET: {
472 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
473 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
474 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
475 d.width += padding.width;
476 d.height += padding.height;
477 size = maxdim(size, d);
478 break;
479 }
480 }
481 }
482
483 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
484 {
485 switch (widget) {
487 /* Raw industries might be prospected. Show this fact by changing the string
488 * In Editor, you just build, while ingame, or you fund or you prospect */
489 if (_game_mode == GameMode::Editor) {
490 /* We've chosen many random industries but no industries have been specified */
491 return GetString(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
492 }
493 if (this->selected_type != IT_INVALID) {
494 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
495 return GetString((_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
496 }
497 return GetString(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
498
499 default:
500 return this->Window::GetWidgetString(widget, stringid);
501 }
502 }
503
504 void DrawWidget(const Rect &r, WidgetID widget) const override
505 {
506 switch (widget) {
508 bool rtl = _current_text_dir == TD_RTL;
509 Rect text = r.WithHeight(this->resize.step_height).Shrink(WidgetDimensions::scaled.matrix);
510 Rect icon = text.WithWidth(this->legend.width, rtl);
511 text = text.Indent(this->legend.width + WidgetDimensions::scaled.hsep_wide, rtl);
512
513 /* Vertical offset for legend icon. */
514 icon.top = r.top + (this->resize.step_height - this->legend.height + 1) / 2;
515 icon.bottom = icon.top + this->legend.height - 1;
516
517 auto badge_column_widths = badge_classes.GetColumnWidths();
518
519 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->list);
520 for (auto it = first; it != last; ++it) {
521 IndustryType type = *it;
522 bool selected = this->selected_type == type;
523 const IndustrySpec *indsp = GetIndustrySpec(type);
524
525 Rect tr = text;
526 if (badge_column_widths.size() >= 1 && badge_column_widths[0] > 0) {
527 DrawBadgeColumn(tr.WithWidth(badge_column_widths[0], rtl), 0, this->badge_classes, indsp->badges, GrfSpecFeature::Industries, std::nullopt, PAL_NONE);
528 tr = tr.Indent(badge_column_widths[0], rtl);
529 }
530 if (badge_column_widths.size() >= 2 && badge_column_widths[1] > 0) {
531 DrawBadgeColumn(tr.WithWidth(badge_column_widths[1], !rtl), 0, this->badge_classes, indsp->badges, GrfSpecFeature::Industries, std::nullopt, PAL_NONE);
532 tr = tr.Indent(badge_column_widths[1], !rtl);
533 }
534
535 /* Draw the name of the industry in white is selected, otherwise, in orange */
536 DrawString(tr, indsp->name, selected ? TextColour::White : TextColour::Orange);
537 GfxFillRect(icon, selected ? PC_WHITE : PC_BLACK);
540
541 text = text.Translate(0, this->resize.step_height);
542 icon = icon.Translate(0, this->resize.step_height);
543 }
544 break;
545 }
546
547 case WID_DPI_INFOPANEL: {
548 Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
549
550 if (this->selected_type == IT_INVALID) {
551 DrawStringMultiLine(ir, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
552 break;
553 }
554
555 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
556
557 if (_game_mode != GameMode::Editor) {
558 DrawString(ir, GetString(STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST, indsp->GetConstructionCost()));
560 }
561
562 CargoSuffix cargo_suffix[std::tuple_size_v<decltype(indsp->accepts_cargo)>];
563
564 /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
565 GetAllCargoSuffixes(CargoSuffixDirection::In, CargoSuffixType::Fund, nullptr, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
566 std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
567 ir.top = DrawStringMultiLine(ir, cargostring);
568
569 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
570 GetAllCargoSuffixes(CargoSuffixDirection::Out, CargoSuffixType::Fund, nullptr, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
571 cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
572 ir.top = DrawStringMultiLine(ir, cargostring);
573
574 ir.top = DrawBadgeNameList(ir, indsp->badges, GrfSpecFeature::Industries);
575
576 /* Get the additional purchase info text, if it has not already been queried. */
578 std::array<int32_t, 16> regs100;
579 uint16_t callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, nullptr, this->selected_type, INVALID_TILE, regs100);
580 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
581 std::string str;
582 if (callback_res == 0x40F) {
583 str = GetGRFStringWithTextStack(indsp->grf_prop.grffile, static_cast<GRFStringID>(regs100[0]), std::span{regs100}.subspan(1));
584 } else if (callback_res > 0x400) {
586 } else {
587 str = GetGRFStringWithTextStack(indsp->grf_prop.grffile, GRFSTR_MISC_GRF_TEXT + callback_res, regs100);
588 }
589 if (!str.empty()) {
591 }
592 }
593 }
594 break;
595 }
596 }
597 }
598
599 static void AskManyRandomIndustriesCallback(Window *, bool confirmed)
600 {
601 if (!confirmed) return;
602
603 if (Town::GetNumItems() == 0) {
604 ShowErrorMessage(GetEncodedString(STR_ERROR_CAN_T_GENERATE_INDUSTRIES), GetEncodedString(STR_ERROR_MUST_FOUND_TOWN_FIRST), WarningLevel::Info);
605 } else {
606 Map::CountLandTiles();
607 AutoRestoreBackup old_generating_world(_generating_world, true);
611 }
612 }
613
614 static void AskRemoveAllIndustriesCallback(Window *, bool confirmed)
615 {
616 if (!confirmed) return;
617
618 for (Industry *industry : Industry::Iterate()) delete industry;
619
620 /* Clear farmland. */
621 for (const auto tile : Map::Iterate()) {
624 }
625 }
626
628 }
629
630 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
631 {
632 switch (widget) {
634 assert(_game_mode == GameMode::Editor);
636 ShowQuery(
637 GetEncodedString(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_CAPTION),
638 GetEncodedString(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_QUERY),
639 nullptr, AskManyRandomIndustriesCallback);
640 break;
641 }
642
644 assert(_game_mode == GameMode::Editor);
646 ShowQuery(
647 GetEncodedString(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_CAPTION),
648 GetEncodedString(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_QUERY),
649 nullptr, AskRemoveAllIndustriesCallback);
650 break;
651 }
652
654 auto it = this->vscroll->GetScrolledItemFromWidget(this->list, pt.y, this, WID_DPI_MATRIX_WIDGET);
655 if (it != this->list.end()) { // Is it within the boundaries of available data?
656 this->selected_type = *it;
657 this->UpdateAvailability();
658
659 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
660
661 this->SetDirty();
662
663 if (_thd.GetCallbackWnd() == this &&
664 ((_game_mode != GameMode::Editor && _settings_game.construction.raw_industry_construction == 2 && indsp != nullptr && indsp->IsRawIndustry()) || !this->enabled)) {
665 /* Reset the button state if going to prospecting or "build many industries" */
666 this->RaiseButtons();
668 }
669
670 this->SetButtons();
671 if (this->enabled && click_count > 1) this->OnClick(pt, WID_DPI_FUND_WIDGET, 1);
672 }
673 break;
674 }
675
677 if (this->selected_type != IT_INVALID) ShowIndustryCargoesWindow(this->selected_type);
678 break;
679
680 case WID_DPI_FUND_WIDGET: {
681 if (this->selected_type != IT_INVALID) {
682 if (_game_mode != GameMode::Editor && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
683 Command<Commands::BuildIndustry>::Post(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY, TileIndex{}, this->selected_type, 0, false, InteractiveRandom());
685 } else {
687 }
688 }
689 break;
690 }
691 }
692 }
693
694 void OnResize() override
695 {
696 /* Adjust the number of items in the matrix depending of the resize */
697 this->vscroll->SetCapacityFromWidget(this, WID_DPI_MATRIX_WIDGET);
698 }
699
700 void OnPlaceObject([[maybe_unused]] Point pt, TileIndex tile) override
701 {
702 bool success = true;
703 /* We do not need to protect ourselves against "Random Many Industries" in this mode */
704 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
705 uint32_t seed = InteractiveRandom();
706 uint32_t layout_index = InteractiveRandomRange((uint32_t)indsp->layouts.size());
707
708 if (_game_mode == GameMode::Editor) {
709 /* Show error if no town exists at all */
710 if (Town::GetNumItems() == 0) {
711 ShowErrorMessage(GetEncodedString(STR_ERROR_CAN_T_BUILD_HERE, indsp->name),
712 GetEncodedString(STR_ERROR_MUST_FOUND_TOWN_FIRST), WarningLevel::Info, pt.x, pt.y);
713 return;
714 }
715
716 AutoRestoreBackup backup_cur_company(_current_company, OWNER_NONE);
717 AutoRestoreBackup backup_generating_world(_generating_world, true);
718 AutoRestoreBackup backup_ignore_industry_restritions(_ignore_industry_restrictions, true);
719
720 Command<Commands::BuildIndustry>::Post(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY, tile, this->selected_type, layout_index, false, seed);
721 } else {
722 success = Command<Commands::BuildIndustry>::Post(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY, tile, this->selected_type, layout_index, false, seed);
723 }
724
725 /* If an industry has been built, just reset the cursor and the system */
726 if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
727 }
728
729 const IntervalTimer<TimerWindow> update_interval = {std::chrono::seconds(3), [this](auto) {
730 if (_game_mode == GameMode::Editor) return;
731 if (this->selected_type == IT_INVALID) return;
732
733 bool enabled = this->enabled;
734 this->UpdateAvailability();
735 if (enabled != this->enabled) {
736 this->SetButtons();
737 this->SetDirty();
738 }
739 }};
740
741 void OnTimeout() override
742 {
743 this->RaiseButtons();
744 }
745
746 void OnPlaceObjectAbort() override
747 {
748 this->RaiseButtons();
749 }
750
756 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
757 {
758 if (!gui_scope) return;
759 this->SetupArrays();
760 this->SetButtons();
761 this->SetDirty();
762 }
763};
764
765void ShowBuildIndustryWindow()
766{
767 if (_game_mode != GameMode::Editor && !Company::IsValidID(_local_company)) return;
768 if (BringWindowToFrontById(WindowClass::BuildIndustry, 0)) return;
770}
771
772static void UpdateIndustryProduction(Industry *i);
773
774static inline bool IsProductionAlterable(const Industry *i)
775{
776 const IndustrySpec *is = GetIndustrySpec(i->type);
777 bool has_prod = std::any_of(std::begin(is->production_rate), std::end(is->production_rate), [](auto rate) { return rate != 0; });
778 return ((_game_mode == GameMode::Editor || _cheats.setup_prod.value) &&
779 (has_prod || is->IsRawIndustry()) &&
780 !_networking);
781}
782
783class IndustryViewWindow : public Window
784{
786 enum class Editability : uint8_t {
790 };
791
793 using ClickedCargoLine = int8_t;
794
795 /* Special clicked cargo line values. */
796 static constexpr ClickedCargoLine CCL_NONE = -1;
797 static constexpr ClickedCargoLine CCL_MULTIPLIER = -2;
798
803 uint8_t clicked_button = 0;
805 int info_height = 0;
807
808public:
809 IndustryViewWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc)
810 {
812 this->info_height = WidgetDimensions::scaled.framerect.Vertical() + 2 * GetCharacterHeight(FontSize::Normal); // Info panel has at least two lines text.
813
814 this->InitNested(window_number);
816 nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCentreTile(), ScaleZoomGUI(ZoomLevel::Industry));
817
820
821 this->InvalidateData();
822 }
823
826 {
827 CloseWindowById(WindowClass::IndustryProductionGraph, this->window_number, false);
828 }
829
830 void OnInit() override
831 {
832 /* This only used when the cheat to alter industry production is enabled */
833 this->cheat_line_height = std::max(SETTING_BUTTON_HEIGHT + WidgetDimensions::scaled.vsep_normal, GetCharacterHeight(FontSize::Normal));
834 this->cargo_icon_size = GetLargestCargoIconSize();
835 }
836
837 void OnPaint() override
838 {
839 this->DrawWidgets();
840
841 if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
842
843 const Rect r = this->GetWidget<NWidgetBase>(WID_IV_INFO)->GetCurrentRect();
844 int expected = this->DrawInfo(r);
845 if (expected != r.bottom) {
846 this->info_height = expected - r.top + 1;
847 this->ReInit();
848 return;
849 }
850 }
851
852 void DrawCargoIcon(const Rect &r, CargoType cargo_type) const
853 {
854 bool rtl = _current_text_dir == TD_RTL;
855 SpriteID icon = CargoSpec::Get(cargo_type)->GetCargoIcon();
856 Dimension d = GetSpriteSize(icon);
857 Rect ir = r.WithWidth(this->cargo_icon_size.width, rtl).WithHeight(GetCharacterHeight(FontSize::Normal));
858 DrawSprite(icon, PAL_NONE, CentreBounds(ir.left, ir.right, d.width), CentreBounds(ir.top, ir.bottom, this->cargo_icon_size.height));
859 }
860
861 std::string GetAcceptedCargoString(const Industry::AcceptedCargo &ac, const CargoSuffix &suffix) const
862 {
863 auto params = MakeParameters(CargoSpec::Get(ac.cargo)->name, ac.cargo, ac.waiting, suffix.text);
864 switch (suffix.display) {
865 case CargoSuffixDisplay::AmountAndText: return GetStringWithArgs(STR_INDUSTRY_VIEW_ACCEPT_CARGO_AMOUNT_SUFFIX, params);
866 case CargoSuffixDisplay::Text: return GetStringWithArgs(STR_INDUSTRY_VIEW_ACCEPT_CARGO_SUFFIX, params);
867 case CargoSuffixDisplay::Amount: return GetStringWithArgs(STR_INDUSTRY_VIEW_ACCEPT_CARGO_AMOUNT_NOSUFFIX, params);
868 case CargoSuffixDisplay::None: return GetStringWithArgs(STR_INDUSTRY_VIEW_ACCEPT_CARGO_NOSUFFIX, params);
869 default: NOT_REACHED();
870 }
871 }
872
878 int DrawInfo(const Rect &r)
879 {
880 bool rtl = _current_text_dir == TD_RTL;
882 const IndustrySpec *ind = GetIndustrySpec(i->type);
883 Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
884 bool first = true;
885 bool has_accept = false;
886
887 /* Use all the available space past the rect, so that we can enlarge the window if needed. */
888 ir.bottom = INT_MAX;
889
890 if (i->prod_level == PRODLEVEL_CLOSURE) {
891 DrawString(ir, STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE);
893 }
894
895 const int label_indent = WidgetDimensions::scaled.hsep_normal + this->cargo_icon_size.width;
897
898 for (const auto &a : i->accepted) {
899 if (!IsValidCargoType(a.cargo)) continue;
900 has_accept = true;
901 if (first) {
902 DrawString(ir, STR_INDUSTRY_VIEW_REQUIRES);
904 first = false;
905 }
906
907 DrawCargoIcon(ir, a.cargo);
908
909 CargoSuffix suffix;
910 GetCargoSuffix(CargoSuffixDirection::In, CargoSuffixType::View, i, i->type, ind, a.cargo, &a - i->accepted.data(), suffix);
911 /* if the industry is not stockpiling then don't show amount in the acceptance display. */
912 if (!stockpiling && suffix.display == CargoSuffixDisplay::AmountAndText) suffix.display = CargoSuffixDisplay::Text;
913 if (!stockpiling && suffix.display == CargoSuffixDisplay::Amount) suffix.display = CargoSuffixDisplay::None;
914
915 DrawString(ir.Indent(label_indent, rtl), this->GetAcceptedCargoString(a, suffix));
917 }
918
919 int line_height = this->editable == Editability::Rate ? this->cheat_line_height : GetCharacterHeight(FontSize::Normal);
920 int text_y_offset = (line_height - GetCharacterHeight(FontSize::Normal)) / 2;
921 int button_y_offset = (line_height - SETTING_BUTTON_HEIGHT) / 2;
922 first = true;
923 for (const auto &p : i->produced) {
924 if (!IsValidCargoType(p.cargo)) continue;
925 if (first) {
926 if (has_accept) ir.top += WidgetDimensions::scaled.vsep_wide;
927 DrawString(ir, TimerGameEconomy::UsingWallclockUnits() ? STR_INDUSTRY_VIEW_PRODUCTION_LAST_MINUTE_TITLE : STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
929 if (this->editable == Editability::Rate) this->production_offset_y = ir.top;
930 first = false;
931 }
932
933 DrawCargoIcon(ir, p.cargo);
934
935 CargoSuffix suffix;
936 GetCargoSuffix(CargoSuffixDirection::Out, CargoSuffixType::View, i, i->type, ind, p.cargo, &p - i->produced.data(), suffix);
937
938 DrawString(ir.Indent(label_indent + (this->editable == Editability::Rate ? SETTING_BUTTON_WIDTH + WidgetDimensions::scaled.hsep_normal : 0), rtl).Translate(0, text_y_offset),
939 GetString(STR_INDUSTRY_VIEW_TRANSPORTED, p.cargo, p.history[LAST_MONTH].production, suffix.text, ToPercent8(p.history[LAST_MONTH].PctTransported())));
940 /* Let's put out those buttons.. */
941 if (this->editable == Editability::Rate) {
942 DrawArrowButtons(ir.Indent(label_indent, rtl).WithWidth(SETTING_BUTTON_WIDTH, rtl).left, ir.top + button_y_offset, Colours::Yellow, (this->clicked_line == &p - i->produced.data()) ? this->clicked_button : 0,
943 p.rate > 0, p.rate < 255);
944 }
945 ir.top += line_height;
946 }
947
948 /* Display production multiplier if editable */
949 if (this->editable == Editability::Multiplier) {
950 line_height = this->cheat_line_height;
951 text_y_offset = (line_height - GetCharacterHeight(FontSize::Normal)) / 2;
952 button_y_offset = (line_height - SETTING_BUTTON_HEIGHT) / 2;
953 ir.top += WidgetDimensions::scaled.vsep_wide;
954 this->production_offset_y = ir.top;
955 DrawString(ir.Indent(label_indent + SETTING_BUTTON_WIDTH + WidgetDimensions::scaled.hsep_normal, rtl).Translate(0, text_y_offset),
956 GetString(STR_INDUSTRY_VIEW_PRODUCTION_LEVEL, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT)));
957 DrawArrowButtons(ir.Indent(label_indent, rtl).WithWidth(SETTING_BUTTON_WIDTH, rtl).left, ir.top + button_y_offset, Colours::Yellow, (this->clicked_line == CCL_MULTIPLIER) ? this->clicked_button : 0,
959 ir.top += line_height;
960 }
961
962 /* Get the extra message for the GUI */
964 std::array<int32_t, 16> regs100;
965 uint16_t callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile, regs100);
966 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
967 std::string str;
968 if (callback_res == 0x40F) {
969 str = GetGRFStringWithTextStack(ind->grf_prop.grffile, static_cast<GRFStringID>(regs100[0]), std::span{regs100}.subspan(1));
970 } else if (callback_res > 0x400) {
972 } else {
973 str = GetGRFStringWithTextStack(ind->grf_prop.grffile, GRFSTR_MISC_GRF_TEXT + callback_res, regs100);
974 }
975 if (!str.empty()) {
976 ir.top += WidgetDimensions::scaled.vsep_wide;
977 ir.top = DrawStringMultiLine(ir, str, TextColour::Yellow);
978 }
979 }
980 }
981
982 if (!i->text.empty()) {
983 ir.top += WidgetDimensions::scaled.vsep_wide;
985 }
986
987 /* Return required bottom position, the last pixel row plus some padding. */
988 return ir.top - 1 + WidgetDimensions::scaled.framerect.bottom;
989 }
990
991 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
992 {
993 if (widget == WID_IV_CAPTION) return GetString(STR_INDUSTRY_VIEW_CAPTION, this->window_number);
994
995 return this->Window::GetWidgetString(widget, stringid);
996 }
997
998 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
999 {
1000 if (widget == WID_IV_INFO) size.height = this->info_height;
1001 }
1002
1003 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1004 {
1005 switch (widget) {
1006 case WID_IV_INFO: {
1009
1010 switch (this->editable) {
1011 case Editability::None: break;
1012
1014 if (IsInsideBS(pt.y, this->production_offset_y, this->cheat_line_height)) line = CCL_MULTIPLIER;
1015 break;
1016
1017 case Editability::Rate:
1018 if (pt.y >= this->production_offset_y) {
1019 int row = (pt.y - this->production_offset_y) / this->cheat_line_height;
1020 for (auto itp = std::begin(i->produced); itp != std::end(i->produced); ++itp) {
1021 if (!IsValidCargoType(itp->cargo)) continue;
1022 row--;
1023 if (row < 0) {
1024 line = itp - std::begin(i->produced);
1025 break;
1026 }
1027 }
1028 }
1029 break;
1030 }
1031 if (line == CCL_NONE) return;
1032
1033 bool rtl = _current_text_dir == TD_RTL;
1034 Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect).Indent(this->cargo_icon_size.width + WidgetDimensions::scaled.hsep_normal, rtl);
1035
1036 if (r.WithWidth(SETTING_BUTTON_WIDTH, rtl).Contains(pt)) {
1037 /* Clicked buttons, decrease or increase production */
1038 bool decrease = r.WithWidth(SETTING_BUTTON_WIDTH / 2, rtl).Contains(pt);
1039 switch (this->editable) {
1041 if (decrease) {
1042 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
1043 i->prod_level = static_cast<uint8_t>(std::max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM));
1044 } else {
1045 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
1046 i->prod_level = static_cast<uint8_t>(std::min<uint>(i->prod_level * 2, PRODLEVEL_MAXIMUM));
1047 }
1048 break;
1049
1050 case Editability::Rate:
1051 if (decrease) {
1052 if (i->produced[line].rate <= 0) return;
1053 i->produced[line].rate = std::max(i->produced[line].rate / 2, 0);
1054 } else {
1055 if (i->produced[line].rate >= 255) return;
1056 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
1057 int new_prod = i->produced[line].rate == 0 ? 1 : i->produced[line].rate * 2;
1058 i->produced[line].rate = ClampTo<uint8_t>(new_prod);
1059 }
1060 break;
1061
1062 default: NOT_REACHED();
1063 }
1064
1065 UpdateIndustryProduction(i);
1066 this->SetDirty();
1067 this->SetTimeout();
1068 this->clicked_line = line;
1069 this->clicked_button = (decrease ^ rtl) ? 1 : 2;
1070 } else if (r.Indent(SETTING_BUTTON_WIDTH + WidgetDimensions::scaled.hsep_normal, rtl).Contains(pt)) {
1071 /* clicked the text */
1072 this->editbox_line = line;
1073 switch (this->editable) {
1075 ShowQueryString(GetString(STR_JUST_INT, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT)), STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, {});
1076 break;
1077
1078 case Editability::Rate:
1079 ShowQueryString(GetString(STR_JUST_INT, i->produced[line].rate * 8), STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, {});
1080 break;
1081
1082 default: NOT_REACHED();
1083 }
1084 }
1085 break;
1086 }
1087
1088 case WID_IV_GOTO: {
1090 if (IsCtrlPressed()) {
1092 } else {
1094 }
1095 break;
1096 }
1097
1098 case WID_IV_DISPLAY: {
1101 break;
1102 }
1103
1104 case WID_IV_GRAPH:
1105 ShowIndustryProductionGraph(this->window_number);
1106 break;
1107 }
1108 }
1109
1110 void OnTimeout() override
1111 {
1112 this->clicked_line = CCL_NONE;
1113 this->clicked_button = 0;
1114 this->SetDirty();
1115 }
1116
1117 void OnResize() override
1118 {
1119 if (this->viewport != nullptr) {
1121 nvp->UpdateViewportCoordinates(this);
1122
1123 ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCentreTile(), this, true); // Re-center viewport.
1124 }
1125 }
1126
1127 void OnMouseWheel(int wheel, WidgetID widget) override
1128 {
1129 if (widget != WID_IV_VIEWPORT) return;
1130 if (_settings_client.gui.scrollwheel_scrolling != ScrollWheelScrolling::Off) {
1131 DoZoomInOutWindow(wheel < 0 ? ZOOM_IN : ZOOM_OUT, this);
1132 }
1133 }
1134
1135 void OnQueryTextFinished(std::optional<std::string> str) override
1136 {
1137 if (!str.has_value() || str->empty()) return;
1138
1140 auto value = ParseInteger(*str, 10, true);
1141 if (!value.has_value()) return;
1142 switch (this->editbox_line) {
1143 case CCL_NONE: NOT_REACHED();
1144
1145 case CCL_MULTIPLIER:
1147 break;
1148
1149 default:
1150 i->produced[this->editbox_line].rate = ClampU(RoundDivSU(*value, 8), 0, 255);
1151 break;
1152 }
1153 UpdateIndustryProduction(i);
1154 this->SetDirty();
1155 }
1156
1162 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1163 {
1164 if (!gui_scope) return;
1165 const Industry *i = Industry::Get(this->window_number);
1166 if (IsProductionAlterable(i)) {
1167 const IndustrySpec *ind = GetIndustrySpec(i->type);
1169 } else {
1170 this->editable = Editability::None;
1171 }
1172 }
1173
1174 bool IsNewGRFInspectable() const override
1175 {
1176 return ::IsNewGRFInspectable(GrfSpecFeature::Industries, this->window_number);
1177 }
1178
1183};
1184
1185static void UpdateIndustryProduction(Industry *i)
1186{
1187 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1189
1190 for (auto &p : i->produced) {
1191 if (IsValidCargoType(p.cargo)) {
1192 p.history[LAST_MONTH].production = ScaleByCargoScale(8 * p.rate, false);
1193 }
1194 }
1195}
1196
1198static constexpr std::initializer_list<NWidgetPart> _nested_industry_view_widgets = {
1202 NWidget(WWT_PUSHIMGBTN, Colours::Cream, WID_IV_GOTO), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetSpriteTip(SPR_GOTO_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
1207 EndContainer(),
1211 EndContainer(),
1212 EndContainer(),
1214 EndContainer(),
1216 NWidget(WWT_PUSHTXTBTN, Colours::Cream, WID_IV_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
1217 NWidget(WWT_PUSHTXTBTN, Colours::Cream, WID_IV_GRAPH), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_INDUSTRY_VIEW_CARGO_GRAPH, STR_INDUSTRY_VIEW_CARGO_GRAPH_TOOLTIP),
1219 EndContainer(),
1220};
1221
1224 WindowPosition::Automatic, "view_industry", 260, 120,
1225 WindowClass::IndustryView, WindowClass::None,
1226 {},
1228);
1229
1230void ShowIndustryViewWindow(IndustryID industry)
1231{
1233}
1234
1236static constexpr std::initializer_list<NWidgetPart> _nested_industry_directory_widgets = {
1243 EndContainer(),
1247 NWidget(WWT_TEXTBTN, Colours::Brown, WID_ID_DROPDOWN_ORDER), SetStringTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1249 NWidget(WWT_EDITBOX, Colours::Brown, WID_ID_FILTER), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
1250 EndContainer(),
1252 NWidget(WWT_DROPDOWN, Colours::Brown, WID_ID_FILTER_BY_ACC_CARGO), SetMinimalSize(225, 12), SetFill(0, 1), SetToolTip(STR_TOOLTIP_FILTER_CRITERIA),
1253 NWidget(WWT_DROPDOWN, Colours::Brown, WID_ID_FILTER_BY_PROD_CARGO), SetMinimalSize(225, 12), SetFill(0, 1), SetToolTip(STR_TOOLTIP_FILTER_CRITERIA),
1255 EndContainer(),
1257 EndContainer(),
1258 EndContainer(),
1260 EndContainer(),
1264 EndContainer(),
1265};
1266
1268
1276static bool CargoFilter(const Industry * const *industry, const std::pair<CargoType, CargoType> &cargoes)
1277{
1278 auto accepted_cargo = cargoes.first;
1279 auto produced_cargo = cargoes.second;
1280
1281 bool accepted_cargo_matches;
1282
1283 switch (accepted_cargo) {
1285 accepted_cargo_matches = true;
1286 break;
1287
1289 accepted_cargo_matches = !(*industry)->IsCargoAccepted();
1290 break;
1291
1292 default:
1293 accepted_cargo_matches = (*industry)->IsCargoAccepted(accepted_cargo);
1294 break;
1295 }
1296
1297 bool produced_cargo_matches;
1298
1299 switch (produced_cargo) {
1301 produced_cargo_matches = true;
1302 break;
1303
1305 produced_cargo_matches = !(*industry)->IsCargoProduced();
1306 break;
1307
1308 default:
1309 produced_cargo_matches = (*industry)->IsCargoProduced(produced_cargo);
1310 break;
1311 }
1312
1313 return accepted_cargo_matches && produced_cargo_matches;
1314}
1315
1316static GUIIndustryList::FilterFunction * const _industry_filter_funcs[] = { &CargoFilter };
1317
1321class IndustryDirectoryWindow : public Window {
1322protected:
1323 /* Runtime saved values */
1324 static Listing last_sorting;
1325
1327 static inline const StringID sorter_names[] = {
1328 STR_SORT_BY_NAME,
1329 STR_SORT_BY_TYPE,
1330 STR_SORT_BY_PRODUCTION,
1331 STR_SORT_BY_TRANSPORTED,
1332 };
1333 static const std::initializer_list<GUIIndustryList::SortFunction * const> sorter_funcs;
1334
1335 GUIIndustryList industries{IndustryDirectoryWindow::produced_cargo_filter};
1336 Scrollbar *vscroll{};
1337 Scrollbar *hscroll{};
1338
1341 static CargoType produced_cargo_filter;
1342
1343 const int MAX_FILTER_LENGTH = 16;
1346
1354
1360 {
1361 if (this->produced_cargo_filter_criteria != cargo_type) {
1362 this->produced_cargo_filter_criteria = cargo_type;
1363 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1364 bool is_filtering_necessary = this->produced_cargo_filter_criteria != CargoFilterCriteria::CF_ANY || this->accepted_cargo_filter_criteria != CargoFilterCriteria::CF_ANY;
1365
1366 this->industries.SetFilterState(is_filtering_necessary);
1367 this->industries.SetFilterType(0);
1368 this->industries.ForceRebuild();
1369 }
1370 }
1371
1377 {
1378 if (this->accepted_cargo_filter_criteria != cargo_type) {
1379 this->accepted_cargo_filter_criteria = cargo_type;
1380 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1381 bool is_filtering_necessary = this->produced_cargo_filter_criteria != CargoFilterCriteria::CF_ANY || this->accepted_cargo_filter_criteria != CargoFilterCriteria::CF_ANY;
1382
1383 this->industries.SetFilterState(is_filtering_necessary);
1384 this->industries.SetFilterType(0);
1385 this->industries.ForceRebuild();
1386 }
1387 }
1388
1389 StringID GetCargoFilterLabel(CargoType cargo_type) const
1390 {
1391 switch (cargo_type) {
1392 case CargoFilterCriteria::CF_ANY: return STR_INDUSTRY_DIRECTORY_FILTER_ALL_TYPES;
1393 case CargoFilterCriteria::CF_NONE: return STR_INDUSTRY_DIRECTORY_FILTER_NONE;
1394 default: return CargoSpec::Get(cargo_type)->name;
1395 }
1396 }
1397
1402 {
1403 this->produced_cargo_filter_criteria = CargoFilterCriteria::CF_ANY;
1404 this->accepted_cargo_filter_criteria = CargoFilterCriteria::CF_ANY;
1405
1406 this->industries.SetFilterFuncs(_industry_filter_funcs);
1407
1408 bool is_filtering_necessary = this->produced_cargo_filter_criteria != CargoFilterCriteria::CF_ANY || this->accepted_cargo_filter_criteria != CargoFilterCriteria::CF_ANY;
1409
1410 this->industries.SetFilterState(is_filtering_necessary);
1411 }
1412
1418 {
1419 uint width = this->hscroll->GetCount();
1420 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->industries);
1421 for (auto it = first; it != last; ++it) {
1422 width = std::max(width, GetStringBoundingBox(this->GetIndustryString(*it)).width);
1423 }
1424 return width;
1425 }
1426
1429 {
1430 if (this->industries.NeedRebuild()) {
1431 this->industries.clear();
1432 this->industries.reserve(Industry::GetNumItems());
1433
1434 for (const Industry *i : Industry::Iterate()) {
1435 if (this->string_filter.IsEmpty()) {
1436 this->industries.push_back(i);
1437 continue;
1438 }
1439 this->string_filter.ResetState();
1440 this->string_filter.AddLine(i->GetCachedName());
1441 if (this->string_filter.GetState()) this->industries.push_back(i);
1442 }
1443
1444 this->industries.RebuildDone();
1445
1446 auto filter = std::make_pair(this->accepted_cargo_filter_criteria, this->produced_cargo_filter_criteria);
1447
1448 this->industries.Filter(filter);
1449
1450 this->vscroll->SetCount(this->industries.size()); // Update scrollbar as well.
1451 }
1452
1453 IndustryDirectoryWindow::produced_cargo_filter = this->produced_cargo_filter_criteria;
1454 this->industries.Sort();
1455
1456 this->SetDirty();
1457 }
1458
1466 {
1467 if (!IsValidCargoType(p.cargo)) return -1;
1468 return ToPercent8(p.history[LAST_MONTH].PctTransported());
1469 }
1470
1479 {
1480 CargoType filter = IndustryDirectoryWindow::produced_cargo_filter;
1481 if (filter == CargoFilterCriteria::CF_NONE) return 0;
1482
1483 int percentage = 0, produced_cargo_count = 0;
1484 for (const auto &p : i->produced) {
1485 if (filter == CargoFilterCriteria::CF_ANY) {
1486 int transported = GetCargoTransportedPercentsIfValid(p);
1487 if (transported != -1) {
1488 produced_cargo_count++;
1489 percentage += transported;
1490 }
1491 if (produced_cargo_count == 0 && &p == &i->produced.back() && percentage == 0) {
1492 return transported;
1493 }
1494 } else if (filter == p.cargo) {
1496 }
1497 }
1498
1499 if (produced_cargo_count == 0) return percentage;
1500 return percentage / produced_cargo_count;
1501 }
1502
1504 static bool IndustryNameSorter(const Industry * const &a, const Industry * const &b, [[maybe_unused]] const CargoType &filter)
1505 {
1506 int r = StrNaturalCompare(a->GetCachedName(), b->GetCachedName()); // Sort by name (natural sorting).
1507 if (r == 0) return a->index < b->index;
1508 return r < 0;
1509 }
1510
1512 static bool IndustryTypeSorter(const Industry * const &a, const Industry * const &b, const CargoType &filter)
1513 {
1514 int it_a = 0;
1515 while (it_a != NUM_INDUSTRYTYPES && a->type != _sorted_industry_types[it_a]) it_a++;
1516 int it_b = 0;
1517 while (it_b != NUM_INDUSTRYTYPES && b->type != _sorted_industry_types[it_b]) it_b++;
1518 int r = it_a - it_b;
1519 return (r == 0) ? IndustryNameSorter(a, b, filter) : r < 0;
1520 }
1521
1523 static bool IndustryProductionSorter(const Industry * const &a, const Industry * const &b, const CargoType &filter)
1524 {
1525 if (filter == CargoFilterCriteria::CF_NONE) return IndustryTypeSorter(a, b, filter);
1526
1527 uint prod_a = 0, prod_b = 0;
1528 if (filter == CargoFilterCriteria::CF_ANY) {
1529 for (const auto &pa : a->produced) {
1530 if (IsValidCargoType(pa.cargo)) prod_a += pa.history[LAST_MONTH].production;
1531 }
1532 for (const auto &pb : b->produced) {
1533 if (IsValidCargoType(pb.cargo)) prod_b += pb.history[LAST_MONTH].production;
1534 }
1535 } else {
1536 if (auto ita = a->GetCargoProduced(filter); ita != std::end(a->produced)) prod_a = ita->history[LAST_MONTH].production;
1537 if (auto itb = b->GetCargoProduced(filter); itb != std::end(b->produced)) prod_b = itb->history[LAST_MONTH].production;
1538 }
1539 int r = prod_a - prod_b;
1540
1541 return (r == 0) ? IndustryTypeSorter(a, b, filter) : r < 0;
1542 }
1543
1545 static bool IndustryTransportedCargoSorter(const Industry * const &a, const Industry * const &b, const CargoType &filter)
1546 {
1548 return (r == 0) ? IndustryNameSorter(a, b, filter) : r < 0;
1549 }
1550
1551 StringID GetStringForNumCargo(size_t count) const
1552 {
1553 switch (count) {
1554 case 0: return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
1555 case 1: return STR_INDUSTRY_DIRECTORY_ITEM_PROD1;
1556 case 2: return STR_INDUSTRY_DIRECTORY_ITEM_PROD2;
1557 case 3: return STR_INDUSTRY_DIRECTORY_ITEM_PROD3;
1558 default: return STR_INDUSTRY_DIRECTORY_ITEM_PRODMORE;
1559 }
1560 }
1561
1567 std::string GetIndustryString(const Industry *i) const
1568 {
1569 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1570
1571 /* Get industry productions (CargoType, production, suffix, transported) */
1572 struct CargoInfo {
1573 CargoType cargo_type;
1574 uint16_t production;
1575 uint transported;
1576 std::string suffix;
1577
1578 CargoInfo(CargoType cargo_type, uint16_t production, uint transported, std::string &&suffix) : cargo_type(cargo_type), production(production), transported(transported), suffix(std::move(suffix)) {}
1579 };
1580 std::vector<CargoInfo> cargos;
1581
1582 for (auto itp = std::begin(i->produced); itp != std::end(i->produced); ++itp) {
1583 if (!IsValidCargoType(itp->cargo)) continue;
1584 CargoSuffix cargo_suffix;
1585 GetCargoSuffix(CargoSuffixDirection::Out, CargoSuffixType::Directory, i, i->type, indsp, itp->cargo, itp - std::begin(i->produced), cargo_suffix);
1586 cargos.emplace_back(itp->cargo, itp->history[LAST_MONTH].production, ToPercent8(itp->history[LAST_MONTH].PctTransported()), std::move(cargo_suffix.text));
1587 }
1588
1589 switch (static_cast<IndustryDirectoryWindow::SorterType>(this->industries.SortType())) {
1593 /* Sort by descending production, then descending transported */
1594 std::sort(cargos.begin(), cargos.end(), [](const CargoInfo &a, const CargoInfo &b) {
1595 if (a.production != b.production) return a.production > b.production;
1596 return a.transported > b.transported;
1597 });
1598 break;
1599
1601 /* Sort by descending transported, then descending production */
1602 std::sort(cargos.begin(), cargos.end(), [](const CargoInfo &a, const CargoInfo &b) {
1603 if (a.transported != b.transported) return a.transported > b.transported;
1604 return a.production > b.production;
1605 });
1606 break;
1607 }
1608
1609 /* If the produced cargo filter is active then move the filtered cargo to the beginning of the list,
1610 * because this is the one the player interested in, and that way it is not hidden in the 'n' more cargos */
1611 const CargoType cargo_type = this->produced_cargo_filter_criteria;
1612 if (cargo_type != CargoFilterCriteria::CF_ANY && cargo_type != CargoFilterCriteria::CF_NONE) {
1613 auto filtered_ci = std::ranges::find(cargos, cargo_type, &CargoInfo::cargo_type);
1614 if (filtered_ci != cargos.end()) {
1615 std::rotate(cargos.begin(), filtered_ci, filtered_ci + 1);
1616 }
1617 }
1618
1619 static constexpr size_t MAX_DISPLAYED_CARGOES = 3;
1620 std::array<StringParameter, 2 + 5 * MAX_DISPLAYED_CARGOES> params{};
1621 auto it = params.begin();
1622
1623 /* Industry name */
1624 *it++ = i->index;
1625
1626 /* Display first MAX_DISPLAYED_CARGOES cargoes */
1627 for (CargoInfo &ci : cargos | std::views::take(MAX_DISPLAYED_CARGOES)) {
1628 *it++ = STR_INDUSTRY_DIRECTORY_ITEM_INFO;
1629 *it++ = ci.cargo_type;
1630 *it++ = ci.production;
1631 *it++ = std::move(ci.suffix);
1632 *it++ = ci.transported;
1633 }
1634
1635 /* Undisplayed cargos if any */
1636 if (std::size(cargos) > MAX_DISPLAYED_CARGOES) *it++ = std::size(cargos) - MAX_DISPLAYED_CARGOES;
1637
1638 return GetStringWithArgs(GetStringForNumCargo(std::size(cargos)), {params.begin(), it});
1639 }
1640
1641public:
1643 {
1644 this->CreateNestedTree();
1645 this->vscroll = this->GetScrollbar(WID_ID_VSCROLLBAR);
1646 this->hscroll = this->GetScrollbar(WID_ID_HSCROLLBAR);
1647
1648 this->industries.SetListing(this->last_sorting);
1650 this->industries.ForceRebuild();
1651
1652 this->FinishInitNested(0);
1653
1655
1656 this->querystrings[WID_ID_FILTER] = &this->industry_editbox;
1657 this->industry_editbox.cancel_button = QueryString::ACTION_CLEAR;
1658 }
1659
1662 {
1663 this->last_sorting = this->industries.GetListing();
1664 }
1665
1666 void OnInit() override
1667 {
1668 this->SetCargoFilterArray();
1669 this->hscroll->SetStepSize(GetCharacterHeight(FontSize::Normal)); // Speed up horizontal scrollbar
1670 this->hscroll->SetCount(0);
1671 }
1672
1673 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
1674 {
1675 switch (widget) {
1676 case WID_ID_CAPTION:
1677 return GetString(STR_INDUSTRY_DIRECTORY_CAPTION, this->vscroll->GetCount(), Industry::GetNumItems());
1678
1680 return GetString(IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
1681
1683 return GetString(STR_INDUSTRY_DIRECTORY_ACCEPTED_CARGO_FILTER, this->GetCargoFilterLabel(this->accepted_cargo_filter_criteria));
1684
1686 return GetString(STR_INDUSTRY_DIRECTORY_PRODUCED_CARGO_FILTER, this->GetCargoFilterLabel(this->produced_cargo_filter_criteria));
1687
1688 default:
1689 return this->Window::GetWidgetString(widget, stringid);
1690 }
1691 }
1692
1693 void DrawWidget(const Rect &r, WidgetID widget) const override
1694 {
1695 switch (widget) {
1697 this->DrawSortButton(widget, this->industries.IsDescSortOrder());
1698 break;
1699
1700 case WID_ID_INDUSTRY_LIST: {
1701 Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
1702
1703 /* Setup a clipping rectangle... */
1704 DrawPixelInfo tmp_dpi;
1705 if (!FillDrawPixelInfo(&tmp_dpi, ir)) return;
1706 /* ...but keep coordinates relative to the window. */
1707 tmp_dpi.left += ir.left;
1708 tmp_dpi.top += ir.top;
1709
1710 AutoRestoreBackup dpi_backup(_cur_dpi, &tmp_dpi);
1711
1712 ir = ScrollRect(ir, *this->hscroll, 1);
1713
1714 if (this->industries.empty()) {
1715 DrawString(ir, STR_INDUSTRY_DIRECTORY_NONE);
1716 break;
1717 }
1718 const CargoType acf_cargo_type = this->accepted_cargo_filter_criteria;
1719 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->industries);
1720 for (auto it = first; it != last; ++it) {
1722 if (acf_cargo_type != CargoFilterCriteria::CF_ANY && acf_cargo_type != CargoFilterCriteria::CF_NONE) {
1723 Industry *ind = const_cast<Industry *>(*it);
1724 if (IndustryTemporarilyRefusesCargo(ind, acf_cargo_type)) {
1726 }
1727 }
1728 DrawString(ir, this->GetIndustryString(*it), tc);
1729
1730 ir.top += this->resize.step_height;
1731 }
1732 break;
1733 }
1734 }
1735 }
1736
1737 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1738 {
1739 switch (widget) {
1740 case WID_ID_DROPDOWN_ORDER: {
1742 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1743 d.height += padding.height;
1744 size = maxdim(size, d);
1745 break;
1746 }
1747
1750 d.width += padding.width;
1751 d.height += padding.height;
1752 size = maxdim(size, d);
1753 break;
1754 }
1755
1756 case WID_ID_INDUSTRY_LIST: {
1757 Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
1758 fill.height = resize.height = d.height;
1759 d.height *= 5;
1760 d.width += padding.width;
1761 d.height += padding.height;
1762 size = maxdim(size, d);
1763 break;
1764 }
1765 }
1766 }
1767
1768 DropDownList BuildCargoDropDownList() const
1769 {
1770 DropDownList list;
1771
1772 /* Add item for disabling filtering. */
1773 list.push_back(MakeDropDownListStringItem(this->GetCargoFilterLabel(CargoFilterCriteria::CF_ANY), CargoFilterCriteria::CF_ANY));
1774 /* Add item for industries not producing anything, e.g. power plants */
1776
1777 /* Add cargos */
1779 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1780 list.push_back(MakeDropDownListIconItem(d, cs->GetCargoIcon(), PAL_NONE, cs->name, cs->Index()));
1781 }
1782
1783 return list;
1784 }
1785
1786 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1787 {
1788 switch (widget) {
1790 this->industries.ToggleSortOrder();
1791 this->SetDirty();
1792 break;
1793
1796 break;
1797
1798 case WID_ID_FILTER_BY_ACC_CARGO: { // Cargo filter dropdown
1799 static std::string acc_cargo_filter;
1800 ShowDropDownList(this, this->BuildCargoDropDownList(), this->accepted_cargo_filter_criteria, widget, 0, DropDownOption::Filterable, &acc_cargo_filter);
1801 break;
1802 }
1803
1804 case WID_ID_FILTER_BY_PROD_CARGO: { // Cargo filter dropdown
1805 static std::string prod_cargo_filter;
1806 ShowDropDownList(this, this->BuildCargoDropDownList(), this->produced_cargo_filter_criteria, widget, 0, DropDownOption::Filterable, &prod_cargo_filter);
1807 break;
1808 }
1809
1810 case WID_ID_INDUSTRY_LIST: {
1811 auto it = this->vscroll->GetScrolledItemFromWidget(this->industries, pt.y, this, WID_ID_INDUSTRY_LIST, WidgetDimensions::scaled.framerect.top);
1812 if (it != this->industries.end()) {
1813 if (IsCtrlPressed()) {
1814 ShowExtraViewportWindow((*it)->location.tile);
1815 } else {
1816 ScrollMainWindowToTile((*it)->location.tile);
1817 }
1818 }
1819 break;
1820 }
1821 }
1822 }
1823
1824 void OnDropdownSelect(WidgetID widget, int index, int) override
1825 {
1826 switch (widget) {
1828 if (this->industries.SortType() != index) {
1829 this->industries.SetSortType(index);
1831 }
1832 break;
1833 }
1834
1836 this->SetAcceptedCargoFilter(static_cast<CargoType>(index));
1838 break;
1839 }
1840
1842 this->SetProducedCargoFilter(static_cast<CargoType>(index));
1844 break;
1845 }
1846 }
1847 }
1848
1849 void OnResize() override
1850 {
1851 this->vscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST, WidgetDimensions::scaled.framerect.Vertical());
1852 this->hscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST, WidgetDimensions::scaled.framerect.Horizontal());
1853 }
1854
1855 void OnEditboxChanged(WidgetID wid) override
1856 {
1857 if (wid == WID_ID_FILTER) {
1858 this->string_filter.SetFilterTerm(this->industry_editbox.text.GetText());
1859 this->InvalidateData(IDIWD_FORCE_REBUILD);
1860 }
1861 }
1862
1863 void OnPaint() override
1864 {
1865 if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
1866 this->hscroll->SetCount(this->GetIndustryListWidth());
1867 this->DrawWidgets();
1868 }
1869
1871 const IntervalTimer<TimerWindow> rebuild_interval = {std::chrono::seconds(3), [this](auto) {
1872 this->industries.ForceResort();
1874 }};
1875
1881 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1882 {
1883 switch (data) {
1884 case IDIWD_FORCE_REBUILD:
1885 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1886 this->industries.ForceRebuild();
1887 break;
1888
1889 case IDIWD_PRODUCTION_CHANGE:
1890 if (this->industries.SortType() == 2) this->industries.ForceResort();
1891 break;
1892
1893 default:
1894 this->industries.ForceResort();
1895 break;
1896 }
1897 }
1898
1899 static inline HotkeyList hotkeys {"industrydirectory", {
1900 Hotkey('F', "focus_filter_box", WID_ID_FILTER),
1901 }};
1902};
1903
1904Listing IndustryDirectoryWindow::last_sorting = {false, 0};
1905
1906/* Available station sorting functions. */
1907const std::initializer_list<GUIIndustryList::SortFunction * const> IndustryDirectoryWindow::sorter_funcs = {
1912};
1913
1914CargoType IndustryDirectoryWindow::produced_cargo_filter = CargoFilterCriteria::CF_ANY;
1915
1916
1919 WindowPosition::Automatic, "list_industries", 428, 190,
1920 WindowClass::IndustryDirectory, WindowClass::None,
1921 {},
1923 &IndustryDirectoryWindow::hotkeys
1924);
1925
1926void ShowIndustryDirectory()
1927{
1929}
1930
1932static constexpr std::initializer_list<NWidgetPart> _nested_industry_cargoes_widgets = {
1938 NWidget(WWT_IMGBTN, Colours::Brown, WID_IC_TOGGLE_SIZE), SetSpriteTip(SPR_LARGE_SMALL_WINDOW, STR_TOOLTIP_TOGGLE_LARGE_SMALL_WINDOW), SetAspect(WidgetDimensions::ASPECT_TOGGLE_SIZE),
1942 EndContainer(),
1946 EndContainer(),
1949 SetStringTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
1952 SetStringTip(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY, STR_INDUSTRY_CARGOES_SELECT_INDUSTRY_TOOLTIP),
1954 SetStringTip(STR_INDUSTRY_CARGOES_SELECT_CARGO, STR_INDUSTRY_CARGOES_SELECT_CARGO_TOOLTIP),
1956 EndContainer(),
1957};
1958
1961 WindowPosition::Automatic, "industry_cargoes", 300, 210,
1962 WindowClass::IndustryCargoes, WindowClass::None,
1963 {},
1965);
1966
1969public:
1970 static constexpr uint MAX_CARGOES = 16;
1971
1972 using CargoSlotMask = uint16_t;
1973 static_assert(std::numeric_limits<CargoSlotMask>::digits >= MAX_CARGOES);
1974
1975 static constexpr CargoSlotMask ALL_CARGO_SLOTS{std::numeric_limits<CargoSlotMask>::max()};
1976
1977 static_assert(MAX_CARGOES >= std::tuple_size_v<decltype(IndustrySpec::produced_cargo)>);
1978 static_assert(MAX_CARGOES >= std::tuple_size_v<decltype(IndustrySpec::accepts_cargo)>);
1979
1981
1983
1984 static inline CargoTypes town_accepts;
1986
1987 static inline int vert_inter_industry_space;
1988 static inline int blob_distance;
1989
1990 static inline Dimension legend;
1991 static inline Dimension cargo_border;
1992 static inline Dimension cargo_line;
1993 static inline Dimension cargo_space;
1994 static inline Dimension cargo_stub;
1995
1996 static inline int small_height;
1997 static inline int normal_height;
1998 static inline int connection_field_width;
1999 static inline int industry_width;
2000 static inline uint max_cargoes;
2001
2010
2011 virtual ~ChainField() = default;
2012
2018 template <typename T> T *Get() { return dynamic_cast<T *>(this); }
2019
2025 template <typename T> const T *Get() const { return dynamic_cast<const T *>(this); }
2026
2031 virtual int Width() const { return ChainField::industry_width; }
2032
2037 virtual int Height() const { return ChainField::normal_height; }
2038
2043 virtual void Draw([[maybe_unused]] Rect r) const = 0;
2044
2046 using ClickedAtResult = std::variant<std::monostate, HouseID, IndustryType, CargoType>;
2047
2054 virtual ClickedAtResult ClickedAt([[maybe_unused]] Rect r, [[maybe_unused]] Point pt) const { return {}; }
2055};
2056
2059public:
2061
2067
2068 int Height() const override
2069 {
2071 }
2072
2073 void Draw(Rect r) const override
2074 {
2076 }
2077};
2078
2081public:
2082 std::array<CargoType, ChainField::MAX_CARGOES> vertical_cargoes;
2088 uint8_t num_cargoes;
2089
2095 {
2096 assert(cargo_types.Count() <= std::size(this->vertical_cargoes));
2097
2098 auto it = this->vertical_cargoes.begin();
2099 for (CargoType cargo_type : cargo_types) *it++ = cargo_type;
2100
2101 this->num_cargoes = static_cast<uint8_t>(std::distance(std::begin(this->vertical_cargoes), it));
2102
2103 std::sort(std::begin(this->vertical_cargoes), it, CargoTypeComparator{});
2104 std::fill(it, std::end(this->vertical_cargoes), INVALID_CARGO);
2105 }
2106
2107 int Width() const override
2108 {
2110 }
2111
2112 void Draw(Rect r) const override
2113 {
2114 if (this->skip_cargoes == ALL_CARGO_SLOTS) return;
2115
2116 int col_step = ChainField::cargo_line.width + ChainField::cargo_space.width;
2117 int row_step = ChainField::cargo_line.height + ChainField::cargo_space.height;
2118 uint width = this->num_cargoes * col_step - ChainField::cargo_space.width;
2119 Rect col_base = r.CentreToWidth(width).WithWidth(ChainField::cargo_line.width, false);
2121
2122 CargoSlotMask hor_left, hor_right;
2123 if (_current_text_dir == TD_RTL) {
2124 hor_left = this->cust_cargoes;
2125 hor_right = this->supp_cargoes;
2126 } else {
2127 hor_left = this->supp_cargoes;
2128 hor_right = this->cust_cargoes;
2129 }
2130
2131 /* Draw columns */
2132 for (int i = 0; i < this->num_cargoes; ++i) {
2133 if (!HasBit(this->skip_cargoes, i)) {
2134 Rect col = col_base;
2135 RectPadding col_padding = WidgetDimensions::scaled.bevel;
2136 if (HasBit(this->top_end, i)) {
2137 col.top = row_base.top;
2138 } else {
2139 col_padding.top = 0;
2141 }
2142 if (HasBit(this->bottom_end, i)) {
2143 col.bottom = row_base.bottom;
2144 } else {
2145 col_padding.bottom = 0;
2146 col.bottom += ChainField::vert_inter_industry_space / 2;
2147 }
2148
2150
2151 if (HasBit(hor_left, i)) GfxFillRect(row_base.WithX(row_base.left, col_base.left), CARGO_LINE_COLOUR);
2152 if (HasBit(hor_right, i)) GfxFillRect(row_base.WithX(col_base.right, row_base.right), CARGO_LINE_COLOUR);
2153
2154 PixelColour pc = CargoSpec::Get(this->vertical_cargoes[i])->legend_colour;
2155 GfxFillRect(col.Shrink(col_padding), pc);
2156
2157 if (HasBit(hor_left, i)) GfxFillRect(row_base.WithX(row_base.left, col_base.left + WidgetDimensions::scaled.bevel.left - 1).Shrink(RectPadding::zero, WidgetDimensions::scaled.bevel), pc);
2158 if (HasBit(hor_right, i)) GfxFillRect(row_base.WithX(col_base.right - WidgetDimensions::scaled.bevel.left + 1, row_base.right).Shrink(RectPadding::zero, WidgetDimensions::scaled.bevel), pc);
2159 }
2160
2161 col_base = col_base.Translate(col_step, 0);
2162 row_base = row_base.Translate(0, row_step);
2163 }
2164 }
2165
2166 ClickedAtResult ClickedAt(Rect r, Point pt) const override
2167 {
2168 if (this->skip_cargoes == ALL_CARGO_SLOTS) return {};
2169
2170 int col_step = ChainField::cargo_line.width + ChainField::cargo_space.width;
2171 int row_step = ChainField::cargo_line.height + ChainField::cargo_space.height;
2172 uint width = this->num_cargoes * col_step - ChainField::cargo_space.width;
2173 Rect col_base = r.CentreToWidth(width).WithWidth(ChainField::cargo_line.width, false);
2175
2176 CargoSlotMask hor_left, hor_right;
2177 if (_current_text_dir == TD_RTL) {
2178 hor_left = this->cust_cargoes;
2179 hor_right = this->supp_cargoes;
2180 } else {
2181 hor_left = this->supp_cargoes;
2182 hor_right = this->cust_cargoes;
2183 }
2184
2185 col_base = col_base.Translate(this->num_cargoes * col_step, 0);
2186 row_base = row_base.Translate(0, this->num_cargoes * row_step);
2187
2188 /* Work backwards as higher slots are drawn last. */
2189 for (int i = static_cast<int>(this->num_cargoes) - 1; i >= 0; --i) {
2190 col_base = col_base.Translate(-col_step, 0);
2191 row_base = row_base.Translate(0, -row_step);
2192
2193 if (HasBit(this->skip_cargoes, i)) continue;
2194
2195 Rect col = col_base;
2196 if (HasBit(this->top_end, i)) {
2197 col.top = row_base.top;
2198 } else {
2200 }
2201 if (HasBit(this->bottom_end, i)) {
2202 col.bottom = row_base.bottom;
2203 } else {
2204 col.bottom += ChainField::vert_inter_industry_space / 2;
2205 }
2206
2207 CargoType cargo_type = this->vertical_cargoes[i];
2208
2209 if (col.Contains(pt)) return cargo_type;
2210 if (HasBit(hor_left, i) && row_base.WithX(row_base.left, col_base.left).Contains(pt)) return cargo_type;
2211 if (HasBit(hor_right, i) && row_base.WithX(col_base.right, row_base.right).Contains(pt)) return cargo_type;
2212 }
2213
2214 return {};
2215 }
2216
2223 int ConnectCargo(CargoType cargo, bool producer)
2224 {
2225 assert(IsValidCargoType(cargo));
2226
2227 /* Find the vertical cargo column carrying the cargo. */
2228 auto it = std::ranges::find(this->vertical_cargoes, cargo);
2229 if (it == this->vertical_cargoes.end()) return -1;
2230
2231 int column = static_cast<int>(std::distance(this->vertical_cargoes.begin(), it));
2232
2233 if (producer) {
2234 assert(!HasBit(this->supp_cargoes, column));
2235 SetBit(this->supp_cargoes, column);
2236 } else {
2237 assert(!HasBit(this->cust_cargoes, column));
2238 SetBit(this->cust_cargoes, column);
2239 }
2240
2241 return column;
2242 }
2243
2250 CargoSlotMask GetConnections(bool accepting, bool supplying) const
2251 {
2252 CargoSlotMask mask = 0;
2253 if (accepting) mask |= this->supp_cargoes;
2254 if (supplying) mask |= this->cust_cargoes;
2255 return mask;
2256 }
2257};
2258
2261public:
2262 std::array<CargoType, ChainField::MAX_CARGOES> other_produced;
2263 std::array<CargoType, ChainField::MAX_CARGOES> other_accepted;
2264
2269 {
2270 this->other_produced.fill(INVALID_CARGO);
2271 this->other_accepted.fill(INVALID_CARGO);
2272 }
2273
2274 void Draw(Rect r) const override
2275 {
2276 bool rtl = _current_text_dir == TD_RTL;
2277
2278 /* Draw the other_produced/other_accepted cargoes. */
2279 std::span<const CargoType> other_right, other_left;
2280 if (rtl) {
2281 other_right = this->other_accepted;
2282 other_left = this->other_produced;
2283 } else {
2284 other_right = this->other_produced;
2285 other_left = this->other_accepted;
2286 }
2287
2288 /* Draw the unconnected cargo stubs. */
2290 for (uint i = 0; i < ChainField::max_cargoes; ++i) {
2291 if (IsValidCargoType(other_right[i])) {
2292 Rect r_stub = r.WithX(r.right + 1, r.right + ChainField::cargo_stub.width);
2294 GfxFillRect(r_stub.Shrink({0, WidgetDimensions::scaled.bevel.top, WidgetDimensions::scaled.bevel.right, WidgetDimensions::scaled.bevel.bottom}), CargoSpec::Get(other_right[i])->legend_colour);
2295 }
2296
2297 if (IsValidCargoType(other_left[i])) {
2298 Rect r_stub = r.WithX(r.left - ChainField::cargo_stub.width, r.left - 1);
2300 GfxFillRect(r_stub.Shrink({WidgetDimensions::scaled.bevel.left, WidgetDimensions::scaled.bevel.top, 0, WidgetDimensions::scaled.bevel.bottom}), CargoSpec::Get(other_left[i])->legend_colour);
2301 }
2302
2304 }
2305 }
2306
2307 ClickedAtResult ClickedAt(Rect r, Point pt) const override
2308 {
2309 /* Click is outside the rect, check the cargo stubs. */
2310 bool rtl = _current_text_dir == TD_RTL;
2311
2312 std::span<const CargoType> other_right, other_left;
2313 if (rtl) {
2314 other_right = this->other_accepted;
2315 other_left = this->other_produced;
2316 } else {
2317 other_right = this->other_produced;
2318 other_left = this->other_accepted;
2319 }
2320
2322 for (uint i = 0; i < ChainField::max_cargoes; ++i) {
2323 if (IsValidCargoType(other_right[i])) {
2324 Rect r_stub = r.WithX(r.right + 1, r.right + ChainField::cargo_stub.width);
2325 if (r_stub.Contains(pt)) return other_right[i];
2326 }
2327
2328 if (IsValidCargoType(other_left[i])) {
2329 Rect r_stub = r.WithX(r.left - ChainField::cargo_stub.width, r.left - 1);
2330 if (r_stub.Contains(pt)) return other_left[i];
2331 }
2332
2334 }
2335
2336 return {};
2337 }
2338
2344
2350};
2351
2354public:
2355 IndustryType industry_type;
2357
2363 {
2364 const IndustrySpec *indsp = GetIndustrySpec(this->industry_type);
2366 this->colour = Colours::LightBlue;
2367 } else if (indsp->life_type.Test(IndustryLifeType::Processing)) {
2368 this->colour = Colours::Brown;
2369 } else if (indsp->life_type.Test(IndustryLifeType::Organic)) {
2370 this->colour = Colours::DarkGreen;
2371 } else {
2372 /* Black hole industry */
2373 this->colour = Colours::Mauve;
2374 }
2375 }
2376
2377 void Draw(Rect r) const override
2378 {
2379 const IndustrySpec *indsp = GetIndustrySpec(this->industry_type);
2380 DrawFrameRect(r, this->colour, {});
2381 DrawStringMultiLine(r.Shrink(WidgetDimensions::scaled.frametext), indsp->name, TextColour::White, {AlignmentH::Centre, AlignmentV::Middle}, false, ChainField::fontsize);
2382
2384 GfxFillRect(blob, PC_BLACK);
2386
2388 }
2389
2390 ClickedAtResult ClickedAt(Rect r, Point pt) const override
2391 {
2392 if (r.Contains(pt)) return this->industry_type;
2393 return this->AcceptsProducesChainField::ClickedAt(r, pt);
2394 }
2395
2397 {
2398 const IndustrySpec *indsp = GetIndustrySpec(this->industry_type);
2399 return CargoTypes(indsp->produced_cargo);
2400 }
2401
2403 {
2404 const IndustrySpec *indsp = GetIndustrySpec(this->industry_type);
2405 return CargoTypes(indsp->accepts_cargo);
2406 }
2407};
2408
2411public:
2412 void Draw(Rect r) const override
2413 {
2415 DrawStringMultiLine(r.Shrink(WidgetDimensions::scaled.frametext), STR_INDUSTRY_CARGOES_HOUSES, TextColour::White, {AlignmentH::Centre, AlignmentV::Middle}, false, ChainField::fontsize);
2416
2418 }
2419
2420 ClickedAtResult ClickedAt(Rect r, Point pt) const override
2421 {
2422 if (r.Contains(pt)) return HouseID{};
2423 return this->AcceptsProducesChainField::ClickedAt(r, pt);
2424 }
2425
2427 {
2429 }
2430
2432 {
2434 }
2435};
2436
2439public:
2440 std::array<CargoType, ChainField::MAX_CARGOES> cargo_types;
2442
2448 CargoChainField(std::span<const CargoType> cargo_types, Alignment align) : align(align)
2449 {
2450 assert(std::size(cargo_types) <= std::size(this->cargo_types));
2451
2452 auto r = std::ranges::copy(cargo_types, std::begin(this->cargo_types));
2453 std::fill(r.out, std::end(this->cargo_types), INVALID_CARGO);
2454 }
2455
2456 void Draw(Rect r) const override
2457 {
2459
2460 for (uint i = 0; i < ChainField::MAX_CARGOES; ++i) {
2461 if (IsValidCargoType(this->cargo_types[i])) {
2462 DrawString(r.Shrink(WidgetDimensions::scaled.framerect, RectPadding::zero), CargoSpec::Get(this->cargo_types[i])->name, TextColour::White, this->align, false, ChainField::fontsize);
2463 }
2465 }
2466 }
2467
2468 ClickedAtResult ClickedAt(Rect r, Point pt) const override
2469 {
2472
2473 for (CargoType cargo_type : this->cargo_types) {
2474 if (!IsValidCargoType(cargo_type)) break;
2475 if (r.Contains(pt)) return cargo_type;
2477 }
2478
2479 return {};
2480 }
2481};
2482
2485public:
2486 static const int MAX_COLUMNS = 5;
2487 std::array<std::unique_ptr<ChainField>, MAX_COLUMNS> columns{};
2488
2494 static bool IsValidColumn(int column)
2495 {
2496 return column >= 0 && column < static_cast<int>(std::tuple_size_v<decltype(ChainRow::columns)>);
2497 }
2498
2503 int Height() const
2504 {
2505 int height = 0;
2506 for (const std::unique_ptr<ChainField> &fld : this->columns) {
2507 if (fld == nullptr) continue;
2508 height = std::max(height, fld->Height());
2509 }
2510 return height;
2511 }
2512
2517 void Draw(Rect r) const
2518 {
2519 bool rtl = _current_text_dir == TD_RTL;
2520 for (int col = 0; col < MAX_COLUMNS; ++col) {
2522 if (this->columns[col] != nullptr) this->columns[col]->Draw(r.WithWidth(width, rtl));
2523 r = r.Indent(width, rtl);
2524 }
2525 }
2526
2534 {
2535 bool rtl = _current_text_dir == TD_RTL;
2536
2537 for (int col = 0; col < MAX_COLUMNS; ++col) {
2539 Rect r_col = r.WithWidth(width, rtl);
2540
2541 if (IsValidColumn(col) && this->columns[col] != nullptr) {
2542 auto result = this->columns[col]->ClickedAt(r_col, pt);
2543 if (!std::holds_alternative<std::monostate>(result)) return result;
2544 }
2545
2546 r = r.Indent(width, rtl);
2547 }
2548
2549 return {};
2550 }
2551
2556 void ConnectProducedCargo(int column)
2557 {
2558 assert(IsValidColumn(column));
2559 AcceptsProducesChainField *ind_fld = this->columns[column]->Get<AcceptsProducesChainField>();
2560 ConnectionChainField *conn_fld = IsValidColumn(column + 1) ? this->columns[column + 1]->Get<ConnectionChainField>() : nullptr;
2561 assert(ind_fld != nullptr);
2562
2563 ind_fld->other_produced.fill(INVALID_CARGO);
2564 CargoTypes others = ind_fld->GetProduced();
2565
2566 ChainField::CargoSlotMask used_slots{};
2567 if (conn_fld != nullptr) {
2568 for (CargoType cargo_type : others) {
2569 if (conn_fld->ConnectCargo(cargo_type, true) >= 0) others.Reset(cargo_type);
2570 }
2571 used_slots = conn_fld->supp_cargoes;
2572 }
2573
2574 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2575 auto it = others.begin();
2576 auto last = others.end();
2577 for (uint i = 0; i != ChainField::max_cargoes && it != last; ++i) {
2578 if (HasBit(used_slots, i)) continue;
2579 ind_fld->other_produced[i] = *it;
2580 ++it;
2581 }
2582 }
2583
2589 void MakeCargoLabel(int column, bool accepting)
2590 {
2591 assert(IsValidColumn(column) && IsValidColumn(accepting ? column - 1 : column + 1));
2592 assert(this->columns[column] == nullptr);
2593
2594 std::array<CargoType, ChainField::ChainField::MAX_CARGOES> cargo_types;
2595 cargo_types.fill(INVALID_CARGO);
2596
2597 ConnectionChainField *conn_fld = this->columns[accepting ? column - 1 : column + 1]->Get<ConnectionChainField>();
2598 assert(conn_fld != nullptr);
2599
2600 for (uint i = 0; i < conn_fld->num_cargoes; ++i) {
2601 int col = conn_fld->ConnectCargo(conn_fld->vertical_cargoes[i], !accepting);
2602 if (col >= 0) cargo_types[col] = conn_fld->vertical_cargoes[i];
2603 }
2604
2605 this->columns[column] = std::make_unique<CargoChainField>(cargo_types, accepting ? AlignmentH::Start : AlignmentH::End);
2606 }
2607
2612 void ConnectAcceptedCargo(int column)
2613 {
2614 assert(IsValidColumn(column));
2615 AcceptsProducesChainField *ind_fld = this->columns[column]->Get<AcceptsProducesChainField>();
2616 ConnectionChainField *conn_fld = IsValidColumn(column - 1) ? this->columns[column - 1]->Get<ConnectionChainField>() : nullptr;
2617 assert(ind_fld != nullptr);
2618
2619 ind_fld->other_accepted.fill(INVALID_CARGO);
2620 CargoTypes others = ind_fld->GetAccepted();
2621
2622 ChainField::CargoSlotMask used_slots{};
2623 if (conn_fld != nullptr) {
2624 for (CargoType cargo_type : others) {
2625 if (conn_fld->ConnectCargo(cargo_type, false) >= 0) others.Reset(cargo_type);
2626 }
2627 used_slots = conn_fld->cust_cargoes;
2628 }
2629
2630 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2631 auto it = others.begin();
2632 auto last = others.end();
2633 for (uint i = 0; i != ChainField::max_cargoes && it != last; ++i) {
2634 if (HasBit(used_slots, i)) continue;
2635 ind_fld->other_accepted[i] = *it;
2636 ++it;
2637 }
2638 }
2639};
2640
2647{
2648 auto op = [fs](const Dimension &d, const CargoSpec *cs) { return maxdim(d, GetStringBoundingBox(cs->name, fs)); };
2649 return std::accumulate(_sorted_cargo_specs.begin(), _sorted_cargo_specs.end(), Dimension{}, op);
2650}
2651
2658{
2659 auto op = [fs](const Dimension &d, IndustryType it) { return maxdim(d, GetStringBoundingBox(GetIndustrySpec(it)->name, fs)); };
2660 return std::accumulate(_sorted_industry_types.begin(), _sorted_industry_types.end(), Dimension{}, op);
2661}
2662
2689struct IndustryCargoesWindow : public Window {
2690 std::vector<std::pair<ChainField::ClickedAtResult, int>> history;
2691 size_t history_pos = 0;
2692
2693 std::vector<ChainRow> rows{};
2697 Scrollbar *vscroll = nullptr;
2698 static inline bool small = false;
2699
2700 IndustryCargoesWindow(int id) : Window(_industry_cargoes_desc)
2701 {
2702 this->OnInit();
2703 this->CreateNestedTree();
2704 this->vscroll = this->GetScrollbar(WID_IC_SCROLLBAR);
2705 this->FinishInitNested(0);
2706 this->OnInvalidateData(id);
2708 }
2709
2714 {
2715 this->SetWidgetDisabledState(WID_IC_NAVBACK, this->history_pos == 0);
2716 this->SetWidgetDisabledState(WID_IC_NAVFORWARD, this->history_pos + 1 >= this->history.size());
2717 this->SetDirty();
2718 }
2719
2724 {
2725 if (!this->history.empty()) this->history.erase(this->history.begin() + this->history_pos + 1, this->history.end());
2726 /* Limit history to 256 entries. */
2727 if (this->history.size() >= 256) this->history.erase(this->history.begin());
2728 this->history.emplace_back(this->ind_cargo, 0);
2729 this->history_pos = this->history.size() - 1;
2731 }
2732
2737 {
2738 if (!this->history.empty()) this->history[this->history_pos].second = this->GetScrollbar(WID_IC_SCROLLBAR)->GetPosition();
2739 }
2740
2745 void NavigateHistory(int delta)
2746 {
2747 if (delta == 0 || this->history.empty()) return;
2748
2749 this->history_pos = Clamp(static_cast<int>(this->history_pos) + delta, 0, static_cast<int>(this->history.size()) - 1);
2750
2751 this->ComputeDisplay(this->history[this->history_pos].first, false);
2752 this->GetScrollbar(WID_IC_SCROLLBAR)->SetPosition(this->history[this->history_pos].second);
2754 }
2755
2761 {
2762 uint max_cargoes = 0;
2763 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; ++it) {
2764 const IndustrySpec *indsp = GetIndustrySpec(it);
2765 if (!indsp->enabled) continue;
2766 max_cargoes = std::max<uint>(max_cargoes, std::ranges::count_if(indsp->accepts_cargo, IsValidCargoType));
2767 max_cargoes = std::max<uint>(max_cargoes, std::ranges::count_if(indsp->produced_cargo, IsValidCargoType));
2768 }
2769 return max_cargoes;
2770 }
2771
2778 {
2779 HouseZones climate_mask = GetClimateMaskForLandscape();
2780
2783
2784 /* Count cargoes accepted by houses. Houses are a single field, so we need the total across all house types. */
2785 for (const HouseSpec &hs : HouseSpec::Specs()) {
2786 if (!hs.enabled || !hs.building_availability.Any(climate_mask)) continue;
2787 ChainField::town_accepts.Set({hs.accepts_cargo});
2788 }
2789
2790 /* Count cargoes produced by town effects. */
2791 for (const CargoSpec *cs : _sorted_cargo_specs) {
2792 if (cs->town_production_effect != TownProductionEffect::None) ChainField::town_produces.Set(cs->Index());
2793 }
2794
2796 }
2797
2798 void OnInit() override
2799 {
2801
2802 /* Initialize static CargoesField size variables. */
2803 Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_SOURCES, ChainField::fontsize);
2804 d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_DESTINATIONS, ChainField::fontsize));
2805 ChainField::small_height = d.height + WidgetDimensions::scaled.frametext.Vertical();
2806
2807 /* Size of the legend blob -- same size as the smallmap legend blob. */
2810
2811 /* Size of cargo lines. */
2814
2815 /* Size of border between cargo lines and industry boxes. */
2818
2819 /* Size of space between cargo lines. */
2822
2823 /* Size of cargo stub (unconnected cargo line.) */
2824 ChainField::cargo_stub.width = ChainField::cargo_line.width * 2 / 3;
2825 ChainField::cargo_stub.height = ChainField::cargo_line.height; /* Unused */
2826
2829
2830 /* Get the number of cargo types that need to be displayed. */
2831 ChainField::max_cargoes = std::max<uint>(this->CountIndustryCargoTypes(), this->CountHouseCargoTypes());
2832
2833 /* Compute size of the cargo and industry labels. */
2836
2837 d.width += WidgetDimensions::scaled.frametext.Horizontal();
2838 /* Ensure the height is enough for all connections. */
2839 uint min_ind_height = ChainField::cargo_border.height * 2 + ChainField::GetConnectionHeight();
2840 d.height = std::max(d.height + WidgetDimensions::scaled.frametext.Vertical(), min_ind_height);
2841
2844
2845 /* Width of a cargo connection field. */
2847
2848 /* Compute size for cargo selection dropdown. */
2849 this->cargo_textsize = GetMaximalSizeCargoString();
2850 this->cargo_textsize.width += GetLargestCargoIconSize().width + WidgetDimensions::scaled.hsep_normal;
2851 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
2852
2853 /* Compute size for industry selection dropdown. */
2854 this->ind_textsize = maxdim(GetMaximalSizeIndustryString(), GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
2855 }
2856
2857 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2858 {
2859 switch (widget) {
2860 case WID_IC_PANEL:
2863 size.height = ChainField::small_height + 2 * resize.height + WidgetDimensions::scaled.frametext.Vertical();
2864 break;
2865
2867 size.width = std::max(size.width, this->ind_textsize.width + padding.width);
2868 break;
2869
2871 size.width = std::max(size.width, this->cargo_textsize.width + padding.width);
2872 break;
2873 }
2874 }
2875
2876 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
2877 {
2878 if (widget != WID_IC_CAPTION) return this->Window::GetWidgetString(widget, stringid);
2879
2880 struct visitor {
2881 std::string operator()(std::monostate) { return GetString(STR_NULL); }
2882 std::string operator()(IndustryType industry_type) { return GetString(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, GetIndustrySpec(industry_type)->name); }
2883 std::string operator()(CargoType cargo_type) { return GetString(STR_INDUSTRY_CARGOES_CARGO_CAPTION, CargoSpec::Get(cargo_type)->name); }
2884 std::string operator()(HouseID) { return GetString(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_INDUSTRY_CARGOES_HOUSES); }
2885 };
2886 return std::visit(visitor{}, this->ind_cargo);
2887 }
2888
2894 static bool HousesCanSupply(CargoTypes cargoes)
2895 {
2896 return ChainField::town_produces.Any(cargoes);
2897 }
2898
2904 static bool HousesCanAccept(CargoTypes cargoes)
2905 {
2906 return ChainField::town_accepts.Any(cargoes);
2907 }
2908
2915 {
2916 int count = 0;
2917 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2918 const IndustrySpec *indsp = GetIndustrySpec(it);
2919 if (!indsp->enabled) continue;
2920
2921 if (cargoes.Any({indsp->accepts_cargo})) ++count;
2922 }
2923 return count;
2924 }
2925
2932 {
2933 int count = 0;
2934 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; ++it) {
2935 const IndustrySpec *indsp = GetIndustrySpec(it);
2936 if (!indsp->enabled) continue;
2937
2938 if (cargoes.Any({indsp->produced_cargo})) ++count;
2939 }
2940 return count;
2941 }
2942
2952 void ShortenConnectionsColumn(int column, int top, int middle, int bottom, bool accepting, bool supplying)
2953 {
2955
2956 for (int i = top; i <= middle; ++i) {
2957 ConnectionChainField *fld = this->rows[i].columns[column]->Get<ConnectionChainField>();
2958 if (fld == nullptr) continue;
2959
2960 fld->top_end = last_skip;
2961
2962 if (accepting && this->rows[i].columns[column + 1]->Get<CargoChainField>() != nullptr) break;
2963 if (i == middle) break;
2964
2965 /* Skip cargos until they are first connected. */
2966 fld->skip_cargoes = last_skip & ~fld->GetConnections(accepting, supplying);
2967 last_skip = fld->skip_cargoes;
2968 }
2969
2971 for (int i = bottom; i >= middle; --i) {
2972 ConnectionChainField *fld = this->rows[i].columns[column]->Get<ConnectionChainField>();
2973 if (fld == nullptr) continue;
2974
2975 fld->bottom_end = last_skip;
2976
2977 if (supplying && this->rows[i].columns[column - 1]->Get<CargoChainField>() != nullptr) break;
2978 if (i == middle) break;
2979
2980 /* Skip cargos until they are first connected. */
2981 fld->skip_cargoes = last_skip & ~fld->GetConnections(accepting, supplying);
2982 last_skip = fld->skip_cargoes;
2983 }
2984 }
2985
2992 void PlaceAndConnect(std::unique_ptr<AcceptsProducesChainField> &&field, int row, int col)
2993 {
2994 assert(this->rows[row].columns[col] == nullptr);
2995 this->rows[row].columns[col] = std::move(field);
2996 this->rows[row].ConnectProducedCargo(col);
2997 this->rows[row].ConnectAcceptedCargo(col);
2998 }
2999
3004 {
3005 if (!this->IsWidgetLowered(WID_IC_NOTIFY)) return;
3006
3007 /* Only notify the smallmap window if it exists. In particular, do not
3008 * bring it to the front to prevent messing up any nice layout of the user. */
3009 InvalidateWindowClassesData(WindowClass::SmallMap, 0);
3010 }
3011
3018 void ComputeAcceptsProducesIndustryDisplay(std::unique_ptr<AcceptsProducesChainField> &&field, CargoTypes accepts, CargoTypes produces)
3019 {
3020 this->rows.clear();
3021 ChainRow &first_row = this->rows.emplace_back();
3022 first_row.columns[0] = std::make_unique<HeaderChainField>(STR_INDUSTRY_CARGOES_SOURCES);
3023 first_row.columns[4] = std::make_unique<HeaderChainField>(STR_INDUSTRY_CARGOES_DESTINATIONS);
3024
3025 bool houses_supply = HousesCanSupply(accepts);
3026 bool houses_accept = HousesCanAccept(produces);
3027
3028 int num_supp = CountMatchingProducingIndustries(accepts) + houses_supply;
3029 int num_cust = CountMatchingAcceptingIndustries(produces) + houses_accept;
3030 int num_indrows = std::max(3, std::max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
3031
3032 /* Make a field consisting of two cargo columns. */
3033 for (int i = 0; i < num_indrows; i++) {
3034 ChainRow &row = this->rows.emplace_back();
3035 row.columns[1] = std::make_unique<ConnectionChainField>(accepts);
3036 row.columns[3] = std::make_unique<ConnectionChainField>(produces);
3037 }
3038
3039 /* Add central accepts/produces field. */
3040 int central_row = 1 + num_indrows / 2;
3041 this->rows[central_row].columns[2] = std::move(field);
3042 this->rows[central_row].ConnectProducedCargo(2);
3043 this->rows[central_row].ConnectAcceptedCargo(2);
3044
3045 /* Add cargo labels. */
3046 this->rows[central_row - 1].MakeCargoLabel(2, true);
3047 this->rows[central_row + 1].MakeCargoLabel(2, false);
3048
3049 /* Determine start positions, with different rounding to look better with the label position for each side. */
3050 int supp_pos = 1 + (num_indrows + 1 - num_supp) / 2;
3051 int cust_pos = 1 + (num_indrows - num_cust) / 2;
3052
3053 /* Add suppliers and customers. */
3054 for (IndustryType it : _sorted_industry_types) {
3055 const IndustrySpec *indsp = GetIndustrySpec(it);
3056 if (!indsp->enabled) continue;
3057
3058 if (accepts.Any({indsp->produced_cargo})) {
3059 this->PlaceAndConnect(std::make_unique<IndustryChainField>(it), supp_pos++, 0);
3060 _displayed_industries.set(it);
3061 }
3062 if (produces.Any({indsp->accepts_cargo})) {
3063 this->PlaceAndConnect(std::make_unique<IndustryChainField>(it), cust_pos++, 4);
3064 _displayed_industries.set(it);
3065 }
3066 }
3067
3068 if (houses_supply) this->PlaceAndConnect(std::make_unique<HouseChainField>(), supp_pos++, 0);
3069 if (houses_accept) this->PlaceAndConnect(std::make_unique<HouseChainField>(), cust_pos++, 4);
3070
3071 this->ShortenConnectionsColumn(1, 1, central_row, num_indrows, true, false);
3072 this->ShortenConnectionsColumn(3, 1, central_row, num_indrows, false, true);
3073 this->vscroll->SetCount(num_indrows);
3074 this->SetDirty();
3075 this->NotifySmallmap();
3076 }
3077
3083 bool ComputeIndustryDisplay(IndustryType industry_type)
3084 {
3085 if (industry_type >= NUM_INDUSTRYTYPES) return false;
3086 if (const IndustryType *ptr = std::get_if<IndustryType>(&this->ind_cargo); ptr != nullptr && *ptr == industry_type) return false;
3087
3088 this->ind_cargo = industry_type;
3089 _displayed_industries.reset();
3090 _displayed_industries.set(industry_type);
3091
3092 const IndustrySpec *indsp = GetIndustrySpec(industry_type);
3093 ComputeAcceptsProducesIndustryDisplay(std::make_unique<IndustryChainField>(industry_type), {indsp->accepts_cargo}, {indsp->produced_cargo});
3094 return true;
3095 }
3096
3102 {
3103 if (const HouseID *ptr = std::get_if<HouseID>(&this->ind_cargo); ptr != nullptr && *ptr == HouseID{}) return false;
3104
3105 /* All houses are handled by a single House field, so the HouseID value itself does not matter. */
3106 this->ind_cargo = HouseID{};
3107 _displayed_industries.reset();
3108
3110 return true;
3111 }
3112
3119 {
3120 if (!IsValidCargoType(cargo_type)) return false;
3121 if (const CargoType *ptr = std::get_if<CargoType>(&this->ind_cargo); ptr != nullptr && *ptr == cargo_type) return false;
3122
3123 this->ind_cargo = cargo_type;
3124 _displayed_industries.reset();
3125
3126 this->rows.clear();
3127 ChainRow &first_row = this->rows.emplace_back();
3128 first_row.columns[0] = std::make_unique<HeaderChainField>(STR_INDUSTRY_CARGOES_SOURCES);
3129 first_row.columns[2] = std::make_unique<HeaderChainField>(STR_INDUSTRY_CARGOES_DESTINATIONS);
3130
3131 CargoTypes cargoes = cargo_type;
3132 bool houses_supply = HousesCanSupply(cargoes);
3133 bool houses_accept = HousesCanAccept(cargoes);
3134 int num_supp = CountMatchingProducingIndustries(cargoes) + houses_supply + 1; // Ensure room for the cargo label.
3135 int num_cust = CountMatchingAcceptingIndustries(cargoes) + houses_accept;
3136 int num_indrows = std::max(num_supp, num_cust);
3137 for (int i = 0; i < num_indrows; i++) {
3138 ChainRow &row = this->rows.emplace_back();
3139 row.columns[1] = std::make_unique<ConnectionChainField>(cargoes);
3140 }
3141
3142 /* Add suppliers and customers of the cargo. */
3143 int supp_pos = 1 + (num_indrows - num_supp) / 2;
3144 int cust_pos = 1 + (num_indrows - num_cust) / 2;
3145 for (IndustryType it : _sorted_industry_types) {
3146 const IndustrySpec *indsp = GetIndustrySpec(it);
3147 if (!indsp->enabled) continue;
3148
3149 if (cargoes.Any({indsp->produced_cargo})) {
3150 this->PlaceAndConnect(std::make_unique<IndustryChainField>(it), supp_pos++, 0);
3151 _displayed_industries.set(it);
3152 }
3153 if (cargoes.Any({indsp->accepts_cargo})) {
3154 this->PlaceAndConnect(std::make_unique<IndustryChainField>(it), cust_pos++, 2);
3155 _displayed_industries.set(it);
3156 }
3157 }
3158 if (houses_supply) this->PlaceAndConnect(std::make_unique<HouseChainField>(), supp_pos++, 0);
3159 if (houses_accept) this->PlaceAndConnect(std::make_unique<HouseChainField>(), cust_pos++, 2);
3160
3161 this->rows[supp_pos].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
3162
3163 this->ShortenConnectionsColumn(1, 1, num_indrows, num_indrows, true, true);
3164 this->vscroll->SetCount(num_indrows);
3165 this->SetDirty();
3166 this->NotifySmallmap();
3167 return true;
3168 }
3169
3177 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
3178 {
3179 if (!gui_scope) return;
3180 if (data == NUM_INDUSTRYTYPES) {
3182 return;
3183 }
3184
3185 assert(data >= 0 && data < NUM_INDUSTRYTYPES);
3186 this->ComputeDisplay(static_cast<IndustryType>(data));
3187 }
3188
3194 Rect GetRowRect(const Rect &r) const
3195 {
3197 bool showing_cargo = std::holds_alternative<CargoType>(this->ind_cargo);
3198
3199 return r
3201 .Translate(0, -this->vscroll->GetPosition() * nw->resize_y)
3202 .CentreToWidth(showing_cargo
3205 }
3206
3207 void DrawWidget(const Rect &r, WidgetID widget) const override
3208 {
3209 if (widget != WID_IC_PANEL) return;
3210
3211 Rect ir = r.Shrink(WidgetDimensions::scaled.bevel);
3212 DrawPixelInfo tmp_dpi;
3213 if (!FillDrawPixelInfo(&tmp_dpi, ir)) return;
3214 /* Keep coordinates relative to the window. */
3215 tmp_dpi.left += ir.left;
3216 tmp_dpi.top += ir.top;
3217 AutoRestoreBackup dpi_backup(_cur_dpi, &tmp_dpi);
3218
3219 Rect r_row = this->GetRowRect(r);
3220 for (const ChainRow &row : this->rows) {
3221 int row_height = row.Height();
3222 row.Draw(r_row.WithHeight(row_height));
3223 r_row = r_row.Translate(0, row_height + ChainField::vert_inter_industry_space);
3224 }
3225 }
3226
3233 {
3235 Rect r = this->GetRowRect(nw->GetCurrentRect());
3236
3237 for (auto it = this->rows.begin(); it != this->rows.end(); ++it) {
3238 uint row_height = it->Height();
3239
3240 auto result = it->ClickedAt(r.WithHeight(row_height), pt);
3241 if (!std::holds_alternative<std::monostate>(result)) return result;
3242
3243 r = r.Translate(0, row_height + ChainField::vert_inter_industry_space);
3244 }
3245
3246 return {};
3247 }
3248
3254 void ComputeDisplay(ChainField::ClickedAtResult clicked_at, bool update_history = true)
3255 {
3256 if (update_history) this->UpdateHistoryScrollpos();
3257
3258 struct visitor {
3259 IndustryCargoesWindow *w;
3260 bool operator()(std::monostate) { return false; }
3261 bool operator()(HouseID) { return this->w->ComputeHouseDisplay(); }
3262 bool operator()(IndustryType industry_type) { return this->w->ComputeIndustryDisplay(industry_type); }
3263 bool operator()(CargoType cargo_type) { return this->w->ComputeCargoDisplay(cargo_type); }
3264 };
3265 if (std::visit(visitor{this}, clicked_at) && update_history) {
3266 this->AppendHistory();
3267 SndClickBeep();
3268 }
3269 }
3270
3271 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
3272 {
3273 switch (widget) {
3274 case WID_IC_TOGGLE_SIZE:
3275 this->small = !this->small;
3276 this->ReInit();
3277 break;
3278
3279 case WID_IC_PANEL:
3280 this->ComputeDisplay(this->ClickedAt(pt));
3281 break;
3282
3283 case WID_IC_NAVBACK:
3284 this->NavigateHistory(-1);
3285 break;
3286
3287 case WID_IC_NAVFORWARD:
3288 this->NavigateHistory(+1);
3289 break;
3290
3291 case WID_IC_NOTIFY:
3294 SndClickBeep();
3295
3296 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
3297 if (FindWindowByClass(WindowClass::SmallMap) == nullptr) ShowSmallMap();
3298 this->NotifySmallmap();
3299 }
3300 break;
3301
3302 case WID_IC_CARGO_DROPDOWN: {
3303 DropDownList lst;
3305 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
3306 lst.push_back(MakeDropDownListIconItem(d, cs->GetCargoIcon(), PAL_NONE, cs->name, cs->Index()));
3307 }
3308 if (!lst.empty()) {
3309 static std::string cargo_filter;
3310 int selected = -1;
3311 if (CargoType *ptr = std::get_if<CargoType>(&this->ind_cargo); ptr != nullptr) selected = to_underlying(*ptr);
3312 ShowDropDownList(this, std::move(lst), selected, WID_IC_CARGO_DROPDOWN, 0, DropDownOption::Filterable, &cargo_filter);
3313 }
3314 break;
3315 }
3316
3317 case WID_IC_IND_DROPDOWN: {
3318 DropDownList lst;
3319 for (IndustryType ind : _sorted_industry_types) {
3320 const IndustrySpec *indsp = GetIndustrySpec(ind);
3321 if (!indsp->enabled) continue;
3322 lst.push_back(MakeDropDownListStringItem(indsp->name, ind));
3323 }
3324 if (!lst.empty()) lst.push_back(MakeDropDownListDividerItem());
3325 lst.push_back(MakeDropDownListStringItem(STR_INDUSTRY_CARGOES_HOUSES, INT_MAX));
3326 if (!lst.empty()) {
3327 static std::string cargo_filter;
3328 int selected = -1;
3329 if (IndustryType *ptr = std::get_if<IndustryType>(&this->ind_cargo); ptr != nullptr) {
3330 selected = *ptr;
3331 } else if (std::holds_alternative<HouseID>(this->ind_cargo)) {
3332 selected = INT_MAX;
3333 }
3334 ShowDropDownList(this, std::move(lst), selected, WID_IC_IND_DROPDOWN, 0, DropDownOption::Filterable, &cargo_filter);
3335 }
3336 break;
3337 }
3338 }
3339 }
3340
3341 void OnX1Click([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget) override
3342 {
3343 this->NavigateHistory(-1);
3344 }
3345
3346 void OnX2Click([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget) override
3347 {
3348 this->NavigateHistory(1);
3349 }
3350
3351 void OnDropdownSelect(WidgetID widget, int index, int) override
3352 {
3353 switch (widget) {
3355 if (index >= 0) this->ComputeDisplay(static_cast<CargoType>(index));
3356 break;
3357
3359 if (index == INT_MAX) {
3360 this->ComputeDisplay(HouseID{});
3361 } else if (index >= 0) {
3362 this->ComputeDisplay(static_cast<IndustryType>(index));
3363 }
3364 break;
3365 }
3366 }
3367
3368 bool OnTooltip([[maybe_unused]] Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
3369 {
3370 if (widget != WID_IC_PANEL) return false;
3371
3372 struct visitor {
3373 IndustryCargoesWindow *w;
3374 TooltipCloseCondition close_cond;
3375 bool operator()(std::monostate)
3376 {
3377 return false;
3378 }
3379 bool operator()(HouseID)
3380 {
3381 GuiShowTooltips(this->w, GetEncodedString(STR_INDUSTRY_CARGOES_ACCEPTS_PRODUCES_TOOLTIP, STR_INDUSTRY_CARGOES_HOUSES, ChainField::town_accepts, ChainField::town_produces), this->close_cond);
3382 return true;
3383 }
3384 bool operator()(IndustryType industry_type)
3385 {
3386 const IndustrySpec *indsp = GetIndustrySpec(industry_type);
3387 GuiShowTooltips(this->w, GetEncodedString(STR_INDUSTRY_CARGOES_ACCEPTS_PRODUCES_TOOLTIP, indsp->name, CargoTypes{indsp->accepts_cargo}, CargoTypes{indsp->produced_cargo}), this->close_cond);
3388 return true;
3389 }
3390 bool operator()(CargoType cargo_type)
3391 {
3392 if (!IsValidCargoType(cargo_type)) return false;
3393 GuiShowTooltips(this->w, GetEncodedString(CargoSpec::Get(cargo_type)->name), close_cond);
3394 return true;
3395 }
3396 };
3397
3398 return std::visit(visitor{this, close_cond}, this->ClickedAt(pt));
3399 }
3400
3401 void OnResize() override
3402 {
3403 this->vscroll->SetCapacityFromWidget(this, WID_IC_PANEL, WidgetDimensions::scaled.framerect.Vertical() + ChainField::small_height);
3404 }
3405};
3406
3411static void ShowIndustryCargoesWindow(IndustryType id)
3412{
3413 if (id >= NUM_INDUSTRYTYPES) {
3414 for (IndustryType ind : _sorted_industry_types) {
3415 const IndustrySpec *indsp = GetIndustrySpec(ind);
3416 if (indsp->enabled) {
3417 id = ind;
3418 break;
3419 }
3420 }
3421 if (id >= NUM_INDUSTRYTYPES) return;
3422 }
3423
3424 Window *w = BringWindowToFrontById(WindowClass::IndustryCargoes, 0);
3425 if (w != nullptr) {
3426 w->InvalidateData(id);
3427 return;
3428 }
3429 new IndustryCargoesWindow(id);
3430}
3431
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Types related to cargoes...
static constexpr CargoType INVALID_CARGO
Invalid marker for cargoes.
Definition cargo_type.h:83
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
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
Dimension GetLargestCargoIconSize()
Get dimensions of largest cargo icon.
std::span< const CargoSpec * > _sorted_standard_cargo_specs
Standard cargo specifications sorted alphabetically by name.
std::vector< const CargoSpec * > _sorted_cargo_specs
Cargo specifications sorted alphabetically by name.
@ None
Town will not produce this cargo type.
Definition cargotype.h:36
Cheats _cheats
All the cheats.
Definition cheat.cpp:16
Types related to cheating.
Field representing something that accepts and produces cargo.
ClickedAtResult ClickedAt(Rect r, Point pt) const override
Decide which industry/house or cargo was clicked at.
virtual CargoTypes GetProduced()=0
Connected the cargo types produced by this field.
virtual CargoTypes GetAccepted()=0
Connected the cargo types accepted by this field.
std::array< CargoType, ChainField::MAX_CARGOES > other_accepted
Cargoes accepted but not used in this figure.
void Draw(Rect r) const override
Draw the field.
AcceptsProducesChainField()
Construct a new Accepts/Produces chain field.
std::array< CargoType, ChainField::MAX_CARGOES > other_produced
Cargoes produced but not used in this figure.
uint Count() const
Count the number of set bits.
auto end() const
Returns an iterator to the end of the set bits.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
auto begin() const
Returns an iterator to begin of the set bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Build (fund or prospect) a new industry,.
IndustryType selected_type
industry corresponding to the above index
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Dimension legend
Dimension of the legend 'blob'.
void OnInit() override
Notification that the nested widget tree gets initialized.
void SetButtons()
Update status of the fund and display-chain widgets.
static const int MAX_MINWIDTH_LINEHEIGHTS
The largest allowed minimum-width of the window, given in line heights.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnPlaceObject(Point pt, TileIndex tile) override
The user clicked some place on the map when a tile highlight mode has been set.
void OnPlaceObjectAbort() override
The user cancelled a tile highlight mode that has been set.
std::string MakeCargoListString(const std::span< const CargoType > cargolist, const std::span< const CargoSuffix > cargo_suffix, StringID prefixstr) const
Build a string of cargo names with suffixes attached.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void OnTimeout() override
Called when this window's timeout has been reached.
void OnResize() override
Called after the window got resized.
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.
std::vector< IndustryType > list
List of industries.
bool enabled
Availability state of the selected industry.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
ClickedAtResult ClickedAt(Rect r, Point pt) const override
Decide which industry/house or cargo was clicked at.
Alignment align
The text alignment.
void Draw(Rect r) const override
Draw the field.
std::array< CargoType, ChainField::MAX_CARGOES > cargo_types
Cargoes to display (or INVALID_CARGO).
CargoChainField(std::span< const CargoType > cargo_types, Alignment align)
Construct a new cargo label chain field.
Base cargo chain field.
const T * Get() const
Get this field as a specific type implemention.
static constexpr CargoSlotMask ALL_CARGO_SLOTS
Value representing all cargo slots.
static uint max_cargoes
Largest number of cargoes actually on any industry.
static Dimension cargo_border
Dimensions of border between cargo lines and industry boxes.
std::variant< std::monostate, HouseID, IndustryType, CargoType > ClickedAtResult
Result type of testing clicked position.
static int normal_height
Height of the non-header rows.
uint16_t CargoSlotMask
Type representing a mask of cargo slots.
static Dimension cargo_line
Dimensions of cargo lines.
static CargoTypes town_produces
Mask of cargo types produced by towns.
static constexpr PixelColour CARGO_LINE_COLOUR
Line colour around the cargo.
static int connection_field_width
Width of a cargo connection field.
static uint GetConnectionHeight()
Get the height of all cargo connections in a row.
virtual int Width() const
Get the width of this field.
static constexpr uint MAX_CARGOES
Maximum number of cargoes carried in a field.
static int industry_width
Width of an industry field.
T * Get()
Get this field as a specific type implemention.
virtual ClickedAtResult ClickedAt(Rect r, Point pt) const
Decide which industry/house or cargo was clicked at.
virtual int Height() const
Get the height of this field.
static int blob_distance
Distance of the industry legend colour from the edge of the industry box.
static Dimension legend
Dimension of the legend blob.
static int vert_inter_industry_space
Amount of space between two industries in a column.
static CargoTypes town_accepts
Mask of cargo types accepted by towns.
static FontSize fontsize
Font size of industry chain strings.
static Dimension cargo_stub
Dimensions of cargo stub (unconnected cargo line.).
static Dimension cargo_space
Dimensions of space between cargo lines.
virtual void Draw(Rect r) const =0
Draw the field.
static int small_height
Height of the header row.
A single row of ChainField.
void Draw(Rect r) const
Draw this row of fields.
void ConnectAcceptedCargo(int column)
Connect accepted cargoes to the connection column before it.
ChainField::ClickedAtResult ClickedAt(Rect r, Point pt) const
Get the ClickedAt result for a field in this row.
static const int MAX_COLUMNS
Maximum number of columns in a row.
std::array< std::unique_ptr< ChainField >, MAX_COLUMNS > columns
One row of fields.
void MakeCargoLabel(int column, bool accepting)
Construct a Cargo chain field.
static bool IsValidColumn(int column)
Test if a given column index is valid.
void ConnectProducedCargo(int column)
Connect produced cargoes to the connection column after it.
int Height() const
Get the height of this row of fields.
Field representing cargo connections.
CargoSlotMask skip_cargoes
Stop at the top of the vertical cargoes.
void Draw(Rect r) const override
Draw the field.
int ConnectCargo(CargoType cargo, bool producer)
Connect a cargo to the cargo column.
CargoSlotMask supp_cargoes
Bitmask of cargoes in vertical_cargoes entering from the left.
CargoSlotMask cust_cargoes
Bitmask of cargoes in vertical_cargoes leaving to the right.
CargoSlotMask GetConnections(bool accepting, bool supplying) const
Get the cargo connections.
uint8_t num_cargoes
Number of cargoes.
std::array< CargoType, ChainField::MAX_CARGOES > vertical_cargoes
Cargoes running from top to bottom (cargo type or INVALID_CARGO).
ConnectionChainField(CargoTypes cargo_types)
Construct a new cargo connection chain field.
CargoSlotMask bottom_end
Stop at the bottom of the vertical cargoes.
CargoSlotMask top_end
Stop at the top of the vertical cargoes.
int Width() const override
Get the width of this field.
ClickedAtResult ClickedAt(Rect r, Point pt) const override
Decide which industry/house or cargo was clicked at.
std::string GetDecodedString() const
Decode the encoded string.
Definition strings.cpp:206
uint GetTotalColumnsWidth() const
Get total width of all columns.
List template of 'things' T to sort in a GUI.
bool Filter(FilterFunction *decide, F filter_data)
Filter the list.
void RebuildDone()
Notify the sortlist that the rebuild is done.
void SetListing(Listing l)
Import sort conditions.
void SetFilterState(bool state)
Enable or disable the filter.
bool IsDescSortOrder() const
Check if the sort order is descending.
void ToggleSortOrder()
Toggle the sort order Since that is the worst condition for the sort function reverse the list here.
void SetFilterFuncs(std::span< FilterFunction *const > n_funcs)
Hand the filter function pointers to the GUIList.
bool NeedRebuild() const
Check if a rebuild is needed.
void SetFilterType(uint8_t n_type)
Set the filtertype of the list.
void ForceRebuild()
Force that a rebuild is needed.
bool Sort(Comp compare)
Sort the list.
void ForceResort()
Force a resort next Sort call Reset the resort timer if used too.
uint8_t SortType() const
Get the sorttype of the list.
bool(const const Industry **item, const std::pair< CargoType, CargoType > &filter) FilterFunction
Listing GetListing() const
Export current sort conditions.
void SetSortFuncs(std::span< SortFunction *const > n_funcs)
Hand the sort function pointers to the GUIList.
void SetSortType(uint8_t n_type)
Set the sorttype of the list.
void Draw(Rect r) const override
Draw the field.
int Height() const override
Get the height of this field.
HeaderChainField(StringID header)
Construct a new Header chain field.
StringID header
Header string.
Field representing a house.
CargoTypes GetProduced() override
Connected the cargo types produced by this field.
CargoTypes GetAccepted() override
Connected the cargo types accepted by this field.
void Draw(Rect r) const override
Draw the field.
ClickedAtResult ClickedAt(Rect r, Point pt) const override
Decide which industry/house or cargo was clicked at.
ClickedAtResult ClickedAt(Rect r, Point pt) const override
Decide which industry/house or cargo was clicked at.
IndustryChainField(IndustryType industry_type)
Construct a new Industry chain field.
CargoTypes GetAccepted() override
Connected the cargo types accepted by this field.
IndustryType industry_type
Industry type (NUM_INDUSTRYTYPES means 'houses').
void Draw(Rect r) const override
Draw the field.
CargoTypes GetProduced() override
Connected the cargo types produced by this field.
Colours colour
Colour for this industry.
The list of industries.
~IndustryDirectoryWindow() override
Save the last sorting state.
const IntervalTimer< TimerWindow > rebuild_interval
Rebuild the industry list on a regular interval.
void OnEditboxChanged(WidgetID wid) override
The text in an editbox has been edited.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
static bool IndustryTypeSorter(const Industry *const &a, const Industry *const &b, const CargoType &filter)
Sort industries by type and name.
static int GetCargoTransportedSortValue(const Industry *i)
Returns value representing industry's transported cargo percentage for industry sorting.
static const StringID sorter_names[]
Strings describing how industries are sorted.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
const int MAX_FILTER_LENGTH
The max length of the filter, in chars.
void SetCargoFilterArray()
Populate the filter list and set the cargo filter criteria.
void OnResize() override
Called after the window got resized.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void SetProducedCargoFilter(CargoType cargo_type)
Set produced cargo filter for the industry list.
static int GetCargoTransportedPercentsIfValid(const Industry::ProducedCargo &p)
Returns percents of cargo transported if industry produces this cargo, else -1.
SorterType
Ways to sort industries.
@ ByName
Sorter type to sort by name.
@ ByTransported
Sorter type to sort by transported percentage.
@ ByProduction
Sorter type to sort by production amount.
@ ByType
Sorter type to sort by type.
std::string GetIndustryString(const Industry *i) const
Get the StringID to draw and set the appropriate DParams.
uint GetIndustryListWidth() const
Get the width needed to draw the longest industry line.
static const std::initializer_list< GUIIndustryList::SortFunction *const > sorter_funcs
Functions to sort industries.
static bool IndustryTransportedCargoSorter(const Industry *const &a, const Industry *const &b, const CargoType &filter)
Sort industries by transported cargo and name.
QueryString industry_editbox
Filter editbox.
StringFilter string_filter
Filter for industries.
static bool IndustryProductionSorter(const Industry *const &a, const Industry *const &b, const CargoType &filter)
Sort industries by production and name.
static bool IndustryNameSorter(const Industry *const &a, const Industry *const &b, const CargoType &filter)
Sort industries by name.
void BuildSortIndustriesList()
(Re)Build industries list
CargoType accepted_cargo_filter_criteria
Selected accepted cargo filter index.
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 OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void SetAcceptedCargoFilter(CargoType cargo_type)
Set accepted cargo filter for the industry list.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
CargoType produced_cargo_filter_criteria
Selected produced cargo filter index.
void OnPaint() override
The window must be repainted.
void OnInit() override
Notification that the nested widget tree gets initialized.
void OnResize() override
Called after the window got resized.
int cheat_line_height
Height of each line for the WID_IV_INFO panel.
int production_offset_y
The offset of the production texts/buttons.
void OnPaint() override
The window must be repainted.
Editability editable
Mode for changing production.
ClickedCargoLine editbox_line
The line clicked to open the edit box.
void OnTimeout() override
Called when this window's timeout has been reached.
~IndustryViewWindow() override
Close the industry production window.
bool IsNewGRFInspectable() const override
Is the data related to this window NewGRF inspectable?
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
int info_height
Height needed for the WID_IV_INFO panel.
Dimension cargo_icon_size
Largest cargo icon dimension.
void OnMouseWheel(int wheel, WidgetID widget) override
The mouse wheel has been turned.
void ShowNewGRFInspectWindow() const override
Show the NewGRF inspection window.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
static constexpr ClickedCargoLine CCL_NONE
No cargo line has been clicked.
void OnInit() override
Notification that the nested widget tree gets initialized.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
uint8_t clicked_button
The button that has been clicked (to raise).
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
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.
int8_t ClickedCargoLine
Clicked cargo line in the info panel.
int DrawInfo(const Rect &r)
Draw the text in the WID_IV_INFO panel.
ClickedCargoLine clicked_line
The line of the button that has been clicked.
static constexpr ClickedCargoLine CCL_MULTIPLIER
Product multiplier line is clicked.
Editability
Modes for changing production.
@ Rate
Allow changing the production rates.
@ Multiplier
Allow changing the production multiplier.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
Baseclass for nested widgets.
uint resize_y
Vertical resize step (0 means not resizable).
Nested widget to display a viewport in a window.
void UpdateViewportCoordinates(Window *w)
Update the position and size of the viewport (after eg a resize).
Definition widget.cpp:2451
void InitializeViewport(Window *w, std::variant< TileIndex, VehicleID > focus, ZoomLevel zoom)
Initialize the viewport of the window.
Definition widget.cpp:2442
TileIndex tile
The base tile of the area.
TileIndex GetCentreTile() const
Get the centre tile.
Scrollbar data structure.
void SetCount(size_t num)
Sets the number of elements in the list.
auto GetScrolledItemFromWidget(Tcontainer &container, int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Return an iterator pointing to the element of a scrolled widget that a user clicked in.
bool SetPosition(size_type position)
Sets the position of the first visible element.
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.
auto GetVisibleRangeIterators(Tcontainer &container) const
Get a pair of iterators for the range of visible elements in a container.
void SetStepSize(size_t stepsize)
Set the distance to scroll when using the buttons or the wheel.
size_type GetPosition() const
Gets the position of the first visible element in the list.
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
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
Map accessors for 'clear' tiles.
@ Fields
Farm fields (3).
Definition clear_map.h:25
@ Grass
Plain grass with dirt transition (0-3).
Definition clear_map.h:22
void MakeClear(Tile t, ClearGround g, uint density)
Make a clear tile.
Definition clear_map.h:253
ClearGround GetClearGround(Tile t)
Get the type of clear tile.
Definition clear_map.h:52
Functions related to commands.
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
static constexpr Owner OWNER_NONE
The tile has no ownership.
void ShowDropDownMenu(Window *w, std::span< const StringID > strings, int selected, WidgetID button, uint32_t disabled_mask, uint32_t hidden_mask, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a dropdown menu window near a widget of the parent window.
Definition dropdown.cpp:633
std::unique_ptr< DropDownListItem > MakeDropDownListDividerItem()
Creates new DropDownListDividerItem.
Definition dropdown.cpp:36
std::unique_ptr< DropDownListItem > MakeDropDownListIconItem(SpriteID sprite, PaletteID palette, StringID str, int value, bool masked, bool shaded)
Creates new DropDownListIconItem.
Definition dropdown.cpp:70
std::unique_ptr< DropDownListItem > MakeDropDownListStringItem(StringID str, int value, bool masked, bool shaded)
Creates new DropDownListStringItem.
Definition dropdown.cpp:49
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a drop down list.
Definition dropdown.cpp:591
Functions related to the drop down widget.
Types related to the drop down widget.
std::vector< std::unique_ptr< const DropDownListItem > > DropDownList
A drop down list is a collection of drop down list items.
@ Filterable
Set if the dropdown is filterable.
uint ScaleByCargoScale(uint num, bool town)
Scale a number by the cargo scale setting.
#define T
Climate temperate.
Definition engines.h:91
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
Functions related to errors.
@ Info
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition error.h:22
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
bool _generating_world
Whether we are generating the map or not.
Definition genworld.cpp:70
Functions related to world/map generation.
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
@ 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.
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
Dimension GetStringListBoundingBox(std::span< const StringID > list, FontSize fontsize)
Get maximum dimension of a list of strings.
Definition gfx.cpp:933
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
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 DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:782
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
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
Set up a clipping area for only drawing into a certain area.
Definition gfx.cpp:1567
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
FontSize
Available font sizes.
Definition gfx_type.h:248
@ 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
Colours
One of 16 base colours used for companies and windows/widgets.
Definition gfx_type.h:283
@ Mauve
Mauve.
Definition gfx_type.h:295
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ LightBlue
Light blue.
Definition gfx_type.h:290
@ Yellow
Yellow.
Definition gfx_type.h:288
@ Grey
Grey.
Definition gfx_type.h:299
@ Cream
Cream.
Definition gfx_type.h:294
@ Brown
Brown.
Definition gfx_type.h:298
@ DarkGreen
Dark green.
Definition gfx_type.h:292
@ Forced
Ignore colour changes from strings.
Definition gfx_type.h:343
@ White
White colour.
Definition gfx_type.h:330
@ Yellow
Yellow colour.
Definition gfx_type.h:326
@ FromString
Marker for telling to use the colour from the string.
Definition gfx_type.h:317
@ Orange
Orange colour.
Definition gfx_type.h:324
@ Grey
Grey colour.
Definition gfx_type.h:332
@ Black
Black colour.
Definition gfx_type.h:334
@ Industry
Destination is an industry.
Definition goal_type.h:54
Graph GUI functions.
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 SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetSpriteTip(SpriteID sprite, StringID tip={})
Widget part function for setting the sprite 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 SetAspect(float ratio, AspectFlags flags=AspectFlag::ResizeX)
Widget part function for setting the aspect ratio.
constexpr NWidgetPart SetMinimalTextLines(uint8_t lines, uint8_t spacing, FontSize size=FontSize::Normal)
Widget part function for setting the minimal text lines.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetArrowWidgetTypeTip(ArrowWidgetType widget_type, StringID tip={})
Widget part function for setting the arrow widget type and tooltip.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
static const CursorID SPR_CURSOR_INDUSTRY
Definition sprites.h:1581
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
GUI functions that shouldn't be here.
void ShowExtraViewportWindow(TileIndex tile=INVALID_TILE)
Show a new Extra Viewport window.
Hotkey related functions.
HouseZones GetClimateMaskForLandscape()
Get the HouseZones climate mask for the current landscape type.
EnumBitSet< HouseZone, uint16_t > HouseZones
Bitset of HouseZone elements.
Definition house.h:75
uint16_t HouseID
OpenTTD ID of house types.
Definition house_type.h:15
Base of all industries.
static constexpr uint8_t PRODLEVEL_MAXIMUM
the industry is running at full speed
Definition industry.h:38
static constexpr uint8_t PRODLEVEL_DEFAULT
default level set when the industry is created
Definition industry.h:37
static constexpr uint8_t PRODLEVEL_MINIMUM
below this level, the industry is set to be closing
Definition industry.h:36
static constexpr uint8_t PRODLEVEL_CLOSURE
signal set to actually close the industry
Definition industry.h:35
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
Command definitions related to industries.
static constexpr std::initializer_list< NWidgetPart > _nested_industry_directory_widgets
Widget definition of the industry directory gui.
void ShowIndustryCargoesWindow()
Open the industry and cargoes window with an industry.
static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, CargoSuffix &suffix)
Gets the string to display after the cargo name (using callback 37).
CargoSuffixType
Cargo suffix type (for which window is it requested).
@ View
View-industry window.
@ Fund
Fund-industry window.
@ Directory
Industry-directory window.
static WindowDesc _industry_directory_desc(WindowPosition::Automatic, "list_industries", 428, 190, WindowClass::IndustryDirectory, WindowClass::None, {}, _nested_industry_directory_widgets, &IndustryDirectoryWindow::hotkeys)
Window definition of the industry directory gui.
static bool CargoFilter(const Industry *const *industry, const std::pair< CargoType, CargoType > &cargoes)
Cargo filter functions.
CargoSuffixDirection
Cargo direction for cargo suffixes.
@ Out
Get cargo suffix for output cargoes.
@ In
Get cargo suffix for input cargoes.
void GenerateIndustries()
This function will create random industries during game creation.
static WindowDesc _build_industry_desc(WindowPosition::Automatic, "build_industry", 170, 212, WindowClass::BuildIndustry, WindowClass::None, WindowDefaultFlag::Construction, _nested_build_industry_widgets)
Window definition of the dynamic place industries gui.
static bool IndustryTypeNameSorter(const IndustryType &a, const IndustryType &b)
Sort industry types by their name.
CargoSuffixDisplay
Ways of displaying the cargo.
@ AmountAndText
Display the cargo, amount, and string (cb37 result 000-3FF).
@ None
Display the cargo without sub-type (cb37 result 401).
@ Text
Display the cargo and supplied string (cb37 result 800-BFF).
@ Amount
Display the cargo and amount (if useful), but no sub-type (cb37 result 400 or fail).
static Dimension GetMaximalSizeIndustryString(FontSize fs=FontSize::Normal)
Get the maximal size for industry type names.
static WindowDesc _industry_view_desc(WindowPosition::Automatic, "view_industry", 260, 120, WindowClass::IndustryView, WindowClass::None, {}, _nested_industry_view_widgets)
Window definition of the view industry gui.
std::array< IndustryType, NUM_INDUSTRYTYPES > _sorted_industry_types
Industry types sorted by name.
static WindowDesc _industry_cargoes_desc(WindowPosition::Automatic, "industry_cargoes", 300, 210, WindowClass::IndustryCargoes, WindowClass::None, {}, _nested_industry_cargoes_widgets)
Window description for the industry cargoes window.
static void GetAllCargoSuffixes(CargoSuffixDirection use_input, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
Gets all strings to display after the cargoes of industries (using callback 37).
std::bitset< NUM_INDUSTRYTYPES > _displayed_industries
Communication from the industry chain window to the smallmap window about what industries to display.
static constexpr std::initializer_list< NWidgetPart > _nested_industry_view_widgets
Widget definition of the view industry gui.
static Dimension GetMaximalSizeCargoString(FontSize fs=FontSize::Normal)
Get the maximal size for cargo names.
void SortIndustryTypes()
Initialize the list of sorted industry types.
static constexpr std::initializer_list< NWidgetPart > _nested_industry_cargoes_widgets
Widgets of the industry cargoes window.
static const int INDUSTRY_ORIGINAL_NUM_INPUTS
Original number of accepted cargo types.
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like IT_...
static const int INDUSTRY_ORIGINAL_NUM_OUTPUTS
Original number of produced cargo types.
Types related to the industry widgets.
@ WID_DPI_MATRIX_WIDGET
Matrix of the industries.
@ WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET
Remove all industries button.
@ WID_DPI_INFOPANEL
Info panel about the industry.
@ WID_DPI_SCENARIO_EDITOR_PANE
Pane containing SE-only widgets.
@ WID_DPI_SCROLLBAR
Scrollbar of the matrix.
@ WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET
Create random industries button.
@ WID_DPI_FUND_WIDGET
Fund button.
@ WID_DPI_DISPLAY_WIDGET
Display chain button.
@ WID_ID_HSCROLLBAR
Horizontal scrollbar of the list.
@ WID_ID_INDUSTRY_LIST
Industry list.
@ WID_ID_DROPDOWN_ORDER
Dropdown for the order of the sort.
@ WID_ID_FILTER_BY_PROD_CARGO
Produced cargo filter dropdown list.
@ WID_ID_DROPDOWN_CRITERIA
Dropdown for the criteria of the sort.
@ WID_ID_CAPTION
Caption of the window.
@ WID_ID_FILTER
Textbox to filter industry name.
@ WID_ID_FILTER_BY_ACC_CARGO
Accepted cargo filter dropdown list.
@ WID_ID_VSCROLLBAR
Vertical scrollbar of the list.
@ WID_IC_SCROLLBAR
Scrollbar of the panel.
@ WID_IC_NOTIFY
Row of buttons at the bottom.
@ WID_IC_NAVFORWARD
Navigate forward button.
@ WID_IC_IND_DROPDOWN
Select industry dropdown.
@ WID_IC_CAPTION
Caption of the window.
@ WID_IC_PANEL
Panel that shows the chain.
@ WID_IC_CARGO_DROPDOWN
Select cargo dropdown.
@ WID_IC_NAVBACK
Navigate back button.
@ WID_IC_TOGGLE_SIZE
Toggle size button.
@ WID_IV_INFO
Info of the industry.
@ WID_IV_CAPTION
Caption of the window.
@ WID_IV_GRAPH
Production history button.
@ WID_IV_DISPLAY
Display chain button.
@ WID_IV_GOTO
Goto button.
@ WID_IV_VIEWPORT
Viewport of the industry.
@ CargoTypesUnlimited
Allow produced/accepted cargoes callbacks to supply more than 2 and 3 types.
@ Processing
Like factories.
@ Organic
Like forests.
@ Extractive
Like mines.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
Zooms a viewport in a window in or out.
Definition main_gui.cpp:88
bool HandlePlacePushButton(Window *w, WidgetID widget, CursorID cursor, HighLightStyle mode)
This code is shared for the majority of the pushbuttons.
Definition main_gui.cpp:58
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
constexpr uint ToPercent8(uint i)
Converts a "fract" value 0..255 to "percent" value 0..100.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
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
void ShowQuery(EncodedString &&caption, EncodedString &&message, Window *parent, QueryCallbackProc *callback, bool focus)
Show a confirmation window with standard 'yes' and 'no' buttons The window is aligned to the centre o...
void ShowQueryString(std::string_view str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
Show a query popup window with a textbox in it.
static constexpr CargoType CF_NONE
Show only items which do not carry cargo (e.g. train engines).
Definition cargo_type.h:98
static constexpr CargoType CF_ANY
Show all items independent of carried cargo (i.e. no filtering).
Definition cargo_type.h:97
bool _networking
are we in networking mode?
Definition network.cpp:63
Basic functions/variables used all over the place.
@ Industries
Industries feature.
Definition newgrf.h:92
int DrawBadgeNameList(Rect r, std::span< const BadgeID > badges, GrfSpecFeature)
Draw names for a list of badge labels.
void DrawBadgeColumn(Rect r, int column_group, const GUIBadgeClasses &gui_classes, std::span< const BadgeID > badges, GrfSpecFeature feature, std::optional< TimerGameCalendar::Date > introduction_date, PaletteID remap)
Draw a badge column group.
GUI functions related to NewGRF badges.
@ CargoSuffix
Show suffix after cargo name.
@ WindowMoreText
additional text in industry window
@ FundMoreText
additional text in fund window
@ Production256Ticks
call production callback every 256 ticks
@ ProductionCargoArrival
call production callback when cargo arrives at the industry
@ CargoSuffix
cargo sub-type display
@ CBID_INDUSTRY_WINDOW_MORE_TEXT
Called to determine more text in the industry window.
@ CBID_INDUSTRY_CARGO_SUFFIX
Called to determine text to display after cargo name.
@ CBID_INDUSTRY_FUND_MORE_TEXT
Called to determine more text in the fund industry window.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Functions/types related to NewGRF debugging.
uint16_t GetIndustryCallback(CallbackID callback, uint32_t param1, uint32_t param2, Industry *industry, IndustryType type, TileIndex tile, std::span< int32_t > regs100)
Perform an industry callback.
uint32_t GetIndustryProbabilityCallback(IndustryType type, IndustryAvailabilityCallType creation_type, uint32_t default_prob)
Check with callback CBID_INDUSTRY_PROBABILITY whether the industry can be built.
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoType cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
Functions for NewGRF industries.
@ UserCreation
from the Fund/build window
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
std::string GetGRFStringWithTextStack(const struct GRFFile *grffile, GRFStringID grfstringid, std::span< const int32_t > textstack)
Format a GRF string using the text ref stack for parameters.
Header of Action 04 "universal holder" structure and functions.
StrongType::Typedef< uint32_t, struct GRFStringIDTag, StrongType::Compare, StrongType::Integer > GRFStringID
Type for GRF-internal string IDs.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
@ Editor
In the scenario editor.
Definition openttd.h:21
static constexpr PixelColour PC_BLACK
Black palette colour.
static constexpr PixelColour PC_WHITE
White palette colour.
Base for the GUIs that have an edit box in them.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
void DrawArrowButtons(int x, int y, Colours button_colour, uint8_t state, bool clickable_left, bool clickable_right)
Draw [<][>] boxes.
Functions for setting GUIs.
#define SETTING_BUTTON_WIDTH
Width of setting buttons.
#define SETTING_BUTTON_HEIGHT
Height of setting buttons.
@ Off
Scroll wheel has no effect.
void ShowSmallMap()
Show the smallmap window.
Smallmap GUI functions.
Base types for having sorted lists in GUIs.
void SndClickBeep()
Play a beep sound for a click event if enabled in settings.
Definition sound.cpp:252
Functions related to sound.
@ Count
by amount of cargo
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
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
Definition string.cpp:428
Parse strings.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
Functions related to low-level strings.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
Searching and filtering using a stringterm.
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:335
std::string_view GetListSeparator()
Get the list separator string for the current language.
Definition strings.cpp:298
void AppendStringInPlace(std::string &result, StringID string)
Resolve the given StringID and append in place into an existing std::string with formatting but no pa...
Definition strings.cpp:433
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
uint64_t GetParamMaxDigits(uint count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:217
Functions related to OTTD's strings.
auto MakeParameters(Args &&... args)
Helper to create the StringParameters with its own buffer with the given parameter values.
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.
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Horizontal and vertical alignment.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
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
SpriteID GetCargoIcon() const
Get sprite for showing cargo of this type.
PixelColour legend_colour
Colour in legends and graphs.
Definition cargotype.h:79
StringID name
Name of this type of cargo.
Definition cargotype.h:93
Transfer storage of cargo suffix information.
std::string text
Cargo suffix text.
CargoSuffixDisplay display
How to display the cargo and text.
Comparator to sort CargoType by according to desired order.
Definition cargotype.h:294
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.
Data about how and where to blit pixels.
Definition gfx_type.h:157
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
GrfID grfid
grfid that introduced this entity.
const struct GRFFile * grffile
grf file that introduced this entity
bool HasGrfFile() const
Test if this entity was introduced by NewGRF.
std::array< uint8_t, NUM_CARGO > cargo_map
Inverse cargo translation table (CargoType -> local ID).
Definition newgrf.h:148
uint8_t grf_version
GRF version (See https://newgrf-specs.tt-wiki.net/wiki/Version_numbers#GRF_version).
Definition newgrf.h:129
List of hotkeys for a window.
Definition hotkeys.h:44
All data for a single hotkey.
Definition hotkeys.h:20
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
Window displaying the cargo connections around an industry (or cargo).
Dimension cargo_textsize
Size to hold any cargo text, as well as STR_INDUSTRY_CARGOES_SELECT_CARGO.
static bool HousesCanAccept(CargoTypes cargoes)
Can houses be used as customers of the produced cargoes?
static bool small
Set if industry chain display should be smaller.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
bool ComputeCargoDisplay(CargoType cargo_type)
Compute what and where to display for cargo type cargo_type.
void OnX2Click(Point pt, WidgetID widget) override
A click with the X2 mouse button has been made on the window.
std::vector< ChainRow > rows
Fields to display in the WID_IC_PANEL.
void UpdateHistoryScrollpos()
Update the current navigation history scroll position.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
bool ComputeIndustryDisplay(IndustryType industry_type)
Compute the display for an industry type.
void OnInit() override
Notification that the nested widget tree gets initialized.
bool OnTooltip(Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
Event to display a custom tooltip.
Dimension ind_textsize
Size to hold any industry type text, as well as STR_INDUSTRY_CARGOES_SELECT_INDUSTRY.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
ChainField::ClickedAtResult ind_cargo
The displayed house, industry or cargo type.
void OnResize() override
Called after the window got resized.
void AppendHistory()
Place current house/industry/cargo choice in the navigation history.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
uint CountHouseCargoTypes() const
Count the maximal number of cargo types handled by all houses.
size_t history_pos
Position in browsing history.
void NavigateHistory(int delta)
Move within navigation history.
Scrollbar * vscroll
Vertical scrollbar of window.
void ShortenConnectionsColumn(int column, int top, int middle, int bottom, bool accepting, bool supplying)
Shorten the cargo column to just the part between industries.
static int CountMatchingProducingIndustries(CargoTypes cargoes)
Count how many industries have produced cargoes in common with one of the supplied set.
void ComputeAcceptsProducesIndustryDisplay(std::unique_ptr< AcceptsProducesChainField > &&field, CargoTypes accepts, CargoTypes produces)
Compute what and where to display for an Accepts/Produces chain field.
bool ComputeHouseDisplay()
Compute the display for a house.
static bool HousesCanSupply(CargoTypes cargoes)
Can houses be used to supply one of the cargoes?
static int CountMatchingAcceptingIndustries(CargoTypes cargoes)
Count how many industries have accepted cargoes in common with one of the supplied set.
uint CountIndustryCargoTypes()
Count the maximal number of cargo types handled by all industry types.
ChainField::ClickedAtResult ClickedAt(Point pt) const
Calculate in which field was clicked.
void NotifySmallmap()
Notify smallmap that new displayed industries have been selected (in _displayed_industries).
void PlaceAndConnect(std::unique_ptr< AcceptsProducesChainField > &&field, int row, int col)
Place an industry/house in the fields.
void ComputeDisplay(ChainField::ClickedAtResult clicked_at, bool update_history=true)
Compute the cargo chain display.
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.
Rect GetRowRect(const Rect &r) const
Get the area covered by the cargo chain display.
void UpdateNavigationButtons()
Update state of navigation buttons.
std::vector< std::pair< ChainField::ClickedAtResult, int > > history
Browsing history in this window.
void OnX1Click(Point pt, WidgetID widget) override
A click with the X1 mouse button has been made on the window.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
Defines the data structure for constructing industry.
IndustryCallbackMasks callback_mask
Bitmask of industry callbacks that have to be called.
std::array< CargoType, INDUSTRY_NUM_INPUTS > accepts_cargo
16 accepted cargoes.
bool UsesOriginalEconomy() const
Determines whether this industrytype uses standard/newgrf production changes.
SubstituteGRFFileProps grf_prop
properties related to the grf file
StringID name
Displayed name of the industry.
bool IsRawIndustry() const
Is an industry with the spec a raw industry?
IndustryBehaviours behaviour
How this industry will behave, and how others entities can use it.
std::vector< IndustryTileLayout > layouts
List of possible tile layouts for the industry.
bool enabled
entity still available (by default true).newgrf can disable it, though
Money GetConstructionCost() const
Get the cost for constructing this industry.
IndustryLifeTypes life_type
This is also known as Industry production flag, in newgrf specs.
PixelColour map_colour
colour used for the small map
CargoType cargo
Cargo type.
Definition industry.h:88
uint16_t waiting
Amount of cargo waiting to processed.
Definition industry.h:89
CargoType cargo
Cargo type.
Definition industry.h:76
HistoryData< ProducedHistory > history
History of cargo produced and transported for this month and 24 previous months.
Definition industry.h:79
Defines the internal data of a functional industry.
Definition industry.h:64
IndustryType type
type of industry.
Definition industry.h:117
bool IsCargoAccepted() const
Test if this industry accepts any cargo.
Definition industry.h:225
uint8_t prod_level
general production level
Definition industry.h:114
void RecomputeProductionMultipliers()
Recompute production_rate for current prod_level.
EncodedString text
General text with additional information.
Definition industry.h:134
ProducedCargoes::iterator GetCargoProduced(CargoType cargo)
Get produced cargo slot for a specific cargo type.
Definition industry.h:182
ProducedCargoes produced
produced cargo slots
Definition industry.h:112
AcceptedCargoes accepted
accepted cargo slots
Definition industry.h:113
static uint16_t GetIndustryTypeCount(IndustryType type)
Get the count of industries for this type.
Definition industry.h:267
TileArea location
Location of the industry.
Definition industry.h:108
bool IsCargoProduced() const
Test if this industry produces any cargo.
Definition industry.h:231
Data structure describing how to show the list (what sort direction and criteria).
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition map_func.h:366
Colour for pixel/line drawing.
Definition gfx_type.h:307
static Pool::IterateWrapper< Industry > Iterate(size_t from=0)
static Industry * Get(auto index)
Data stored about a string that can be modified in the GUI.
int cancel_button
Widget button of parent window to simulate when pressing CANCEL in OSK.
static const int ACTION_CLEAR
Clear editbox.
Padding dimensions to apply to each side of a Rect.
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 CentreToHeight(int height) const
Centre a vertical dimension within this Rect.
Rect CentreToWidth(int width) const
Centre a horizontal dimension within this Rect.
Rect WithX(int new_left, int new_right) const
Create a new Rect, replacing the left and right coordinates.
Rect Translate(int x, int y) const
Copy and translate Rect by x,y pixels.
bool Contains(const Point &pt) const
Test if a point falls inside this Rect.
String filter and state.
bool IsEmpty() const
Check whether any filter words were entered.
void SetFilterTerm(std::string_view str)
Set the term to filter on.
void ResetState()
Reset the matching state to process a new item.
bool GetState() const
Get the matching state of the current item.
std::string_view GetText() const
Get the current text.
Definition textbuf.cpp:283
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 ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
Definition window.cpp:1025
static int SortButtonWidth()
Get width of up/down arrow of sort button state.
Definition widget.cpp:839
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
std::map< WidgetID, QueryString * > querystrings
QueryString associated to WWT_EDITBOX widgets.
Definition window_gui.h:319
void DrawWidgets() const
Paint all widgets of a window.
Definition widget.cpp:792
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 SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
std::unique_ptr< ViewportData > viewport
Pointer to viewport data, if present.
Definition window_gui.h:317
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
void RaiseWidgetWhenLowered(WidgetID widget_index)
Marks a widget as raised and dirty (redraw), when it is marked as lowered.
Definition window_gui.h:477
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void DisableWidget(WidgetID widget_index)
Sets a widget to disabled.
Definition window_gui.h:390
void DrawSortButton(WidgetID widget, bool descending) const
Draw a sort button's up or down arrow symbol.
Definition widget.cpp:824
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition window_gui.h:490
void RaiseButtons(bool autoraise=false)
Raise the buttons of the window.
Definition window.cpp:539
bool IsShaded() const
Is window shaded currently?
Definition window_gui.h:561
void SetTimeout()
Set the timeout flag of the window and initiate the timer.
Definition window_gui.h:354
int top
y position of top edge of the window
Definition window_gui.h:309
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void HandleButtonClick(WidgetID widget)
Do all things to make a button look clicked and mark it to be unclicked in a few ticks.
Definition window.cpp:604
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1869
WindowFlags flags
Window flags.
Definition window_gui.h:299
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
Stuff related to the text buffer GUI.
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
@ Clear
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition tile_type.h:49
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
@ HT_RECT
rectangle (stations, depots, ...)
Definition of Interval and OneShot timers.
Definition of the Window system.
Base of the town class.
bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
Scrolls the viewport in a window to a given location.
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Functions related to (drawing on) viewports.
@ ZOOM_IN
Zoom in (get more detailed view).
@ ZOOM_OUT
Zoom out (get helicopter view).
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
Draw frame rectangle.
Definition widget.cpp:308
Rect ScrollRect(Rect r, const Scrollbar &sb, int resize_step)
Apply 'scroll' to a rect to be drawn in.
Definition widget.cpp:2565
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ WWT_INSET
Pressed (inset) panel, most commonly used as combo box text area.
Definition widget_type.h:40
@ WWT_IMGBTN
(Toggle) Button with image
Definition widget_type.h:41
@ WWT_PUSHIMGBTN
Normal push-button (no toggle button) with image caption.
@ WWT_PUSHARROWBTN
Normal push-button (no toggle button) with arrow caption.
@ WWT_EDITBOX
a textbox for typing
Definition widget_type.h:62
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_TEXTBTN
(Toggle) Button with text
Definition widget_type.h:44
@ 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
@ NWID_HSCROLLBAR
Horizontal scrollbar.
Definition widget_type.h:75
@ 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
@ NWID_VIEWPORT
Nested widget containing a viewport.
Definition widget_type.h:73
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:61
@ WWT_DEBUGBOX
NewGRF debug box (at top-right of a window, between WWT_CAPTION and WWT_SHADEBOX).
Definition widget_type.h:54
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:71
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
@ Decrease
Arrow to the left or in case of RTL to the right.
Definition widget_type.h:20
@ Increase
Arrow to the right or in case of RTL to the left.
Definition widget_type.h:21
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
Window * FindWindowByClass(WindowClass cls)
Find any window by its class.
Definition window.cpp:1214
Window * BringWindowToFrontById(WindowClass cls, WindowNumber number)
Find a window and make it the relative top-window on the screen.
Definition window.cpp:1326
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
Window functions not directly related to making/drawing windows.
@ Construction
This window is used for construction; close it whenever changing company.
Definition window_gui.h:154
TooltipCloseCondition
Definition window_gui.h:262
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ DisableVpScroll
Window does not do autoscroll,.
Definition window_gui.h:230
@ Automatic
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:21
Functions related to zooming.
ZoomLevel ScaleZoomGUI(ZoomLevel value)
Scale zoom level relative to GUI zoom.
Definition zoom_func.h:87
@ Industry
Default zoom level for the industry view.
Definition zoom_type.h:36