Add: allow making heightmap screenshot via console
[openttd-github.git] / src / industry_gui.cpp
blobcce96e6d63b1a22c2ce88ce0442635560b102d22
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file industry_gui.cpp GUIs related to industries. */
10 #include "stdafx.h"
11 #include "error.h"
12 #include "gui.h"
13 #include "settings_gui.h"
14 #include "sound_func.h"
15 #include "window_func.h"
16 #include "textbuf_gui.h"
17 #include "command_func.h"
18 #include "viewport_func.h"
19 #include "industry.h"
20 #include "town.h"
21 #include "cheat_type.h"
22 #include "newgrf_industries.h"
23 #include "newgrf_text.h"
24 #include "newgrf_debug.h"
25 #include "network/network.h"
26 #include "strings_func.h"
27 #include "company_func.h"
28 #include "tilehighlight_func.h"
29 #include "string_func.h"
30 #include "sortlist_type.h"
31 #include "widgets/dropdown_func.h"
32 #include "company_base.h"
33 #include "core/geometry_func.hpp"
34 #include "core/random_func.hpp"
35 #include "core/backup_type.hpp"
36 #include "genworld.h"
37 #include "smallmap_gui.h"
38 #include "widgets/dropdown_type.h"
39 #include "widgets/industry_widget.h"
40 #include "clear_map.h"
42 #include "table/strings.h"
44 #include <bitset>
46 #include "safeguards.h"
48 bool _ignore_restrictions;
49 std::bitset<NUM_INDUSTRYTYPES> _displayed_industries; ///< Communication from the industry chain window to the smallmap window about what industries to display.
51 /** Cargo suffix type (for which window is it requested) */
52 enum CargoSuffixType {
53 CST_FUND, ///< Fund-industry window
54 CST_VIEW, ///< View-industry window
55 CST_DIR, ///< Industry-directory window
58 /** Ways of displaying the cargo. */
59 enum CargoSuffixDisplay {
60 CSD_CARGO, ///< Display the cargo without sub-type (cb37 result 401).
61 CSD_CARGO_AMOUNT, ///< Display the cargo and amount (if useful), but no sub-type (cb37 result 400 or fail).
62 CSD_CARGO_TEXT, ///< Display then cargo and supplied string (cb37 result 800-BFF).
63 CSD_CARGO_AMOUNT_TEXT, ///< Display then cargo, amount, and string (cb37 result 000-3FF).
66 /** Transfer storage of cargo suffix information. */
67 struct CargoSuffix {
68 CargoSuffixDisplay display; ///< How to display the cargo and text.
69 char text[512]; ///< Cargo suffix text.
72 static void ShowIndustryCargoesWindow(IndustryType id);
74 /**
75 * Gets the string to display after the cargo name (using callback 37)
76 * @param cargo the cargo for which the suffix is requested, meaning depends on presence of flag 18 in prop 1A
77 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
78 * @param ind the industry (nullptr if in fund window)
79 * @param ind_type the industry type
80 * @param indspec the industry spec
81 * @param suffix is filled with the string to display
83 static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, CargoSuffix &suffix)
85 suffix.text[0] = '\0';
86 suffix.display = CSD_CARGO_AMOUNT;
88 if (HasBit(indspec->callback_mask, CBM_IND_CARGO_SUFFIX)) {
89 TileIndex t = (cst != CST_FUND) ? ind->location.tile : INVALID_TILE;
90 uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, const_cast<Industry *>(ind), ind_type, t);
91 if (callback == CALLBACK_FAILED) return;
93 if (indspec->grf_prop.grffile->grf_version < 8) {
94 if (GB(callback, 0, 8) == 0xFF) return;
95 if (callback < 0x400) {
96 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
97 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), lastof(suffix.text));
98 StopTextRefStackUsage();
99 suffix.display = CSD_CARGO_AMOUNT_TEXT;
100 return;
102 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
103 return;
105 } else { // GRF version 8 or higher.
106 if (callback == 0x400) return;
107 if (callback == 0x401) {
108 suffix.display = CSD_CARGO;
109 return;
111 if (callback < 0x400) {
112 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
113 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), lastof(suffix.text));
114 StopTextRefStackUsage();
115 suffix.display = CSD_CARGO_AMOUNT_TEXT;
116 return;
118 if (callback >= 0x800 && callback < 0xC00) {
119 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
120 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 - 0x800 + callback), lastof(suffix.text));
121 StopTextRefStackUsage();
122 suffix.display = CSD_CARGO_TEXT;
123 return;
125 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
126 return;
131 enum CargoSuffixInOut {
132 CARGOSUFFIX_OUT = 0,
133 CARGOSUFFIX_IN = 1,
137 * Gets all strings to display after the cargoes of industries (using callback 37)
138 * @param use_input get suffixes for output cargoes or input cargoes?
139 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
140 * @param ind the industry (nullptr if in fund window)
141 * @param ind_type the industry type
142 * @param indspec the industry spec
143 * @param cargoes array with cargotypes. for CT_INVALID no suffix will be determined
144 * @param suffixes is filled with the suffixes
146 template <typename TC, typename TS>
147 static inline void GetAllCargoSuffixes(CargoSuffixInOut use_input, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
149 static_assert(lengthof(cargoes) <= lengthof(suffixes));
151 if (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) {
152 /* Reworked behaviour with new many-in-many-out scheme */
153 for (uint j = 0; j < lengthof(suffixes); j++) {
154 if (cargoes[j] != CT_INVALID) {
155 byte local_id = indspec->grf_prop.grffile->cargo_map[cargoes[j]]; // should we check the value for valid?
156 uint cargotype = local_id << 16 | use_input;
157 GetCargoSuffix(cargotype, cst, ind, ind_type, indspec, suffixes[j]);
158 } else {
159 suffixes[j].text[0] = '\0';
160 suffixes[j].display = CSD_CARGO;
163 } else {
164 /* Compatible behaviour with old 3-in-2-out scheme */
165 for (uint j = 0; j < lengthof(suffixes); j++) {
166 suffixes[j].text[0] = '\0';
167 suffixes[j].display = CSD_CARGO;
169 switch (use_input) {
170 case CARGOSUFFIX_OUT:
171 if (cargoes[0] != CT_INVALID) GetCargoSuffix(3, cst, ind, ind_type, indspec, suffixes[0]);
172 if (cargoes[1] != CT_INVALID) GetCargoSuffix(4, cst, ind, ind_type, indspec, suffixes[1]);
173 break;
174 case CARGOSUFFIX_IN:
175 if (cargoes[0] != CT_INVALID) GetCargoSuffix(0, cst, ind, ind_type, indspec, suffixes[0]);
176 if (cargoes[1] != CT_INVALID) GetCargoSuffix(1, cst, ind, ind_type, indspec, suffixes[1]);
177 if (cargoes[2] != CT_INVALID) GetCargoSuffix(2, cst, ind, ind_type, indspec, suffixes[2]);
178 break;
179 default:
180 NOT_REACHED();
185 std::array<IndustryType, NUM_INDUSTRYTYPES> _sorted_industry_types; ///< Industry types sorted by name.
187 /** Sort industry types by their name. */
188 static bool IndustryTypeNameSorter(const IndustryType &a, const IndustryType &b)
190 static char industry_name[2][64];
192 const IndustrySpec *indsp1 = GetIndustrySpec(a);
193 GetString(industry_name[0], indsp1->name, lastof(industry_name[0]));
195 const IndustrySpec *indsp2 = GetIndustrySpec(b);
196 GetString(industry_name[1], indsp2->name, lastof(industry_name[1]));
198 int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
200 /* If the names are equal, sort by industry type. */
201 return (r != 0) ? r < 0 : (a < b);
205 * Initialize the list of sorted industry types.
207 void SortIndustryTypes()
209 /* Add each industry type to the list. */
210 for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
211 _sorted_industry_types[i] = i;
214 /* Sort industry types by name. */
215 std::sort(_sorted_industry_types.begin(), _sorted_industry_types.end(), IndustryTypeNameSorter);
219 * Command callback. In case of failure to build an industry, show an error message.
220 * @param result Result of the command.
221 * @param tile Tile where the industry is placed.
222 * @param p1 Additional data of the #CMD_BUILD_INDUSTRY command.
223 * @param p2 Additional data of the #CMD_BUILD_INDUSTRY command.
224 * @param cmd Unused.
226 void CcBuildIndustry(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd)
228 if (result.Succeeded()) return;
230 uint8 indtype = GB(p1, 0, 8);
231 if (indtype < NUM_INDUSTRYTYPES) {
232 const IndustrySpec *indsp = GetIndustrySpec(indtype);
233 if (indsp->enabled) {
234 SetDParam(0, indsp->name);
235 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
240 static const NWidgetPart _nested_build_industry_widgets[] = {
241 NWidget(NWID_HORIZONTAL),
242 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
243 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
244 NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
245 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
246 NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
247 EndContainer(),
248 NWidget(NWID_SELECTION, COLOUR_DARK_GREEN, WID_DPI_SCENARIO_EDITOR_PANE),
249 NWidget(NWID_VERTICAL),
250 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET), SetMinimalSize(0, 12), SetFill(1, 0), SetResize(1, 0),
251 SetDataTip(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP),
252 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET), SetMinimalSize(0, 12), SetFill(1, 0), SetResize(1, 0),
253 SetDataTip(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES, STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_TOOLTIP),
254 EndContainer(),
255 EndContainer(),
256 NWidget(NWID_HORIZONTAL),
257 NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, WID_DPI_MATRIX_WIDGET), SetMatrixDataTip(1, 0, STR_FUND_INDUSTRY_SELECTION_TOOLTIP), SetFill(1, 0), SetResize(1, 1), SetScrollbar(WID_DPI_SCROLLBAR),
258 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_DPI_SCROLLBAR),
259 EndContainer(),
260 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_DPI_INFOPANEL), SetResize(1, 0),
261 EndContainer(),
262 NWidget(NWID_HORIZONTAL),
263 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
264 SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
265 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
266 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
267 EndContainer(),
270 /** Window definition of the dynamic place industries gui */
271 static WindowDesc _build_industry_desc(
272 WDP_AUTO, "build_industry", 170, 212,
273 WC_BUILD_INDUSTRY, WC_NONE,
274 WDF_CONSTRUCTION,
275 _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
278 /** Build (fund or prospect) a new industry, */
279 class BuildIndustryWindow : public Window {
280 int selected_index; ///< index of the element in the matrix
281 IndustryType selected_type; ///< industry corresponding to the above index
282 uint16 count; ///< How many industries are loaded
283 IndustryType index[NUM_INDUSTRYTYPES + 1]; ///< Type of industry, in the order it was loaded
284 bool enabled[NUM_INDUSTRYTYPES + 1]; ///< availability state, coming from CBID_INDUSTRY_PROBABILITY (if ever)
285 Scrollbar *vscroll;
287 /** The offset for the text in the matrix. */
288 static const int MATRIX_TEXT_OFFSET = 17;
289 /** The largest allowed minimum-width of the window, given in line heights */
290 static const int MAX_MINWIDTH_LINEHEIGHTS = 20;
292 void SetupArrays()
294 this->count = 0;
296 for (uint i = 0; i < lengthof(this->index); i++) {
297 this->index[i] = INVALID_INDUSTRYTYPE;
298 this->enabled[i] = false;
301 /* Fill the arrays with industries.
302 * The tests performed after the enabled allow to load the industries
303 * In the same way they are inserted by grf (if any)
305 for (IndustryType ind : _sorted_industry_types) {
306 const IndustrySpec *indsp = GetIndustrySpec(ind);
307 if (indsp->enabled) {
308 /* Rule is that editor mode loads all industries.
309 * In game mode, all non raw industries are loaded too
310 * and raw ones are loaded only when setting allows it */
311 if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
312 /* Unselect if the industry is no longer in the list */
313 if (this->selected_type == ind) this->selected_index = -1;
314 continue;
316 this->index[this->count] = ind;
317 this->enabled[this->count] = (_game_mode == GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
318 /* Keep the selection to the correct line */
319 if (this->selected_type == ind) this->selected_index = this->count;
320 this->count++;
324 /* first industry type is selected if the current selection is invalid.
325 * I'll be damned if there are none available ;) */
326 if (this->selected_index == -1) {
327 this->selected_index = 0;
328 this->selected_type = this->index[0];
331 this->vscroll->SetCount(this->count);
334 /** Update status of the fund and display-chain widgets. */
335 void SetButtons()
337 this->SetWidgetDisabledState(WID_DPI_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
338 this->SetWidgetDisabledState(WID_DPI_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
342 * Build a string of cargo names with suffixes attached.
343 * This is distinct from the CARGO_LIST string formatting code in two ways:
344 * - This cargo list uses the order defined by the industry, rather than alphabetic.
345 * - NewGRF-supplied suffix strings can be attached to each cargo.
347 * @param cargolist Array of CargoID to display
348 * @param cargo_suffix Array of suffixes to attach to each cargo
349 * @param cargolistlen Length of arrays
350 * @param prefixstr String to use for the first item
351 * @return A formatted raw string
353 std::string MakeCargoListString(const CargoID *cargolist, const CargoSuffix *cargo_suffix, int cargolistlen, StringID prefixstr) const
355 std::string cargostring;
356 char buf[1024];
357 int numcargo = 0;
358 int firstcargo = -1;
360 for (byte j = 0; j < cargolistlen; j++) {
361 if (cargolist[j] == CT_INVALID) continue;
362 numcargo++;
363 if (firstcargo < 0) {
364 firstcargo = j;
365 continue;
367 SetDParam(0, CargoSpec::Get(cargolist[j])->name);
368 SetDParamStr(1, cargo_suffix[j].text);
369 GetString(buf, STR_INDUSTRY_VIEW_CARGO_LIST_EXTENSION, lastof(buf));
370 cargostring += buf;
373 if (numcargo > 0) {
374 SetDParam(0, CargoSpec::Get(cargolist[firstcargo])->name);
375 SetDParamStr(1, cargo_suffix[firstcargo].text);
376 GetString(buf, prefixstr, lastof(buf));
377 cargostring = std::string(buf) + cargostring;
378 } else {
379 SetDParam(0, STR_JUST_NOTHING);
380 SetDParamStr(1, "");
381 GetString(buf, prefixstr, lastof(buf));
382 cargostring = std::string(buf);
385 return cargostring;
388 public:
389 BuildIndustryWindow() : Window(&_build_industry_desc)
391 this->selected_index = -1;
392 this->selected_type = INVALID_INDUSTRYTYPE;
394 this->CreateNestedTree();
395 this->vscroll = this->GetScrollbar(WID_DPI_SCROLLBAR);
396 this->FinishInitNested(0);
398 this->SetButtons();
400 /* Show scenario editor tools in editor. */
401 if (_game_mode != GM_EDITOR) {
402 auto *se_tools = this->GetWidget<NWidgetStacked>(WID_DPI_SCENARIO_EDITOR_PANE);
403 se_tools->SetDisplayedPlane(SZSP_HORIZONTAL);
404 this->ReInit();
408 void OnInit() override
410 this->SetupArrays();
413 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
415 switch (widget) {
416 case WID_DPI_MATRIX_WIDGET: {
417 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
418 for (byte i = 0; i < this->count; i++) {
419 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
420 d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
422 resize->height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
423 d.width += MATRIX_TEXT_OFFSET + padding.width;
424 d.height = 5 * resize->height;
425 *size = maxdim(*size, d);
426 break;
429 case WID_DPI_INFOPANEL: {
430 /* Extra line for cost outside of editor. */
431 int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1);
432 uint extra_lines_req = 0;
433 uint extra_lines_prd = 0;
434 uint extra_lines_newgrf = 0;
435 uint max_minwidth = FONT_HEIGHT_NORMAL * MAX_MINWIDTH_LINEHEIGHTS;
436 Dimension d = {0, 0};
437 for (byte i = 0; i < this->count; i++) {
438 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
440 const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
441 CargoSuffix cargo_suffix[lengthof(indsp->accepts_cargo)];
443 /* Measure the accepted cargoes, if any. */
444 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
445 std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
446 Dimension strdim = GetStringBoundingBox(cargostring.c_str());
447 if (strdim.width > max_minwidth) {
448 extra_lines_req = std::max(extra_lines_req, strdim.width / max_minwidth + 1);
449 strdim.width = max_minwidth;
451 d = maxdim(d, strdim);
453 /* Measure the produced cargoes, if any. */
454 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
455 cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
456 strdim = GetStringBoundingBox(cargostring.c_str());
457 if (strdim.width > max_minwidth) {
458 extra_lines_prd = std::max(extra_lines_prd, strdim.width / max_minwidth + 1);
459 strdim.width = max_minwidth;
461 d = maxdim(d, strdim);
463 if (indsp->grf_prop.grffile != nullptr) {
464 /* Reserve a few extra lines for text from an industry NewGRF. */
465 extra_lines_newgrf = 4;
469 /* Set it to something more sane :) */
470 height += extra_lines_prd + extra_lines_req + extra_lines_newgrf;
471 size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
472 size->width = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
473 break;
476 case WID_DPI_FUND_WIDGET: {
477 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
478 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
479 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
480 d.width += padding.width;
481 d.height += padding.height;
482 *size = maxdim(*size, d);
483 break;
488 void SetStringParameters(int widget) const override
490 switch (widget) {
491 case WID_DPI_FUND_WIDGET:
492 /* Raw industries might be prospected. Show this fact by changing the string
493 * In Editor, you just build, while ingame, or you fund or you prospect */
494 if (_game_mode == GM_EDITOR) {
495 /* We've chosen many random industries but no industries have been specified */
496 SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
497 } else {
498 const IndustrySpec *indsp = GetIndustrySpec(this->index[this->selected_index]);
499 SetDParam(0, (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
501 break;
505 void DrawWidget(const Rect &r, int widget) const override
507 switch (widget) {
508 case WID_DPI_MATRIX_WIDGET: {
509 uint text_left, text_right, icon_left, icon_right;
510 if (_current_text_dir == TD_RTL) {
511 icon_right = r.right - WD_MATRIX_RIGHT;
512 icon_left = icon_right - 10;
513 text_right = icon_right - BuildIndustryWindow::MATRIX_TEXT_OFFSET;
514 text_left = r.left + WD_MATRIX_LEFT;
515 } else {
516 icon_left = r.left + WD_MATRIX_LEFT;
517 icon_right = icon_left + 10;
518 text_left = icon_left + BuildIndustryWindow::MATRIX_TEXT_OFFSET;
519 text_right = r.right - WD_MATRIX_RIGHT;
522 for (byte i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
523 int y = r.top + WD_MATRIX_TOP + i * this->resize.step_height;
524 bool selected = this->selected_index == i + this->vscroll->GetPosition();
526 if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
527 DrawString(text_left, text_right, y, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
528 continue;
530 const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
532 /* Draw the name of the industry in white is selected, otherwise, in orange */
533 DrawString(text_left, text_right, y, indsp->name, selected ? TC_WHITE : TC_ORANGE);
534 GfxFillRect(icon_left, y + 1, icon_right, y + 7, selected ? PC_WHITE : PC_BLACK);
535 GfxFillRect(icon_left + 1, y + 2, icon_right - 1, y + 6, indsp->map_colour);
537 break;
540 case WID_DPI_INFOPANEL: {
541 int y = r.top + WD_FRAMERECT_TOP;
542 int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
543 int left = r.left + WD_FRAMERECT_LEFT;
544 int right = r.right - WD_FRAMERECT_RIGHT;
546 if (this->selected_type == INVALID_INDUSTRYTYPE) {
547 DrawStringMultiLine(left, right, y, bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
548 break;
551 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
553 if (_game_mode != GM_EDITOR) {
554 SetDParam(0, indsp->GetConstructionCost());
555 DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
556 y += FONT_HEIGHT_NORMAL;
559 CargoSuffix cargo_suffix[lengthof(indsp->accepts_cargo)];
561 /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
562 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
563 std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
564 y = DrawStringMultiLine(left, right, y, bottom, cargostring.c_str());
566 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
567 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
568 cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
569 y = DrawStringMultiLine(left, right, y, bottom, cargostring.c_str());
571 /* Get the additional purchase info text, if it has not already been queried. */
572 if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
573 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, nullptr, this->selected_type, INVALID_TILE);
574 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
575 if (callback_res > 0x400) {
576 ErrorUnknownCallbackResult(indsp->grf_prop.grffile->grfid, CBID_INDUSTRY_FUND_MORE_TEXT, callback_res);
577 } else {
578 StringID str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res); // No. here's the new string
579 if (str != STR_UNDEFINED) {
580 StartTextRefStackUsage(indsp->grf_prop.grffile, 6);
581 DrawStringMultiLine(left, right, y, bottom, str, TC_YELLOW);
582 StopTextRefStackUsage();
587 break;
592 static void AskManyRandomIndustriesCallback(Window *w, bool confirmed)
594 if (!confirmed) return;
596 if (Town::GetNumItems() == 0) {
597 ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
598 } else {
599 extern void GenerateIndustries();
600 _generating_world = true;
601 GenerateIndustries();
602 _generating_world = false;
606 static void AskRemoveAllIndustriesCallback(Window *w, bool confirmed)
608 if (!confirmed) return;
610 for (Industry *industry : Industry::Iterate()) delete industry;
612 /* Clear farmland. */
613 for (TileIndex tile = 0; tile < MapSize(); tile++) {
614 if (IsTileType(tile, MP_CLEAR) && GetRawClearGround(tile) == CLEAR_FIELDS) {
615 MakeClear(tile, CLEAR_GRASS, 3);
619 MarkWholeScreenDirty();
622 void OnClick(Point pt, int widget, int click_count) override
624 switch (widget) {
625 case WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET: {
626 assert(_game_mode == GM_EDITOR);
627 this->HandleButtonClick(WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET);
628 ShowQuery(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_CAPTION, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_QUERY, nullptr, AskManyRandomIndustriesCallback);
629 break;
632 case WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET: {
633 assert(_game_mode == GM_EDITOR);
634 this->HandleButtonClick(WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET);
635 ShowQuery(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_CAPTION, STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_QUERY, nullptr, AskRemoveAllIndustriesCallback);
636 break;
639 case WID_DPI_MATRIX_WIDGET: {
640 int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_DPI_MATRIX_WIDGET);
641 if (y < this->count) { // Is it within the boundaries of available data?
642 this->selected_index = y;
643 this->selected_type = this->index[y];
644 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? nullptr : GetIndustrySpec(this->selected_type);
646 this->SetDirty();
648 if (_thd.GetCallbackWnd() == this &&
649 ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != nullptr && indsp->IsRawIndustry()) ||
650 this->selected_type == INVALID_INDUSTRYTYPE ||
651 !this->enabled[this->selected_index])) {
652 /* Reset the button state if going to prospecting or "build many industries" */
653 this->RaiseButtons();
654 ResetObjectToPlace();
657 this->SetButtons();
658 if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, WID_DPI_FUND_WIDGET, 1);
660 break;
663 case WID_DPI_DISPLAY_WIDGET:
664 if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
665 break;
667 case WID_DPI_FUND_WIDGET: {
668 if (this->selected_type != INVALID_INDUSTRYTYPE) {
669 if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
670 DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
671 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
672 } else {
673 HandlePlacePushButton(this, WID_DPI_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
676 break;
681 void OnResize() override
683 /* Adjust the number of items in the matrix depending of the resize */
684 this->vscroll->SetCapacityFromWidget(this, WID_DPI_MATRIX_WIDGET);
687 void OnPlaceObject(Point pt, TileIndex tile) override
689 bool success = true;
690 /* We do not need to protect ourselves against "Random Many Industries" in this mode */
691 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
692 uint32 seed = InteractiveRandom();
693 uint32 layout_index = InteractiveRandomRange((uint32)indsp->layouts.size());
695 if (_game_mode == GM_EDITOR) {
696 /* Show error if no town exists at all */
697 if (Town::GetNumItems() == 0) {
698 SetDParam(0, indsp->name);
699 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
700 return;
703 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
704 _generating_world = true;
705 _ignore_restrictions = true;
707 DoCommandP(tile, (layout_index << 8) | this->selected_type, seed,
708 CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY), &CcBuildIndustry);
710 cur_company.Restore();
711 _ignore_restrictions = false;
712 _generating_world = false;
713 } else {
714 success = DoCommandP(tile, (layout_index << 8) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
717 /* If an industry has been built, just reset the cursor and the system */
718 if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
721 void OnHundredthTick() override
723 if (_game_mode == GM_EDITOR) return;
724 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
726 if (indsp->enabled) {
727 bool call_back_result = GetIndustryProbabilityCallback(this->selected_type, IACT_USERCREATION, 1) > 0;
729 /* Only if result does match the previous state would it require a redraw. */
730 if (call_back_result != this->enabled[this->selected_index]) {
731 this->enabled[this->selected_index] = call_back_result;
732 this->SetButtons();
733 this->SetDirty();
738 void OnTimeout() override
740 this->RaiseButtons();
743 void OnPlaceObjectAbort() override
745 this->RaiseButtons();
749 * Some data on this window has become invalid.
750 * @param data Information about the changed data.
751 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
753 void OnInvalidateData(int data = 0, bool gui_scope = true) override
755 if (!gui_scope) return;
756 this->SetupArrays();
758 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? nullptr : GetIndustrySpec(this->selected_type);
759 if (indsp == nullptr) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
760 this->SetButtons();
764 void ShowBuildIndustryWindow()
766 if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
767 if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
768 new BuildIndustryWindow();
771 static void UpdateIndustryProduction(Industry *i);
773 static inline bool IsProductionAlterable(const Industry *i)
775 const IndustrySpec *is = GetIndustrySpec(i->type);
776 bool has_prod = false;
777 for (size_t j = 0; j < lengthof(is->production_rate); j++) {
778 if (is->production_rate[j] != 0) {
779 has_prod = true;
780 break;
783 return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
784 (has_prod || is->IsRawIndustry()) &&
785 !_networking);
788 class IndustryViewWindow : public Window
790 /** Modes for changing production */
791 enum Editability {
792 EA_NONE, ///< Not alterable
793 EA_MULTIPLIER, ///< Allow changing the production multiplier
794 EA_RATE, ///< Allow changing the production rates
797 /** Specific lines in the info panel */
798 enum InfoLine {
799 IL_NONE, ///< No line
800 IL_MULTIPLIER, ///< Production multiplier
801 IL_RATE1, ///< Production rate of cargo 1
802 IL_RATE2, ///< Production rate of cargo 2
805 Editability editable; ///< Mode for changing production
806 InfoLine editbox_line; ///< The line clicked to open the edit box
807 InfoLine clicked_line; ///< The line of the button that has been clicked
808 byte clicked_button; ///< The button that has been clicked (to raise)
809 int production_offset_y; ///< The offset of the production texts/buttons
810 int info_height; ///< Height needed for the #WID_IV_INFO panel
812 public:
813 IndustryViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
815 this->flags |= WF_DISABLE_VP_SCROLL;
816 this->editbox_line = IL_NONE;
817 this->clicked_line = IL_NONE;
818 this->clicked_button = 0;
819 this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
821 this->InitNested(window_number);
822 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
823 nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ZOOM_LVL_INDUSTRY);
825 this->InvalidateData();
828 void OnPaint() override
830 this->DrawWidgets();
832 if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
834 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_IV_INFO);
835 uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
836 if (expected > nwi->current_y - 1) {
837 this->info_height = expected + 1;
838 this->ReInit();
839 return;
844 * Draw the text in the #WID_IV_INFO panel.
845 * @param left Left edge of the panel.
846 * @param right Right edge of the panel.
847 * @param top Top edge of the panel.
848 * @return Expected position of the bottom edge of the panel.
850 int DrawInfo(uint left, uint right, uint top)
852 Industry *i = Industry::Get(this->window_number);
853 const IndustrySpec *ind = GetIndustrySpec(i->type);
854 int y = top + WD_FRAMERECT_TOP;
855 bool first = true;
856 bool has_accept = false;
858 if (i->prod_level == PRODLEVEL_CLOSURE) {
859 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE);
860 y += 2 * FONT_HEIGHT_NORMAL;
863 CargoSuffix cargo_suffix[lengthof(i->accepts_cargo)];
864 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
865 bool stockpiling = HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS);
867 uint left_side = left + WD_FRAMERECT_LEFT * 4; // Indent accepted cargoes.
868 for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
869 if (i->accepts_cargo[j] == CT_INVALID) continue;
870 has_accept = true;
871 if (first) {
872 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_REQUIRES);
873 y += FONT_HEIGHT_NORMAL;
874 first = false;
876 SetDParam(0, CargoSpec::Get(i->accepts_cargo[j])->name);
877 SetDParam(1, i->accepts_cargo[j]);
878 SetDParam(2, i->incoming_cargo_waiting[j]);
879 SetDParamStr(3, "");
880 StringID str = STR_NULL;
881 switch (cargo_suffix[j].display) {
882 case CSD_CARGO_AMOUNT_TEXT:
883 SetDParamStr(3, cargo_suffix[j].text);
884 FALLTHROUGH;
885 case CSD_CARGO_AMOUNT:
886 str = stockpiling ? STR_INDUSTRY_VIEW_ACCEPT_CARGO_AMOUNT : STR_INDUSTRY_VIEW_ACCEPT_CARGO;
887 break;
889 case CSD_CARGO_TEXT:
890 SetDParamStr(3, cargo_suffix[j].text);
891 FALLTHROUGH;
892 case CSD_CARGO:
893 str = STR_INDUSTRY_VIEW_ACCEPT_CARGO;
894 break;
896 default:
897 NOT_REACHED();
899 DrawString(left_side, right - WD_FRAMERECT_RIGHT, y, str);
900 y += FONT_HEIGHT_NORMAL;
903 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
904 first = true;
905 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
906 if (i->produced_cargo[j] == CT_INVALID) continue;
907 if (first) {
908 if (has_accept) y += WD_PAR_VSEP_WIDE;
909 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
910 y += FONT_HEIGHT_NORMAL;
911 if (this->editable == EA_RATE) this->production_offset_y = y;
912 first = false;
915 SetDParam(0, i->produced_cargo[j]);
916 SetDParam(1, i->last_month_production[j]);
917 SetDParamStr(2, cargo_suffix[j].text);
918 SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
919 uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? SETTING_BUTTON_WIDTH + 10 : 0);
920 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
921 /* Let's put out those buttons.. */
922 if (this->editable == EA_RATE) {
923 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
924 i->production_rate[j] > 0, i->production_rate[j] < 255);
926 y += FONT_HEIGHT_NORMAL;
929 /* Display production multiplier if editable */
930 if (this->editable == EA_MULTIPLIER) {
931 y += WD_PAR_VSEP_WIDE;
932 this->production_offset_y = y;
933 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
934 uint x = left + WD_FRAMETEXT_LEFT + SETTING_BUTTON_WIDTH + 10;
935 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
936 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
937 i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
938 y += FONT_HEIGHT_NORMAL;
941 /* Get the extra message for the GUI */
942 if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
943 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
944 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
945 if (callback_res > 0x400) {
946 ErrorUnknownCallbackResult(ind->grf_prop.grffile->grfid, CBID_INDUSTRY_WINDOW_MORE_TEXT, callback_res);
947 } else {
948 StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
949 if (message != STR_NULL && message != STR_UNDEFINED) {
950 y += WD_PAR_VSEP_WIDE;
952 StartTextRefStackUsage(ind->grf_prop.grffile, 6);
953 /* Use all the available space left from where we stand up to the
954 * end of the window. We ALSO enlarge the window if needed, so we
955 * can 'go' wild with the bottom of the window. */
956 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message, TC_BLACK);
957 StopTextRefStackUsage();
963 if (!i->text.empty()) {
964 SetDParamStr(0, i->text.c_str());
965 y += WD_PAR_VSEP_WIDE;
966 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, STR_JUST_RAW_STRING, TC_BLACK);
969 return y + WD_FRAMERECT_BOTTOM;
972 void SetStringParameters(int widget) const override
974 if (widget == WID_IV_CAPTION) SetDParam(0, this->window_number);
977 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
979 if (widget == WID_IV_INFO) size->height = this->info_height;
982 void OnClick(Point pt, int widget, int click_count) override
984 switch (widget) {
985 case WID_IV_INFO: {
986 Industry *i = Industry::Get(this->window_number);
987 InfoLine line = IL_NONE;
989 switch (this->editable) {
990 case EA_NONE: break;
992 case EA_MULTIPLIER:
993 if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
994 break;
996 case EA_RATE:
997 if (pt.y >= this->production_offset_y) {
998 int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
999 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
1000 if (i->produced_cargo[j] == CT_INVALID) continue;
1001 row--;
1002 if (row < 0) {
1003 line = (InfoLine)(IL_RATE1 + j);
1004 break;
1008 break;
1010 if (line == IL_NONE) return;
1012 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
1013 int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
1014 int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
1015 if (IsInsideMM(pt.x, left, left + SETTING_BUTTON_WIDTH)) {
1016 /* Clicked buttons, decrease or increase production */
1017 byte button = (pt.x < left + SETTING_BUTTON_WIDTH / 2) ? 1 : 2;
1018 switch (this->editable) {
1019 case EA_MULTIPLIER:
1020 if (button == 1) {
1021 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
1022 i->prod_level = std::max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
1023 } else {
1024 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
1025 i->prod_level = std::min<uint>(i->prod_level * 2, PRODLEVEL_MAXIMUM);
1027 break;
1029 case EA_RATE:
1030 if (button == 1) {
1031 if (i->production_rate[line - IL_RATE1] <= 0) return;
1032 i->production_rate[line - IL_RATE1] = std::max(i->production_rate[line - IL_RATE1] / 2, 0);
1033 } else {
1034 if (i->production_rate[line - IL_RATE1] >= 255) return;
1035 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
1036 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
1037 i->production_rate[line - IL_RATE1] = std::min<uint>(new_prod, 255);
1039 break;
1041 default: NOT_REACHED();
1044 UpdateIndustryProduction(i);
1045 this->SetDirty();
1046 this->SetTimeout();
1047 this->clicked_line = line;
1048 this->clicked_button = button;
1049 } else if (IsInsideMM(pt.x, left + SETTING_BUTTON_WIDTH + 10, right)) {
1050 /* clicked the text */
1051 this->editbox_line = line;
1052 switch (this->editable) {
1053 case EA_MULTIPLIER:
1054 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
1055 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, QSF_NONE);
1056 break;
1058 case EA_RATE:
1059 SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
1060 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, QSF_NONE);
1061 break;
1063 default: NOT_REACHED();
1066 break;
1069 case WID_IV_GOTO: {
1070 Industry *i = Industry::Get(this->window_number);
1071 if (_ctrl_pressed) {
1072 ShowExtraViewportWindow(i->location.GetCenterTile());
1073 } else {
1074 ScrollMainWindowToTile(i->location.GetCenterTile());
1076 break;
1079 case WID_IV_DISPLAY: {
1080 Industry *i = Industry::Get(this->window_number);
1081 ShowIndustryCargoesWindow(i->type);
1082 break;
1087 void OnTimeout() override
1089 this->clicked_line = IL_NONE;
1090 this->clicked_button = 0;
1091 this->SetDirty();
1094 void OnResize() override
1096 if (this->viewport != nullptr) {
1097 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
1098 nvp->UpdateViewportCoordinates(this);
1100 ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
1104 void OnQueryTextFinished(char *str) override
1106 if (StrEmpty(str)) return;
1108 Industry *i = Industry::Get(this->window_number);
1109 uint value = atoi(str);
1110 switch (this->editbox_line) {
1111 case IL_NONE: NOT_REACHED();
1113 case IL_MULTIPLIER:
1114 i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
1115 break;
1117 default:
1118 i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
1119 break;
1121 UpdateIndustryProduction(i);
1122 this->SetDirty();
1126 * Some data on this window has become invalid.
1127 * @param data Information about the changed data.
1128 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1130 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1132 if (!gui_scope) return;
1133 const Industry *i = Industry::Get(this->window_number);
1134 if (IsProductionAlterable(i)) {
1135 const IndustrySpec *ind = GetIndustrySpec(i->type);
1136 this->editable = ind->UsesOriginalEconomy() ? EA_MULTIPLIER : EA_RATE;
1137 } else {
1138 this->editable = EA_NONE;
1142 bool IsNewGRFInspectable() const override
1144 return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
1147 void ShowNewGRFInspectWindow() const override
1149 ::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
1153 static void UpdateIndustryProduction(Industry *i)
1155 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1156 if (indspec->UsesOriginalEconomy()) i->RecomputeProductionMultipliers();
1158 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1159 if (i->produced_cargo[j] != CT_INVALID) {
1160 i->last_month_production[j] = 8 * i->production_rate[j];
1165 /** Widget definition of the view industry gui */
1166 static const NWidgetPart _nested_industry_view_widgets[] = {
1167 NWidget(NWID_HORIZONTAL),
1168 NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
1169 NWidget(WWT_CAPTION, COLOUR_CREAM, WID_IV_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1170 NWidget(WWT_PUSHIMGBTN, COLOUR_CREAM, WID_IV_GOTO), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
1171 NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
1172 NWidget(WWT_SHADEBOX, COLOUR_CREAM),
1173 NWidget(WWT_DEFSIZEBOX, COLOUR_CREAM),
1174 NWidget(WWT_STICKYBOX, COLOUR_CREAM),
1175 EndContainer(),
1176 NWidget(WWT_PANEL, COLOUR_CREAM),
1177 NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
1178 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_IV_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetPadding(1, 1, 1, 1), SetResize(1, 1),
1179 EndContainer(),
1180 EndContainer(),
1181 NWidget(WWT_PANEL, COLOUR_CREAM, WID_IV_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
1182 EndContainer(),
1183 NWidget(NWID_HORIZONTAL),
1184 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
1185 NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
1186 EndContainer(),
1189 /** Window definition of the view industry gui */
1190 static WindowDesc _industry_view_desc(
1191 WDP_AUTO, "view_industry", 260, 120,
1192 WC_INDUSTRY_VIEW, WC_NONE,
1194 _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
1197 void ShowIndustryViewWindow(int industry)
1199 AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
1202 /** Widget definition of the industry directory gui */
1203 static const NWidgetPart _nested_industry_directory_widgets[] = {
1204 NWidget(NWID_HORIZONTAL),
1205 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1206 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1207 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1208 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1209 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1210 EndContainer(),
1211 NWidget(NWID_HORIZONTAL),
1212 NWidget(NWID_VERTICAL),
1213 NWidget(NWID_HORIZONTAL),
1214 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_ID_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1215 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
1216 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_FILTER_BY_ACC_CARGO), SetMinimalSize(225, 12), SetFill(0, 1), SetDataTip(STR_INDUSTRY_DIRECTORY_ACCEPTED_CARGO_FILTER, STR_TOOLTIP_FILTER_CRITERIA),
1217 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_FILTER_BY_PROD_CARGO), SetMinimalSize(225, 12), SetFill(0, 1), SetDataTip(STR_INDUSTRY_DIRECTORY_PRODUCED_CARGO_FILTER, STR_TOOLTIP_FILTER_CRITERIA),
1218 NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
1219 EndContainer(),
1220 NWidget(WWT_PANEL, COLOUR_BROWN, WID_ID_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(WID_ID_SCROLLBAR), EndContainer(),
1221 EndContainer(),
1222 NWidget(NWID_VERTICAL),
1223 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_ID_SCROLLBAR),
1224 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1225 EndContainer(),
1226 EndContainer(),
1229 typedef GUIList<const Industry *, const std::pair<CargoID, CargoID> &> GUIIndustryList;
1231 /** Special cargo filter criteria */
1232 enum CargoFilterSpecialType {
1233 CF_ANY = CT_NO_REFIT, ///< Show all industries (i.e. no filtering)
1234 CF_NONE = CT_INVALID, ///< Show only industries which do not produce/accept cargo
1237 /** Cargo filter functions */
1239 * Check whether an industry accepts and produces a certain cargo pair.
1240 * @param industry The industry whose cargoes will being checked.
1241 * @param cargoes The accepted and produced cargo pair to look for.
1242 * @return bool Whether the given cargoes accepted and produced by the industry.
1244 static bool CDECL CargoFilter(const Industry * const *industry, const std::pair<CargoID, CargoID> &cargoes)
1246 auto accepted_cargo = cargoes.first;
1247 auto produced_cargo = cargoes.second;
1249 bool accepted_cargo_matches;
1251 switch (accepted_cargo) {
1252 case CF_ANY:
1253 accepted_cargo_matches = true;
1254 break;
1256 case CF_NONE:
1257 accepted_cargo_matches = std::all_of(std::begin((*industry)->accepts_cargo), std::end((*industry)->accepts_cargo), [](CargoID cargo) {
1258 return cargo == CT_INVALID;
1260 break;
1262 default:
1263 const auto &ac = (*industry)->accepts_cargo;
1264 accepted_cargo_matches = std::find(std::begin(ac), std::end(ac), accepted_cargo) != std::end(ac);
1265 break;
1268 bool produced_cargo_matches;
1270 switch (produced_cargo) {
1271 case CF_ANY:
1272 produced_cargo_matches = true;
1273 break;
1275 case CF_NONE:
1276 produced_cargo_matches = std::all_of(std::begin((*industry)->produced_cargo), std::end((*industry)->produced_cargo), [](CargoID cargo) {
1277 return cargo == CT_INVALID;
1279 break;
1281 default:
1282 const auto &pc = (*industry)->produced_cargo;
1283 produced_cargo_matches = std::find(std::begin(pc), std::end(pc), produced_cargo) != std::end(pc);
1284 break;
1287 return accepted_cargo_matches && produced_cargo_matches;
1290 static GUIIndustryList::FilterFunction * const _filter_funcs[] = { &CargoFilter };
1294 * The list of industries.
1296 class IndustryDirectoryWindow : public Window {
1297 protected:
1298 /* Runtime saved values */
1299 static Listing last_sorting;
1301 /* Constants for sorting stations */
1302 static const StringID sorter_names[];
1303 static GUIIndustryList::SortFunction * const sorter_funcs[];
1305 GUIIndustryList industries;
1306 Scrollbar *vscroll;
1308 CargoID cargo_filter[NUM_CARGO + 2]; ///< Available cargo filters; CargoID or CF_ANY or CF_NONE
1309 StringID cargo_filter_texts[NUM_CARGO + 3]; ///< Texts for filter_cargo, terminated by INVALID_STRING_ID
1310 byte produced_cargo_filter_criteria; ///< Selected produced cargo filter index
1311 byte accepted_cargo_filter_criteria; ///< Selected accepted cargo filter index
1314 * Set cargo filter list item index.
1315 * @param index The index of the cargo to be set
1317 void SetProducedCargoFilterIndex(byte index)
1319 if (this->produced_cargo_filter_criteria != index) {
1320 this->produced_cargo_filter_criteria = index;
1321 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1322 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1324 this->industries.SetFilterState(is_filtering_necessary);
1325 this->industries.SetFilterType(0);
1326 this->industries.ForceRebuild();
1331 * Set cargo filter list item index.
1332 * @param index The index of the cargo to be set
1334 void SetAcceptedCargoFilterIndex(byte index)
1336 if (this->accepted_cargo_filter_criteria != index) {
1337 this->accepted_cargo_filter_criteria = index;
1338 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1339 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1341 this->industries.SetFilterState(is_filtering_necessary);
1342 this->industries.SetFilterType(0);
1343 this->industries.ForceRebuild();
1348 * Populate the filter list and set the cargo filter criteria.
1350 void SetCargoFilterArray()
1352 byte filter_items = 0;
1354 /* Add item for disabling filtering. */
1355 this->cargo_filter[filter_items] = CF_ANY;
1356 this->cargo_filter_texts[filter_items] = STR_INDUSTRY_DIRECTORY_FILTER_ALL_TYPES;
1357 this->produced_cargo_filter_criteria = filter_items;
1358 this->accepted_cargo_filter_criteria = filter_items;
1359 filter_items++;
1361 /* Add item for industries not producing anything, e.g. power plants */
1362 this->cargo_filter[filter_items] = CF_NONE;
1363 this->cargo_filter_texts[filter_items] = STR_INDUSTRY_DIRECTORY_FILTER_NONE;
1364 filter_items++;
1366 /* Collect available cargo types for filtering. */
1367 const CargoSpec *cs;
1368 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1369 this->cargo_filter[filter_items] = cs->Index();
1370 this->cargo_filter_texts[filter_items] = cs->name;
1371 filter_items++;
1374 /* Terminate the filter list. */
1375 this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
1377 this->industries.SetFilterFuncs(_filter_funcs);
1379 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1381 this->industries.SetFilterState(is_filtering_necessary);
1384 /** (Re)Build industries list */
1385 void BuildSortIndustriesList()
1387 if (this->industries.NeedRebuild()) {
1388 this->industries.clear();
1390 for (const Industry *i : Industry::Iterate()) {
1391 this->industries.push_back(i);
1394 this->industries.shrink_to_fit();
1395 this->industries.RebuildDone();
1398 auto filter = std::make_pair(this->cargo_filter[this->accepted_cargo_filter_criteria],
1399 this->cargo_filter[this->produced_cargo_filter_criteria]);
1401 this->industries.Filter(filter);
1402 this->industries.Sort();
1404 this->vscroll->SetCount((uint)this->industries.size()); // Update scrollbar as well.
1406 this->SetDirty();
1410 * Returns percents of cargo transported if industry produces this cargo, else -1
1412 * @param i industry to check
1413 * @param id cargo slot
1414 * @return percents of cargo transported, or -1 if industry doesn't use this cargo slot
1416 static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
1418 assert(id < lengthof(i->produced_cargo));
1420 if (i->produced_cargo[id] == CT_INVALID) return 101;
1421 return ToPercent8(i->last_month_pct_transported[id]);
1425 * Returns value representing industry's transported cargo
1426 * percentage for industry sorting
1428 * @param i industry to check
1429 * @return value used for sorting
1431 static int GetCargoTransportedSortValue(const Industry *i)
1433 int p1 = GetCargoTransportedPercentsIfValid(i, 0);
1434 int p2 = GetCargoTransportedPercentsIfValid(i, 1);
1436 if (p1 > p2) Swap(p1, p2); // lower value has higher priority
1438 return (p1 << 8) + p2;
1441 /** Sort industries by name */
1442 static bool IndustryNameSorter(const Industry * const &a, const Industry * const &b)
1444 int r = strnatcmp(a->GetCachedName(), b->GetCachedName()); // Sort by name (natural sorting).
1445 if (r == 0) return a->index < b->index;
1446 return r < 0;
1449 /** Sort industries by type and name */
1450 static bool IndustryTypeSorter(const Industry * const &a, const Industry * const &b)
1452 int it_a = 0;
1453 while (it_a != NUM_INDUSTRYTYPES && a->type != _sorted_industry_types[it_a]) it_a++;
1454 int it_b = 0;
1455 while (it_b != NUM_INDUSTRYTYPES && b->type != _sorted_industry_types[it_b]) it_b++;
1456 int r = it_a - it_b;
1457 return (r == 0) ? IndustryNameSorter(a, b) : r < 0;
1460 /** Sort industries by production and name */
1461 static bool IndustryProductionSorter(const Industry * const &a, const Industry * const &b)
1463 uint prod_a = 0, prod_b = 0;
1464 for (uint i = 0; i < lengthof(a->produced_cargo); i++) {
1465 if (a->produced_cargo[i] != CT_INVALID) prod_a += a->last_month_production[i];
1466 if (b->produced_cargo[i] != CT_INVALID) prod_b += b->last_month_production[i];
1468 int r = prod_a - prod_b;
1470 return (r == 0) ? IndustryTypeSorter(a, b) : r < 0;
1473 /** Sort industries by transported cargo and name */
1474 static bool IndustryTransportedCargoSorter(const Industry * const &a, const Industry * const &b)
1476 int r = GetCargoTransportedSortValue(a) - GetCargoTransportedSortValue(b);
1477 return (r == 0) ? IndustryNameSorter(a, b) : r < 0;
1481 * Get the StringID to draw and set the appropriate DParams.
1482 * @param i the industry to get the StringID of.
1483 * @return the StringID.
1485 StringID GetIndustryString(const Industry *i) const
1487 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1488 byte p = 0;
1490 /* Industry name */
1491 SetDParam(p++, i->index);
1493 static CargoSuffix cargo_suffix[lengthof(i->produced_cargo)];
1494 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
1496 /* Get industry productions (CargoID, production, suffix, transported) */
1497 typedef std::tuple<CargoID, uint16, const char*, uint> CargoInfo;
1498 std::vector<CargoInfo> cargos;
1500 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1501 if (i->produced_cargo[j] == CT_INVALID) continue;
1502 cargos.emplace_back(i->produced_cargo[j], i->last_month_production[j], cargo_suffix[j].text, ToPercent8(i->last_month_pct_transported[j]));
1505 /* Sort by descending production, then descending transported */
1506 std::sort(cargos.begin(), cargos.end(), [](const CargoInfo a, const CargoInfo b) {
1507 if (std::get<1>(a) != std::get<1>(b)) return std::get<1>(a) > std::get<1>(b);
1508 return std::get<3>(a) > std::get<3>(b);
1511 /* If the produced cargo filter is active then move the filtered cargo to the beginning of the list,
1512 * because this is the one the player interested in, and that way it is not hidden in the 'n' more cargos */
1513 const CargoID cid = this->cargo_filter[this->produced_cargo_filter_criteria];
1514 if (cid != CF_ANY && cid != CF_NONE) {
1515 auto filtered_ci = std::find_if(cargos.begin(), cargos.end(), [cid](const CargoInfo& ci) -> bool {
1516 return std::get<0>(ci) == cid;
1518 if (filtered_ci != cargos.end()) {
1519 std::rotate(cargos.begin(), filtered_ci, filtered_ci + 1);
1523 /* Display first 3 cargos */
1524 for (size_t j = 0; j < std::min<size_t>(3, cargos.size()); j++) {
1525 CargoInfo ci = cargos[j];
1526 SetDParam(p++, STR_INDUSTRY_DIRECTORY_ITEM_INFO);
1527 SetDParam(p++, std::get<0>(ci));
1528 SetDParam(p++, std::get<1>(ci));
1529 SetDParamStr(p++, std::get<2>(ci));
1530 SetDParam(p++, std::get<3>(ci));
1533 /* Undisplayed cargos if any */
1534 SetDParam(p++, cargos.size() - 3);
1536 /* Drawing the right string */
1537 switch (cargos.size()) {
1538 case 0: return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
1539 case 1: return STR_INDUSTRY_DIRECTORY_ITEM_PROD1;
1540 case 2: return STR_INDUSTRY_DIRECTORY_ITEM_PROD2;
1541 case 3: return STR_INDUSTRY_DIRECTORY_ITEM_PROD3;
1542 default: return STR_INDUSTRY_DIRECTORY_ITEM_PRODMORE;
1546 public:
1547 IndustryDirectoryWindow(WindowDesc *desc, WindowNumber number) : Window(desc)
1549 this->CreateNestedTree();
1550 this->vscroll = this->GetScrollbar(WID_ID_SCROLLBAR);
1552 this->industries.SetListing(this->last_sorting);
1553 this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
1554 this->industries.ForceRebuild();
1555 this->BuildSortIndustriesList();
1557 this->FinishInitNested(0);
1560 ~IndustryDirectoryWindow()
1562 this->last_sorting = this->industries.GetListing();
1565 void OnInit() override
1567 this->SetCargoFilterArray();
1570 void SetStringParameters(int widget) const override
1572 switch (widget) {
1573 case WID_ID_DROPDOWN_CRITERIA:
1574 SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
1575 break;
1577 case WID_ID_FILTER_BY_ACC_CARGO:
1578 SetDParam(0, this->cargo_filter_texts[this->accepted_cargo_filter_criteria]);
1579 break;
1581 case WID_ID_FILTER_BY_PROD_CARGO:
1582 SetDParam(0, this->cargo_filter_texts[this->produced_cargo_filter_criteria]);
1583 break;
1587 void DrawWidget(const Rect &r, int widget) const override
1589 switch (widget) {
1590 case WID_ID_DROPDOWN_ORDER:
1591 this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1592 break;
1594 case WID_ID_INDUSTRY_LIST: {
1595 int n = 0;
1596 int y = r.top + WD_FRAMERECT_TOP;
1597 if (this->industries.size() == 0) {
1598 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
1599 break;
1601 TextColour tc;
1602 const CargoID acf_cid = this->cargo_filter[this->accepted_cargo_filter_criteria];
1603 for (uint i = this->vscroll->GetPosition(); i < this->industries.size(); i++) {
1604 tc = TC_FROMSTRING;
1605 if (acf_cid != CF_ANY && acf_cid != CF_NONE) {
1606 Industry *ind = const_cast<Industry *>(this->industries[i]);
1607 if (IndustryTemporarilyRefusesCargo(ind, acf_cid)) {
1608 tc = TC_GREY | TC_FORCED;
1611 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]), tc);
1613 y += this->resize.step_height;
1614 if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
1616 break;
1621 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1623 switch (widget) {
1624 case WID_ID_DROPDOWN_ORDER: {
1625 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1626 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1627 d.height += padding.height;
1628 *size = maxdim(*size, d);
1629 break;
1632 case WID_ID_DROPDOWN_CRITERIA: {
1633 Dimension d = {0, 0};
1634 for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
1635 d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
1637 d.width += padding.width;
1638 d.height += padding.height;
1639 *size = maxdim(*size, d);
1640 break;
1643 case WID_ID_INDUSTRY_LIST: {
1644 Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
1645 for (uint i = 0; i < this->industries.size(); i++) {
1646 d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
1648 resize->height = d.height;
1649 d.height *= 5;
1650 d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1651 d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1652 *size = maxdim(*size, d);
1653 break;
1659 void OnClick(Point pt, int widget, int click_count) override
1661 switch (widget) {
1662 case WID_ID_DROPDOWN_ORDER:
1663 this->industries.ToggleSortOrder();
1664 this->SetDirty();
1665 break;
1667 case WID_ID_DROPDOWN_CRITERIA:
1668 ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), WID_ID_DROPDOWN_CRITERIA, 0, 0);
1669 break;
1671 case WID_ID_FILTER_BY_ACC_CARGO: // Cargo filter dropdown
1672 ShowDropDownMenu(this, this->cargo_filter_texts, this->accepted_cargo_filter_criteria, WID_ID_FILTER_BY_ACC_CARGO, 0, 0);
1673 break;
1675 case WID_ID_FILTER_BY_PROD_CARGO: // Cargo filter dropdown
1676 ShowDropDownMenu(this, this->cargo_filter_texts, this->produced_cargo_filter_criteria, WID_ID_FILTER_BY_PROD_CARGO, 0, 0);
1677 break;
1679 case WID_ID_INDUSTRY_LIST: {
1680 uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_ID_INDUSTRY_LIST, WD_FRAMERECT_TOP);
1681 if (p < this->industries.size()) {
1682 if (_ctrl_pressed) {
1683 ShowExtraViewportWindow(this->industries[p]->location.tile);
1684 } else {
1685 ScrollMainWindowToTile(this->industries[p]->location.tile);
1688 break;
1693 void OnDropdownSelect(int widget, int index) override
1695 switch (widget) {
1696 case WID_ID_DROPDOWN_CRITERIA: {
1697 if (this->industries.SortType() != index) {
1698 this->industries.SetSortType(index);
1699 this->BuildSortIndustriesList();
1701 break;
1704 case WID_ID_FILTER_BY_ACC_CARGO: {
1705 this->SetAcceptedCargoFilterIndex(index);
1706 this->BuildSortIndustriesList();
1707 break;
1710 case WID_ID_FILTER_BY_PROD_CARGO: {
1711 this->SetProducedCargoFilterIndex(index);
1712 this->BuildSortIndustriesList();
1713 break;
1718 void OnResize() override
1720 this->vscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST);
1723 void OnPaint() override
1725 if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
1726 this->DrawWidgets();
1729 void OnHundredthTick() override
1731 this->industries.ForceResort();
1732 this->BuildSortIndustriesList();
1736 * Some data on this window has become invalid.
1737 * @param data Information about the changed data.
1738 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1740 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1742 switch (data) {
1743 case IDIWD_FORCE_REBUILD:
1744 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1745 this->industries.ForceRebuild();
1746 break;
1748 case IDIWD_PRODUCTION_CHANGE:
1749 if (this->industries.SortType() == 2) this->industries.ForceResort();
1750 break;
1752 default:
1753 this->industries.ForceResort();
1754 break;
1759 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
1761 /* Available station sorting functions. */
1762 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
1763 &IndustryNameSorter,
1764 &IndustryTypeSorter,
1765 &IndustryProductionSorter,
1766 &IndustryTransportedCargoSorter
1769 /* Names of the sorting functions */
1770 const StringID IndustryDirectoryWindow::sorter_names[] = {
1771 STR_SORT_BY_NAME,
1772 STR_SORT_BY_TYPE,
1773 STR_SORT_BY_PRODUCTION,
1774 STR_SORT_BY_TRANSPORTED,
1775 INVALID_STRING_ID
1779 /** Window definition of the industry directory gui */
1780 static WindowDesc _industry_directory_desc(
1781 WDP_AUTO, "list_industries", 428, 190,
1782 WC_INDUSTRY_DIRECTORY, WC_NONE,
1784 _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
1787 void ShowIndustryDirectory()
1789 AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
1792 /** Widgets of the industry cargoes window. */
1793 static const NWidgetPart _nested_industry_cargoes_widgets[] = {
1794 NWidget(NWID_HORIZONTAL),
1795 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1796 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_IC_CAPTION), SetDataTip(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1797 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1798 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1799 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1800 EndContainer(),
1801 NWidget(NWID_HORIZONTAL),
1802 NWidget(NWID_VERTICAL),
1803 NWidget(WWT_PANEL, COLOUR_BROWN, WID_IC_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(WID_IC_SCROLLBAR), EndContainer(),
1804 NWidget(NWID_HORIZONTAL),
1805 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_IC_NOTIFY),
1806 SetDataTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
1807 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(0, 0), EndContainer(),
1808 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_IND_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1809 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY, STR_INDUSTRY_CARGOES_SELECT_INDUSTRY_TOOLTIP),
1810 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_CARGO_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1811 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_CARGO, STR_INDUSTRY_CARGOES_SELECT_CARGO_TOOLTIP),
1812 EndContainer(),
1813 EndContainer(),
1814 NWidget(NWID_VERTICAL),
1815 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_IC_SCROLLBAR),
1816 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1817 EndContainer(),
1818 EndContainer(),
1821 /** Window description for the industry cargoes window. */
1822 static WindowDesc _industry_cargoes_desc(
1823 WDP_AUTO, "industry_cargoes", 300, 210,
1824 WC_INDUSTRY_CARGOES, WC_NONE,
1826 _nested_industry_cargoes_widgets, lengthof(_nested_industry_cargoes_widgets)
1829 /** Available types of field. */
1830 enum CargoesFieldType {
1831 CFT_EMPTY, ///< Empty field.
1832 CFT_SMALL_EMPTY, ///< Empty small field (for the header).
1833 CFT_INDUSTRY, ///< Display industry.
1834 CFT_CARGO, ///< Display cargo connections.
1835 CFT_CARGO_LABEL, ///< Display cargo labels.
1836 CFT_HEADER, ///< Header text.
1839 static const uint MAX_CARGOES = 16; ///< Maximum number of cargoes carried in a #CFT_CARGO field in #CargoesField.
1841 /** Data about a single field in the #IndustryCargoesWindow panel. */
1842 struct CargoesField {
1843 static const int VERT_INTER_INDUSTRY_SPACE;
1844 static const int HOR_CARGO_BORDER_SPACE;
1845 static const int CARGO_STUB_WIDTH;
1846 static const int HOR_CARGO_WIDTH, HOR_CARGO_SPACE;
1847 static const int VERT_CARGO_SPACE, VERT_CARGO_EDGE;
1848 static const int BLOB_DISTANCE, BLOB_WIDTH, BLOB_HEIGHT;
1850 static const int INDUSTRY_LINE_COLOUR;
1851 static const int CARGO_LINE_COLOUR;
1853 static int small_height, normal_height;
1854 static int cargo_field_width;
1855 static int industry_width;
1856 static uint max_cargoes;
1858 CargoesFieldType type; ///< Type of field.
1859 union {
1860 struct {
1861 IndustryType ind_type; ///< Industry type (#NUM_INDUSTRYTYPES means 'houses').
1862 CargoID other_produced[MAX_CARGOES]; ///< Cargoes produced but not used in this figure.
1863 CargoID other_accepted[MAX_CARGOES]; ///< Cargoes accepted but not used in this figure.
1864 } industry; ///< Industry data (for #CFT_INDUSTRY).
1865 struct {
1866 CargoID vertical_cargoes[MAX_CARGOES]; ///< Cargoes running from top to bottom (cargo ID or #INVALID_CARGO).
1867 byte num_cargoes; ///< Number of cargoes.
1868 CargoID supp_cargoes[MAX_CARGOES]; ///< Cargoes entering from the left (index in #vertical_cargoes, or #INVALID_CARGO).
1869 byte top_end; ///< Stop at the top of the vertical cargoes.
1870 CargoID cust_cargoes[MAX_CARGOES]; ///< Cargoes leaving to the right (index in #vertical_cargoes, or #INVALID_CARGO).
1871 byte bottom_end; ///< Stop at the bottom of the vertical cargoes.
1872 } cargo; ///< Cargo data (for #CFT_CARGO).
1873 struct {
1874 CargoID cargoes[MAX_CARGOES]; ///< Cargoes to display (or #INVALID_CARGO).
1875 bool left_align; ///< Align all cargo texts to the left (else align to the right).
1876 } cargo_label; ///< Label data (for #CFT_CARGO_LABEL).
1877 StringID header; ///< Header text (for #CFT_HEADER).
1878 } u; // Data for each type.
1881 * Make one of the empty fields (#CFT_EMPTY or #CFT_SMALL_EMPTY).
1882 * @param type Type of empty field.
1884 void MakeEmpty(CargoesFieldType type)
1886 this->type = type;
1890 * Make an industry type field.
1891 * @param ind_type Industry type (#NUM_INDUSTRYTYPES means 'houses').
1892 * @note #other_accepted and #other_produced should be filled later.
1894 void MakeIndustry(IndustryType ind_type)
1896 this->type = CFT_INDUSTRY;
1897 this->u.industry.ind_type = ind_type;
1898 MemSetT(this->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
1899 MemSetT(this->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
1903 * Connect a cargo from an industry to the #CFT_CARGO column.
1904 * @param cargo Cargo to connect.
1905 * @param producer Cargo is produced (if \c false, cargo is assumed to be accepted).
1906 * @return Horizontal connection index, or \c -1 if not accepted at all.
1908 int ConnectCargo(CargoID cargo, bool producer)
1910 assert(this->type == CFT_CARGO);
1911 if (cargo == INVALID_CARGO) return -1;
1913 /* Find the vertical cargo column carrying the cargo. */
1914 int column = -1;
1915 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1916 if (cargo == this->u.cargo.vertical_cargoes[i]) {
1917 column = i;
1918 break;
1921 if (column < 0) return -1;
1923 if (producer) {
1924 assert(this->u.cargo.supp_cargoes[column] == INVALID_CARGO);
1925 this->u.cargo.supp_cargoes[column] = column;
1926 } else {
1927 assert(this->u.cargo.cust_cargoes[column] == INVALID_CARGO);
1928 this->u.cargo.cust_cargoes[column] = column;
1930 return column;
1934 * Does this #CFT_CARGO field have a horizontal connection?
1935 * @return \c true if a horizontal connection exists, \c false otherwise.
1937 bool HasConnection()
1939 assert(this->type == CFT_CARGO);
1941 for (uint i = 0; i < MAX_CARGOES; i++) {
1942 if (this->u.cargo.supp_cargoes[i] != INVALID_CARGO) return true;
1943 if (this->u.cargo.cust_cargoes[i] != INVALID_CARGO) return true;
1945 return false;
1949 * Make a piece of cargo column.
1950 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
1951 * @param length Number of cargoes in \a cargoes.
1952 * @param count Number of cargoes to display (should be at least the number of valid cargoes, or \c -1 to let the method compute it).
1953 * @param top_end This is the first cargo field of this column.
1954 * @param bottom_end This is the last cargo field of this column.
1955 * @note #supp_cargoes and #cust_cargoes should be filled in later.
1957 void MakeCargo(const CargoID *cargoes, uint length, int count = -1, bool top_end = false, bool bottom_end = false)
1959 this->type = CFT_CARGO;
1960 uint i;
1961 uint num = 0;
1962 for (i = 0; i < MAX_CARGOES && i < length; i++) {
1963 if (cargoes[i] != INVALID_CARGO) {
1964 this->u.cargo.vertical_cargoes[num] = cargoes[i];
1965 num++;
1968 this->u.cargo.num_cargoes = (count < 0) ? num : count;
1969 for (; num < MAX_CARGOES; num++) this->u.cargo.vertical_cargoes[num] = INVALID_CARGO;
1970 this->u.cargo.top_end = top_end;
1971 this->u.cargo.bottom_end = bottom_end;
1972 MemSetT(this->u.cargo.supp_cargoes, INVALID_CARGO, MAX_CARGOES);
1973 MemSetT(this->u.cargo.cust_cargoes, INVALID_CARGO, MAX_CARGOES);
1977 * Make a field displaying cargo type names.
1978 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
1979 * @param length Number of cargoes in \a cargoes.
1980 * @param left_align ALign texts to the left (else to the right).
1982 void MakeCargoLabel(const CargoID *cargoes, uint length, bool left_align)
1984 this->type = CFT_CARGO_LABEL;
1985 uint i;
1986 for (i = 0; i < MAX_CARGOES && i < length; i++) this->u.cargo_label.cargoes[i] = cargoes[i];
1987 for (; i < MAX_CARGOES; i++) this->u.cargo_label.cargoes[i] = INVALID_CARGO;
1988 this->u.cargo_label.left_align = left_align;
1992 * Make a header above an industry column.
1993 * @param textid Text to display.
1995 void MakeHeader(StringID textid)
1997 this->type = CFT_HEADER;
1998 this->u.header = textid;
2002 * For a #CFT_CARGO, compute the left position of the left-most vertical cargo connection.
2003 * @param xpos Left position of the field.
2004 * @return Left position of the left-most vertical cargo column.
2006 int GetCargoBase(int xpos) const
2008 assert(this->type == CFT_CARGO);
2009 int n = this->u.cargo.num_cargoes;
2011 if (n % 2 == 0) {
2012 return xpos + cargo_field_width / 2 - (HOR_CARGO_WIDTH + HOR_CARGO_SPACE / 2) * (n / 2);
2013 } else {
2014 return xpos + cargo_field_width / 2 - HOR_CARGO_WIDTH / 2 - (HOR_CARGO_WIDTH + HOR_CARGO_SPACE) * (n / 2);
2019 * Draw the field.
2020 * @param xpos Position of the left edge.
2021 * @param ypos Position of the top edge.
2023 void Draw(int xpos, int ypos) const
2025 switch (this->type) {
2026 case CFT_EMPTY:
2027 case CFT_SMALL_EMPTY:
2028 break;
2030 case CFT_HEADER:
2031 ypos += (small_height - FONT_HEIGHT_NORMAL) / 2;
2032 DrawString(xpos, xpos + industry_width, ypos, this->u.header, TC_WHITE, SA_HOR_CENTER);
2033 break;
2035 case CFT_INDUSTRY: {
2036 int ypos1 = ypos + VERT_INTER_INDUSTRY_SPACE / 2;
2037 int ypos2 = ypos + normal_height - 1 - VERT_INTER_INDUSTRY_SPACE / 2;
2038 int xpos2 = xpos + industry_width - 1;
2039 GfxDrawLine(xpos, ypos1, xpos2, ypos1, INDUSTRY_LINE_COLOUR);
2040 GfxDrawLine(xpos, ypos1, xpos, ypos2, INDUSTRY_LINE_COLOUR);
2041 GfxDrawLine(xpos, ypos2, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
2042 GfxDrawLine(xpos2, ypos1, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
2043 ypos += (normal_height - FONT_HEIGHT_NORMAL) / 2;
2044 if (this->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2045 const IndustrySpec *indsp = GetIndustrySpec(this->u.industry.ind_type);
2046 DrawString(xpos, xpos2, ypos, indsp->name, TC_WHITE, SA_HOR_CENTER);
2048 /* Draw the industry legend. */
2049 int blob_left, blob_right;
2050 if (_current_text_dir == TD_RTL) {
2051 blob_right = xpos2 - BLOB_DISTANCE;
2052 blob_left = blob_right - BLOB_WIDTH;
2053 } else {
2054 blob_left = xpos + BLOB_DISTANCE;
2055 blob_right = blob_left + BLOB_WIDTH;
2057 GfxFillRect(blob_left, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT, blob_right, ypos2 - BLOB_DISTANCE, PC_BLACK); // Border
2058 GfxFillRect(blob_left + 1, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT + 1, blob_right - 1, ypos2 - BLOB_DISTANCE - 1, indsp->map_colour);
2059 } else {
2060 DrawString(xpos, xpos2, ypos, STR_INDUSTRY_CARGOES_HOUSES, TC_FROMSTRING, SA_HOR_CENTER);
2063 /* Draw the other_produced/other_accepted cargoes. */
2064 const CargoID *other_right, *other_left;
2065 if (_current_text_dir == TD_RTL) {
2066 other_right = this->u.industry.other_accepted;
2067 other_left = this->u.industry.other_produced;
2068 } else {
2069 other_right = this->u.industry.other_produced;
2070 other_left = this->u.industry.other_accepted;
2072 ypos1 += VERT_CARGO_EDGE;
2073 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2074 if (other_right[i] != INVALID_CARGO) {
2075 const CargoSpec *csp = CargoSpec::Get(other_right[i]);
2076 int xp = xpos + industry_width + CARGO_STUB_WIDTH;
2077 DrawHorConnection(xpos + industry_width, xp - 1, ypos1, csp);
2078 GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
2080 if (other_left[i] != INVALID_CARGO) {
2081 const CargoSpec *csp = CargoSpec::Get(other_left[i]);
2082 int xp = xpos - CARGO_STUB_WIDTH;
2083 DrawHorConnection(xp + 1, xpos - 1, ypos1, csp);
2084 GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
2086 ypos1 += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2088 break;
2091 case CFT_CARGO: {
2092 int cargo_base = this->GetCargoBase(xpos);
2093 int top = ypos + (this->u.cargo.top_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0);
2094 int bot = ypos - (this->u.cargo.bottom_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0) + normal_height - 1;
2095 int colpos = cargo_base;
2096 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
2097 if (this->u.cargo.top_end) GfxDrawLine(colpos, top - 1, colpos + HOR_CARGO_WIDTH - 1, top - 1, CARGO_LINE_COLOUR);
2098 if (this->u.cargo.bottom_end) GfxDrawLine(colpos, bot + 1, colpos + HOR_CARGO_WIDTH - 1, bot + 1, CARGO_LINE_COLOUR);
2099 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
2100 colpos++;
2101 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[i]);
2102 GfxFillRect(colpos, top, colpos + HOR_CARGO_WIDTH - 2, bot, csp->legend_colour, FILLRECT_OPAQUE);
2103 colpos += HOR_CARGO_WIDTH - 2;
2104 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
2105 colpos += 1 + HOR_CARGO_SPACE;
2108 const CargoID *hor_left, *hor_right;
2109 if (_current_text_dir == TD_RTL) {
2110 hor_left = this->u.cargo.cust_cargoes;
2111 hor_right = this->u.cargo.supp_cargoes;
2112 } else {
2113 hor_left = this->u.cargo.supp_cargoes;
2114 hor_right = this->u.cargo.cust_cargoes;
2116 ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
2117 for (uint i = 0; i < MAX_CARGOES; i++) {
2118 if (hor_left[i] != INVALID_CARGO) {
2119 int col = hor_left[i];
2120 int dx = 0;
2121 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
2122 for (; col > 0; col--) {
2123 int lf = cargo_base + col * HOR_CARGO_WIDTH + (col - 1) * HOR_CARGO_SPACE;
2124 DrawHorConnection(lf, lf + HOR_CARGO_SPACE - dx, ypos, csp);
2125 dx = 1;
2127 DrawHorConnection(xpos, cargo_base - dx, ypos, csp);
2129 if (hor_right[i] != INVALID_CARGO) {
2130 int col = hor_right[i];
2131 int dx = 0;
2132 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
2133 for (; col < this->u.cargo.num_cargoes - 1; col++) {
2134 int lf = cargo_base + (col + 1) * HOR_CARGO_WIDTH + col * HOR_CARGO_SPACE;
2135 DrawHorConnection(lf + dx - 1, lf + HOR_CARGO_SPACE - 1, ypos, csp);
2136 dx = 1;
2138 DrawHorConnection(cargo_base + col * HOR_CARGO_SPACE + (col + 1) * HOR_CARGO_WIDTH - 1 + dx, xpos + CargoesField::cargo_field_width - 1, ypos, csp);
2140 ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2142 break;
2145 case CFT_CARGO_LABEL:
2146 ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
2147 for (uint i = 0; i < MAX_CARGOES; i++) {
2148 if (this->u.cargo_label.cargoes[i] != INVALID_CARGO) {
2149 const CargoSpec *csp = CargoSpec::Get(this->u.cargo_label.cargoes[i]);
2150 DrawString(xpos + WD_FRAMERECT_LEFT, xpos + industry_width - 1 - WD_FRAMERECT_RIGHT, ypos, csp->name, TC_WHITE,
2151 (this->u.cargo_label.left_align) ? SA_LEFT : SA_RIGHT);
2153 ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2155 break;
2157 default:
2158 NOT_REACHED();
2163 * Decide which cargo was clicked at in a #CFT_CARGO field.
2164 * @param left Left industry neighbour if available (else \c nullptr should be supplied).
2165 * @param right Right industry neighbour if available (else \c nullptr should be supplied).
2166 * @param pt Click position in the cargo field.
2167 * @return Cargo clicked at, or #INVALID_CARGO if none.
2169 CargoID CargoClickedAt(const CargoesField *left, const CargoesField *right, Point pt) const
2171 assert(this->type == CFT_CARGO);
2173 /* Vertical matching. */
2174 int cpos = this->GetCargoBase(0);
2175 uint col;
2176 for (col = 0; col < this->u.cargo.num_cargoes; col++) {
2177 if (pt.x < cpos) break;
2178 if (pt.x < cpos + CargoesField::HOR_CARGO_WIDTH) return this->u.cargo.vertical_cargoes[col];
2179 cpos += CargoesField::HOR_CARGO_WIDTH + CargoesField::HOR_CARGO_SPACE;
2181 /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */
2183 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
2184 uint row;
2185 for (row = 0; row < MAX_CARGOES; row++) {
2186 if (pt.y < vpos) return INVALID_CARGO;
2187 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
2188 vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2190 if (row == MAX_CARGOES) return INVALID_CARGO;
2192 /* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
2193 if (col == 0) {
2194 if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
2195 if (left != nullptr) {
2196 if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
2197 if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
2199 return INVALID_CARGO;
2201 if (col == this->u.cargo.num_cargoes) {
2202 if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
2203 if (right != nullptr) {
2204 if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
2205 if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
2207 return INVALID_CARGO;
2209 if (row >= col) {
2210 /* Clicked somewhere in-between vertical cargo connection.
2211 * Since the horizontal connection is made in the same order as the vertical list, the above condition
2212 * ensures we are left-below the main diagonal, thus at the supplying side.
2214 return (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]] : INVALID_CARGO;
2215 } else {
2216 /* Clicked at a customer connection. */
2217 return (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]] : INVALID_CARGO;
2222 * Decide what cargo the user clicked in the cargo label field.
2223 * @param pt Click position in the cargo label field.
2224 * @return Cargo clicked at, or #INVALID_CARGO if none.
2226 CargoID CargoLabelClickedAt(Point pt) const
2228 assert(this->type == CFT_CARGO_LABEL);
2230 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
2231 uint row;
2232 for (row = 0; row < MAX_CARGOES; row++) {
2233 if (pt.y < vpos) return INVALID_CARGO;
2234 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
2235 vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
2237 if (row == MAX_CARGOES) return INVALID_CARGO;
2238 return this->u.cargo_label.cargoes[row];
2241 private:
2243 * Draw a horizontal cargo connection.
2244 * @param left Left-most coordinate to draw.
2245 * @param right Right-most coordinate to draw.
2246 * @param top Top coordinate of the cargo connection.
2247 * @param csp Cargo to draw.
2249 static void DrawHorConnection(int left, int right, int top, const CargoSpec *csp)
2251 GfxDrawLine(left, top, right, top, CARGO_LINE_COLOUR);
2252 GfxFillRect(left, top + 1, right, top + FONT_HEIGHT_NORMAL - 2, csp->legend_colour, FILLRECT_OPAQUE);
2253 GfxDrawLine(left, top + FONT_HEIGHT_NORMAL - 1, right, top + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
2257 static_assert(MAX_CARGOES >= cpp_lengthof(IndustrySpec, produced_cargo));
2258 static_assert(MAX_CARGOES >= cpp_lengthof(IndustrySpec, accepts_cargo));
2260 int CargoesField::small_height; ///< Height of the header row.
2261 int CargoesField::normal_height; ///< Height of the non-header rows.
2262 int CargoesField::industry_width; ///< Width of an industry field.
2263 int CargoesField::cargo_field_width; ///< Width of a cargo field.
2264 uint CargoesField::max_cargoes; ///< Largest number of cargoes actually on any industry.
2265 const int CargoesField::VERT_INTER_INDUSTRY_SPACE = 6; ///< Amount of space between two industries in a column.
2267 const int CargoesField::HOR_CARGO_BORDER_SPACE = 15; ///< Amount of space between the left/right edge of a #CFT_CARGO field, and the left/right most vertical cargo.
2268 const int CargoesField::CARGO_STUB_WIDTH = 10; ///< Width of a cargo not carried in the column (should be less than #HOR_CARGO_BORDER_SPACE).
2269 const int CargoesField::HOR_CARGO_WIDTH = 15; ///< Width of a vertical cargo column (inclusive the border line).
2270 const int CargoesField::HOR_CARGO_SPACE = 5; ///< Amount of horizontal space between two vertical cargoes.
2271 const int CargoesField::VERT_CARGO_EDGE = 4; ///< Amount of vertical space between top/bottom and the top/bottom connected cargo at an industry.
2272 const int CargoesField::VERT_CARGO_SPACE = 4; ///< Amount of vertical space between two connected cargoes at an industry.
2274 const int CargoesField::BLOB_DISTANCE = 5; ///< Distance of the industry legend colour from the edge of the industry box.
2275 const int CargoesField::BLOB_WIDTH = 12; ///< Width of the industry legend colour, including border.
2276 const int CargoesField::BLOB_HEIGHT = 9; ///< Height of the industry legend colour, including border
2278 const int CargoesField::INDUSTRY_LINE_COLOUR = PC_YELLOW; ///< Line colour of the industry type box.
2279 const int CargoesField::CARGO_LINE_COLOUR = PC_YELLOW; ///< Line colour around the cargo.
2281 /** A single row of #CargoesField. */
2282 struct CargoesRow {
2283 CargoesField columns[5]; ///< One row of fields.
2286 * Connect industry production cargoes to the cargo column after it.
2287 * @param column Column of the industry.
2289 void ConnectIndustryProduced(int column)
2291 CargoesField *ind_fld = this->columns + column;
2292 CargoesField *cargo_fld = this->columns + column + 1;
2293 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
2295 MemSetT(ind_fld->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
2297 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2298 CargoID others[MAX_CARGOES]; // Produced cargoes not carried in the cargo column.
2299 int other_count = 0;
2301 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
2302 assert(CargoesField::max_cargoes <= lengthof(indsp->produced_cargo));
2303 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2304 int col = cargo_fld->ConnectCargo(indsp->produced_cargo[i], true);
2305 if (col < 0) others[other_count++] = indsp->produced_cargo[i];
2308 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2309 for (uint i = 0; i < CargoesField::max_cargoes && other_count > 0; i++) {
2310 if (cargo_fld->u.cargo.supp_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_produced[i] = others[--other_count];
2312 } else {
2313 /* Houses only display what is demanded. */
2314 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2315 CargoID cid = cargo_fld->u.cargo.vertical_cargoes[i];
2316 if (cid == CT_PASSENGERS || cid == CT_MAIL) cargo_fld->ConnectCargo(cid, true);
2322 * Construct a #CFT_CARGO_LABEL field.
2323 * @param column Column to create the new field.
2324 * @param accepting Display accepted cargo (if \c false, display produced cargo).
2326 void MakeCargoLabel(int column, bool accepting)
2328 CargoID cargoes[MAX_CARGOES];
2329 MemSetT(cargoes, INVALID_CARGO, lengthof(cargoes));
2331 CargoesField *label_fld = this->columns + column;
2332 CargoesField *cargo_fld = this->columns + (accepting ? column - 1 : column + 1);
2334 assert(cargo_fld->type == CFT_CARGO && label_fld->type == CFT_EMPTY);
2335 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2336 int col = cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], !accepting);
2337 if (col >= 0) cargoes[col] = cargo_fld->u.cargo.vertical_cargoes[i];
2339 label_fld->MakeCargoLabel(cargoes, lengthof(cargoes), accepting);
2344 * Connect industry accepted cargoes to the cargo column before it.
2345 * @param column Column of the industry.
2347 void ConnectIndustryAccepted(int column)
2349 CargoesField *ind_fld = this->columns + column;
2350 CargoesField *cargo_fld = this->columns + column - 1;
2351 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
2353 MemSetT(ind_fld->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
2355 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2356 CargoID others[MAX_CARGOES]; // Accepted cargoes not carried in the cargo column.
2357 int other_count = 0;
2359 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
2360 assert(CargoesField::max_cargoes <= lengthof(indsp->accepts_cargo));
2361 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2362 int col = cargo_fld->ConnectCargo(indsp->accepts_cargo[i], false);
2363 if (col < 0) others[other_count++] = indsp->accepts_cargo[i];
2366 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2367 for (uint i = 0; i < CargoesField::max_cargoes && other_count > 0; i++) {
2368 if (cargo_fld->u.cargo.cust_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_accepted[i] = others[--other_count];
2370 } else {
2371 /* Houses only display what is demanded. */
2372 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2373 for (uint h = 0; h < NUM_HOUSES; h++) {
2374 HouseSpec *hs = HouseSpec::Get(h);
2375 if (!hs->enabled) continue;
2377 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2378 if (hs->cargo_acceptance[j] > 0 && cargo_fld->u.cargo.vertical_cargoes[i] == hs->accepts_cargo[j]) {
2379 cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
2380 goto next_cargo;
2384 next_cargo: ;
2392 * Window displaying the cargo connections around an industry (or cargo).
2394 * The main display is constructed from 'fields', rectangles that contain an industry, piece of the cargo connection, cargo labels, or headers.
2395 * For a nice display, the following should be kept in mind:
2396 * - A #CFT_HEADER is always at the top of an column of #CFT_INDUSTRY fields.
2397 * - A #CFT_CARGO_LABEL field is also always put in a column of #CFT_INDUSTRY fields.
2398 * - The top row contains #CFT_HEADER and #CFT_SMALL_EMPTY fields.
2399 * - Cargo connections have a column of their own (#CFT_CARGO fields).
2400 * - Cargo accepted or produced by an industry, but not carried in a cargo connection, is drawn in the space of a cargo column attached to the industry.
2401 * The information however is part of the industry.
2403 * This results in the following invariants:
2404 * - Width of a #CFT_INDUSTRY column is large enough to hold all industry type labels, all cargo labels, and all header texts.
2405 * - Height of a #CFT_INDUSTRY is large enough to hold a header line, or a industry type line, \c N cargo labels
2406 * (where \c N is the maximum number of cargoes connected between industries), \c N connections of cargo types, and space
2407 * between two industry types (1/2 above it, and 1/2 underneath it).
2408 * - Width of a cargo field (#CFT_CARGO) is large enough to hold \c N vertical columns (one for each type of cargo).
2409 * Also, space is needed between an industry and the leftmost/rightmost column to draw the non-carried cargoes.
2410 * - Height of a #CFT_CARGO field is equally high as the height of the #CFT_INDUSTRY.
2411 * - A field at the top (#CFT_HEADER or #CFT_SMALL_EMPTY) match the width of the fields below them (#CFT_INDUSTRY respectively
2412 * #CFT_CARGO), the height should be sufficient to display the header text.
2414 * When displaying the cargoes around an industry type, five columns are needed (supplying industries, accepted cargoes, the industry,
2415 * produced cargoes, customer industries). Displaying the industries around a cargo needs three columns (supplying industries, the cargo,
2416 * customer industries). The remaining two columns are set to #CFT_EMPTY with a width equal to the average of a cargo and an industry column.
2418 struct IndustryCargoesWindow : public Window {
2419 static const int HOR_TEXT_PADDING, VERT_TEXT_PADDING;
2421 typedef std::vector<CargoesRow> Fields;
2423 Fields fields; ///< Fields to display in the #WID_IC_PANEL.
2424 uint ind_cargo; ///< If less than #NUM_INDUSTRYTYPES, an industry type, else a cargo id + NUM_INDUSTRYTYPES.
2425 Dimension cargo_textsize; ///< Size to hold any cargo text, as well as STR_INDUSTRY_CARGOES_SELECT_CARGO.
2426 Dimension ind_textsize; ///< Size to hold any industry type text, as well as STR_INDUSTRY_CARGOES_SELECT_INDUSTRY.
2427 Scrollbar *vscroll;
2429 IndustryCargoesWindow(int id) : Window(&_industry_cargoes_desc)
2431 this->OnInit();
2432 this->CreateNestedTree();
2433 this->vscroll = this->GetScrollbar(WID_IC_SCROLLBAR);
2434 this->FinishInitNested(0);
2435 this->OnInvalidateData(id);
2438 void OnInit() override
2440 /* Initialize static CargoesField size variables. */
2441 Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_PRODUCERS);
2442 d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_CUSTOMERS));
2443 d.width += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
2444 d.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM;
2445 CargoesField::small_height = d.height;
2447 /* Decide about the size of the box holding the text of an industry type. */
2448 this->ind_textsize.width = 0;
2449 this->ind_textsize.height = 0;
2450 CargoesField::max_cargoes = 0;
2451 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2452 const IndustrySpec *indsp = GetIndustrySpec(it);
2453 if (!indsp->enabled) continue;
2454 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(indsp->name));
2455 CargoesField::max_cargoes = std::max<uint>(CargoesField::max_cargoes, std::count_if(indsp->accepts_cargo, endof(indsp->accepts_cargo), IsCargoIDValid));
2456 CargoesField::max_cargoes = std::max<uint>(CargoesField::max_cargoes, std::count_if(indsp->produced_cargo, endof(indsp->produced_cargo), IsCargoIDValid));
2458 d.width = std::max(d.width, this->ind_textsize.width);
2459 d.height = this->ind_textsize.height;
2460 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
2462 /* Compute max size of the cargo texts. */
2463 this->cargo_textsize.width = 0;
2464 this->cargo_textsize.height = 0;
2465 for (uint i = 0; i < NUM_CARGO; i++) {
2466 const CargoSpec *csp = CargoSpec::Get(i);
2467 if (!csp->IsValid()) continue;
2468 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(csp->name));
2470 d = maxdim(d, this->cargo_textsize); // Box must also be wide enough to hold any cargo label.
2471 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
2473 d.width += 2 * HOR_TEXT_PADDING;
2474 /* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
2475 uint min_ind_height = CargoesField::VERT_CARGO_EDGE * 2 + CargoesField::max_cargoes * FONT_HEIGHT_NORMAL + (CargoesField::max_cargoes - 1) * CargoesField::VERT_CARGO_SPACE;
2476 d.height = std::max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
2478 CargoesField::industry_width = d.width;
2479 CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
2481 /* Width of a #CFT_CARGO field. */
2482 CargoesField::cargo_field_width = CargoesField::HOR_CARGO_BORDER_SPACE * 2 + CargoesField::HOR_CARGO_WIDTH * CargoesField::max_cargoes + CargoesField::HOR_CARGO_SPACE * (CargoesField::max_cargoes - 1);
2485 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2487 switch (widget) {
2488 case WID_IC_PANEL:
2489 size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::cargo_field_width * 2 + WD_FRAMETEXT_RIGHT;
2490 break;
2492 case WID_IC_IND_DROPDOWN:
2493 size->width = std::max(size->width, this->ind_textsize.width + padding.width);
2494 break;
2496 case WID_IC_CARGO_DROPDOWN:
2497 size->width = std::max(size->width, this->cargo_textsize.width + padding.width);
2498 break;
2503 CargoesFieldType type; ///< Type of field.
2504 void SetStringParameters (int widget) const override
2506 if (widget != WID_IC_CAPTION) return;
2508 if (this->ind_cargo < NUM_INDUSTRYTYPES) {
2509 const IndustrySpec *indsp = GetIndustrySpec(this->ind_cargo);
2510 SetDParam(0, indsp->name);
2511 } else {
2512 const CargoSpec *csp = CargoSpec::Get(this->ind_cargo - NUM_INDUSTRYTYPES);
2513 SetDParam(0, csp->name);
2518 * Do the two sets of cargoes have a valid cargo in common?
2519 * @param cargoes1 Base address of the first cargo array.
2520 * @param length1 Number of cargoes in the first cargo array.
2521 * @param cargoes2 Base address of the second cargo array.
2522 * @param length2 Number of cargoes in the second cargo array.
2523 * @return Arrays have at least one valid cargo in common.
2525 static bool HasCommonValidCargo(const CargoID *cargoes1, uint length1, const CargoID *cargoes2, uint length2)
2527 while (length1 > 0) {
2528 if (*cargoes1 != INVALID_CARGO) {
2529 for (uint i = 0; i < length2; i++) if (*cargoes1 == cargoes2[i]) return true;
2531 cargoes1++;
2532 length1--;
2534 return false;
2538 * Can houses be used to supply one of the cargoes?
2539 * @param cargoes Base address of the cargo array.
2540 * @param length Number of cargoes in the array.
2541 * @return Houses can supply at least one of the cargoes.
2543 static bool HousesCanSupply(const CargoID *cargoes, uint length)
2545 for (uint i = 0; i < length; i++) {
2546 if (cargoes[i] == INVALID_CARGO) continue;
2547 if (cargoes[i] == CT_PASSENGERS || cargoes[i] == CT_MAIL) return true;
2549 return false;
2553 * Can houses be used as customers of the produced cargoes?
2554 * @param cargoes Base address of the cargo array.
2555 * @param length Number of cargoes in the array.
2556 * @return Houses can accept at least one of the cargoes.
2558 static bool HousesCanAccept(const CargoID *cargoes, uint length)
2560 HouseZones climate_mask;
2561 switch (_settings_game.game_creation.landscape) {
2562 case LT_TEMPERATE: climate_mask = HZ_TEMP; break;
2563 case LT_ARCTIC: climate_mask = HZ_SUBARTC_ABOVE | HZ_SUBARTC_BELOW; break;
2564 case LT_TROPIC: climate_mask = HZ_SUBTROPIC; break;
2565 case LT_TOYLAND: climate_mask = HZ_TOYLND; break;
2566 default: NOT_REACHED();
2568 for (uint i = 0; i < length; i++) {
2569 if (cargoes[i] == INVALID_CARGO) continue;
2571 for (uint h = 0; h < NUM_HOUSES; h++) {
2572 HouseSpec *hs = HouseSpec::Get(h);
2573 if (!hs->enabled || !(hs->building_availability & climate_mask)) continue;
2575 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2576 if (hs->cargo_acceptance[j] > 0 && cargoes[i] == hs->accepts_cargo[j]) return true;
2580 return false;
2584 * Count how many industries have accepted cargoes in common with one of the supplied set.
2585 * @param cargoes Cargoes to search.
2586 * @param length Number of cargoes in \a cargoes.
2587 * @return Number of industries that have an accepted cargo in common with the supplied set.
2589 static int CountMatchingAcceptingIndustries(const CargoID *cargoes, uint length)
2591 int count = 0;
2592 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2593 const IndustrySpec *indsp = GetIndustrySpec(it);
2594 if (!indsp->enabled) continue;
2596 if (HasCommonValidCargo(cargoes, length, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) count++;
2598 return count;
2602 * Count how many industries have produced cargoes in common with one of the supplied set.
2603 * @param cargoes Cargoes to search.
2604 * @param length Number of cargoes in \a cargoes.
2605 * @return Number of industries that have a produced cargo in common with the supplied set.
2607 static int CountMatchingProducingIndustries(const CargoID *cargoes, uint length)
2609 int count = 0;
2610 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2611 const IndustrySpec *indsp = GetIndustrySpec(it);
2612 if (!indsp->enabled) continue;
2614 if (HasCommonValidCargo(cargoes, length, indsp->produced_cargo, lengthof(indsp->produced_cargo))) count++;
2616 return count;
2620 * Shorten the cargo column to just the part between industries.
2621 * @param column Column number of the cargo column.
2622 * @param top Current top row.
2623 * @param bottom Current bottom row.
2625 void ShortenCargoColumn(int column, int top, int bottom)
2627 while (top < bottom && !this->fields[top].columns[column].HasConnection()) {
2628 this->fields[top].columns[column].MakeEmpty(CFT_EMPTY);
2629 top++;
2631 this->fields[top].columns[column].u.cargo.top_end = true;
2633 while (bottom > top && !this->fields[bottom].columns[column].HasConnection()) {
2634 this->fields[bottom].columns[column].MakeEmpty(CFT_EMPTY);
2635 bottom--;
2637 this->fields[bottom].columns[column].u.cargo.bottom_end = true;
2641 * Place an industry in the fields.
2642 * @param row Row of the new industry.
2643 * @param col Column of the new industry.
2644 * @param it Industry to place.
2646 void PlaceIndustry(int row, int col, IndustryType it)
2648 assert(this->fields[row].columns[col].type == CFT_EMPTY);
2649 this->fields[row].columns[col].MakeIndustry(it);
2650 if (col == 0) {
2651 this->fields[row].ConnectIndustryProduced(col);
2652 } else {
2653 this->fields[row].ConnectIndustryAccepted(col);
2658 * Notify smallmap that new displayed industries have been selected (in #_displayed_industries).
2660 void NotifySmallmap()
2662 if (!this->IsWidgetLowered(WID_IC_NOTIFY)) return;
2664 /* Only notify the smallmap window if it exists. In particular, do not
2665 * bring it to the front to prevent messing up any nice layout of the user. */
2666 InvalidateWindowClassesData(WC_SMALLMAP, 0);
2670 * Compute what and where to display for industry type \a it.
2671 * @param it Industry type to display.
2673 void ComputeIndustryDisplay(IndustryType it)
2675 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION;
2676 this->ind_cargo = it;
2677 _displayed_industries.reset();
2678 _displayed_industries.set(it);
2680 this->fields.clear();
2681 CargoesRow &row = this->fields.emplace_back();
2682 row.columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2683 row.columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2684 row.columns[2].MakeEmpty(CFT_SMALL_EMPTY);
2685 row.columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2686 row.columns[4].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2688 const IndustrySpec *central_sp = GetIndustrySpec(it);
2689 bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2690 bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2691 /* Make a field consisting of two cargo columns. */
2692 int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
2693 int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
2694 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.
2695 for (int i = 0; i < num_indrows; i++) {
2696 CargoesRow &row = this->fields.emplace_back();
2697 row.columns[0].MakeEmpty(CFT_EMPTY);
2698 row.columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2699 row.columns[2].MakeEmpty(CFT_EMPTY);
2700 row.columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2701 row.columns[4].MakeEmpty(CFT_EMPTY);
2703 /* Add central industry. */
2704 int central_row = 1 + num_indrows / 2;
2705 this->fields[central_row].columns[2].MakeIndustry(it);
2706 this->fields[central_row].ConnectIndustryProduced(2);
2707 this->fields[central_row].ConnectIndustryAccepted(2);
2709 /* Add cargo labels. */
2710 this->fields[central_row - 1].MakeCargoLabel(2, true);
2711 this->fields[central_row + 1].MakeCargoLabel(2, false);
2713 /* Add suppliers and customers of the 'it' industry. */
2714 int supp_count = 0;
2715 int cust_count = 0;
2716 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2717 const IndustrySpec *indsp = GetIndustrySpec(it);
2718 if (!indsp->enabled) continue;
2720 if (HasCommonValidCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo), indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2721 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2722 _displayed_industries.set(it);
2723 supp_count++;
2725 if (HasCommonValidCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo), indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2726 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, it);
2727 _displayed_industries.set(it);
2728 cust_count++;
2731 if (houses_supply) {
2732 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2733 supp_count++;
2735 if (houses_accept) {
2736 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, NUM_INDUSTRYTYPES);
2737 cust_count++;
2740 this->ShortenCargoColumn(1, 1, num_indrows);
2741 this->ShortenCargoColumn(3, 1, num_indrows);
2742 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2743 this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
2744 this->SetDirty();
2745 this->NotifySmallmap();
2749 * Compute what and where to display for cargo id \a cid.
2750 * @param cid Cargo id to display.
2752 void ComputeCargoDisplay(CargoID cid)
2754 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_CARGO_CAPTION;
2755 this->ind_cargo = cid + NUM_INDUSTRYTYPES;
2756 _displayed_industries.reset();
2758 this->fields.clear();
2759 CargoesRow &row = this->fields.emplace_back();
2760 row.columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2761 row.columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2762 row.columns[2].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2763 row.columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2764 row.columns[4].MakeEmpty(CFT_SMALL_EMPTY);
2766 bool houses_supply = HousesCanSupply(&cid, 1);
2767 bool houses_accept = HousesCanAccept(&cid, 1);
2768 int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
2769 int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
2770 int num_indrows = std::max(num_supp, num_cust);
2771 for (int i = 0; i < num_indrows; i++) {
2772 CargoesRow &row = this->fields.emplace_back();
2773 row.columns[0].MakeEmpty(CFT_EMPTY);
2774 row.columns[1].MakeCargo(&cid, 1);
2775 row.columns[2].MakeEmpty(CFT_EMPTY);
2776 row.columns[3].MakeEmpty(CFT_EMPTY);
2777 row.columns[4].MakeEmpty(CFT_EMPTY);
2780 this->fields[num_indrows].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
2782 /* Add suppliers and customers of the cargo. */
2783 int supp_count = 0;
2784 int cust_count = 0;
2785 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2786 const IndustrySpec *indsp = GetIndustrySpec(it);
2787 if (!indsp->enabled) continue;
2789 if (HasCommonValidCargo(&cid, 1, indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2790 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2791 _displayed_industries.set(it);
2792 supp_count++;
2794 if (HasCommonValidCargo(&cid, 1, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2795 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, it);
2796 _displayed_industries.set(it);
2797 cust_count++;
2800 if (houses_supply) {
2801 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2802 supp_count++;
2804 if (houses_accept) {
2805 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, NUM_INDUSTRYTYPES);
2806 cust_count++;
2809 this->ShortenCargoColumn(1, 1, num_indrows);
2810 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2811 this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
2812 this->SetDirty();
2813 this->NotifySmallmap();
2817 * Some data on this window has become invalid.
2818 * @param data Information about the changed data.
2819 * - data = 0 .. NUM_INDUSTRYTYPES - 1: Display the chain around the given industry.
2820 * - data = NUM_INDUSTRYTYPES: Stop sending updates to the smallmap window.
2821 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
2823 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2825 if (!gui_scope) return;
2826 if (data == NUM_INDUSTRYTYPES) {
2827 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2828 this->RaiseWidget(WID_IC_NOTIFY);
2829 this->SetWidgetDirty(WID_IC_NOTIFY);
2831 return;
2834 assert(data >= 0 && data < NUM_INDUSTRYTYPES);
2835 this->ComputeIndustryDisplay(data);
2838 void DrawWidget(const Rect &r, int widget) const override
2840 if (widget != WID_IC_PANEL) return;
2842 DrawPixelInfo tmp_dpi, *old_dpi;
2843 int width = r.right - r.left + 1;
2844 int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
2845 if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
2846 old_dpi = _cur_dpi;
2847 _cur_dpi = &tmp_dpi;
2849 int left_pos = WD_FRAMERECT_LEFT;
2850 if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::cargo_field_width) / 2;
2851 int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2853 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2854 int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
2855 for (uint i = 0; i < this->fields.size(); i++) {
2856 int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
2857 if (vpos + row_height >= 0) {
2858 int xpos = left_pos;
2859 int col, dir;
2860 if (_current_text_dir == TD_RTL) {
2861 col = last_column;
2862 dir = -1;
2863 } else {
2864 col = 0;
2865 dir = 1;
2867 while (col >= 0 && col <= last_column) {
2868 this->fields[i].columns[col].Draw(xpos, vpos);
2869 xpos += (col & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width;
2870 col += dir;
2873 vpos += row_height;
2874 if (vpos >= height) break;
2877 _cur_dpi = old_dpi;
2881 * Calculate in which field was clicked, and within the field, at what position.
2882 * @param pt Clicked position in the #WID_IC_PANEL widget.
2883 * @param fieldxy If \c true is returned, field x/y coordinate of \a pt.
2884 * @param xy If \c true is returned, x/y coordinate with in the field.
2885 * @return Clicked at a valid position.
2887 bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
2889 const NWidgetBase *nw = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2890 pt.x -= nw->pos_x;
2891 pt.y -= nw->pos_y;
2893 int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
2894 if (pt.y < vpos) return false;
2896 int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
2897 if (row + 1 >= (int)this->fields.size()) return false;
2898 vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
2899 row++; // rebase row to match index of this->fields.
2901 int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 : (CargoesField::industry_width + CargoesField::cargo_field_width) / 2);
2902 if (pt.x < xpos) return false;
2903 int column;
2904 for (column = 0; column <= 5; column++) {
2905 int width = (column & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width;
2906 if (pt.x < xpos + width) break;
2907 xpos += width;
2909 int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2910 if (column > num_columns) return false;
2911 xpos = pt.x - xpos;
2913 /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
2914 fieldxy->y = row;
2915 xy->y = vpos;
2916 if (_current_text_dir == TD_RTL) {
2917 fieldxy->x = num_columns - column;
2918 xy->x = ((column & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width) - xpos;
2919 } else {
2920 fieldxy->x = column;
2921 xy->x = xpos;
2923 return true;
2926 void OnClick(Point pt, int widget, int click_count) override
2928 switch (widget) {
2929 case WID_IC_PANEL: {
2930 Point fieldxy, xy;
2931 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
2933 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
2934 switch (fld->type) {
2935 case CFT_INDUSTRY:
2936 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
2937 break;
2939 case CFT_CARGO: {
2940 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : nullptr;
2941 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : nullptr;
2942 CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
2943 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
2944 break;
2947 case CFT_CARGO_LABEL: {
2948 CargoID cid = fld->CargoLabelClickedAt(xy);
2949 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
2950 break;
2953 default:
2954 break;
2956 break;
2959 case WID_IC_NOTIFY:
2960 this->ToggleWidgetLoweredState(WID_IC_NOTIFY);
2961 this->SetWidgetDirty(WID_IC_NOTIFY);
2962 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
2964 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2965 if (FindWindowByClass(WC_SMALLMAP) == nullptr) ShowSmallMap();
2966 this->NotifySmallmap();
2968 break;
2970 case WID_IC_CARGO_DROPDOWN: {
2971 DropDownList lst;
2972 const CargoSpec *cs;
2973 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
2974 lst.emplace_back(new DropDownListStringItem(cs->name, cs->Index(), false));
2976 if (!lst.empty()) {
2977 int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1;
2978 ShowDropDownList(this, std::move(lst), selected, WID_IC_CARGO_DROPDOWN, 0, true);
2980 break;
2983 case WID_IC_IND_DROPDOWN: {
2984 DropDownList lst;
2985 for (IndustryType ind : _sorted_industry_types) {
2986 const IndustrySpec *indsp = GetIndustrySpec(ind);
2987 if (!indsp->enabled) continue;
2988 lst.emplace_back(new DropDownListStringItem(indsp->name, ind, false));
2990 if (!lst.empty()) {
2991 int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1;
2992 ShowDropDownList(this, std::move(lst), selected, WID_IC_IND_DROPDOWN, 0, true);
2994 break;
2999 void OnDropdownSelect(int widget, int index) override
3001 if (index < 0) return;
3003 switch (widget) {
3004 case WID_IC_CARGO_DROPDOWN:
3005 this->ComputeCargoDisplay(index);
3006 break;
3008 case WID_IC_IND_DROPDOWN:
3009 this->ComputeIndustryDisplay(index);
3010 break;
3014 bool OnTooltip(Point pt, int widget, TooltipCloseCondition close_cond) override
3016 if (widget != WID_IC_PANEL) return false;
3018 Point fieldxy, xy;
3019 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return false;
3021 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
3022 CargoID cid = INVALID_CARGO;
3023 switch (fld->type) {
3024 case CFT_CARGO: {
3025 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : nullptr;
3026 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : nullptr;
3027 cid = fld->CargoClickedAt(lft, rgt, xy);
3028 break;
3031 case CFT_CARGO_LABEL: {
3032 cid = fld->CargoLabelClickedAt(xy);
3033 break;
3036 case CFT_INDUSTRY:
3037 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
3038 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, nullptr, close_cond);
3040 return true;
3042 default:
3043 break;
3045 if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
3046 const CargoSpec *csp = CargoSpec::Get(cid);
3047 uint64 params[5];
3048 params[0] = csp->name;
3049 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, 1, params, close_cond);
3050 return true;
3053 return false;
3056 void OnResize() override
3058 this->vscroll->SetCapacityFromWidget(this, WID_IC_PANEL);
3062 const int IndustryCargoesWindow::HOR_TEXT_PADDING = 5; ///< Horizontal padding around the industry type text.
3063 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5; ///< Vertical padding around the industry type text.
3066 * Open the industry and cargoes window.
3067 * @param id Industry type to display, \c NUM_INDUSTRYTYPES selects a default industry type.
3069 static void ShowIndustryCargoesWindow(IndustryType id)
3071 if (id >= NUM_INDUSTRYTYPES) {
3072 for (IndustryType ind : _sorted_industry_types) {
3073 const IndustrySpec *indsp = GetIndustrySpec(ind);
3074 if (indsp->enabled) {
3075 id = ind;
3076 break;
3079 if (id >= NUM_INDUSTRYTYPES) return;
3082 Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
3083 if (w != nullptr) {
3084 w->InvalidateData(id);
3085 return;
3087 new IndustryCargoesWindow(id);
3090 /** Open the industry and cargoes window with an industry. */
3091 void ShowIndustryCargoesWindow()
3093 ShowIndustryCargoesWindow(NUM_INDUSTRYTYPES);