OpenTTD Source 20261129-master-g72a8bdc861
town_gui.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "town.h"
12#include "viewport_func.h"
13#include "error.h"
14#include "gui.h"
15#include "house.h"
16#include "newgrf_cargo.h"
17#include "newgrf_house.h"
18#include "newgrf_text.h"
19#include "picker_gui.h"
20#include "command_func.h"
21#include "company_func.h"
22#include "company_base.h"
23#include "company_gui.h"
24#include "network/network.h"
25#include "string_func.h"
26#include "strings_func.h"
27#include "sound_func.h"
28#include "tilehighlight_func.h"
29#include "sortlist_type.h"
30#include "road_cmd.h"
31#include "landscape.h"
32#include "querystring_gui.h"
33#include "textbuf_gui.h"
34#include "window_func.h"
35#include "townname_func.h"
36#include "core/backup_type.hpp"
39#include "genworld.h"
40#include "fios.h"
41#include "stringfilter_type.h"
42#include "dropdown_func.h"
43#include "town_kdtree.h"
44#include "town_cmd.h"
45#include "timer/timer.h"
47#include "timer/timer_window.h"
48#include "zoom_func.h"
49#include "hotkeys.h"
50#include "graph_gui.h"
51
52#include "widgets/town_widget.h"
53
54#include "table/strings.h"
55
56#include "safeguards.h"
57
58TownKdtree _town_local_authority_kdtree{};
59
60typedef GUIList<const Town*, const bool &> GUITownList;
61
62static constexpr std::initializer_list<NWidgetPart> _nested_town_authority_widgets = {
66 NWidget(WWT_TEXTBTN, Colours::Brown, WID_TA_ZONE_BUTTON), SetMinimalSize(50, 0), SetStringTip(STR_LOCAL_AUTHORITY_ZONE, STR_LOCAL_AUTHORITY_ZONE_TOOLTIP),
72 NWidget(WWT_PANEL, Colours::Brown, WID_TA_COMMAND_LIST), SetMinimalSize(317, 52), SetResize(1, 0), SetToolTip(STR_LOCAL_AUTHORITY_ACTIONS_TOOLTIP), EndContainer(),
75 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_TA_EXECUTE), SetMinimalSize(317, 12), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_LOCAL_AUTHORITY_DO_IT_BUTTON, STR_LOCAL_AUTHORITY_DO_IT_TOOLTIP),
78};
79
81struct TownAuthorityWindow : Window {
82private:
83 Town *town = nullptr;
88 std::array<StringID, to_underlying(TownAction::End)> action_tooltips{};
89
92
99 {
100 TownActions enabled{};
101 enabled.Set();
102
103 if (!_settings_game.economy.fund_roads) enabled.Reset(TownAction::RoadRebuild);
104 if (!_settings_game.economy.fund_buildings) enabled.Reset(TownAction::FundBuildings);
105 if (!_settings_game.economy.exclusive_rights) enabled.Reset(TownAction::BuyRights);
106 if (!_settings_game.economy.bribe) enabled.Reset(TownAction::Bribe);
107
108 return enabled;
109 }
110
111public:
113 {
114 this->town = Town::Get(window_number);
115 this->enabled_actions = GetEnabledActions();
116
118 this->action_tooltips[0] = STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_SMALL_ADVERTISING;
119 this->action_tooltips[1] = STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_MEDIUM_ADVERTISING;
120 this->action_tooltips[2] = STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_LARGE_ADVERTISING;
121 this->action_tooltips[3] = realtime ? STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_ROAD_RECONSTRUCTION_MINUTES : STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_ROAD_RECONSTRUCTION_MONTHS;
122 this->action_tooltips[4] = STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_STATUE_OF_COMPANY;
123 this->action_tooltips[5] = STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_NEW_BUILDINGS;
124 this->action_tooltips[6] = realtime ? STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_EXCLUSIVE_TRANSPORT_MINUTES : STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_EXCLUSIVE_TRANSPORT_MONTHS;
125 this->action_tooltips[7] = STR_LOCAL_AUTHORITY_ACTION_TOOLTIP_BRIBE;
126
127 this->InitNested(window_number);
128 }
129
130 void OnInit() override
131 {
132 this->icon_size = GetSpriteSize(SPR_COMPANY_ICON);
133 this->exclusive_size = GetSpriteSize(SPR_EXCLUSIVE_TRANSPORT);
134 }
135
136 void OnPaint() override
137 {
138 this->available_actions = GetMaskOfTownActions(_local_company, this->town);
139 if (this->available_actions != displayed_actions_on_previous_painting) this->SetDirty();
140 displayed_actions_on_previous_painting = this->available_actions;
141
143 this->SetWidgetDisabledState(WID_TA_EXECUTE, (this->sel_action == TownAction::End) || !this->available_actions.Test(this->sel_action));
144
145 this->DrawWidgets();
146 if (!this->IsShaded())
147 {
148 this->DrawRatings();
149 this->DrawActions();
150 }
151 }
152
153 StringID GetRatingString(int rating) const
154 {
155 if (rating > RATING_EXCELLENT) return STR_CARGO_RATING_OUTSTANDING;
156 if (rating > RATING_VERYGOOD) return STR_CARGO_RATING_EXCELLENT;
157 if (rating > RATING_GOOD) return STR_CARGO_RATING_VERY_GOOD;
158 if (rating > RATING_MEDIOCRE) return STR_CARGO_RATING_GOOD;
159 if (rating > RATING_POOR) return STR_CARGO_RATING_MEDIOCRE;
160 if (rating > RATING_VERYPOOR) return STR_CARGO_RATING_POOR;
161 if (rating > RATING_APPALLING) return STR_CARGO_RATING_VERY_POOR;
162 return STR_CARGO_RATING_APPALLING;
163 }
164
167 {
168 Rect r = this->GetWidget<NWidgetBase>(WID_TA_RATING_INFO)->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect);
169
170 int text_y_offset = (this->resize.step_height - GetCharacterHeight(FontSize::Normal)) / 2;
171 int icon_y_offset = (this->resize.step_height - this->icon_size.height) / 2;
172 int exclusive_y_offset = (this->resize.step_height - this->exclusive_size.height) / 2;
173
174 DrawString(r.left, r.right, r.top + text_y_offset, STR_LOCAL_AUTHORITY_COMPANY_RATINGS);
175 r.top += this->resize.step_height;
176
177 bool rtl = _current_text_dir == TD_RTL;
178 Rect icon = r.WithWidth(this->icon_size.width, rtl);
179 Rect exclusive = r.Indent(this->icon_size.width + WidgetDimensions::scaled.hsep_normal, rtl).WithWidth(this->exclusive_size.width, rtl);
180 Rect text = r.Indent(this->icon_size.width + WidgetDimensions::scaled.hsep_normal + this->exclusive_size.width + WidgetDimensions::scaled.hsep_normal, rtl);
181
182 /* Draw list of companies */
183 for (const Company *c : Company::Iterate()) {
184 if ((this->town->have_ratings.Test(c->index) || this->town->exclusivity == c->index)) {
185 DrawCompanyIcon(c->index, icon.left, text.top + icon_y_offset);
186
187 if (this->town->exclusivity == c->index) {
188 DrawSprite(SPR_EXCLUSIVE_TRANSPORT, GetCompanyPalette(c->index), exclusive.left, text.top + exclusive_y_offset);
189 }
190
191 int rating = this->town->ratings[c->index];
192 DrawString(text.left, text.right, text.top + text_y_offset, GetString(STR_LOCAL_AUTHORITY_COMPANY_RATING, c->index, c->index, GetRatingString(rating)));
193 text.top += this->resize.step_height;
194 }
195 }
196
197 text.bottom = text.top - 1;
198 if (text.bottom > r.bottom) {
199 /* If the company list is too big to fit, mark ourself dirty and draw again. */
200 ResizeWindow(this, 0, text.bottom - r.bottom, false);
201 }
202 }
203
206 {
207 Rect r = this->GetWidget<NWidgetBase>(WID_TA_COMMAND_LIST)->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect);
208
209 DrawString(r, STR_LOCAL_AUTHORITY_ACTIONS_TITLE);
211
212 /* Draw list of enabled actions */
213 for (TownAction i : this->enabled_actions) {
214 /* Set colour of action based on ability to execute and if selected. */
216 if (this->available_actions.Test(i)) action_colour = TextColour::Orange;
217 if (this->sel_action == i) action_colour = TextColour::White;
218
219 DrawString(r, STR_LOCAL_AUTHORITY_ACTION_SMALL_ADVERTISING_CAMPAIGN + to_underlying(i), action_colour);
221 }
222 }
223
224 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
225 {
226 if (widget == WID_TA_CAPTION) return GetString(STR_LOCAL_AUTHORITY_CAPTION, this->window_number);
227
228 return this->Window::GetWidgetString(widget, stringid);
229 }
230
231 void DrawWidget(const Rect &r, WidgetID widget) const override
232 {
233 switch (widget) {
235 if (this->sel_action != TownAction::End) {
236 Money action_cost = _price[Price::TownAction] * GetTownActionCost(this->sel_action) >> 8;
237 bool affordable = Company::IsValidID(_local_company) && action_cost < GetAvailableMoney(_local_company);
238
240 GetString(this->action_tooltips[to_underlying(this->sel_action)], action_cost),
241 affordable ? TextColour::Yellow : TextColour::Red);
242 }
243 break;
244 }
245 }
246
247 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
248 {
249 switch (widget) {
250 case WID_TA_ACTION_INFO: {
251 assert(size.width > padding.width && size.height > padding.height);
252 Dimension d = {0, 0};
254 Money price = _price[Price::TownAction] * GetTownActionCost(i) >> 8;
255 d = maxdim(d, GetStringMultiLineBoundingBox(GetString(this->action_tooltips[to_underlying(i)], price), size));
256 }
257 d.width += padding.width;
258 d.height += padding.height;
259 size = maxdim(size, d);
260 break;
261 }
262
265 size.width = GetStringBoundingBox(STR_LOCAL_AUTHORITY_ACTIONS_TITLE).width;
267 size.width = std::max(size.width, GetStringBoundingBox(STR_LOCAL_AUTHORITY_ACTION_SMALL_ADVERTISING_CAMPAIGN + to_underlying(i)).width + padding.width);
268 }
269 size.width += padding.width;
270 break;
271
273 fill.height = resize.height = std::max({this->icon_size.height + WidgetDimensions::scaled.vsep_normal, this->exclusive_size.height + WidgetDimensions::scaled.vsep_normal, (uint)GetCharacterHeight(FontSize::Normal)});
274 size.height = 9 * resize.height + padding.height;
275 break;
276 }
277 }
278
279 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
280 {
281 switch (widget) {
282 case WID_TA_ZONE_BUTTON: {
283 bool new_show_state = !this->town->show_zone;
284 TownID index = this->town->index;
285
286 new_show_state ? _town_local_authority_kdtree.Insert(index) : _town_local_authority_kdtree.Remove(index);
287
288 this->town->show_zone = new_show_state;
289 this->SetWidgetLoweredState(widget, new_show_state);
290 SndClickBeep();
292 break;
293 }
294
295 case WID_TA_COMMAND_LIST: {
297
298 auto action = this->enabled_actions.GetNthSetBit(y);
299 if (!action.has_value()) break;
300
301 this->sel_action = *action;
302 this->SetDirty();
303
304 /* When double-clicking, continue */
305 if (click_count == 1 || !this->available_actions.Test(this->sel_action)) break;
306 [[fallthrough]];
307 }
308
309 case WID_TA_EXECUTE:
310 Command<Commands::TownAction>::Post(STR_ERROR_CAN_T_DO_THIS, this->town->xy, static_cast<TownID>(this->window_number), this->sel_action);
311 break;
312 }
313 }
314
316 const IntervalTimer<TimerWindow> redraw_interval = {std::chrono::seconds(3), [this](auto) {
317 this->SetDirty();
318 }};
319
320 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
321 {
322 if (!gui_scope) return;
323
324 this->enabled_actions = this->GetEnabledActions();
325 if (!this->enabled_actions.Test(this->sel_action)) {
326 this->sel_action = TownAction::End;
327 }
328 }
329};
330
333 WindowPosition::Automatic, "view_town_authority", 317, 222,
334 WindowClass::TownAuthority, WindowClass::None,
335 {},
336 _nested_town_authority_widgets
337);
338
339static void ShowTownAuthorityWindow(uint town)
340{
342}
343
344
346struct TownViewWindow : Window {
347private:
348 Town *town = nullptr;
349
350public:
351 static const int WID_TV_HEIGHT_NORMAL = 150;
352
353 TownViewWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc)
354 {
355 this->CreateNestedTree();
356
357 this->town = Town::Get(window_number);
358
359 this->FinishInitNested(window_number);
360
363 nvp->InitializeViewport(this, this->town->xy, ScaleZoomGUI(ZoomLevel::Town));
364
365 /* disable renaming town in network games if you are not the server */
367 }
368
369 void Close([[maybe_unused]] int data = 0) override
370 {
372 this->Window::Close();
373 }
374
375 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
376 {
377 if (widget == WID_TV_CAPTION) return GetString(this->town->larger_town ? STR_TOWN_VIEW_CITY_CAPTION : STR_TOWN_VIEW_TOWN_CAPTION, this->town->index);
378
379 return this->Window::GetWidgetString(widget, stringid);
380 }
381
382 void OnPaint() override
383 {
384 extern const Town *_viewport_highlight_town;
386
387 this->DrawWidgets();
388 }
389
390 void DrawWidget(const Rect &r, WidgetID widget) const override
391 {
392 if (widget != WID_TV_INFO) return;
393
394 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
395
396 DrawString(tr, GetString(STR_TOWN_VIEW_POPULATION_HOUSES, this->town->cache.population, this->town->cache.num_houses));
398
399 StringID str_last_period = TimerGameEconomy::UsingWallclockUnits() ? STR_TOWN_VIEW_CARGO_LAST_MINUTE_MAX : STR_TOWN_VIEW_CARGO_LAST_MONTH_MAX;
400
402 for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
403 CargoType cargo_type = cs->Index();
404 auto it = this->town->GetCargoSupplied(cargo_type);
405 if (it == std::end(this->town->supplied)) {
406 DrawString(tr, GetString(str_last_period, 1ULL << cargo_type, 0, 0));
407 } else {
408 DrawString(tr, GetString(str_last_period, 1ULL << cargo_type, it->history[LAST_MONTH].transported, it->history[LAST_MONTH].production));
409 }
411 }
412 }
413
414 bool first = true;
416 if (this->town->goal[i] == 0) continue;
417 if (this->town->goal[i] == TOWN_GROWTH_WINTER && (TileHeight(this->town->xy) < LowestSnowLine() || this->town->cache.population <= 90)) continue;
418 if (this->town->goal[i] == TOWN_GROWTH_DESERT && (GetTropicZone(this->town->xy) != TropicZone::Desert || this->town->cache.population <= 60)) continue;
419
420 if (first) {
421 DrawString(tr, STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH);
423 first = false;
424 }
425
426 bool rtl = _current_text_dir == TD_RTL;
427
429 assert(cargo != nullptr);
430
431 StringID string;
432
433 if (this->town->goal[i] == TOWN_GROWTH_DESERT || this->town->goal[i] == TOWN_GROWTH_WINTER) {
434 /* For 'original' gameplay, don't show the amount required (you need 1 or more ..) */
435 string = STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_DELIVERED_GENERAL;
436 if (this->town->received[i].old_act == 0) {
437 string = STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_REQUIRED_GENERAL;
438
439 if (this->town->goal[i] == TOWN_GROWTH_WINTER && TileHeight(this->town->xy) < GetSnowLine()) {
440 string = STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_REQUIRED_WINTER;
441 }
442 }
443
444 DrawString(tr.Indent(20, rtl), GetString(string, cargo->name));
445 } else {
446 string = STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_DELIVERED;
447 if (this->town->received[i].old_act < this->town->goal[i]) {
448 string = STR_TOWN_VIEW_CARGO_FOR_TOWNGROWTH_REQUIRED;
449 }
450 DrawString(tr.Indent(20, rtl), GetString(string, cargo->Index(), this->town->received[i].old_act, cargo->Index(), this->town->goal[i]));
451 }
453 }
454
455 if (this->town->flags.Test(TownFlag::IsGrowing)) {
456 DrawString(tr, GetString(this->town->fund_buildings_months == 0 ? STR_TOWN_VIEW_TOWN_GROWS_EVERY : STR_TOWN_VIEW_TOWN_GROWS_EVERY_FUNDED, RoundDivSU(this->town->growth_rate + 1, Ticks::DAY_TICKS)));
458 } else {
459 DrawString(tr, STR_TOWN_VIEW_TOWN_GROW_STOPPED);
461 }
462
463 /* only show the town noise, if the noise option is activated. */
464 if (_settings_game.economy.station_noise_level) {
465 DrawString(tr, GetString(STR_TOWN_VIEW_NOISE_IN_TOWN, this->town->noise_reached, this->town->MaxTownNoise()));
467 }
468
469 if (!this->town->text.empty()) {
470 tr.top = DrawStringMultiLine(tr, this->town->text.GetDecodedString(), TextColour::Black);
471 }
472 }
473
474 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
475 {
476 switch (widget) {
477 case WID_TV_CENTER_VIEW: // scroll to location
478 if (IsCtrlPressed()) {
479 ShowExtraViewportWindow(this->town->xy);
480 } else {
481 ScrollMainWindowToTile(this->town->xy);
482 }
483 break;
484
485 case WID_TV_SHOW_AUTHORITY: // town authority
486 ShowTownAuthorityWindow(this->window_number);
487 break;
488
489 case WID_TV_CHANGE_NAME: // rename
491 break;
492
493 case WID_TV_CATCHMENT:
495 SndClickBeep();
496 break;
497
498 case WID_TV_EXPAND: // expand town - only available on Scenario editor
499 Command<Commands::ExpandTown>::Post(STR_ERROR_CAN_T_EXPAND_TOWN, static_cast<TownID>(this->window_number), 0, {TownExpandMode::Buildings, TownExpandMode::Roads});
500 break;
501
502 case WID_TV_EXPAND_BUILDINGS: // expand buildings of town - only available on Scenario editor
503 Command<Commands::ExpandTown>::Post(STR_ERROR_CAN_T_EXPAND_TOWN, static_cast<TownID>(this->window_number), 0, {TownExpandMode::Buildings});
504 break;
505
506 case WID_TV_EXPAND_ROADS: // expand roads of town - only available on Scenario editor
507 Command<Commands::ExpandTown>::Post(STR_ERROR_CAN_T_EXPAND_TOWN, static_cast<TownID>(this->window_number), 0, {TownExpandMode::Roads});
508 break;
509
510 case WID_TV_DELETE: // delete town - only available on Scenario editor
511 Command<Commands::DeleteTown>::Post(STR_ERROR_TOWN_CAN_T_DELETE, static_cast<TownID>(this->window_number));
512 break;
513
514 case WID_TV_GRAPH: {
515 ShowTownCargoGraph(this->window_number);
516 break;
517 }
518 }
519 }
520
521 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
522 {
523 switch (widget) {
524 case WID_TV_INFO:
525 size.height = GetDesiredInfoHeight(size.width) + padding.height;
526 break;
527 }
528 }
529
536 {
538
539 bool first = true;
541 if (this->town->goal[i] == 0) continue;
542 if (this->town->goal[i] == TOWN_GROWTH_WINTER && (TileHeight(this->town->xy) < LowestSnowLine() || this->town->cache.population <= 90)) continue;
543 if (this->town->goal[i] == TOWN_GROWTH_DESERT && (GetTropicZone(this->town->xy) != TropicZone::Desert || this->town->cache.population <= 60)) continue;
544
545 if (first) {
546 aimed_height += GetCharacterHeight(FontSize::Normal);
547 first = false;
548 }
549 aimed_height += GetCharacterHeight(FontSize::Normal);
550 }
551 aimed_height += GetCharacterHeight(FontSize::Normal);
552
553 if (_settings_game.economy.station_noise_level) aimed_height += GetCharacterHeight(FontSize::Normal);
554
555 if (!this->town->text.empty()) {
556 aimed_height += GetStringHeight(this->town->text.GetDecodedString(), width - WidgetDimensions::scaled.framerect.Horizontal());
557 }
558
559 return aimed_height;
560 }
561
562 void ResizeWindowAsNeeded()
563 {
564 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_TV_INFO);
565 uint aimed_height = GetDesiredInfoHeight(nwid_info->current_x);
566 if (aimed_height > nwid_info->current_y || (aimed_height < nwid_info->current_y && nwid_info->current_y > nwid_info->smallest_y)) {
567 this->ReInit();
568 }
569 }
570
571 void OnResize() override
572 {
573 if (this->viewport != nullptr) {
575 nvp->UpdateViewportCoordinates(this);
576
577 ScrollWindowToTile(this->town->xy, this, true); // Re-center viewport.
578 }
579 }
580
581 void OnMouseWheel(int wheel, WidgetID widget) override
582 {
583 if (widget != WID_TV_VIEWPORT) return;
584 if (_settings_client.gui.scrollwheel_scrolling != ScrollWheelScrolling::Off) {
585 DoZoomInOutWindow(wheel < 0 ? ZOOM_IN : ZOOM_OUT, this);
586 }
587 }
588
594 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
595 {
596 if (!gui_scope) return;
597 /* Called when setting station noise or required cargoes have changed, in order to resize the window */
598 this->SetDirty(); // refresh display for current size. This will allow to avoid glitches when downgrading
599 this->ResizeWindowAsNeeded();
600 }
601
602 void OnQueryTextFinished(std::optional<std::string> str) override
603 {
604 if (!str.has_value()) return;
605
606 Command<Commands::RenameTown>::Post(STR_ERROR_CAN_T_RENAME_TOWN, static_cast<TownID>(this->window_number), *str);
607 }
608
609 const IntervalTimer<TimerGameCalendar> daily_interval = {{TimerGameCalendar::Trigger::Day, TimerGameCalendar::Priority::None}, [this](auto) {
610 /* Refresh after possible snowline change */
611 this->SetDirty();
612 }};
613};
614
615static constexpr std::initializer_list<NWidgetPart> _nested_town_game_view_widgets = {
618 NWidget(WWT_PUSHIMGBTN, Colours::Brown, WID_TV_CHANGE_NAME), SetAspect(WidgetDimensions::ASPECT_RENAME), SetSpriteTip(SPR_RENAME, STR_TOWN_VIEW_RENAME_TOOLTIP),
620 NWidget(WWT_PUSHIMGBTN, Colours::Brown, WID_TV_CENTER_VIEW), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetSpriteTip(SPR_GOTO_LOCATION, STR_TOWN_VIEW_CENTER_TOOLTIP),
624 EndContainer(),
628 EndContainer(),
629 EndContainer(),
632 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_TV_SHOW_AUTHORITY), SetMinimalSize(80, 12), SetFill(1, 1), SetResize(1, 0), SetStringTip(STR_TOWN_VIEW_LOCAL_AUTHORITY_BUTTON, STR_TOWN_VIEW_LOCAL_AUTHORITY_TOOLTIP),
633 NWidget(WWT_TEXTBTN, Colours::Brown, WID_TV_CATCHMENT), SetMinimalSize(40, 12), SetFill(1, 1), SetResize(1, 0), SetStringTip(STR_BUTTON_CATCHMENT, STR_TOOLTIP_CATCHMENT),
634 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_TV_GRAPH), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_TOWN_VIEW_CARGO_GRAPH, STR_TOWN_VIEW_CARGO_GRAPH_TOOLTIP),
636 EndContainer(),
637};
638
641 WindowPosition::Automatic, "view_town", 260, TownViewWindow::WID_TV_HEIGHT_NORMAL,
642 WindowClass::TownView, WindowClass::None,
643 {},
644 _nested_town_game_view_widgets
645);
646
647static constexpr std::initializer_list<NWidgetPart> _nested_town_editor_view_widgets = {
650 NWidget(WWT_PUSHIMGBTN, Colours::Brown, WID_TV_CHANGE_NAME), SetAspect(WidgetDimensions::ASPECT_RENAME), SetSpriteTip(SPR_RENAME, STR_TOWN_VIEW_RENAME_TOOLTIP),
651 NWidget(WWT_CAPTION, Colours::Brown, WID_TV_CAPTION), SetToolTip(STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
652 NWidget(WWT_PUSHIMGBTN, Colours::Brown, WID_TV_CENTER_VIEW), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetSpriteTip(SPR_GOTO_LOCATION, STR_TOWN_VIEW_CENTER_TOOLTIP),
656 EndContainer(),
660 EndContainer(),
661 EndContainer(),
664 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_TV_EXPAND), SetFill(1, 1), SetResize(1, 0), SetStringTip(STR_TOWN_VIEW_EXPAND_BUTTON, STR_TOWN_VIEW_EXPAND_TOOLTIP),
665 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_TV_EXPAND_BUILDINGS), SetFill(1, 1), SetResize(1, 0), SetStringTip(STR_TOWN_VIEW_EXPAND_BUILDINGS_BUTTON, STR_TOWN_VIEW_EXPAND_BUILDINGS_TOOLTIP),
666 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_TV_EXPAND_ROADS), SetFill(1, 1), SetResize(1, 0), SetStringTip(STR_TOWN_VIEW_EXPAND_ROADS_BUTTON, STR_TOWN_VIEW_EXPAND_ROADS_TOOLTIP),
667 EndContainer(),
669 NWidget(WWT_PUSHTXTBTN, Colours::Brown, WID_TV_DELETE), SetFill(1, 1), SetResize(1, 0), SetStringTip(STR_TOWN_VIEW_DELETE_BUTTON, STR_TOWN_VIEW_DELETE_TOOLTIP),
670 NWidget(WWT_TEXTBTN, Colours::Brown, WID_TV_CATCHMENT), SetFill(1, 1), SetResize(1, 0), SetStringTip(STR_BUTTON_CATCHMENT, STR_TOOLTIP_CATCHMENT),
672 EndContainer(),
673};
674
677 WindowPosition::Automatic, "view_town_scen", 260, TownViewWindow::WID_TV_HEIGHT_NORMAL,
678 WindowClass::TownView, WindowClass::None,
679 {},
680 _nested_town_editor_view_widgets
681);
682
683void ShowTownViewWindow(TownID town)
684{
685 if (_game_mode == GameMode::Editor) {
687 } else {
689 }
690}
691
692static constexpr std::initializer_list<NWidgetPart> _nested_town_directory_widgets = {
699 EndContainer(),
703 NWidget(WWT_TEXTBTN, Colours::Brown, WID_TD_SORT_ORDER), SetStringTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
705 NWidget(WWT_EDITBOX, Colours::Brown, WID_TD_FILTER), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
706 EndContainer(),
707 NWidget(WWT_PANEL, Colours::Brown, WID_TD_LIST), SetToolTip(STR_TOWN_DIRECTORY_LIST_TOOLTIP),
711 EndContainer(),
712 EndContainer(),
716 EndContainer(),
717 EndContainer(),
718};
719
721struct TownDirectoryWindow : public Window {
722private:
724 static Listing last_sorting;
725
727 static inline const StringID sorter_names[] = {
728 STR_SORT_BY_NAME,
729 STR_SORT_BY_POPULATION,
730 STR_SORT_BY_RATING,
731 STR_SORT_BY_PRODUCTION,
732 STR_SORT_BY_TRANSPORTED,
733 };
734 static const std::initializer_list<GUITownList::SortFunction * const> sorter_funcs;
735
738
739 GUITownList towns{TownDirectoryWindow::last_sorting.order};
740
741 Scrollbar *vscroll = nullptr;
742
743 void BuildSortTownList()
744 {
745 if (this->towns.NeedRebuild()) {
746 this->towns.clear();
747 this->towns.reserve(Town::GetNumItems());
748
749 for (const Town *t : Town::Iterate()) {
750 if (this->string_filter.IsEmpty()) {
751 this->towns.push_back(t);
752 continue;
753 }
754 this->string_filter.ResetState();
755 this->string_filter.AddLine(t->GetCachedName());
756 if (this->string_filter.GetState()) this->towns.push_back(t);
757 }
758
759 this->towns.RebuildDone();
760 this->vscroll->SetCount(this->towns.size()); // Update scrollbar as well.
761 }
762 /* Always sort the towns. */
763 this->towns.Sort();
764 this->SetWidgetDirty(WID_TD_LIST); // Force repaint of the displayed towns.
765 }
766
768 static bool TownNameSorter(const Town * const &a, const Town * const &b, [[maybe_unused]] const bool &filter)
769 {
770 return StrNaturalCompare(a->GetCachedName(), b->GetCachedName()) < 0; // Sort by name (natural sorting).
771 }
772
774 static bool TownPopulationSorter(const Town * const &a, const Town * const &b, const bool &filter)
775 {
776 uint32_t a_population = a->cache.population;
777 uint32_t b_population = b->cache.population;
778 if (a_population == b_population) return TownDirectoryWindow::TownNameSorter(a, b, filter);
779 return a_population < b_population;
780 }
781
783 static bool TownRatingSorter(const Town * const &a, const Town * const &b, const bool &filter)
784 {
785 bool before = !filter; // Value to get 'a' before 'b'.
786
787 /* Towns without rating are always after towns with rating. */
790 int16_t a_rating = a->ratings[_local_company];
791 int16_t b_rating = b->ratings[_local_company];
792 if (a_rating == b_rating) return TownDirectoryWindow::TownNameSorter(a, b, filter);
793 return a_rating < b_rating;
794 }
795 return before;
796 }
797 if (b->have_ratings.Test(_local_company)) return !before;
798
799 /* Sort unrated towns always on ascending town name. */
800 if (before) return TownDirectoryWindow::TownNameSorter(a, b, filter);
801 return TownDirectoryWindow::TownNameSorter(b, a, filter);
802 }
803
805 static bool TownProductionSorter(const Town * const &a, const Town * const &b, const bool &filter)
806 {
807 constexpr auto sum_production = [](int v, const Town::SuppliedCargo &s) -> int {
808 return v + s.history[LAST_MONTH].production;
809 };
810
811 int a_production = std::accumulate(a->supplied.begin(), a->supplied.end(), 0, sum_production);
812 int b_production = std::accumulate(b->supplied.begin(), b->supplied.end(), 0, sum_production);
813
814 if (a_production == b_production) TownDirectoryWindow::TownNameSorter(b, a, filter);
815 return a_production < b_production;
816 }
817
819 static bool TownTransportedSorter(const Town * const &a, const Town * const &b, const bool &filter)
820 {
821 constexpr auto percent_transported = [](int v, const Town::SuppliedCargo &s) -> int {
822 if (s.history[LAST_MONTH].production == 0) return v;
823 return v + (s.history[LAST_MONTH].transported * 256 / s.history[LAST_MONTH].production);
824 };
825
826 int a_transported = a->supplied.empty() ? 0 : std::accumulate(a->supplied.begin(), a->supplied.end(), 0, percent_transported) / static_cast<int>(a->supplied.size());
827 int b_transported = b->supplied.empty() ? 0 : std::accumulate(b->supplied.begin(), b->supplied.end(), 0, percent_transported) / static_cast<int>(b->supplied.size());
828
829 if (a_transported == b_transported) TownDirectoryWindow::TownNameSorter(b, a, filter);
830 return a_transported < b_transported;
831 }
832
833public:
835 {
836 this->CreateNestedTree();
837
838 this->vscroll = this->GetScrollbar(WID_TD_SCROLLBAR);
839
840 this->towns.SetListing(this->last_sorting);
842 this->towns.ForceRebuild();
843 this->BuildSortTownList();
844
845 this->FinishInitNested(0);
846
847 this->querystrings[WID_TD_FILTER] = &this->townname_editbox;
848 this->townname_editbox.cancel_button = QueryString::ACTION_CLEAR;
849 }
850
851 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
852 {
853 switch (widget) {
854 case WID_TD_CAPTION:
855 return GetString(STR_TOWN_DIRECTORY_CAPTION, this->vscroll->GetCount(), Town::GetNumItems());
856
858 return GetString(STR_TOWN_POPULATION, GetWorldPopulation());
859
862
863 default:
864 return this->Window::GetWidgetString(widget, stringid);
865 }
866 }
867
874 static std::string GetTownString(const Town *t, uint64_t population)
875 {
876 return GetString(t->larger_town ? STR_TOWN_DIRECTORY_CITY : STR_TOWN_DIRECTORY_TOWN, t->index, population);
877 }
878
879 void DrawWidget(const Rect &r, WidgetID widget) const override
880 {
881 switch (widget) {
883 this->DrawSortButton(widget, this->towns.IsDescSortOrder());
884 break;
885
886 case WID_TD_LIST: {
887 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
888 if (this->towns.empty()) { // No towns available.
889 DrawString(tr, STR_TOWN_DIRECTORY_NONE);
890 break;
891 }
892
893 /* At least one town available. */
894 bool rtl = _current_text_dir == TD_RTL;
895 Dimension icon_size = GetSpriteSize(SPR_TOWN_RATING_GOOD);
896 int icon_x = tr.WithWidth(icon_size.width, rtl).left;
897 tr = tr.Indent(icon_size.width + WidgetDimensions::scaled.hsep_normal, rtl);
898
899 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->towns);
900 for (auto it = first; it != last; ++it) {
901 const Town *t = *it;
902 assert(t->xy != INVALID_TILE);
903
904 /* Draw rating icon. */
905 if (_game_mode == GameMode::Editor || !t->have_ratings.Test(_local_company)) {
906 DrawSprite(SPR_TOWN_RATING_NA, PAL_NONE, icon_x, tr.top + (this->resize.step_height - icon_size.height) / 2);
907 } else {
908 SpriteID icon = SPR_TOWN_RATING_APPALLING;
909 if (t->ratings[_local_company] > RATING_VERYPOOR) icon = SPR_TOWN_RATING_MEDIOCRE;
910 if (t->ratings[_local_company] > RATING_GOOD) icon = SPR_TOWN_RATING_GOOD;
911 DrawSprite(icon, PAL_NONE, icon_x, tr.top + (this->resize.step_height - icon_size.height) / 2);
912 }
913
914 DrawString(tr.left, tr.right, tr.top + (this->resize.step_height - GetCharacterHeight(FontSize::Normal)) / 2, GetTownString(t, t->cache.population));
915
916 tr.top += this->resize.step_height;
917 }
918 break;
919 }
920 }
921 }
922
923 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
924 {
925 switch (widget) {
926 case WID_TD_SORT_ORDER: {
928 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
929 d.height += padding.height;
930 size = maxdim(size, d);
931 break;
932 }
935 d.width += padding.width;
936 d.height += padding.height;
937 size = maxdim(size, d);
938 break;
939 }
940 case WID_TD_LIST: {
941 Dimension d = GetStringBoundingBox(STR_TOWN_DIRECTORY_NONE);
942 uint64_t max_value = GetParamMaxDigits(8);
943 for (uint i = 0; i < this->towns.size(); i++) {
944 const Town *t = this->towns[i];
945
946 assert(t != nullptr);
947
948 d = maxdim(d, GetStringBoundingBox(GetTownString(t, max_value)));
949 }
950 Dimension icon_size = GetSpriteSize(SPR_TOWN_RATING_GOOD);
951 d.width += icon_size.width + 2;
952 d.height = std::max(d.height, icon_size.height);
953 fill.height = resize.height = d.height;
954 d.height *= 5;
955 d.width += padding.width;
956 d.height += padding.height;
957 size = maxdim(size, d);
958 break;
959 }
961 Dimension d = GetStringBoundingBox(GetString(STR_TOWN_POPULATION, GetParamMaxDigits(10)));
962 d.width += padding.width;
963 d.height += padding.height;
964 size = maxdim(size, d);
965 break;
966 }
967 }
968 }
969
970 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
971 {
972 switch (widget) {
973 case WID_TD_SORT_ORDER: // Click on sort order button
974 if (this->towns.SortType() != 2) { // A different sort than by rating.
975 this->towns.ToggleSortOrder();
976 this->last_sorting = this->towns.GetListing(); // Store new sorting order.
977 } else {
978 /* Some parts are always sorted ascending on name. */
979 this->last_sorting.order = !this->last_sorting.order;
980 this->towns.SetListing(this->last_sorting);
981 this->towns.ForceResort();
982 this->towns.Sort();
983 }
984 this->SetDirty();
985 break;
986
987 case WID_TD_SORT_CRITERIA: // Click on sort criteria dropdown
989 break;
990
991 case WID_TD_LIST: { // Click on Town Matrix
992 auto it = this->vscroll->GetScrolledItemFromWidget(this->towns, pt.y, this, WID_TD_LIST, WidgetDimensions::scaled.framerect.top);
993 if (it == this->towns.end()) return; // click out of town bounds
994
995 const Town *t = *it;
996 assert(t != nullptr);
997 if (IsCtrlPressed()) {
999 } else {
1001 }
1002 break;
1003 }
1004 }
1005 }
1006
1007 void OnDropdownSelect(WidgetID widget, int index, int) override
1008 {
1009 if (widget != WID_TD_SORT_CRITERIA) return;
1010
1011 if (this->towns.SortType() != index) {
1012 this->towns.SetSortType(index);
1013 this->last_sorting = this->towns.GetListing(); // Store new sorting order.
1014 this->BuildSortTownList();
1015 }
1016 }
1017
1018 void OnPaint() override
1019 {
1020 if (this->towns.NeedRebuild()) this->BuildSortTownList();
1021 this->DrawWidgets();
1022 }
1023
1025 const IntervalTimer<TimerWindow> rebuild_interval = {std::chrono::seconds(3), [this](auto) {
1026 this->BuildSortTownList();
1027 this->SetDirty();
1028 }};
1029
1030 void OnResize() override
1031 {
1032 this->vscroll->SetCapacityFromWidget(this, WID_TD_LIST, WidgetDimensions::scaled.framerect.Vertical());
1033 }
1034
1035 void OnEditboxChanged(WidgetID wid) override
1036 {
1037 if (wid == WID_TD_FILTER) {
1038 this->string_filter.SetFilterTerm(this->townname_editbox.text.GetText());
1039 this->InvalidateData(TDIWD_FORCE_REBUILD);
1040 }
1041 }
1042
1048 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1049 {
1050 switch (data) {
1051 case TDIWD_FORCE_REBUILD:
1052 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1053 this->towns.ForceRebuild();
1054 break;
1055
1056 case TDIWD_POPULATION_CHANGE:
1057 if (this->towns.SortType() == 1) this->towns.ForceResort();
1058 break;
1059
1060 default:
1061 this->towns.ForceResort();
1062 }
1063 }
1064
1065 static inline HotkeyList hotkeys {"towndirectory", {
1066 Hotkey('F', "focus_filter_box", WID_TD_FILTER),
1067 }};
1068};
1069
1071
1073const std::initializer_list<GUITownList::SortFunction * const> TownDirectoryWindow::sorter_funcs = {
1079};
1080
1083 WindowPosition::Automatic, "list_towns", 208, 202,
1084 WindowClass::TownDirectory, WindowClass::None,
1085 {},
1086 _nested_town_directory_widgets,
1087 &TownDirectoryWindow::hotkeys
1088);
1089
1090void ShowTownDirectory()
1091{
1092 if (BringWindowToFrontById(WindowClass::TownDirectory, 0)) return;
1094}
1095
1096void CcFoundTown(Commands, const CommandCost &result, TileIndex tile)
1097{
1098 if (result.Failed()) return;
1099
1100 if (_settings_client.sound.confirm) SndPlayTileFx(SND_1F_CONSTRUCTION_OTHER, tile);
1101 if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
1102}
1103
1104void CcFoundRandomTown(Commands, const CommandCost &result, Money, TownID town_id)
1105{
1106 if (result.Succeeded()) ScrollMainWindowToTile(Town::Get(town_id)->xy);
1107}
1108
1109static constexpr std::initializer_list<NWidgetPart> _nested_found_town_widgets = {
1112 NWidget(WWT_CAPTION, Colours::DarkGreen), SetStringTip(STR_FOUND_TOWN_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1115 EndContainer(),
1116 /* Construct new town(s) buttons. */
1119 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_NEW_TOWN), SetStringTip(STR_FOUND_TOWN_NEW_TOWN_BUTTON, STR_FOUND_TOWN_NEW_TOWN_TOOLTIP), SetFill(1, 0),
1122 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_TF_RANDOM_TOWN), SetStringTip(STR_FOUND_TOWN_RANDOM_TOWN_BUTTON, STR_FOUND_TOWN_RANDOM_TOWN_TOOLTIP), SetFill(1, 0),
1123 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_TF_MANY_RANDOM_TOWNS), SetStringTip(STR_FOUND_TOWN_MANY_RANDOM_TOWNS, STR_FOUND_TOWN_RANDOM_TOWNS_TOOLTIP), SetFill(1, 0),
1124 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_TF_LOAD_FROM_FILE), SetStringTip(STR_FOUND_TOWN_LOAD_FROM_FILE, STR_FOUND_TOWN_LOAD_FROM_FILE_TOOLTIP), SetFill(1, 0),
1125 EndContainer(),
1126 EndContainer(),
1127
1128 /* Town name selection. */
1129 NWidget(WWT_LABEL, Colours::Invalid), SetStringTip(STR_FOUND_TOWN_NAME_TITLE),
1130 NWidget(WWT_EDITBOX, Colours::Grey, WID_TF_TOWN_NAME_EDITBOX), SetStringTip(STR_FOUND_TOWN_NAME_EDITOR_TITLE, STR_FOUND_TOWN_NAME_EDITOR_TOOLTIP), SetFill(1, 0),
1131 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_TF_TOWN_NAME_RANDOM), SetStringTip(STR_FOUND_TOWN_NAME_RANDOM_BUTTON, STR_FOUND_TOWN_NAME_RANDOM_TOOLTIP), SetFill(1, 0),
1132
1133 /* Town size selection. */
1134 NWidget(WWT_LABEL, Colours::Invalid), SetStringTip(STR_FOUND_TOWN_INITIAL_SIZE_TITLE),
1137 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_SIZE_SMALL), SetStringTip(STR_FOUND_TOWN_INITIAL_SIZE_SMALL_BUTTON, STR_FOUND_TOWN_INITIAL_SIZE_TOOLTIP), SetFill(1, 0),
1138 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_SIZE_MEDIUM), SetStringTip(STR_FOUND_TOWN_INITIAL_SIZE_MEDIUM_BUTTON, STR_FOUND_TOWN_INITIAL_SIZE_TOOLTIP), SetFill(1, 0),
1139 EndContainer(),
1142 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_SIZE_LARGE), SetStringTip(STR_FOUND_TOWN_INITIAL_SIZE_LARGE_BUTTON, STR_FOUND_TOWN_INITIAL_SIZE_TOOLTIP), SetFill(1, 0),
1143 EndContainer(),
1144 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_SIZE_RANDOM), SetStringTip(STR_FOUND_TOWN_SIZE_RANDOM, STR_FOUND_TOWN_INITIAL_SIZE_TOOLTIP), SetFill(1, 0),
1145 EndContainer(),
1146 EndContainer(),
1147 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_CITY), SetStringTip(STR_FOUND_TOWN_CITY, STR_FOUND_TOWN_CITY_TOOLTIP), SetFill(1, 0),
1148
1149 /* Town roads selection. */
1152 NWidget(WWT_LABEL, Colours::Invalid), SetStringTip(STR_FOUND_TOWN_ROAD_LAYOUT),
1155 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_LAYOUT_ORIGINAL), SetStringTip(STR_FOUND_TOWN_SELECT_LAYOUT_ORIGINAL, STR_FOUND_TOWN_SELECT_LAYOUT_TOOLTIP), SetFill(1, 0),
1156 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_LAYOUT_BETTER), SetStringTip(STR_FOUND_TOWN_SELECT_LAYOUT_BETTER_ROADS, STR_FOUND_TOWN_SELECT_LAYOUT_TOOLTIP), SetFill(1, 0),
1157 EndContainer(),
1159 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_LAYOUT_GRID2), SetStringTip(STR_FOUND_TOWN_SELECT_LAYOUT_2X2_GRID, STR_FOUND_TOWN_SELECT_LAYOUT_TOOLTIP), SetFill(1, 0),
1160 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_LAYOUT_GRID3), SetStringTip(STR_FOUND_TOWN_SELECT_LAYOUT_3X3_GRID, STR_FOUND_TOWN_SELECT_LAYOUT_TOOLTIP), SetFill(1, 0),
1161 EndContainer(),
1162 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_LAYOUT_RANDOM), SetStringTip(STR_FOUND_TOWN_SELECT_LAYOUT_RANDOM, STR_FOUND_TOWN_SELECT_LAYOUT_TOOLTIP), SetFill(1, 0),
1163 EndContainer(),
1164 EndContainer(),
1165 EndContainer(),
1166
1167 /* Town expansion selection. */
1170 NWidget(WWT_LABEL, Colours::Invalid), SetStringTip(STR_FOUND_TOWN_EXPAND_MODE),
1171 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_TF_EXPAND_ALL_TOWNS), SetStringTip(STR_FOUND_TOWN_EXPAND_ALL_TOWNS, STR_FOUND_TOWN_EXPAND_ALL_TOWNS_TOOLTIP), SetFill(1, 0),
1173 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_EXPAND_BUILDINGS), SetStringTip(STR_FOUND_TOWN_EXPAND_BUILDINGS, STR_FOUND_TOWN_EXPAND_BUILDINGS_TOOLTIP), SetFill(1, 0),
1174 NWidget(WWT_TEXTBTN, Colours::Grey, WID_TF_EXPAND_ROADS), SetStringTip(STR_FOUND_TOWN_EXPAND_ROADS, STR_FOUND_TOWN_EXPAND_ROADS_TOOLTIP), SetFill(1, 0),
1175 EndContainer(),
1176 EndContainer(),
1177 EndContainer(),
1178 EndContainer(),
1179 EndContainer(),
1180};
1181
1183struct FoundTownWindow : Window {
1184private:
1187 bool city = false;
1189 bool townnamevalid = false;
1190 uint32_t townnameparts = 0;
1193
1194public:
1196 Window(desc),
1199 params(_settings_game.game_creation.town_name)
1200 {
1201 this->InitNested(window_number);
1202 this->querystrings[WID_TF_TOWN_NAME_EDITBOX] = &this->townname_editbox;
1203 this->RandomTownName();
1204 this->UpdateButtons(true);
1205 }
1206
1207 void OnInit() override
1208 {
1209 if (_game_mode == GameMode::Editor) return;
1210
1213 this->GetWidget<NWidgetStacked>(WID_TF_SIZE_SEL)->SetDisplayedPlane(SZSP_VERTICAL);
1214 if (_settings_game.economy.found_town != TownFounding::CustomLayout) {
1216 } else {
1217 this->GetWidget<NWidgetStacked>(WID_TF_ROAD_LAYOUT_SEL)->SetDisplayedPlane(0);
1218 }
1219 }
1220
1221 void RandomTownName()
1222 {
1223 this->townnamevalid = GenerateTownName(_interactive_random, &this->townnameparts);
1224
1225 if (!this->townnamevalid) {
1226 this->townname_editbox.text.DeleteAll();
1227 } else {
1228 this->townname_editbox.text.Assign(GetTownName(&this->params, this->townnameparts));
1229 }
1231
1233 }
1234
1235 void UpdateButtons(bool check_availability)
1236 {
1237 if (check_availability && _game_mode != GameMode::Editor) {
1239 this->ReInit();
1240 }
1241
1242 for (WidgetID i = WID_TF_SIZE_SMALL; i <= WID_TF_SIZE_RANDOM; i++) {
1244 }
1245
1247
1250 }
1251
1252 this->SetWidgetLoweredState(WID_TF_EXPAND_BUILDINGS, FoundTownWindow::expand_modes.Test(TownExpandMode::Buildings));
1253 this->SetWidgetLoweredState(WID_TF_EXPAND_ROADS, FoundTownWindow::expand_modes.Test(TownExpandMode::Roads));
1254
1255 this->SetDirty();
1256 }
1257
1258 template <typename Tcallback>
1259 void ExecuteFoundTownCommand(TileIndex tile, bool random, StringID errstr, Tcallback cc)
1260 {
1261 std::string name;
1262
1263 if (!this->townnamevalid) {
1264 name = this->townname_editbox.text.GetText();
1265 } else {
1266 /* If user changed the name, send it */
1267 std::string original_name = GetTownName(&this->params, this->townnameparts);
1268 if (original_name != this->townname_editbox.text.GetText()) name = this->townname_editbox.text.GetText();
1269 }
1270
1271 bool success = Command<Commands::FoundTown>::Post(errstr, cc,
1272 tile, this->town_size, this->city, this->town_layout, random, townnameparts, name);
1273
1274 /* Rerandomise name, if success and no cost-estimation. */
1275 if (success && !IsShiftPressed()) this->RandomTownName();
1276 }
1277
1278 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1279 {
1280 switch (widget) {
1281 case WID_TF_NEW_TOWN:
1283 break;
1284
1285 case WID_TF_RANDOM_TOWN:
1286 this->ExecuteFoundTownCommand(TileIndex{}, true, STR_ERROR_CAN_T_GENERATE_TOWN, CcFoundRandomTown);
1287 break;
1288
1290 this->RandomTownName();
1292 break;
1293
1295 std::string default_town_number = fmt::format("{}", GetDefaultTownsForMapSize());
1296 ShowQueryString(default_town_number, STR_MAPGEN_NUMBER_OF_TOWNS, 5, this, CS_NUMERAL, {QueryStringFlag::AcceptUnchanged});
1297 break;
1298 }
1301 break;
1302
1304 for (Town *t : Town::Iterate()) {
1305 Command<Commands::ExpandTown>::Do(DoCommandFlag::Execute, t->index, 0, FoundTownWindow::expand_modes);
1306 }
1307 break;
1308
1310 this->town_size = static_cast<TownSize>(widget - WID_TF_SIZE_SMALL);
1311 this->UpdateButtons(false);
1312 break;
1313
1314 case WID_TF_CITY:
1315 this->city ^= true;
1316 this->SetWidgetLoweredState(WID_TF_CITY, this->city);
1317 this->SetDirty();
1318 break;
1319
1321 FoundTownWindow::expand_modes.Flip(TownExpandMode::Buildings);
1322 this->UpdateButtons(false);
1323 break;
1324
1326 FoundTownWindow::expand_modes.Flip(TownExpandMode::Roads);
1327 this->UpdateButtons(false);
1328 break;
1329
1332 this->town_layout = static_cast<TownLayout>(widget - WID_TF_LAYOUT_ORIGINAL);
1333
1334 /* If we are in the editor, sync the settings of the current game to the chosen layout,
1335 * so that importing towns from file uses the selected layout. */
1336 if (_game_mode == GameMode::Editor) _settings_game.economy.town_layout = this->town_layout;
1337
1338 this->UpdateButtons(false);
1339 break;
1340 }
1341 }
1342
1343 void OnQueryTextFinished(std::optional<std::string> str) override
1344 {
1345 /* Was 'cancel' pressed? */
1346 if (!str.has_value()) return;
1347
1348 auto value = ParseInteger(*str, 10, true);
1349 if (!value.has_value()) return;
1350
1351 AutoRestoreBackup old_generating_world(_generating_world, true);
1352 bool road_pending = UpdateNearestTownForRoadTiles(true);
1353 if (!GenerateTowns(this->town_layout, value)) {
1354 ShowErrorMessage(GetEncodedString(STR_ERROR_CAN_T_GENERATE_TOWN), GetEncodedString(STR_ERROR_NO_SPACE_FOR_TOWN), WarningLevel::Info);
1355 }
1356 if (road_pending) UpdateNearestTownForRoadTiles(false);
1357 }
1358
1359 void OnPlaceObject([[maybe_unused]] Point pt, TileIndex tile) override
1360 {
1361 this->ExecuteFoundTownCommand(tile, false, STR_ERROR_CAN_T_FOUND_TOWN_HERE, CcFoundTown);
1362 }
1363
1364 void OnPlaceObjectAbort() override
1365 {
1366 this->RaiseButtons();
1367 this->UpdateButtons(false);
1368 }
1369
1375 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1376 {
1377 if (!gui_scope) return;
1378 this->UpdateButtons(true);
1379 }
1380};
1381
1384 WindowPosition::Automatic, "build_town", 160, 162,
1385 WindowClass::FoundTown, WindowClass::None,
1387 _nested_found_town_widgets
1388);
1389
1390void ShowFoundTownWindow()
1391{
1392 if (_game_mode != GameMode::Editor && !Company::IsValidID(_local_company)) return;
1394}
1395
1396void InitializeTownGui()
1397{
1398 _town_local_authority_kdtree.Clear();
1399}
1400
1408void DrawHouseInGUI(int x, int y, HouseID house_id, int view)
1409{
1410 auto draw = [](int x, int y, HouseID house_id, int view) {
1411 if (house_id >= NEW_HOUSE_OFFSET) {
1412 /* Houses don't necessarily need new graphics. If they don't have a
1413 * spritegroup associated with them, then the sprite for the substitute
1414 * house id is drawn instead. */
1415 const HouseSpec *spec = HouseSpec::Get(house_id);
1416 if (spec->grf_prop.HasSpriteGroups()) {
1417 DrawNewHouseTileInGUI(x, y, spec, house_id, view);
1418 return;
1419 } else {
1420 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
1421 }
1422 }
1423
1424 /* Retrieve data from the draw town tile struct */
1425 const DrawBuildingsTileStruct &dcts = GetTownDrawTileData()[house_id << 4 | view << 2 | TOWN_HOUSE_COMPLETED];
1426 DrawSprite(dcts.ground.sprite, dcts.ground.pal, x, y);
1427
1428 /* Add a house on top of the ground? */
1429 if (dcts.building.sprite != 0) {
1430 Point pt = RemapCoords(dcts.origin.x, dcts.origin.y, dcts.origin.z);
1431 DrawSprite(dcts.building.sprite, dcts.building.pal, x + UnScaleGUI(pt.x), y + UnScaleGUI(pt.y));
1432 }
1433 };
1434
1435 /* Houses can have 1x1, 1x2, 2x1 and 2x2 layouts which are individual HouseIDs. For the GUI we need
1436 * draw all of the tiles with appropriate positions. */
1437 int x_delta = ScaleSpriteTrad(TILE_PIXELS);
1438 int y_delta = ScaleSpriteTrad(TILE_PIXELS / 2);
1439
1440 const HouseSpec *hs = HouseSpec::Get(house_id);
1442 draw(x, y - y_delta - y_delta, house_id, view); // North corner.
1443 draw(x + x_delta, y - y_delta, house_id + 1, view); // West corner.
1444 draw(x - x_delta, y - y_delta, house_id + 2, view); // East corner.
1445 draw(x, y, house_id + 3, view); // South corner.
1446 } else if (hs->building_flags.Test(BuildingFlag::Size2x1)) {
1447 draw(x + x_delta / 2, y - y_delta, house_id, view); // North east tile.
1448 draw(x - x_delta / 2, y, house_id + 1, view); // South west tile.
1449 } else if (hs->building_flags.Test(BuildingFlag::Size1x2)) {
1450 draw(x - x_delta / 2, y - y_delta, house_id, view); // North west tile.
1451 draw(x + x_delta / 2, y, house_id + 1, view); // South east tile.
1452 } else {
1453 draw(x, y, house_id, view);
1454 }
1455}
1456
1463{
1464 std::array<int32_t, 1> regs100;
1465 uint16_t callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, 1, 0, hs->Index(), nullptr, INVALID_TILE, regs100, true);
1466 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
1467 StringID new_name = STR_NULL;
1468 if (callback_res == 0x40F) {
1469 new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, static_cast<GRFStringID>(regs100[0]));
1470 } else if (callback_res > 0x400) {
1472 } else {
1473 new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, GRFSTR_MISC_GRF_TEXT + callback_res);
1474 }
1475 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
1476 return new_name;
1477 }
1478 }
1479
1480 return hs->building_name;
1481}
1482
1483class HousePickerCallbacks : public PickerCallbacks {
1484public:
1485 HousePickerCallbacks() : PickerCallbacks("fav_houses") {}
1486
1491 {
1492 this->climate_mask = GetClimateMaskForLandscape();
1493
1494 /* In some cases, not all 'classes' (house zones) have distinct houses, so we need to disable those.
1495 * As we need to check all types, and this cannot change with the picker window open, pre-calculate it.
1496 * This loop calls GetTypeName() instead of directly checking properties so that there is no discrepancy. */
1497 this->class_mask = 0;
1498
1499 int num_classes = this->GetClassCount();
1500 for (int cls_id = 0; cls_id < num_classes; ++cls_id) {
1501 int num_types = this->GetTypeCount(cls_id);
1502 for (int id = 0; id < num_types; ++id) {
1503 if (this->GetTypeName(cls_id, id) != INVALID_STRING_ID) {
1504 SetBit(this->class_mask, cls_id);
1505 break;
1506 }
1507 }
1508 }
1509 }
1510
1511 HouseZones climate_mask{};
1512 uint8_t class_mask = 0;
1513
1514 static inline int sel_class;
1515 static inline int sel_type;
1516 static inline int sel_view;
1517
1519 static inline const std::array<StringID, NUM_HOUSE_ZONES> zone_names = {
1520 STR_HOUSE_PICKER_CLASS_ZONE1,
1521 STR_HOUSE_PICKER_CLASS_ZONE2,
1522 STR_HOUSE_PICKER_CLASS_ZONE3,
1523 STR_HOUSE_PICKER_CLASS_ZONE4,
1524 STR_HOUSE_PICKER_CLASS_ZONE5,
1525 };
1526
1528
1529 StringID GetClassTooltip() const override { return STR_PICKER_HOUSE_CLASS_TOOLTIP; }
1530 StringID GetTypeTooltip() const override { return STR_PICKER_HOUSE_TYPE_TOOLTIP; }
1531 StringID GetCollectionTooltip() const override { return STR_PICKER_HOUSE_COLLECTION_TOOLTIP; }
1532 bool IsActive() const override { return true; }
1533
1534 bool HasClassChoice() const override { return true; }
1535 int GetClassCount() const override { return static_cast<int>(zone_names.size()); }
1536
1537 void Close([[maybe_unused]] int data) override { ResetObjectToPlace(); }
1538
1539 int GetSelectedClass() const override { return HousePickerCallbacks::sel_class; }
1540 void SetSelectedClass(int cls_id) const override { HousePickerCallbacks::sel_class = cls_id; }
1541
1542 StringID GetClassName(int id) const override
1543 {
1544 if (id >= GetClassCount()) return INVALID_STRING_ID;
1545 if (!HasBit(this->class_mask, id)) return INVALID_STRING_ID;
1546 return zone_names[id];
1547 }
1548
1549 int GetTypeCount(int cls_id) const override
1550 {
1551 if (cls_id < GetClassCount()) return static_cast<int>(HouseSpec::Specs().size());
1552 return 0;
1553 }
1554
1555 PickerItem GetPickerItem(int cls_id, int id) const override
1556 {
1557 const auto *spec = HouseSpec::Get(id);
1558 if (!spec->grf_prop.HasGrfFile()) return {GrfID{}, spec->Index(), cls_id, id};
1559 return {spec->grf_prop.grfid, spec->grf_prop.local_id, cls_id, id};
1560 }
1561
1562 int GetSelectedType() const override { return sel_type; }
1563 void SetSelectedType(int id) const override { sel_type = id; }
1564
1565 static HouseZone GetHouseZoneFromClassId(int cls_id) { return static_cast<HouseZone>(to_underlying(HouseZone::TownEdge) + cls_id); }
1566 static int GetClassIdFromHouseZone(HouseZones zones) { return FindFirstBit((zones & HZ_ZONE_ALL).base()) - to_underlying(HouseZone::TownEdge); }
1567
1568 StringID GetTypeName(int cls_id, int id) const override
1569 {
1570 const HouseSpec *spec = HouseSpec::Get(id);
1571 if (spec == nullptr) return INVALID_STRING_ID;
1572 if (!spec->enabled) return INVALID_STRING_ID;
1573 if (!spec->building_availability.Any(climate_mask)) return INVALID_STRING_ID;
1574 if (!spec->building_availability.Test(GetHouseZoneFromClassId(cls_id))) return INVALID_STRING_ID;
1575 for (int i = 0; i < cls_id; i++) {
1576 /* Don't include if it's already included in an earlier zone. */
1577 if (spec->building_availability.Test(GetHouseZoneFromClassId(i))) return INVALID_STRING_ID;
1578 }
1579
1580 return GetHouseName(spec);
1581 }
1582
1583 std::span<const BadgeID> GetTypeBadges(int cls_id, int id) const override
1584 {
1585 const auto *spec = HouseSpec::Get(id);
1586 if (spec == nullptr) return {};
1587 if (!spec->enabled) return {};
1588 if (!spec->building_availability.Any(climate_mask)) return {};
1589 if (!spec->building_availability.Test(GetHouseZoneFromClassId(cls_id))) return {};
1590 for (int i = 0; i < cls_id; i++) {
1591 /* Don't include if it's already included in an earlier zone. */
1592 if (spec->building_availability.Test(GetHouseZoneFromClassId(i))) return {};
1593 }
1594
1595 return spec->badges;
1596 }
1597
1598 bool IsTypeAvailable(int, int id) const override
1599 {
1600 const HouseSpec *hs = HouseSpec::Get(id);
1601 return hs->enabled;
1602 }
1603
1604 void DrawType(int x, int y, int, int id) const override
1605 {
1607 }
1608
1609 void FillUsedItems(std::set<PickerItem> &items) override
1610 {
1611 auto id_count = GetBuildingHouseIDCounts();
1612 for (auto it = id_count.begin(); it != id_count.end(); ++it) {
1613 if (*it == 0) continue;
1614 HouseID house = static_cast<HouseID>(std::distance(id_count.begin(), it));
1615 const HouseSpec *hs = HouseSpec::Get(house);
1616 int class_index = GetClassIdFromHouseZone(hs->building_availability);
1617 items.insert({GrfID{}, house, class_index, house});
1618 }
1619 }
1620
1621 std::map<std::string, std::set<PickerItem>> UpdateSavedItems(const std::map<std::string, std::set<PickerItem>> &src) override
1622 {
1623 if (src.empty()) return src;
1624
1625 const auto &specs = HouseSpec::Specs();
1626 std::map<std::string, std::set<PickerItem>> dst;
1627 for (auto group_it = src.begin(); group_it != src.end(); group_it++) {
1628 if (group_it->second.empty() || (group_it->second.size() == 1 && group_it->second.contains({}))) {
1629 dst[group_it->first];
1630 continue;
1631 }
1632
1633 for (const auto &item : group_it->second) {
1634 if (item.grfid.Empty()) {
1635 const HouseSpec *hs = HouseSpec::Get(item.local_id);
1636 if (hs == nullptr) continue;
1637 int class_index = GetClassIdFromHouseZone(hs->building_availability);
1638 dst[group_it->first].emplace(item.grfid, item.local_id, class_index, item.local_id);
1639 } else {
1640 /* Search for spec by grfid and local index. */
1641 auto it = std::ranges::find_if(specs, [&item](const HouseSpec &spec) { return spec.grf_prop.grfid == item.grfid && spec.grf_prop.local_id == item.local_id; });
1642 if (it == specs.end()) {
1643 /* Not preset, hide from UI. */
1644 dst[group_it->first].emplace(item.grfid, item.local_id, -1, -1);
1645 } else {
1646 int class_index = GetClassIdFromHouseZone(it->building_availability);
1647 dst[group_it->first].emplace(item.grfid, item.local_id, class_index, it->Index());
1648 }
1649 }
1650 }
1651 }
1652
1653 return dst;
1654 }
1655
1656 static HousePickerCallbacks instance;
1657};
1658/* static */ HousePickerCallbacks HousePickerCallbacks::instance;
1659
1666{
1667 CargoTypes produced{};
1669 for (uint i = 0; i < 256; i++) {
1670 uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, hs->Index(), nullptr, INVALID_TILE, {}, true);
1671
1672 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
1673
1674 CargoType cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
1675 if (!IsValidCargoType(cargo)) continue;
1676
1677 uint amt = GB(callback, 0, 8);
1678 if (amt == 0) continue;
1679
1680 produced.Set(cargo);
1681 }
1682 } else {
1683 /* Cargo is not controlled by NewGRF, town production effect is used instead. */
1685 for (const CargoSpec *cs : CargoSpec::town_production_cargoes[TownProductionEffect::Mail]) produced.Set(cs->Index());
1686 }
1687 return produced;
1688}
1689
1690struct BuildHouseWindow : public PickerWindow {
1691 std::string house_info{};
1692 static inline bool house_protected;
1693 static inline bool replace;
1694
1695 BuildHouseWindow(WindowDesc &desc, Window *parent) : PickerWindow(desc, parent, 0, HousePickerCallbacks::instance)
1696 {
1697 HousePickerCallbacks::instance.SetClimateMask();
1698 this->ConstructWindow();
1699 }
1700
1701 void UpdateSelectSize(const HouseSpec *spec)
1702 {
1703 if (spec == nullptr) {
1704 SetTileSelectSize(1, 1);
1706 } else {
1709 SetTileSelectSize(2, 2);
1710 } else if (spec->building_flags.Test(BuildingFlag::Size2x1)) {
1711 SetTileSelectSize(2, 1);
1712 } else if (spec->building_flags.Test(BuildingFlag::Size1x2)) {
1713 SetTileSelectSize(1, 2);
1714 } else if (spec->building_flags.Test(BuildingFlag::Size1x1)) {
1715 SetTileSelectSize(1, 1);
1716 }
1717 }
1718 }
1719
1726 static std::string GetHouseYear(TimerGameCalendar::Year min_year, TimerGameCalendar::Year max_year)
1727 {
1728 if (min_year == CalendarTime::MIN_YEAR) {
1729 if (max_year == CalendarTime::MAX_YEAR) {
1730 return GetString(STR_HOUSE_PICKER_YEARS_ANY);
1731 }
1732 return GetString(STR_HOUSE_PICKER_YEARS_UNTIL, max_year);
1733 }
1734 if (max_year == CalendarTime::MAX_YEAR) {
1735 return GetString(STR_HOUSE_PICKER_YEARS_FROM, min_year);
1736 }
1737 return GetString(STR_HOUSE_PICKER_YEARS, min_year, max_year);
1738 }
1739
1745 static std::string GetHouseInformation(const HouseSpec *hs)
1746 {
1747 std::stringstream line;
1748
1749 line << GetString(STR_HOUSE_PICKER_NAME, GetHouseName(hs));
1750 line << "\n";
1751
1752 line << GetString(STR_HOUSE_PICKER_POPULATION, hs->population);
1753 line << "\n";
1754
1755 line << GetHouseYear(hs->min_year, hs->max_year);
1756 line << "\n";
1757
1758 uint8_t size = 0;
1759 if (hs->building_flags.Test(BuildingFlag::Size1x1)) size = 0x11;
1760 if (hs->building_flags.Test(BuildingFlag::Size2x1)) size = 0x21;
1761 if (hs->building_flags.Test(BuildingFlag::Size1x2)) size = 0x12;
1762 if (hs->building_flags.Test(BuildingFlag::Size2x2)) size = 0x22;
1763 line << GetString(STR_HOUSE_PICKER_SIZE, GB(size, 0, 4), GB(size, 4, 4));
1764
1765 auto cargo_string = BuildCargoAcceptanceString(GetAcceptedCargoOfHouse(hs), STR_HOUSE_PICKER_CARGO_ACCEPTED);
1766 if (cargo_string.has_value()) {
1767 line << "\n";
1768 line << *cargo_string;
1769 }
1770
1771 CargoTypes produced = GetProducedCargoOfHouse(hs);
1772 if (produced.Any()) {
1773 line << "\n";
1774 line << GetString(STR_HOUSE_PICKER_CARGO_PRODUCED, produced);
1775 }
1776
1777 return line.str();
1778 }
1779
1780 void OnInit() override
1781 {
1782 this->InvalidateData(PICKER_INVALIDATION_ALL);
1783 this->PickerWindow::OnInit();
1784 }
1785
1786 void DrawWidget(const Rect &r, WidgetID widget) const override
1787 {
1788 if (widget == WID_BH_INFO) {
1789 if (!this->house_info.empty()) DrawStringMultiLine(r, this->house_info);
1790 } else {
1791 this->PickerWindow::DrawWidget(r, widget);
1792 }
1793 }
1794
1795 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1796 {
1797 switch (widget) {
1799 BuildHouseWindow::house_protected = !BuildHouseWindow::house_protected;
1800 this->SetWidgetLoweredState(WID_BH_PROTECT_TOGGLE, BuildHouseWindow::house_protected);
1801
1802 SndClickBeep();
1803 this->SetDirty();
1804 break;
1805
1807 BuildHouseWindow::replace = !BuildHouseWindow::replace;
1808 this->SetWidgetLoweredState(WID_BH_REPLACE_TOGGLE, BuildHouseWindow::replace);
1809
1810 SndClickBeep();
1811 this->SetDirty();
1812 break;
1813
1814 default:
1815 this->PickerWindow::OnClick(pt, widget, click_count);
1816 break;
1817 }
1818 }
1819
1820 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1821 {
1822 this->PickerWindow::OnInvalidateData(data, gui_scope);
1823 if (!gui_scope) return;
1824
1826
1827 PickerInvalidations pi(data);
1829 UpdateSelectSize(spec);
1830 this->house_info = spec->enabled ? GetHouseInformation(spec) : "";
1831 }
1832
1833 /* The protection button only shows the player's choice.
1834 * Houses also have a property and a callback for protection, but these are not shown
1835 * since we cannot know the possible results of the callback in runtime. */
1836 this->SetWidgetLoweredState(WID_BH_PROTECT_TOGGLE, BuildHouseWindow::house_protected);
1837
1838 this->SetWidgetLoweredState(WID_BH_REPLACE_TOGGLE, BuildHouseWindow::replace);
1839 }
1840
1841 void OnPlaceObject([[maybe_unused]] Point pt, TileIndex tile) override
1842 {
1844
1847 } else {
1848 Command<Commands::PlaceHouse>::Post(STR_ERROR_CAN_T_BUILD_HOUSE, CcPlaySound_CONSTRUCTION_OTHER, tile, spec->Index(), BuildHouseWindow::house_protected, BuildHouseWindow::replace);
1849 }
1850 }
1851
1852 void OnPlaceDrag(ViewportPlaceMethod select_method, [[maybe_unused]] ViewportDragDropSelectionProcess select_proc, [[maybe_unused]] Point pt) override
1853 {
1854 VpSelectTilesWithMethod(pt.x, pt.y, select_method);
1855 }
1856
1857 void OnPlaceMouseUp([[maybe_unused]] ViewportPlaceMethod select_method, [[maybe_unused]] ViewportDragDropSelectionProcess select_proc, [[maybe_unused]] Point pt, TileIndex start_tile, TileIndex end_tile) override
1858 {
1859 if (pt.x == -1) return;
1860
1861 assert(select_proc == DDSP_PLACE_HOUSE);
1862
1864 Command<Commands::PlaceHouseArea>::Post(STR_ERROR_CAN_T_BUILD_HOUSE, CcPlaySound_CONSTRUCTION_OTHER,
1865 end_tile, start_tile, spec->Index(), BuildHouseWindow::house_protected, BuildHouseWindow::replace, IsCtrlPressed());
1866 }
1867
1868 const IntervalTimer<TimerWindow> view_refresh_interval = {std::chrono::milliseconds(2500), [this](auto) {
1869 /* There are four different 'views' that are random based on house tile position. As this is not
1870 * user-controllable, instead we automatically cycle through them. */
1872 this->SetDirty();
1873 }};
1874
1875 static inline HotkeyList hotkeys{"buildhouse", {
1876 Hotkey('F', "focus_filter_box", PCWHK_FOCUS_FILTER_BOX),
1877 }};
1878};
1879
1881static constexpr std::initializer_list<NWidgetPart> _nested_build_house_widgets = {
1884 NWidget(WWT_CAPTION, Colours::DarkGreen), SetStringTip(STR_HOUSE_PICKER_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1888 EndContainer(),
1895 NWidget(WWT_TEXTBTN, Colours::Grey, WID_BH_PROTECT_TOGGLE), SetMinimalSize(60, 12), SetStringTip(STR_HOUSE_PICKER_PROTECT, STR_HOUSE_PICKER_PROTECT_TOOLTIP),
1896 NWidget(WWT_TEXTBTN, Colours::Grey, WID_BH_REPLACE_TOGGLE), SetMinimalSize(60, 12), SetStringTip(STR_HOUSE_PICKER_REPLACE, STR_HOUSE_PICKER_REPLACE_TOOLTIP),
1897 EndContainer(),
1898 EndContainer(),
1899 EndContainer(),
1901 EndContainer(),
1902};
1903
1906 WindowPosition::Automatic, "build_house", 0, 0,
1907 WindowClass::BuildHouse, WindowClass::BuildToolbar,
1910 &BuildHouseWindow::hotkeys
1911);
1912
1913void ShowBuildHousePicker(Window *parent)
1914{
1915 if (BringWindowToFrontById(WindowClass::BuildHouse, 0)) return;
1917}
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
std::optional< std::string > BuildCargoAcceptanceString(const CargoArray &acceptance, StringID label)
Build comma-separated cargo acceptance string.
@ Mail
Cargo behaves mail-like for production.
Definition cargotype.h:38
@ Passengers
Cargo behaves passenger-like for production.
Definition cargotype.h:37
TownAcceptanceEffect
Town growth effect when delivering cargo.
Definition cargotype.h:21
@ End
End of town effects.
Definition cargotype.h:29
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
std::optional< Tvalue_type > GetNthSetBit(uint n) const
Get the value of the Nth set bit.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
bool Failed() const
Did this command fail?
std::string GetDecodedString() const
Decode the encoded string.
Definition strings.cpp:206
Iterate a range of enum values.
List template of 'things' T to sort in a GUI.
void RebuildDone()
Notify the sortlist that the rebuild is done.
void SetListing(Listing l)
Import sort conditions.
bool IsDescSortOrder() const
Check if the sort order is descending.
void ToggleSortOrder()
Toggle the sort order Since that is the worst condition for the sort function reverse the list here.
bool NeedRebuild() const
Check if a rebuild is needed.
void ForceRebuild()
Force that a rebuild is needed.
bool Sort(Comp compare)
Sort the list.
void ForceResort()
Force a resort next Sort call Reset the resort timer if used too.
uint8_t SortType() const
Get the sorttype of the list.
Listing GetListing() const
Export current sort conditions.
void SetSortFuncs(std::span< SortFunction *const > n_funcs)
Hand the sort function pointers to the GUIList.
void SetSortType(uint8_t n_type)
Set the sorttype of the list.
PickerItem GetPickerItem(int cls_id, int id) const override
Get data about an item.
bool IsActive() const override
Should picker class/type selection be enabled?
void SetClimateMask()
Set climate mask for filtering buildings from current landscape.
void SetSelectedClass(int cls_id) const override
Set the selected class.
StringID GetClassTooltip() const override
Get the tooltip string for the class list.
GrfSpecFeature GetFeature() const override
NewGRF feature this picker is for.
std::span< const BadgeID > GetTypeBadges(int cls_id, int id) const override
Get the item's badges of a type.
void DrawType(int x, int y, int, int id) const override
Draw preview image of an item.
static int sel_view
Currently selected 'view'. This is not controllable as its based on random data.
int GetClassCount() const override
Get the number of classes.
void FillUsedItems(std::set< PickerItem > &items) override
Fill a set with all items that are used by the current player.
static int sel_type
Currently selected HouseID.
int GetSelectedClass() const override
Get the index of the selected class.
StringID GetTypeTooltip() const override
Get the tooltip string for the type grid.
void SetSelectedType(int id) const override
Set the selected type.
StringID GetCollectionTooltip() const override
Get the tooltip string for the collection list.
StringID GetTypeName(int cls_id, int id) const override
Get the item name of a type.
int GetSelectedType() const override
Get the selected type.
bool IsTypeAvailable(int, int id) const override
Test if an item is currently buildable.
bool HasClassChoice() const override
Are there multiple classes to chose from?
std::map< std::string, std::set< PickerItem > > UpdateSavedItems(const std::map< std::string, std::set< PickerItem > > &src) override
Update link between grfid/localidx and class_index/index in saved items.
uint8_t class_mask
Mask of available 'classes'.
static const std::array< StringID, NUM_HOUSE_ZONES > zone_names
Houses do not have classes like NewGRFClass.
int GetTypeCount(int cls_id) const override
Get the number of types in a class.
void Close(int data) override
Hide the window and all its child windows, and mark them for a later deletion.
StringID GetClassName(int id) const override
Get the name of a class.
static int sel_class
Currently selected 'class'.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
Baseclass for nested widgets.
uint current_x
Current horizontal size (after resizing).
uint smallest_y
Smallest vertical size of the widget in a filled window.
uint current_y
Current vertical size (after resizing).
Nested widget to display a viewport in a window.
void UpdateViewportCoordinates(Window *w)
Update the position and size of the viewport (after eg a resize).
Definition widget.cpp:2451
void InitializeViewport(Window *w, std::variant< TileIndex, VehicleID > focus, ZoomLevel zoom)
Initialize the viewport of the window.
Definition widget.cpp:2442
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
@ Position
Update scroll positions.
Definition picker_gui.h:329
@ PCWHK_FOCUS_FILTER_BOX
Focus the edit box for editing the filter string.
Definition picker_gui.h:373
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
EnumBitSet< PickerInvalidation, uint8_t > PickerInvalidations
Bitset of Pickerinvalidation elements.
Definition picker_gui.h:335
void OnInit() override
Notification that the nested widget tree gets initialized.
Scrollbar data structure.
auto GetScrolledItemFromWidget(Tcontainer &container, int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Return an iterator pointing to the element of a scrolled widget that a user clicked in.
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2548
size_type GetCount() const
Gets the number of elements in the list.
auto GetVisibleRangeIterators(Tcontainer &container) const
Get a pair of iterators for the range of visible elements in a container.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGame< struct Calendar >::Year MIN_YEAR
static constexpr TimerGame< struct Calendar >::Year MAX_YEAR
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
StrongType::Typedef< int32_t, struct YearTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Year
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
Functions related to commands.
@ Execute
execute the given command
Commands
List of commands.
Definition of stuff that is very close to a company, like the company struct itself.
void DrawCompanyIcon(CompanyID c, int x, int y)
Draw the icon of a company.
PaletteID GetCompanyPalette(CompanyID company)
Get the palette for recolouring with a company colour.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Functions related to companies.
GUI Functions related to companies.
void ShowDropDownMenu(Window *w, std::span< const StringID > strings, int selected, WidgetID button, uint32_t disabled_mask, uint32_t hidden_mask, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a dropdown menu window near a widget of the parent window.
Definition dropdown.cpp:633
Functions related to the drop down widget.
Prices _price
Prices and also the fractional part.
Definition economy.cpp:94
@ TownAction
Price for interaction with local authorities.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
Functions related to errors.
@ Info
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition error.h:22
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
@ Load
File is being loaded.
Definition fileio_type.h:53
@ TownData
town data file
Definition fileio_type.h:21
Declarations for savegames operations.
void ShowSaveLoadDialog(AbstractFileType abstract_filetype, SaveLoadOperation fop)
Launch save/load dialog in the given mode.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
bool _generating_world
Whether we are generating the map or not.
Definition genworld.cpp:70
Functions related to world/map generation.
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
int GetStringHeight(std::string_view str, int maxw, FontSize fontsize)
Calculates height of string (in pixels).
Definition gfx.cpp:711
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:966
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
Dimension GetStringListBoundingBox(std::span< const StringID > list, FontSize fontsize)
Get maximum dimension of a list of strings.
Definition gfx.cpp:933
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
Calculate string bounding box for multi-line strings.
Definition gfx.cpp:747
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:782
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
bool IsShiftPressed()
Test if the shift key is pressed.
Definition gfx_func.h:88
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Grey
Grey.
Definition gfx_type.h:299
@ Brown
Brown.
Definition gfx_type.h:298
@ DarkGreen
Dark green.
Definition gfx_type.h:292
@ NoShade
Do not add shading to this text colour.
Definition gfx_type.h:342
@ White
White colour.
Definition gfx_type.h:330
@ Yellow
Yellow colour.
Definition gfx_type.h:326
@ Orange
Orange colour.
Definition gfx_type.h:324
@ Grey
Grey colour.
Definition gfx_type.h:332
@ Black
Black colour.
Definition gfx_type.h:334
@ Red
Red colour.
Definition gfx_type.h:321
Graph GUI functions.
constexpr NWidgetPart NWidgetFunction(NWidgetFunctionType *func_ptr)
Obtain a nested widget (sub)tree from an external source.
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetSpriteTip(SpriteID sprite, StringID tip={})
Widget part function for setting the sprite and tooltip.
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetPadding(uint8_t top, uint8_t right, uint8_t bottom, uint8_t left)
Widget part function for setting additional space around a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetAspect(float ratio, AspectFlags flags=AspectFlag::ResizeX)
Widget part function for setting the aspect ratio.
constexpr NWidgetPart SetMinimalTextLines(uint8_t lines, uint8_t spacing, FontSize size=FontSize::Normal)
Widget part function for setting the minimal text lines.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
uint8_t LowestSnowLine()
Get the lowest possible snow line height, either variable or static.
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
static const CursorID SPR_CURSOR_TOWN
Definition sprites.h:1580
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
GUI functions that shouldn't be here.
void ShowExtraViewportWindow(TileIndex tile=INVALID_TILE)
Show a new Extra Viewport window.
Hotkey related functions.
Definition of HouseSpec and accessors.
HouseZones GetClimateMaskForLandscape()
Get the HouseZones climate mask for the current landscape type.
@ Size1x1
The building is a single tile.
Definition house.h:39
@ Size2x2
The building is 2x2 tiles.
Definition house.h:43
@ Size2x1
The building is 2x1 tiles, i.e. wider on the X-axis.
Definition house.h:41
@ Size1x2
The building is 1x2 tiles, i.e. wider on the Y-axis.
Definition house.h:42
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition house.h:28
EnumBitSet< HouseZone, uint16_t > HouseZones
Bitset of HouseZone elements.
Definition house.h:75
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition house.h:25
HouseZone
Concentric rings of zoning around the centre of a town.
Definition house.h:59
@ TownEdge
Edge of the town; roads without pavement.
Definition house.h:60
uint16_t HouseID
OpenTTD ID of house types.
Definition house_type.h:15
Functions related to OTTD's landscape.
Point RemapCoords(int x, int y, int z)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:81
#define Point
Macro that prevents name conflicts between included headers.
bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
Zooms a viewport in a window in or out.
Definition main_gui.cpp:88
bool HandlePlacePushButton(Window *w, WidgetID widget, CursorID cursor, HighLightStyle mode)
This code is shared for the majority of the pushbuttons.
Definition main_gui.cpp:58
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
void ShowQueryString(std::string_view str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
Show a query popup window with a textbox in it.
bool _networking
are we in networking mode?
Definition network.cpp:63
bool _network_server
network-server is active
Definition network.cpp:64
Basic functions/variables used all over the place.
GrfSpecFeature
Definition newgrf.h:81
@ Houses
Houses feature.
Definition newgrf.h:89
@ CBID_HOUSE_CUSTOM_NAME
Called on the Get Tile Description for an house tile.
@ CBID_HOUSE_PRODUCE_CARGO
Called to determine how much cargo a town building produces.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
@ ProduceCargo
custom cargo production
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
CargoType GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoType.
Cargo support for NewGRFs.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
std::span< const uint > GetBuildingHouseIDCounts()
Get read-only span of total HouseID building counts.
void DrawNewHouseTileInGUI(int x, int y, const HouseSpec *spec, HouseID house_id, int view)
Draw representation of a house tile for GUI purposes.
uint16_t GetHouseCallback(CallbackID callback, uint32_t param1, uint32_t param2, HouseID house_id, Town *town, TileIndex tile, std::span< int32_t > regs100, bool not_yet_constructed, uint8_t initial_random_bits, CargoTypes watched_cargo_triggers, int view)
Get the result of a house callback.
Functions related to NewGRF houses.
StringID GetGRFStringID(GrfID grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
StrongType::Typedef< uint32_t, struct GRFStringIDTag, StrongType::Compare, StrongType::Integer > GRFStringID
Type for GRF-internal string IDs.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
Label< struct GrfIDTag > GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:17
@ Editor
In the scenario editor.
Definition openttd.h:21
void UpdateOSKOriginalText(const Window *parent, WidgetID button)
Updates the original text of the OSK so when the 'parent' changes the original and you press on cance...
Definition osk_gui.cpp:411
std::unique_ptr< NWidgetBase > MakePickerClassWidgets()
Create nested widgets for the class picker widgets.
std::unique_ptr< NWidgetBase > MakePickerTypeWidgets()
Create nested widgets for the type picker widgets.
Functions/types etc.
Base for the GUIs that have an edit box in them.
Randomizer _interactive_random
Random used everywhere else, where it does not (directly) influence the game state.
bool UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Road related functions.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
@ Off
Scroll wheel has no effect.
Base types for having sorted lists in GUIs.
void SndClickBeep()
Play a beep sound for a click event if enabled in settings.
Definition sound.cpp:252
Functions related to sound.
@ SND_1F_CONSTRUCTION_OTHER
29 == 0x1D Construction: other (non-water, non-rail, non-bridge)
Definition sound_type.h:76
static const SpriteID SPR_COMPANY_ICON
Icon showing company colour.
Definition sprites.h:386
Definition of base types and functions in a cross-platform compatible way.
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
Definition string.cpp:428
Parse strings.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
Functions related to low-level strings.
@ CS_NUMERAL
Only numeric ones.
Definition string_type.h:26
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
Searching and filtering using a stringterm.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
uint64_t GetParamMaxDigits(uint count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:217
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames).
@ TD_RTL
Text is written right-to-left by default.
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
static std::string GetHouseYear(TimerGameCalendar::Year min_year, TimerGameCalendar::Year max_year)
Get a date range string for house availability year.
void OnPlaceObject(Point pt, TileIndex tile) override
The user clicked some place on the map when a tile highlight mode has been set.
void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt) override
The user is dragging over the map when the tile highlight mode has been set.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile) override
The user has dragged over the map when the tile highlight mode has been set.
static std::string GetHouseInformation(const HouseSpec *hs)
Get information string for a house.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnInit() override
Notification that the nested widget tree gets initialized.
Specification of a cargo type.
Definition cargotype.h:76
static EnumIndexArray< std::vector< const CargoSpec * >, TownProductionEffect, TownProductionEffect::End > town_production_cargoes
List of cargo specs for each Town Product Effect.
Definition cargotype.h:242
CargoType Index() const
Determines index of this cargospec.
Definition cargotype.h:110
StringID name
Name of this type of cargo.
Definition cargotype.h:93
T y
Y coordinate.
T x
X coordinate.
T x
X coordinate.
T y
Y coordinate.
T z
Z coordinate.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
This structure is the same for both Industries and Houses.
Definition sprite.h:90
TownFounding found_town
town founding.
TownLayout town_layout
select town layout,
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
Found a town window class.
uint32_t townnameparts
Generated town name.
TownLayout town_layout
Selected town layout.
void OnPlaceObject(Point pt, TileIndex tile) override
The user clicked some place on the map when a tile highlight mode has been set.
QueryString townname_editbox
Townname editbox.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void OnInit() override
Notification that the nested widget tree gets initialized.
TownSize town_size
Selected town size.
bool townnamevalid
Is generated town name valid?
TownNameParams params
Town name parameters.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnPlaceObjectAbort() override
The user cancelled a tile highlight mode that has been set.
bool city
Are we building a city?
GrfID grfid
grfid that introduced this entity.
const struct GRFFile * grffile
grf file that introduced this entity
uint16_t local_id
id defined by the grf file for this entity
GrfID grfid
The GRF ID.
Definition newgrf.h:128
EconomySettings economy
settings to change the economy
List of hotkeys for a window.
Definition hotkeys.h:44
All data for a single hotkey.
Definition hotkeys.h:20
SubstituteGRFFileProps grf_prop
Properties related the the grf file.
Definition house.h:122
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition house.h:119
static HouseSpec * Get(size_t house_id)
Get the spec for a house ID.
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition house.h:117
TimerGameCalendar::Year max_year
last year it can be built
Definition house.h:109
HouseCallbackMasks callback_mask
Bitmask of house callbacks that have to be called.
Definition house.h:123
uint8_t population
population (Zero on other tiles in multi tile house.)
Definition house.h:110
TimerGameCalendar::Year min_year
introduction year of the house
Definition house.h:108
HouseID Index() const
Gets the index of this spec.
StringID building_name
building name
Definition house.h:112
HouseZones building_availability
where can it be built (climates, zones)
Definition house.h:118
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
Data structure describing how to show the list (what sort direction and criteria).
bool order
Ascending/descending.
SpriteID sprite
The 'real' sprite.
Definition gfx_type.h:23
PaletteID pal
The palette (use PAL_NONE) if not needed).
Definition gfx_type.h:24
static Pool::IterateWrapper< Company > Iterate(size_t from=0)
static Town * Get(auto index)
Data stored about a string that can be modified in the GUI.
int cancel_button
Widget button of parent window to simulate when pressing CANCEL in OSK.
static const int ACTION_CLEAR
Clear editbox.
Specification of a rectangle with absolute coordinates of all edges.
Rect WithWidth(int width, bool end) const
Copy Rect and set its width.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Rect Indent(int indent, bool end) const
Copy Rect and indent it from its position.
Coord3D< int8_t > origin
Position of northern corner within tile.
Definition sprite.h:19
bool HasSpriteGroups() const
Check whether the entity has sprite groups.
String filter and state.
bool IsEmpty() const
Check whether any filter words were entered.
void SetFilterTerm(std::string_view str)
Set the term to filter on.
uint16_t subst_id
The id of the entity to replace.
void DeleteAll()
Delete every character in the textbuffer.
Definition textbuf.cpp:111
std::string_view GetText() const
Get the current text.
Definition textbuf.cpp:283
Town authority window.
Definition town_gui.cpp:81
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
Definition town_gui.cpp:320
void DrawActions()
Draws the contents of the actions panel.
Definition town_gui.cpp:205
Dimension icon_size
Dimensions of company icon.
Definition town_gui.cpp:90
void OnInit() override
Notification that the nested widget tree gets initialized.
Definition town_gui.cpp:130
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
Definition town_gui.cpp:231
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
Definition town_gui.cpp:247
Town * town
Town being displayed.
Definition town_gui.cpp:83
TownActions enabled_actions
Actions that are enabled in settings.
Definition town_gui.cpp:86
TownAction sel_action
Currently selected town action, TownAction::End means no action selected.
Definition town_gui.cpp:84
TownActions available_actions
Actions that are available to execute for the current company.
Definition town_gui.cpp:87
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Definition town_gui.cpp:279
void DrawRatings()
Draw the contents of the ratings panel.
Definition town_gui.cpp:166
const IntervalTimer< TimerWindow > redraw_interval
Redraw the whole window on a regular interval.
Definition town_gui.cpp:316
Dimension exclusive_size
Dimensions of exclusive icon.
Definition town_gui.cpp:91
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
Definition town_gui.cpp:224
static TownActions GetEnabledActions()
Gets all town authority actions enabled in settings.
Definition town_gui.cpp:98
void OnPaint() override
The window must be repainted.
Definition town_gui.cpp:136
TownActions displayed_actions_on_previous_painting
Actions that were available on the previous call to OnPaint().
Definition town_gui.cpp:85
uint32_t population
Current population of people.
Definition town.h:54
Town directory window class.
Definition town_gui.cpp:721
static bool TownPopulationSorter(const Town *const &a, const Town *const &b, const bool &filter)
Sort by population (default descending, as big towns are of the most interest).
Definition town_gui.cpp:774
static const std::initializer_list< GUITownList::SortFunction *const > sorter_funcs
Functions to sort towns.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
Definition town_gui.cpp:879
static Listing last_sorting
Retains sorting setting when closing the window.
static bool TownProductionSorter(const Town *const &a, const Town *const &b, const bool &filter)
Sort by cargo production.
Definition town_gui.cpp:805
QueryString townname_editbox
Filter editbox.
Definition town_gui.cpp:737
static bool TownRatingSorter(const Town *const &a, const Town *const &b, const bool &filter)
Sort by town rating.
Definition town_gui.cpp:783
static bool TownTransportedSorter(const Town *const &a, const Town *const &b, const bool &filter)
Sort by cargo transported.
Definition town_gui.cpp:819
void OnEditboxChanged(WidgetID wid) override
The text in an editbox has been edited.
void OnResize() override
Called after the window got resized.
StringFilter string_filter
Filter for towns.
Definition town_gui.cpp:736
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
const IntervalTimer< TimerWindow > rebuild_interval
Redraw the whole window on a regular interval.
static bool TownNameSorter(const Town *const &a, const Town *const &b, const bool &filter)
Sort by town name.
Definition town_gui.cpp:768
void OnPaint() override
The window must be repainted.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Definition town_gui.cpp:970
static std::string GetTownString(const Town *t, uint64_t population)
Get the string to draw the town name.
Definition town_gui.cpp:874
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
Definition town_gui.cpp:923
static const StringID sorter_names[]
Strings describing how towns are sorted.
Definition town_gui.cpp:727
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
Definition town_gui.cpp:851
Struct holding parameters used to generate town name.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Definition town_gui.cpp:474
Town * town
Town displayed by the window.
Definition town_gui.cpp:348
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
Definition town_gui.cpp:594
void OnMouseWheel(int wheel, WidgetID widget) override
The mouse wheel has been turned.
Definition town_gui.cpp:581
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
Definition town_gui.cpp:521
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
Definition town_gui.cpp:390
uint GetDesiredInfoHeight(int width) const
Gets the desired height for the information panel.
Definition town_gui.cpp:535
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
Definition town_gui.cpp:375
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
Definition town_gui.cpp:369
void OnPaint() override
The window must be repainted.
Definition town_gui.cpp:382
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
Definition town_gui.cpp:602
void OnResize() override
Called after the window got resized.
Definition town_gui.cpp:571
Town data structure.
Definition town.h:64
EncodedString text
General text with additional information.
Definition town.h:137
bool larger_town
if this is a larger town and should grow more quickly
Definition town.h:199
TileIndex xy
town center tile
Definition town.h:65
uint8_t fund_buildings_months
fund buildings program in action?
Definition town.h:196
uint16_t noise_reached
level of noise that all the airports are generating
Definition town.h:80
SuppliedCargoes supplied
Cargo statistics about supplied cargo.
Definition town.h:131
TownFlags flags
See TownFlags.
Definition town.h:78
TownCache cache
Container for all cacheable data.
Definition town.h:67
CompanyID exclusivity
which company has exclusivity
Definition town.h:87
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition town.h:202
EnumIndexArray< TransportedCargoStat< uint16_t >, TownAcceptanceEffect, TownAcceptanceEffect::End > received
Cargo statistics about received cargotypes.
Definition town.h:133
CompanyMask have_ratings
which companies have a rating
Definition town.h:85
TypedIndexContainer< std::array< int16_t, MAX_COMPANIES >, CompanyID > ratings
ratings of each company for this town
Definition town.h:89
uint16_t growth_rate
town growth rate
Definition town.h:194
EnumIndexArray< uint32_t, TownAcceptanceEffect, TownAcceptanceEffect::End > goal
Amount of cargo required for the town to grow.
Definition town.h:134
High level window description.
Definition window_gui.h:171
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
void ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
Definition window.cpp:1025
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1150
static int SortButtonWidth()
Get width of up/down arrow of sort button state.
Definition widget.cpp:839
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
std::map< WidgetID, QueryString * > querystrings
QueryString associated to WWT_EDITBOX widgets.
Definition window_gui.h:319
void DrawWidgets() const
Paint all widgets of a window.
Definition widget.cpp:792
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
Window * parent
Parent window.
Definition window_gui.h:327
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
std::unique_ptr< ViewportData > viewport
Pointer to viewport data, if present.
Definition window_gui.h:317
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void DrawSortButton(WidgetID widget, bool descending) const
Draw a sort button's up or down arrow symbol.
Definition widget.cpp:824
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
bool SetFocusedWidget(WidgetID widget_index)
Set focus within this window to the given widget.
Definition window.cpp:494
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition window_gui.h:490
void RaiseButtons(bool autoraise=false)
Raise the buttons of the window.
Definition window.cpp:539
void SetWidgetLoweredState(WidgetID widget_index, bool lowered_stat)
Sets the lowered/raised status of a widget.
Definition window_gui.h:440
bool IsShaded() const
Is window shaded currently?
Definition window_gui.h:561
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
int GetRowFromWidget(int clickpos, WidgetID widget, int padding, int line_height=-1) const
Compute the row of a widget that a user clicked in.
Definition window.cpp:218
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1869
WindowFlags flags
Window flags.
Definition window_gui.h:299
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Stuff related to the text buffer GUI.
@ AcceptUnchanged
return success even when the text didn't change
Definition textbuf_gui.h:19
@ EnableDefault
enable the 'Default' button ("\0" is returned)
Definition textbuf_gui.h:20
@ LengthIsInChars
the length of the string is counted in characters
Definition textbuf_gui.h:21
static uint TileHeight(Tile tile)
Returns the height of a tile.
Definition tile_map.h:29
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition tile_map.h:238
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
@ Desert
Tile is desert.
Definition tile_type.h:83
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_PIXELS
Pixel distance between tile columns/rows in ZOOM_BASE.
Definition tile_type.h:17
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
Selects tiles while dragging.
void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
Prepare state for highlighting tiles while dragging with the mouse.
@ HT_DIAGONAL
Also allow 'diagonal rectangles'. Only usable in combination with HT_RECT or HT_POINT.
@ HT_RECT
rectangle (stations, depots, ...)
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the Window system.
Base of the town class.
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount).
Definition town.h:32
uint GetDefaultTownsForMapSize()
Calculate the number of towns which should be on the map according to the current "town density" newg...
TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
Get a list of available town authority actions.
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount).
Definition town.h:33
EnumBitSet< TownAction, uint8_t > TownActions
Bitset of TownAction elements.
Definition town.h:310
bool GenerateTowns(TownLayout layout, std::optional< uint > number=std::nullopt)
Generate a number of towns with a given layout.
uint32_t GetWorldPopulation()
Get the total population, the sum of all towns in the world.
Definition town_cmd.cpp:440
CargoArray GetAcceptedCargoOfHouse(const HouseSpec *hs)
Get accepted cargo of a house prototype.
Definition town_cmd.cpp:831
uint8_t GetTownActionCost(TownAction action)
Get cost factors for a TownAction.
TownAction
Town actions of a company.
Definition town.h:297
@ RoadRebuild
Rebuild the roads.
Definition town.h:301
@ Bribe
Try to bribe the council.
Definition town.h:305
@ End
End marker.
Definition town.h:306
@ BuyRights
Buy exclusive transport rights.
Definition town.h:304
@ FundBuildings
Fund new buildings.
Definition town.h:303
@ IsGrowing
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition town.h:42
Command definitions related to towns.
static WindowDesc _town_authority_desc(WindowPosition::Automatic, "view_town_authority", 317, 222, WindowClass::TownAuthority, WindowClass::None, {}, _nested_town_authority_widgets)
Window definition for the town authority window.
void DrawHouseInGUI(int x, int y, HouseID house_id, int view)
Draw a house that does not exist.
static WindowDesc _town_editor_view_desc(WindowPosition::Automatic, "view_town_scen", 260, TownViewWindow::WID_TV_HEIGHT_NORMAL, WindowClass::TownView, WindowClass::None, {}, _nested_town_editor_view_widgets)
Window definition for the town view window of the scenario edtior.
static WindowDesc _found_town_desc(WindowPosition::Automatic, "build_town", 160, 162, WindowClass::FoundTown, WindowClass::None, WindowDefaultFlag::Construction, _nested_found_town_widgets)
Window definition for the town funding window.
static StringID GetHouseName(const HouseSpec *hs)
Get name for a prototype house.
static CargoTypes GetProducedCargoOfHouse(const HouseSpec *hs)
Get the cargo types produced by a house.
static WindowDesc _town_directory_desc(WindowPosition::Automatic, "list_towns", 208, 202, WindowClass::TownDirectory, WindowClass::None, {}, _nested_town_directory_widgets, &TownDirectoryWindow::hotkeys)
Window definition for the town directory window.
static constexpr std::initializer_list< NWidgetPart > _nested_build_house_widgets
Nested widget definition for the build NewGRF rail waypoint window.
static WindowDesc _town_game_view_desc(WindowPosition::Automatic, "view_town", 260, TownViewWindow::WID_TV_HEIGHT_NORMAL, WindowClass::TownView, WindowClass::None, {}, _nested_town_game_view_widgets)
Window definition for the town view window.
static WindowDesc _build_house_desc(WindowPosition::Automatic, "build_house", 0, 0, WindowClass::BuildHouse, WindowClass::BuildToolbar, WindowDefaultFlag::Construction, _nested_build_house_widgets, &BuildHouseWindow::hotkeys)
Window definition for the house building window.
Declarations for accessing the k-d tree of towns.
TownLayout
Town Layouts.
Definition town_type.h:83
@ CustomLayout
Allowed, with custom town layout.
Definition town_type.h:107
TownSize
Supported initial town sizes.
Definition town_type.h:21
@ Medium
Medium town.
Definition town_type.h:23
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including '\0'.
Definition town_type.h:116
@ Roads
Allow town to place roads.
Definition town_type.h:97
@ Buildings
Allow town to place buildings.
Definition town_type.h:96
EnumBitSet< TownExpandMode, uint8_t > TownExpandModes
Bitset of TownExpandMode elements.
Definition town_type.h:101
Types related to the town widgets.
@ WID_TA_EXECUTE
Do-it button.
Definition town_widget.h:32
@ WID_TA_ACTION_INFO
Additional information about the action.
Definition town_widget.h:31
@ WID_TA_RATING_INFO
Overview with ratings for each company.
Definition town_widget.h:28
@ WID_TA_CAPTION
Caption of window.
Definition town_widget.h:26
@ WID_TA_ZONE_BUTTON
Turn on/off showing local authority zone.
Definition town_widget.h:27
@ WID_TA_COMMAND_LIST
List of commands for the player.
Definition town_widget.h:29
@ WID_TV_VIEWPORT
View of the center of the town.
Definition town_widget.h:38
@ WID_TV_EXPAND_BUILDINGS
Expand number of buildings this town (scenario editor only).
Definition town_widget.h:45
@ WID_TV_INFO
General information about the town.
Definition town_widget.h:39
@ WID_TV_EXPAND
Expand this town (scenario editor only).
Definition town_widget.h:44
@ WID_TV_CATCHMENT
Toggle catchment area highlight.
Definition town_widget.h:43
@ WID_TV_SHOW_AUTHORITY
Show the town authority window.
Definition town_widget.h:41
@ WID_TV_CHANGE_NAME
Change the name of this town.
Definition town_widget.h:42
@ WID_TV_CENTER_VIEW
Center the main view on this town.
Definition town_widget.h:40
@ WID_TV_DELETE
Delete this town (scenario editor only).
Definition town_widget.h:47
@ WID_TV_EXPAND_ROADS
Expand roads of this town (scenario editor only).
Definition town_widget.h:46
@ WID_TV_CAPTION
Caption of window.
Definition town_widget.h:37
@ WID_TF_LAYOUT_RANDOM
Selection for a randomly chosen town layout.
Definition town_widget.h:72
@ WID_TF_LOAD_FROM_FILE
Load town data from file.
Definition town_widget.h:57
@ WID_TF_SIZE_SEL
Container of town size buttons.
Definition town_widget.h:61
@ WID_TF_SIZE_LARGE
Selection for a large town.
Definition town_widget.h:64
@ WID_TF_NEW_TOWN
Create a new town.
Definition town_widget.h:53
@ WID_TF_EXPAND_ALL_TOWNS
Make all towns grow slightly.
Definition town_widget.h:58
@ WID_TF_MANY_RANDOM_TOWNS
Randomly place many towns.
Definition town_widget.h:56
@ WID_TF_SIZE_SMALL
Selection for a small town.
Definition town_widget.h:62
@ WID_TF_EXPAND_BUILDINGS
Expand buildings toggle.
Definition town_widget.h:74
@ WID_TF_LAYOUT_GRID2
Selection for the 2x2 grid town layout.
Definition town_widget.h:70
@ WID_TF_LAYOUT_ORIGINAL
Selection for the original town layout.
Definition town_widget.h:68
@ WID_TF_SIZE_RANDOM
Selection for a randomly sized town.
Definition town_widget.h:65
@ WID_TF_TOWN_NAME_EDITBOX
Editor for the town name.
Definition town_widget.h:59
@ WID_TF_TOWN_ACTION_SEL
Container of town action buttons.
Definition town_widget.h:54
@ WID_TF_SIZE_MEDIUM
Selection for a medium town.
Definition town_widget.h:63
@ WID_TF_TOWN_EXPAND_SEL
Container of town expansion buttons.
Definition town_widget.h:73
@ WID_TF_EXPAND_ROADS
Expand roads toggle.
Definition town_widget.h:75
@ WID_TF_CITY
Selection for the town's city state.
Definition town_widget.h:66
@ WID_TF_RANDOM_TOWN
Randomly place a town.
Definition town_widget.h:55
@ WID_TF_LAYOUT_BETTER
Selection for the better town layout.
Definition town_widget.h:69
@ WID_TF_ROAD_LAYOUT_SEL
Container of town road layout buttons.
Definition town_widget.h:67
@ WID_TF_LAYOUT_GRID3
Selection for the 3x3 grid town layout.
Definition town_widget.h:71
@ WID_TF_TOWN_NAME_RANDOM
Generate a random town name.
Definition town_widget.h:60
@ WID_TD_LIST
List of towns.
Definition town_widget.h:19
@ WID_TD_CAPTION
Caption of the window.
Definition town_widget.h:15
@ WID_TD_FILTER
Filter of name.
Definition town_widget.h:18
@ WID_TD_SORT_ORDER
Direction of sort dropdown.
Definition town_widget.h:16
@ WID_TD_WORLD_POPULATION
The world's population.
Definition town_widget.h:21
@ WID_TD_SCROLLBAR
Scrollbar for the town list.
Definition town_widget.h:20
@ WID_TD_SORT_CRITERIA
Criteria of sort dropdown.
Definition town_widget.h:17
@ WID_BH_REPLACE_TOGGLE
Button to toggle replacing existing houses.
Definition town_widget.h:82
@ WID_BH_PROTECT_TOGGLE
Button to toggle protecting the next house built.
Definition town_widget.h:81
@ WID_BH_INFO
Information panel of selected house.
Definition town_widget.h:80
bool GenerateTownName(Randomizer &randomizer, uint32_t *townnameparts, TownNames *town_names)
Generates valid town name.
Definition townname.cpp:134
Town name generator stuff.
bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
Scrolls the viewport in a window to a given location.
void SetTileSelectSize(int w, int h)
Highlight w by h tiles at the cursor.
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
void SetViewportCatchmentTown(const Town *t, bool sel)
Select or deselect town for coverage area highlight.
const Town * _viewport_highlight_town
Currently selected town for coverage area highlight.
Functions related to (drawing on) viewports.
ViewportPlaceMethod
Viewport place method (type of highlighted area and placed objects).
@ VPM_X_AND_Y
area of land in X and Y directions
@ ZOOM_IN
Zoom in (get more detailed view).
@ ZOOM_OUT
Zoom out (get helicopter view).
ViewportDragDropSelectionProcess
Drag and drop selection process, or, what to do with an area of land when you've selected it.
@ DDSP_PLACE_HOUSE
Place a house.
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ WWT_INSET
Pressed (inset) panel, most commonly used as combo box text area.
Definition widget_type.h:40
@ WWT_PUSHIMGBTN
Normal push-button (no toggle button) with image caption.
@ WWT_LABEL
Centered label.
Definition widget_type.h:48
@ WWT_EDITBOX
a textbox for typing
Definition widget_type.h:62
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_TEXTBTN
(Toggle) Button with text
Definition widget_type.h:44
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX).
Definition widget_type.h:57
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX).
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:37
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
@ NWID_VIEWPORT
Nested widget containing a viewport.
Definition widget_type.h:73
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:61
@ WWT_TEXT
Pure simple text.
Definition widget_type.h:49
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:71
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
@ SZSP_VERTICAL
Display plane with zero size horizontally, and filling and resizing vertically.
@ EqualSize
Containers should keep all their (resizing) children equally large.
void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen, bool schedule_resize)
Resize the window.
Definition window.cpp:2146
Window * BringWindowToFrontById(WindowClass cls, WindowNumber number)
Find a window and make it the relative top-window on the screen.
Definition window.cpp:1326
Window functions not directly related to making/drawing windows.
@ Construction
This window is used for construction; close it whenever changing company.
Definition window_gui.h:154
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ DisableVpScroll
Window does not do autoscroll,.
Definition window_gui.h:230
@ Automatic
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:21
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107
ZoomLevel ScaleZoomGUI(ZoomLevel value)
Scale zoom level relative to GUI zoom.
Definition zoom_func.h:87
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition zoom_func.h:77
@ Town
Default zoom level for the town view.
Definition zoom_type.h:37