Codefix: Documentation comment in IndustryDirectoryWindow (#13059)
[openttd-github.git] / src / vehicle_gui.cpp
blobef502123b9801c6a17db77343da3bb51171eac84
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file vehicle_gui.cpp The base GUI for all vehicles. */
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "company_func.h"
13 #include "gui.h"
14 #include "textbuf_gui.h"
15 #include "command_func.h"
16 #include "vehicle_gui_base.h"
17 #include "viewport_func.h"
18 #include "newgrf_text.h"
19 #include "newgrf_debug.h"
20 #include "roadveh.h"
21 #include "train.h"
22 #include "aircraft.h"
23 #include "depot_map.h"
24 #include "group_gui.h"
25 #include "strings_func.h"
26 #include "vehicle_func.h"
27 #include "autoreplace_gui.h"
28 #include "string_func.h"
29 #include "dropdown_type.h"
30 #include "dropdown_func.h"
31 #include "timetable.h"
32 #include "articulated_vehicles.h"
33 #include "spritecache.h"
34 #include "core/geometry_func.hpp"
35 #include "core/container_func.hpp"
36 #include "company_base.h"
37 #include "engine_func.h"
38 #include "station_base.h"
39 #include "tilehighlight_func.h"
40 #include "zoom_func.h"
41 #include "depot_cmd.h"
42 #include "vehicle_cmd.h"
43 #include "order_cmd.h"
44 #include "roadveh_cmd.h"
45 #include "train_cmd.h"
46 #include "hotkeys.h"
47 #include "group_cmd.h"
49 #include "safeguards.h"
52 BaseVehicleListWindow::GroupBy _grouping[VLT_END][VEH_COMPANY_END];
53 Sorting _sorting[BaseVehicleListWindow::GB_END];
55 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleNumberSorter;
56 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleNameSorter;
57 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleAgeSorter;
58 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleProfitThisYearSorter;
59 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleProfitLastYearSorter;
60 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleCargoSorter;
61 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleReliabilitySorter;
62 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleMaxSpeedSorter;
63 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleModelSorter;
64 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleValueSorter;
65 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleLengthSorter;
66 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleTimeToLiveSorter;
67 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleTimetableDelaySorter;
68 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupLengthSorter;
69 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupTotalProfitThisYearSorter;
70 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupTotalProfitLastYearSorter;
71 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupAverageProfitThisYearSorter;
72 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupAverageProfitLastYearSorter;
74 /** Wrapper to convert a VehicleIndividualSortFunction to a VehicleGroupSortFunction */
75 template <BaseVehicleListWindow::VehicleIndividualSortFunction func>
76 static bool VehicleIndividualToGroupSorterWrapper(GUIVehicleGroup const &a, GUIVehicleGroup const &b)
78 return func(*(a.vehicles_begin), *(b.vehicles_begin));
81 const std::initializer_list<BaseVehicleListWindow::VehicleGroupSortFunction * const> BaseVehicleListWindow::vehicle_group_none_sorter_funcs = {
82 &VehicleIndividualToGroupSorterWrapper<VehicleNumberSorter>,
83 &VehicleIndividualToGroupSorterWrapper<VehicleNameSorter>,
84 &VehicleIndividualToGroupSorterWrapper<VehicleAgeSorter>,
85 &VehicleIndividualToGroupSorterWrapper<VehicleProfitThisYearSorter>,
86 &VehicleIndividualToGroupSorterWrapper<VehicleProfitLastYearSorter>,
87 &VehicleIndividualToGroupSorterWrapper<VehicleCargoSorter>,
88 &VehicleIndividualToGroupSorterWrapper<VehicleReliabilitySorter>,
89 &VehicleIndividualToGroupSorterWrapper<VehicleMaxSpeedSorter>,
90 &VehicleIndividualToGroupSorterWrapper<VehicleModelSorter>,
91 &VehicleIndividualToGroupSorterWrapper<VehicleValueSorter>,
92 &VehicleIndividualToGroupSorterWrapper<VehicleLengthSorter>,
93 &VehicleIndividualToGroupSorterWrapper<VehicleTimeToLiveSorter>,
94 &VehicleIndividualToGroupSorterWrapper<VehicleTimetableDelaySorter>,
97 const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_none_sorter_names_calendar = {
98 STR_SORT_BY_NUMBER,
99 STR_SORT_BY_NAME,
100 STR_SORT_BY_AGE,
101 STR_SORT_BY_PROFIT_THIS_YEAR,
102 STR_SORT_BY_PROFIT_LAST_YEAR,
103 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
104 STR_SORT_BY_RELIABILITY,
105 STR_SORT_BY_MAX_SPEED,
106 STR_SORT_BY_MODEL,
107 STR_SORT_BY_VALUE,
108 STR_SORT_BY_LENGTH,
109 STR_SORT_BY_LIFE_TIME,
110 STR_SORT_BY_TIMETABLE_DELAY,
113 const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_none_sorter_names_wallclock = {
114 STR_SORT_BY_NUMBER,
115 STR_SORT_BY_NAME,
116 STR_SORT_BY_AGE,
117 STR_SORT_BY_PROFIT_THIS_PERIOD,
118 STR_SORT_BY_PROFIT_LAST_PERIOD,
119 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
120 STR_SORT_BY_RELIABILITY,
121 STR_SORT_BY_MAX_SPEED,
122 STR_SORT_BY_MODEL,
123 STR_SORT_BY_VALUE,
124 STR_SORT_BY_LENGTH,
125 STR_SORT_BY_LIFE_TIME,
126 STR_SORT_BY_TIMETABLE_DELAY,
129 const std::initializer_list<BaseVehicleListWindow::VehicleGroupSortFunction * const> BaseVehicleListWindow::vehicle_group_shared_orders_sorter_funcs = {
130 &VehicleGroupLengthSorter,
131 &VehicleGroupTotalProfitThisYearSorter,
132 &VehicleGroupTotalProfitLastYearSorter,
133 &VehicleGroupAverageProfitThisYearSorter,
134 &VehicleGroupAverageProfitLastYearSorter,
137 const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_shared_orders_sorter_names_calendar = {
138 STR_SORT_BY_NUM_VEHICLES,
139 STR_SORT_BY_TOTAL_PROFIT_THIS_YEAR,
140 STR_SORT_BY_TOTAL_PROFIT_LAST_YEAR,
141 STR_SORT_BY_AVERAGE_PROFIT_THIS_YEAR,
142 STR_SORT_BY_AVERAGE_PROFIT_LAST_YEAR,
145 const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_shared_orders_sorter_names_wallclock = {
146 STR_SORT_BY_NUM_VEHICLES,
147 STR_SORT_BY_TOTAL_PROFIT_THIS_PERIOD,
148 STR_SORT_BY_TOTAL_PROFIT_LAST_PERIOD,
149 STR_SORT_BY_AVERAGE_PROFIT_THIS_PERIOD,
150 STR_SORT_BY_AVERAGE_PROFIT_LAST_PERIOD,
153 const std::initializer_list<const StringID> BaseVehicleListWindow::vehicle_group_by_names = {
154 STR_GROUP_BY_NONE,
155 STR_GROUP_BY_SHARED_ORDERS,
158 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
159 STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
160 STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
161 STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
162 STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
165 BaseVehicleListWindow::BaseVehicleListWindow(WindowDesc &desc, WindowNumber wno) : Window(desc), vli(VehicleListIdentifier::UnPack(wno))
167 this->vehicle_sel = INVALID_VEHICLE;
168 this->grouping = _grouping[vli.type][vli.vtype];
169 this->UpdateSortingFromGrouping();
172 std::span<const StringID> BaseVehicleListWindow::GetVehicleSorterNames()
174 switch (this->grouping) {
175 case GB_NONE:
176 return TimerGameEconomy::UsingWallclockUnits() ? vehicle_group_none_sorter_names_wallclock : vehicle_group_none_sorter_names_calendar;
177 case GB_SHARED_ORDERS:
178 return TimerGameEconomy::UsingWallclockUnits() ? vehicle_group_shared_orders_sorter_names_wallclock : vehicle_group_shared_orders_sorter_names_calendar;
179 default:
180 NOT_REACHED();
185 * Get the number of digits of space required for the given number.
186 * @param number The number.
187 * @return The number of digits to allocate space for.
189 uint CountDigitsForAllocatingSpace(uint number)
191 if (number >= 10000) return 5;
192 if (number >= 1000) return 4;
193 if (number >= 100) return 3;
196 * When the smallest unit number is less than 10, it is
197 * quite likely that it will expand to become more than
198 * 10 quite soon.
200 return 2;
204 * Get the number of digits the biggest unit number of a set of vehicles has.
205 * @param vehicles The list of vehicles.
206 * @return The number of digits to allocate space for.
208 uint GetUnitNumberDigits(VehicleList &vehicles)
210 uint unitnumber = 0;
211 for (const Vehicle *v : vehicles) {
212 unitnumber = std::max<uint>(unitnumber, v->unitnumber);
215 return CountDigitsForAllocatingSpace(unitnumber);
218 void BaseVehicleListWindow::BuildVehicleList()
220 if (!this->vehgroups.NeedRebuild()) return;
222 Debug(misc, 3, "Building vehicle list type {} for company {} given index {}", this->vli.type, this->vli.company, this->vli.index);
224 this->vehgroups.clear();
226 GenerateVehicleSortList(&this->vehicles, this->vli);
228 CargoTypes used = 0;
229 for (const Vehicle *v : this->vehicles) {
230 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
231 if (u->cargo_cap > 0) SetBit(used, u->cargo_type);
234 this->used_cargoes = used;
236 if (this->grouping == GB_NONE) {
237 uint max_unitnumber = 0;
238 for (auto it = this->vehicles.begin(); it != this->vehicles.end(); ++it) {
239 this->vehgroups.emplace_back(it, it + 1);
241 max_unitnumber = std::max<uint>(max_unitnumber, (*it)->unitnumber);
243 this->unitnumber_digits = CountDigitsForAllocatingSpace(max_unitnumber);
244 } else {
245 /* Sort by the primary vehicle; we just want all vehicles that share the same orders to form a contiguous range. */
246 std::stable_sort(this->vehicles.begin(), this->vehicles.end(), [](const Vehicle * const &u, const Vehicle * const &v) {
247 return u->FirstShared() < v->FirstShared();
250 uint max_num_vehicles = 0;
252 VehicleList::const_iterator begin = this->vehicles.begin();
253 while (begin != this->vehicles.end()) {
254 VehicleList::const_iterator end = std::find_if_not(begin, this->vehicles.cend(), [first_shared = (*begin)->FirstShared()](const Vehicle * const &v) {
255 return v->FirstShared() == first_shared;
258 this->vehgroups.emplace_back(begin, end);
260 max_num_vehicles = std::max<uint>(max_num_vehicles, static_cast<uint>(end - begin));
262 begin = end;
265 this->unitnumber_digits = CountDigitsForAllocatingSpace(max_num_vehicles);
267 this->FilterVehicleList();
269 this->vehgroups.RebuildDone();
270 this->vscroll->SetCount(this->vehgroups.size());
274 * Check whether a single vehicle should pass the filter.
276 * @param v The vehicle to check.
277 * @param cid The cargo to filter for.
278 * @return true iff the vehicle carries the cargo.
280 static bool CargoFilterSingle(const Vehicle *v, const CargoID cid)
282 if (cid == CargoFilterCriteria::CF_ANY) {
283 return true;
284 } else if (cid == CargoFilterCriteria::CF_NONE) {
285 for (const Vehicle *w = v; w != nullptr; w = w->Next()) {
286 if (w->cargo_cap > 0) {
287 return false;
290 return true;
291 } else if (cid == CargoFilterCriteria::CF_FREIGHT) {
292 bool have_capacity = false;
293 for (const Vehicle *w = v; w != nullptr; w = w->Next()) {
294 if (w->cargo_cap > 0) {
295 if (IsCargoInClass(w->cargo_type, CC_PASSENGERS)) {
296 return false;
297 } else {
298 have_capacity = true;
302 return have_capacity;
303 } else {
304 for (const Vehicle *w = v; w != nullptr; w = w->Next()) {
305 if (w->cargo_cap > 0 && w->cargo_type == cid) {
306 return true;
309 return false;
314 * Check whether a vehicle can carry a specific cargo.
316 * @param vehgroup The vehicle group which contains the vehicle to be checked
317 * @param cid The cargo what we are looking for
318 * @return Whether the vehicle can carry the specified cargo or not
320 static bool CargoFilter(const GUIVehicleGroup *vehgroup, const CargoID cid)
322 auto it = vehgroup->vehicles_begin;
324 /* Check if any vehicle in the group matches; if so, the whole group does. */
325 for (; it != vehgroup->vehicles_end; it++) {
326 if (CargoFilterSingle(*it, cid)) return true;
329 return false;
333 * Test if cargo icon overlays should be drawn.
334 * @returns true iff cargo icon overlays should be drawn.
336 bool ShowCargoIconOverlay()
338 return _shift_pressed && _ctrl_pressed;
342 * Add a cargo icon to the list of overlays.
343 * @param overlays List of overlays.
344 * @param x Horizontal position.
345 * @param width Width available.
346 * @param v Vehicle to add.
348 void AddCargoIconOverlay(std::vector<CargoIconOverlay> &overlays, int x, int width, const Vehicle *v)
350 bool rtl = _current_text_dir == TD_RTL;
351 if (!v->IsArticulatedPart() || v->cargo_type != v->Previous()->cargo_type) {
352 /* Add new overlay slot. */
353 overlays.emplace_back(rtl ? x - width : x, rtl ? x : x + width, v->cargo_type, v->cargo_cap);
354 } else {
355 /* This is an articulated part with the same cargo type, adjust left or right of last overlay slot. */
356 if (rtl) {
357 overlays.back().left -= width;
358 } else {
359 overlays.back().right += width;
361 overlays.back().cargo_cap += v->cargo_cap;
366 * Draw a cargo icon overlaying an existing sprite, with a black contrast outline.
367 * @param x Horizontal position from left.
368 * @param y Vertical position from top.
369 * @param cid Cargo ID to draw icon for.
371 void DrawCargoIconOverlay(int x, int y, CargoID cid)
373 if (!ShowCargoIconOverlay()) return;
374 if (!IsValidCargoID(cid)) return;
376 const CargoSpec *cs = CargoSpec::Get(cid);
378 SpriteID spr = cs->GetCargoIcon();
379 if (spr == 0) return;
381 Dimension d = GetSpriteSize(spr);
382 d.width /= 2;
383 d.height /= 2;
384 int one = ScaleGUITrad(1);
386 /* Draw the cargo icon in black shifted 4 times to create the outline. */
387 DrawSprite(spr, PALETTE_ALL_BLACK, x - d.width - one, y - d.height);
388 DrawSprite(spr, PALETTE_ALL_BLACK, x - d.width + one, y - d.height);
389 DrawSprite(spr, PALETTE_ALL_BLACK, x - d.width, y - d.height - one);
390 DrawSprite(spr, PALETTE_ALL_BLACK, x - d.width, y - d.height + one);
391 /* Draw the cargo icon normally. */
392 DrawSprite(spr, PAL_NONE, x - d.width, y - d.height);
396 * Draw a list of cargo icon overlays.
397 * @param overlays List of overlays.
398 * @param y Vertical position.
400 void DrawCargoIconOverlays(std::span<const CargoIconOverlay> overlays, int y)
402 for (const auto &cio : overlays) {
403 if (cio.cargo_cap == 0) continue;
404 DrawCargoIconOverlay((cio.left + cio.right) / 2, y, cio.cargo_type);
408 static GUIVehicleGroupList::FilterFunction * const _vehicle_group_filter_funcs[] = {
409 &CargoFilter,
413 * Set cargo filter for the vehicle group list.
414 * @param cid The cargo to be set.
416 void BaseVehicleListWindow::SetCargoFilter(CargoID cid)
418 if (this->cargo_filter_criteria != cid) {
419 this->cargo_filter_criteria = cid;
420 /* Deactivate filter if criteria is 'Show All', activate it otherwise. */
421 this->vehgroups.SetFilterState(this->cargo_filter_criteria != CargoFilterCriteria::CF_ANY);
422 this->vehgroups.SetFilterType(0);
423 this->vehgroups.ForceRebuild();
428 *Populate the filter list and set the cargo filter criteria.
430 void BaseVehicleListWindow::SetCargoFilterArray()
432 this->cargo_filter_criteria = CargoFilterCriteria::CF_ANY;
433 this->vehgroups.SetFilterFuncs(_vehicle_group_filter_funcs);
434 this->vehgroups.SetFilterState(this->cargo_filter_criteria != CargoFilterCriteria::CF_ANY);
438 *Filter the engine list against the currently selected cargo filter.
440 void BaseVehicleListWindow::FilterVehicleList()
442 this->vehgroups.Filter(this->cargo_filter_criteria);
443 if (this->vehicles.empty()) {
444 /* No vehicle passed through the filter, invalidate the previously selected vehicle */
445 this->vehicle_sel = INVALID_VEHICLE;
446 } else if (this->vehicle_sel != INVALID_VEHICLE && std::find(this->vehicles.begin(), this->vehicles.end(), Vehicle::Get(this->vehicle_sel)) == this->vehicles.end()) { // previously selected engine didn't pass the filter, remove selection
447 this->vehicle_sel = INVALID_VEHICLE;
452 * Compute the size for the Action dropdown.
453 * @param show_autoreplace If true include the autoreplace item.
454 * @param show_group If true include group-related stuff.
455 * @param show_create If true include group-create item.
456 * @return Required size.
458 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group, bool show_create)
460 Dimension d = {0, 0};
462 if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
463 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
464 d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
466 if (show_group) {
467 d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
468 d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
469 } else if (show_create) {
470 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_CREATE_GROUP));
473 return d;
476 void BaseVehicleListWindow::OnInit()
478 this->order_arrow_width = GetStringBoundingBox(STR_JUST_RIGHT_ARROW, FS_SMALL).width;
479 this->SetCargoFilterArray();
482 StringID BaseVehicleListWindow::GetCargoFilterLabel(CargoID cid) const
484 switch (cid) {
485 case CargoFilterCriteria::CF_ANY: return STR_CARGO_TYPE_FILTER_ALL;
486 case CargoFilterCriteria::CF_FREIGHT: return STR_CARGO_TYPE_FILTER_FREIGHT;
487 case CargoFilterCriteria::CF_NONE: return STR_CARGO_TYPE_FILTER_NONE;
488 default: return CargoSpec::Get(cid)->name;
493 * Build drop down list for cargo filter selection.
494 * @param full If true, build list with all cargo types, instead of only used cargo types.
495 * @return Drop down list for cargo filter.
497 DropDownList BaseVehicleListWindow::BuildCargoDropDownList(bool full) const
499 DropDownList list;
501 /* Add item for disabling filtering. */
502 list.push_back(MakeDropDownListStringItem(this->GetCargoFilterLabel(CargoFilterCriteria::CF_ANY), CargoFilterCriteria::CF_ANY));
503 /* Add item for freight (i.e. vehicles with cargo capacity and with no passenger capacity). */
504 list.push_back(MakeDropDownListStringItem(this->GetCargoFilterLabel(CargoFilterCriteria::CF_FREIGHT), CargoFilterCriteria::CF_FREIGHT));
505 /* Add item for vehicles not carrying anything, e.g. train engines. */
506 list.push_back(MakeDropDownListStringItem(this->GetCargoFilterLabel(CargoFilterCriteria::CF_NONE), CargoFilterCriteria::CF_NONE));
508 /* Add cargos */
509 Dimension d = GetLargestCargoIconSize();
510 for (const CargoSpec *cs : _sorted_cargo_specs) {
511 if (!full && !HasBit(this->used_cargoes, cs->Index())) continue;
512 list.push_back(MakeDropDownListIconItem(d, cs->GetCargoIcon(), PAL_NONE, cs->name, cs->Index(), false, !HasBit(this->used_cargoes, cs->Index())));
515 return list;
519 * Display the Action dropdown window.
520 * @param show_autoreplace If true include the autoreplace item.
521 * @param show_group If true include group-related stuff.
522 * @param show_create If true include group-create item.
523 * @return Itemlist for dropdown
525 DropDownList BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group, bool show_create)
527 DropDownList list;
529 /* Autoreplace actions. */
530 if (show_autoreplace) {
531 list.push_back(MakeDropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE));
532 list.push_back(MakeDropDownListDividerItem());
535 /* Group actions. */
536 if (show_group) {
537 list.push_back(MakeDropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED));
538 list.push_back(MakeDropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL));
539 list.push_back(MakeDropDownListDividerItem());
540 } else if (show_create) {
541 list.push_back(MakeDropDownListStringItem(STR_VEHICLE_LIST_CREATE_GROUP, ADI_CREATE_GROUP));
542 list.push_back(MakeDropDownListDividerItem());
545 /* Depot actions. */
546 list.push_back(MakeDropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE));
547 list.push_back(MakeDropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT));
549 return list;
552 /* cached values for VehicleNameSorter to spare many GetString() calls */
553 static const Vehicle *_last_vehicle[2] = { nullptr, nullptr };
555 void BaseVehicleListWindow::SortVehicleList()
557 if (this->vehgroups.Sort()) return;
559 /* invalidate cached values for name sorter - vehicle names could change */
560 _last_vehicle[0] = _last_vehicle[1] = nullptr;
563 void DepotSortList(VehicleList *list)
565 if (list->size() < 2) return;
566 std::sort(list->begin(), list->end(), &VehicleNumberSorter);
569 /** draw the vehicle profit button in the vehicle list window. */
570 static void DrawVehicleProfitButton(TimerGameEconomy::Date age, Money display_profit_last_year, uint num_vehicles, int x, int y)
572 SpriteID spr;
574 /* draw profit-based coloured icons */
575 if (age <= VEHICLE_PROFIT_MIN_AGE) {
576 spr = SPR_PROFIT_NA;
577 } else if (display_profit_last_year < 0) {
578 spr = SPR_PROFIT_NEGATIVE;
579 } else if (display_profit_last_year < VEHICLE_PROFIT_THRESHOLD * num_vehicles) {
580 spr = SPR_PROFIT_SOME;
581 } else {
582 spr = SPR_PROFIT_LOT;
584 DrawSprite(spr, PAL_NONE, x, y);
587 /** Maximum number of refit cycles we try, to prevent infinite loops. And we store only a byte anyway */
588 static const uint MAX_REFIT_CYCLE = 256;
591 * Get the best fitting subtype when 'cloning'/'replacing' \a v_from with \a v_for.
592 * All articulated parts of both vehicles are tested to find a possibly shared subtype.
593 * For \a v_for only vehicle refittable to \a dest_cargo_type are considered.
594 * @param v_from the vehicle to match the subtype from
595 * @param v_for the vehicle to get the subtype for
596 * @param dest_cargo_type Destination cargo type.
597 * @return the best sub type
599 uint8_t GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
601 v_from = v_from->GetFirstEnginePart();
602 v_for = v_for->GetFirstEnginePart();
604 /* Create a list of subtypes used by the various parts of v_for */
605 static std::vector<StringID> subtypes;
606 subtypes.clear();
607 for (; v_from != nullptr; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : nullptr) {
608 const Engine *e_from = v_from->GetEngine();
609 if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
610 include(subtypes, GetCargoSubtypeText(v_from));
613 uint8_t ret_refit_cyc = 0;
614 bool success = false;
615 if (!subtypes.empty()) {
616 /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
617 for (Vehicle *v = v_for; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
618 const Engine *e = v->GetEngine();
619 if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
620 if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
622 CargoID old_cargo_type = v->cargo_type;
623 uint8_t old_cargo_subtype = v->cargo_subtype;
625 /* Set the 'destination' cargo */
626 v->cargo_type = dest_cargo_type;
628 /* Cycle through the refits */
629 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
630 v->cargo_subtype = refit_cyc;
632 /* Make sure we don't pick up anything cached. */
633 v->First()->InvalidateNewGRFCache();
634 v->InvalidateNewGRFCache();
636 StringID subtype = GetCargoSubtypeText(v);
637 if (subtype == STR_EMPTY) break;
639 if (std::find(subtypes.begin(), subtypes.end(), subtype) == subtypes.end()) continue;
641 /* We found something matching. */
642 ret_refit_cyc = refit_cyc;
643 success = true;
644 break;
647 /* Reset the vehicle's cargo type */
648 v->cargo_type = old_cargo_type;
649 v->cargo_subtype = old_cargo_subtype;
651 /* Make sure we don't taint the vehicle. */
652 v->First()->InvalidateNewGRFCache();
653 v->InvalidateNewGRFCache();
655 if (success) break;
659 return ret_refit_cyc;
662 /** Option to refit a vehicle chain */
663 struct RefitOption {
664 CargoID cargo; ///< Cargo to refit to
665 uint8_t subtype; ///< Subcargo to use
666 StringID string; ///< GRF-local String to display for the cargo
669 * Inequality operator for #RefitOption.
670 * @param other Compare to this #RefitOption.
671 * @return True if both #RefitOption are different.
673 inline bool operator != (const RefitOption &other) const
675 return other.cargo != this->cargo || other.string != this->string;
679 * Equality operator for #RefitOption.
680 * @param other Compare to this #RefitOption.
681 * @return True if both #RefitOption are equal.
683 inline bool operator == (const RefitOption &other) const
685 return other.cargo == this->cargo && other.string == this->string;
689 using RefitOptions = std::map<CargoID, std::vector<RefitOption>, CargoIDComparator>; ///< Available refit options (subtype and string) associated with each cargo type.
692 * Draw the list of available refit options for a consist and highlight the selected refit option (if any).
693 * @param refits Available refit options for each (sorted) cargo.
694 * @param sel Selected refit option in the window
695 * @param pos Position of the selected item in caller widow
696 * @param rows Number of rows(capacity) in caller window
697 * @param delta Step height in caller window
698 * @param r Rectangle of the matrix widget.
700 static void DrawVehicleRefitWindow(const RefitOptions &refits, const RefitOption *sel, uint pos, uint rows, uint delta, const Rect &r)
702 Rect ir = r.Shrink(WidgetDimensions::scaled.matrix);
703 uint current = 0;
705 bool rtl = _current_text_dir == TD_RTL;
706 uint iconwidth = std::max(GetSpriteSize(SPR_CIRCLE_FOLDED).width, GetSpriteSize(SPR_CIRCLE_UNFOLDED).width);
707 uint iconheight = GetSpriteSize(SPR_CIRCLE_FOLDED).height;
708 int linecolour = GetColourGradient(COLOUR_ORANGE, SHADE_NORMAL);
710 int iconleft = rtl ? ir.right - iconwidth : ir.left;
711 int iconcenter = rtl ? ir.right - iconwidth / 2 : ir.left + iconwidth / 2;
712 int iconinner = rtl ? ir.right - iconwidth : ir.left + iconwidth;
714 Rect tr = ir.Indent(iconwidth + WidgetDimensions::scaled.hsep_wide, rtl);
716 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
717 for (const auto &pair : refits) {
718 bool has_subtypes = pair.second.size() > 1;
719 for (const RefitOption &refit : pair.second) {
720 if (current >= pos + rows) break;
722 /* Hide subtypes if selected cargo type does not match */
723 if ((sel == nullptr || sel->cargo != refit.cargo) && refit.subtype != UINT8_MAX) continue;
725 /* Refit options with a position smaller than pos don't have to be drawn. */
726 if (current < pos) {
727 current++;
728 continue;
731 if (has_subtypes) {
732 if (refit.subtype != UINT8_MAX) {
733 /* Draw tree lines */
734 int ycenter = tr.top + GetCharacterHeight(FS_NORMAL) / 2;
735 GfxDrawLine(iconcenter, tr.top - WidgetDimensions::scaled.matrix.top, iconcenter, (&refit == &pair.second.back()) ? ycenter : tr.top - WidgetDimensions::scaled.matrix.top + delta - 1, linecolour);
736 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
737 } else {
738 /* Draw expand/collapse icon */
739 DrawSprite((sel != nullptr && sel->cargo == refit.cargo) ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, tr.top + (GetCharacterHeight(FS_NORMAL) - iconheight) / 2);
743 TextColour colour = (sel != nullptr && sel->cargo == refit.cargo && sel->subtype == refit.subtype) ? TC_WHITE : TC_BLACK;
744 /* Get the cargo name. */
745 SetDParam(0, CargoSpec::Get(refit.cargo)->name);
746 SetDParam(1, refit.string);
747 DrawString(tr, STR_JUST_STRING_STRING, colour);
749 tr.top += delta;
750 current++;
755 /** Refit cargo window. */
756 struct RefitWindow : public Window {
757 const RefitOption *selected_refit; ///< Selected refit option.
758 RefitOptions refit_list; ///< List of refit subtypes available for each sorted cargo.
759 VehicleOrderID order; ///< If not #INVALID_VEH_ORDER_ID, selection is part of a refit order (rather than execute directly).
760 uint information_width; ///< Width required for correctly displaying all cargoes in the information panel.
761 Scrollbar *vscroll; ///< The main scrollbar.
762 Scrollbar *hscroll; ///< Only used for long vehicles.
763 int vehicle_width; ///< Width of the vehicle being drawn.
764 int sprite_left; ///< Left position of the vehicle sprite.
765 int sprite_right; ///< Right position of the vehicle sprite.
766 uint vehicle_margin; ///< Margin to use while selecting vehicles when the vehicle image is centered.
767 int click_x; ///< Position of the first click while dragging.
768 VehicleID selected_vehicle; ///< First vehicle in the current selection.
769 uint8_t num_vehicles; ///< Number of selected vehicles.
770 bool auto_refit; ///< Select cargo for auto-refitting.
773 * Collects all (cargo, subcargo) refit options of a vehicle chain.
775 void BuildRefitList()
777 /* Store the currently selected RefitOption. */
778 std::optional<RefitOption> current_refit_option;
779 if (this->selected_refit != nullptr) current_refit_option = *(this->selected_refit);
780 this->selected_refit = nullptr;
782 this->refit_list.clear();
783 Vehicle *v = Vehicle::Get(this->window_number);
785 /* Check only the selected vehicles. */
786 VehicleSet vehicles_to_refit;
787 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
789 do {
790 if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end()) continue;
791 const Engine *e = v->GetEngine();
792 CargoTypes cmask = e->info.refit_mask;
793 uint8_t callback_mask = e->info.callback_mask;
795 /* Skip this engine if it does not carry anything */
796 if (!e->CanCarryCargo()) continue;
797 /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
798 if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
800 /* Loop through all cargoes in the refit mask */
801 for (const auto &cs : _sorted_cargo_specs) {
802 CargoID cid = cs->Index();
803 /* Skip cargo type if it's not listed */
804 if (!HasBit(cmask, cid)) continue;
806 auto &list = this->refit_list[cid];
807 bool first_vehicle = list.empty();
808 if (first_vehicle) {
809 /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
810 list.push_back({cid, UINT8_MAX, STR_EMPTY});
813 /* Check the vehicle's callback mask for cargo suffixes.
814 * This is not supported for ordered refits, since subtypes only have a meaning
815 * for a specific vehicle at a specific point in time, which conflicts with shared orders,
816 * autoreplace, autorenew, clone, order restoration, ... */
817 if (this->order == INVALID_VEH_ORDER_ID && HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
818 /* Make a note of the original cargo type. It has to be
819 * changed to test the cargo & subtype... */
820 CargoID temp_cargo = v->cargo_type;
821 uint8_t temp_subtype = v->cargo_subtype;
823 v->cargo_type = cid;
825 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
826 v->cargo_subtype = refit_cyc;
828 /* Make sure we don't pick up anything cached. */
829 v->First()->InvalidateNewGRFCache();
830 v->InvalidateNewGRFCache();
832 StringID subtype = GetCargoSubtypeText(v);
834 if (first_vehicle) {
835 /* Append new subtype (don't add duplicates though) */
836 if (subtype == STR_EMPTY) break;
838 RefitOption option;
839 option.cargo = cid;
840 option.subtype = refit_cyc;
841 option.string = subtype;
842 include(list, option);
843 } else {
844 /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
845 if (subtype == STR_EMPTY) {
846 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
847 /* UINT8_MAX item is in front, other subtypes are sorted. So just truncate the list in the right spot */
848 for (uint i = 1; i < list.size(); i++) {
849 if (list[i].subtype >= refit_cyc) {
850 list.resize(i);
851 break;
854 break;
855 } else {
856 /* Check whether the subtype matches with the subtype of earlier vehicles. */
857 uint pos = 1;
858 while (pos < list.size() && list[pos].subtype != refit_cyc) pos++;
859 if (pos < list.size() && list[pos].string != subtype) {
860 /* String mismatch, remove item keeping the order */
861 list.erase(list.begin() + pos);
867 /* Reset the vehicle's cargo type */
868 v->cargo_type = temp_cargo;
869 v->cargo_subtype = temp_subtype;
871 /* And make sure we haven't tainted the cache */
872 v->First()->InvalidateNewGRFCache();
873 v->InvalidateNewGRFCache();
876 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
878 /* Restore the previously selected RefitOption. */
879 if (current_refit_option.has_value()) {
880 for (const auto &pair : this->refit_list) {
881 for (const auto &refit : pair.second) {
882 if (refit.cargo == current_refit_option->cargo && refit.subtype == current_refit_option->subtype) {
883 this->selected_refit = &refit;
884 break;
887 if (this->selected_refit != nullptr) break;
891 this->SetWidgetDisabledState(WID_VR_REFIT, this->selected_refit == nullptr);
895 * Refresh scrollbar after selection changed
897 void RefreshScrollbar()
899 size_t scroll_row = 0;
900 size_t rows = 0;
901 CargoID cargo = this->selected_refit == nullptr ? INVALID_CARGO : this->selected_refit->cargo;
903 for (const auto &pair : this->refit_list) {
904 if (pair.first == cargo) {
905 /* selected_refit points to an element in the vector so no need to search for it. */
906 scroll_row = rows + (this->selected_refit - pair.second.data());
907 rows += pair.second.size();
908 } else {
909 rows++; /* Unselected cargo type is collapsed into one row. */
913 this->vscroll->SetCount(rows);
914 this->vscroll->ScrollTowards(static_cast<int>(scroll_row));
918 * Select a row.
919 * @param click_row Clicked row
921 void SetSelection(uint click_row)
923 uint row = 0;
925 for (const auto &pair : refit_list) {
926 for (const RefitOption &refit : pair.second) {
927 if (row == click_row) {
928 this->selected_refit = &refit;
929 return;
931 row++;
932 /* If this cargo type is not already selected then its subtypes are not visible, so skip the rest. */
933 if (this->selected_refit == nullptr || this->selected_refit->cargo != refit.cargo) break;
937 /* No selection made */
938 this->selected_refit = nullptr;
941 RefitWindow(WindowDesc &desc, const Vehicle *v, VehicleOrderID order, bool auto_refit) : Window(desc)
943 this->auto_refit = auto_refit;
944 this->order = order;
945 this->CreateNestedTree();
947 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
948 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : nullptr);
949 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
950 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
951 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
952 nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
953 nwi->tool_tip = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
954 this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
955 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
957 this->FinishInitNested(v->index);
958 this->owner = v->owner;
960 this->SetWidgetDisabledState(WID_VR_REFIT, this->selected_refit == nullptr);
963 void OnInit() override
965 /* (Re)build the refit list */
966 this->OnInvalidateData(VIWD_CONSIST_CHANGED);
969 void OnPaint() override
971 /* Determine amount of items for scroller. */
972 if (this->hscroll != nullptr) this->hscroll->SetCount(this->vehicle_width);
974 /* Calculate sprite position. */
975 NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
976 int sprite_width = std::max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
977 this->sprite_left = vehicle_panel_display->pos_x;
978 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
979 if (_current_text_dir == TD_RTL) {
980 this->sprite_right -= sprite_width;
981 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
982 } else {
983 this->sprite_left += sprite_width;
984 this->vehicle_margin = sprite_left;
987 this->DrawWidgets();
990 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
992 switch (widget) {
993 case WID_VR_MATRIX:
994 resize.height = GetCharacterHeight(FS_NORMAL) + padding.height;
995 size.height = resize.height * 8;
996 break;
998 case WID_VR_VEHICLE_PANEL_DISPLAY:
999 size.height = ScaleGUITrad(GetVehicleHeight(Vehicle::Get(this->window_number)->type));
1000 break;
1002 case WID_VR_INFO:
1003 size.width = this->information_width + padding.height;
1004 break;
1008 void SetStringParameters(WidgetID widget) const override
1010 if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
1014 * Gets the #StringID to use for displaying capacity.
1015 * @param option Cargo and cargo subtype to check for capacity.
1016 * @return INVALID_STRING_ID if there is no capacity. StringID to use in any other case.
1017 * @post String parameters have been set.
1019 StringID GetCapacityString(const RefitOption &option) const
1021 assert(_current_company == _local_company);
1022 auto [cost, refit_capacity, mail_capacity, cargo_capacities] = Command<CMD_REFIT_VEHICLE>::Do(DC_QUERY_COST, this->selected_vehicle, option.cargo, option.subtype, this->auto_refit, false, this->num_vehicles);
1024 if (cost.Failed()) return INVALID_STRING_ID;
1026 SetDParam(0, option.cargo);
1027 SetDParam(1, refit_capacity);
1029 Money money = cost.GetCost();
1030 if (mail_capacity > 0) {
1031 SetDParam(2, GetCargoIDByLabel(CT_MAIL));
1032 SetDParam(3, mail_capacity);
1033 if (this->order != INVALID_VEH_ORDER_ID) {
1034 /* No predictable cost */
1035 return STR_PURCHASE_INFO_AIRCRAFT_CAPACITY;
1036 } else if (money <= 0) {
1037 SetDParam(4, -money);
1038 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
1039 } else {
1040 SetDParam(4, money);
1041 return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
1043 } else {
1044 if (this->order != INVALID_VEH_ORDER_ID) {
1045 /* No predictable cost */
1046 SetDParam(2, STR_EMPTY);
1047 return STR_PURCHASE_INFO_CAPACITY;
1048 } else if (money <= 0) {
1049 SetDParam(2, -money);
1050 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
1051 } else {
1052 SetDParam(2, money);
1053 return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
1058 void DrawWidget(const Rect &r, WidgetID widget) const override
1060 switch (widget) {
1061 case WID_VR_VEHICLE_PANEL_DISPLAY: {
1062 Vehicle *v = Vehicle::Get(this->window_number);
1063 DrawVehicleImage(v, {this->sprite_left, r.top, this->sprite_right, r.bottom},
1064 INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != nullptr ? this->hscroll->GetPosition() : 0);
1066 /* Highlight selected vehicles. */
1067 if (this->order != INVALID_VEH_ORDER_ID) break;
1068 int x = 0;
1069 switch (v->type) {
1070 case VEH_TRAIN: {
1071 VehicleSet vehicles_to_refit;
1072 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
1074 int left = INT32_MIN;
1075 int width = 0;
1077 /* Determine top & bottom position of the highlight.*/
1078 const int height = ScaleSpriteTrad(12);
1079 const int highlight_top = CenterBounds(r.top, r.bottom, height);
1080 const int highlight_bottom = highlight_top + height - 1;
1082 for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
1083 /* Start checking. */
1084 const bool contained = std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), u->index) != vehicles_to_refit.end();
1085 if (contained && left == INT32_MIN) {
1086 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
1087 width = 0;
1090 /* Draw a selection. */
1091 if ((!contained || u->Next() == nullptr) && left != INT32_MIN) {
1092 if (u->Next() == nullptr && contained) {
1093 int current_width = u->GetDisplayImageWidth();
1094 width += current_width;
1095 x += current_width;
1098 int right = Clamp(left + width, 0, r.right);
1099 left = std::max(0, left);
1101 if (_current_text_dir == TD_RTL) {
1102 right = r.Width() - left;
1103 left = right - width;
1106 if (left != right) {
1107 Rect hr = {left, highlight_top, right, highlight_bottom};
1108 DrawFrameRect(hr.Expand(WidgetDimensions::scaled.bevel), COLOUR_WHITE, FR_BORDERONLY);
1111 left = INT32_MIN;
1114 int current_width = u->GetDisplayImageWidth();
1115 width += current_width;
1116 x += current_width;
1118 break;
1121 default: break;
1123 break;
1126 case WID_VR_MATRIX:
1127 DrawVehicleRefitWindow(this->refit_list, this->selected_refit, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
1128 break;
1130 case WID_VR_INFO:
1131 if (this->selected_refit != nullptr) {
1132 StringID string = this->GetCapacityString(*this->selected_refit);
1133 if (string != INVALID_STRING_ID) {
1134 DrawStringMultiLine(r.Shrink(WidgetDimensions::scaled.framerect), string);
1137 break;
1142 * Some data on this window has become invalid.
1143 * @param data Information about the changed data.
1144 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1146 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1148 switch (data) {
1149 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
1150 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
1151 /* Clear the selection. */
1152 Vehicle *v = Vehicle::Get(this->window_number);
1153 this->selected_vehicle = v->index;
1154 this->num_vehicles = UINT8_MAX;
1155 [[fallthrough]];
1158 case 2: { // The vehicle selection has changed; rebuild the entire list.
1159 if (!gui_scope) break;
1160 this->BuildRefitList();
1162 /* The vehicle width has changed too. */
1163 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
1164 uint max_width = 0;
1166 /* Check the width of all cargo information strings. */
1167 for (const auto &list : this->refit_list) {
1168 for (const RefitOption &refit : list.second) {
1169 StringID string = this->GetCapacityString(refit);
1170 if (string != INVALID_STRING_ID) {
1171 Dimension dim = GetStringBoundingBox(string);
1172 max_width = std::max(dim.width, max_width);
1177 if (this->information_width < max_width) {
1178 this->information_width = max_width;
1179 this->ReInit();
1181 [[fallthrough]];
1184 case 1: // A new cargo has been selected.
1185 if (!gui_scope) break;
1186 this->RefreshScrollbar();
1187 break;
1191 int GetClickPosition(int click_x)
1193 const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
1194 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
1195 click_x -= this->vehicle_margin;
1196 if (this->hscroll != nullptr) click_x += this->hscroll->GetPosition();
1198 return click_x;
1201 void SetSelectedVehicles(int drag_x)
1203 drag_x = GetClickPosition(drag_x);
1205 int left_x = std::min(this->click_x, drag_x);
1206 int right_x = std::max(this->click_x, drag_x);
1207 this->num_vehicles = 0;
1209 Vehicle *v = Vehicle::Get(this->window_number);
1210 /* Find the vehicle part that was clicked. */
1211 switch (v->type) {
1212 case VEH_TRAIN: {
1213 /* Don't select anything if we are not clicking in the vehicle. */
1214 if (left_x >= 0) {
1215 const Train *u = Train::From(v);
1216 bool start_counting = false;
1217 for (; u != nullptr; u = u->Next()) {
1218 int current_width = u->GetDisplayImageWidth();
1219 left_x -= current_width;
1220 right_x -= current_width;
1222 if (left_x < 0 && !start_counting) {
1223 this->selected_vehicle = u->index;
1224 start_counting = true;
1226 /* Count the first vehicle, even if articulated part */
1227 this->num_vehicles++;
1228 } else if (start_counting && !u->IsArticulatedPart()) {
1229 /* Do not count articulated parts */
1230 this->num_vehicles++;
1233 if (right_x < 0) break;
1237 /* If the selection is not correct, clear it. */
1238 if (this->num_vehicles != 0) {
1239 if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
1240 break;
1242 [[fallthrough]];
1245 default:
1246 /* Clear the selection. */
1247 this->selected_vehicle = v->index;
1248 this->num_vehicles = UINT8_MAX;
1249 break;
1253 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1255 switch (widget) {
1256 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1257 if (this->order != INVALID_VEH_ORDER_ID) break;
1258 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1259 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
1260 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1261 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1262 if (!_ctrl_pressed) {
1263 SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1264 } else {
1265 /* The vehicle selection has changed. */
1266 this->InvalidateData(2);
1268 break;
1271 case WID_VR_MATRIX: { // listbox
1272 this->SetSelection(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX));
1273 this->SetWidgetDisabledState(WID_VR_REFIT, this->selected_refit == nullptr);
1274 this->InvalidateData(1);
1276 if (click_count == 1) break;
1277 [[fallthrough]];
1280 case WID_VR_REFIT: // refit button
1281 if (this->selected_refit != nullptr) {
1282 const Vehicle *v = Vehicle::Get(this->window_number);
1284 if (this->order == INVALID_VEH_ORDER_ID) {
1285 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
1286 if (Command<CMD_REFIT_VEHICLE>::Post(GetCmdRefitVehMsg(v), v->tile, this->selected_vehicle, this->selected_refit->cargo, this->selected_refit->subtype, false, false, this->num_vehicles) && delete_window) this->Close();
1287 } else {
1288 if (Command<CMD_ORDER_REFIT>::Post(v->tile, v->index, this->order, this->selected_refit->cargo)) this->Close();
1291 break;
1295 void OnMouseDrag(Point pt, WidgetID widget) override
1297 switch (widget) {
1298 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1299 if (this->order != INVALID_VEH_ORDER_ID) break;
1300 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1301 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1302 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1303 break;
1308 void OnDragDrop(Point pt, WidgetID widget) override
1310 switch (widget) {
1311 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1312 if (this->order != INVALID_VEH_ORDER_ID) break;
1313 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1314 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1315 this->InvalidateData(2);
1316 break;
1321 void OnResize() override
1323 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
1324 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
1325 if (this->hscroll != nullptr) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
1329 static constexpr NWidgetPart _nested_vehicle_refit_widgets[] = {
1330 NWidget(NWID_HORIZONTAL),
1331 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1332 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1333 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1334 EndContainer(),
1335 /* Vehicle display + scrollbar. */
1336 NWidget(NWID_VERTICAL),
1337 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
1338 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
1339 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
1340 EndContainer(),
1341 EndContainer(),
1342 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
1343 /* Matrix + scrollbar. */
1344 NWidget(NWID_HORIZONTAL),
1345 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VR_MATRIX), SetMinimalSize(228, 112), SetResize(1, 14), SetFill(1, 1), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_VR_SCROLLBAR),
1346 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
1347 EndContainer(),
1348 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WidgetDimensions::unscaled.framerect.Vertical()), SetResize(1, 0), EndContainer(),
1349 NWidget(NWID_HORIZONTAL),
1350 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
1351 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1352 EndContainer(),
1355 static WindowDesc _vehicle_refit_desc(
1356 WDP_AUTO, "view_vehicle_refit", 240, 174,
1357 WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
1358 WDF_CONSTRUCTION,
1359 _nested_vehicle_refit_widgets
1363 * Show the refit window for a vehicle
1364 * @param *v The vehicle to show the refit window for
1365 * @param order of the vehicle to assign refit to, or INVALID_VEH_ORDER_ID to refit the vehicle now
1366 * @param parent the parent window of the refit window
1367 * @param auto_refit Choose cargo for auto-refitting
1369 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
1371 CloseWindowById(WC_VEHICLE_REFIT, v->index);
1372 RefitWindow *w = new RefitWindow(_vehicle_refit_desc, v, order, auto_refit);
1373 w->parent = parent;
1376 /** Display list of cargo types of the engine, for the purchase information window */
1377 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1379 /* List of cargo types of this engine */
1380 CargoTypes cmask = GetUnionOfArticulatedRefitMasks(engine, false);
1381 /* List of cargo types available in this climate */
1382 CargoTypes lmask = _cargo_mask;
1384 /* Draw nothing if the engine is not refittable */
1385 if (HasAtMostOneBit(cmask)) return y;
1387 if (cmask == lmask) {
1388 /* Engine can be refitted to all types in this climate */
1389 SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
1390 } else {
1391 /* Check if we are able to refit to more cargo types and unable to. If
1392 * so, invert the cargo types to list those that we can't refit to. */
1393 if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
1394 cmask ^= lmask;
1395 SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
1396 } else {
1397 SetDParam(0, STR_JUST_CARGO_LIST);
1399 SetDParam(1, cmask);
1402 return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
1405 /** Get the cargo subtype text from NewGRF for the vehicle details window. */
1406 StringID GetCargoSubtypeText(const Vehicle *v)
1408 if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
1409 uint16_t cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
1410 if (cb != CALLBACK_FAILED) {
1411 if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
1412 if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
1414 if (cb != CALLBACK_FAILED) {
1415 return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
1418 return STR_EMPTY;
1421 /** Sort vehicle groups by the number of vehicles in the group */
1422 static bool VehicleGroupLengthSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1424 return a.NumVehicles() < b.NumVehicles();
1427 /** Sort vehicle groups by the total profit this year */
1428 static bool VehicleGroupTotalProfitThisYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1430 return a.GetDisplayProfitThisYear() < b.GetDisplayProfitThisYear();
1433 /** Sort vehicle groups by the total profit last year */
1434 static bool VehicleGroupTotalProfitLastYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1436 return a.GetDisplayProfitLastYear() < b.GetDisplayProfitLastYear();
1439 /** Sort vehicle groups by the average profit this year */
1440 static bool VehicleGroupAverageProfitThisYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1442 return a.GetDisplayProfitThisYear() * static_cast<uint>(b.NumVehicles()) < b.GetDisplayProfitThisYear() * static_cast<uint>(a.NumVehicles());
1445 /** Sort vehicle groups by the average profit last year */
1446 static bool VehicleGroupAverageProfitLastYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1448 return a.GetDisplayProfitLastYear() * static_cast<uint>(b.NumVehicles()) < b.GetDisplayProfitLastYear() * static_cast<uint>(a.NumVehicles());
1451 /** Sort vehicles by their number */
1452 static bool VehicleNumberSorter(const Vehicle * const &a, const Vehicle * const &b)
1454 return a->unitnumber < b->unitnumber;
1457 /** Sort vehicles by their name */
1458 static bool VehicleNameSorter(const Vehicle * const &a, const Vehicle * const &b)
1460 static std::string last_name[2] = { {}, {} };
1462 if (a != _last_vehicle[0]) {
1463 _last_vehicle[0] = a;
1464 SetDParam(0, a->index);
1465 last_name[0] = GetString(STR_VEHICLE_NAME);
1468 if (b != _last_vehicle[1]) {
1469 _last_vehicle[1] = b;
1470 SetDParam(0, b->index);
1471 last_name[1] = GetString(STR_VEHICLE_NAME);
1474 int r = StrNaturalCompare(last_name[0], last_name[1]); // Sort by name (natural sorting).
1475 return (r != 0) ? r < 0: VehicleNumberSorter(a, b);
1478 /** Sort vehicles by their age */
1479 static bool VehicleAgeSorter(const Vehicle * const &a, const Vehicle * const &b)
1481 auto r = a->age - b->age;
1482 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1485 /** Sort vehicles by this year profit */
1486 static bool VehicleProfitThisYearSorter(const Vehicle * const &a, const Vehicle * const &b)
1488 int r = ClampTo<int32_t>(a->GetDisplayProfitThisYear() - b->GetDisplayProfitThisYear());
1489 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1492 /** Sort vehicles by last year profit */
1493 static bool VehicleProfitLastYearSorter(const Vehicle * const &a, const Vehicle * const &b)
1495 int r = ClampTo<int32_t>(a->GetDisplayProfitLastYear() - b->GetDisplayProfitLastYear());
1496 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1499 /** Sort vehicles by their cargo */
1500 static bool VehicleCargoSorter(const Vehicle * const &a, const Vehicle * const &b)
1502 const Vehicle *v;
1503 CargoArray diff{};
1505 /* Append the cargo of the connected waggons */
1506 for (v = a; v != nullptr; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1507 for (v = b; v != nullptr; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1509 int r = 0;
1510 for (uint d : diff) {
1511 r = d;
1512 if (r != 0) break;
1515 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1518 /** Sort vehicles by their reliability */
1519 static bool VehicleReliabilitySorter(const Vehicle * const &a, const Vehicle * const &b)
1521 int r = a->reliability - b->reliability;
1522 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1525 /** Sort vehicles by their max speed */
1526 static bool VehicleMaxSpeedSorter(const Vehicle * const &a, const Vehicle * const &b)
1528 int r = a->vcache.cached_max_speed - b->vcache.cached_max_speed;
1529 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1532 /** Sort vehicles by model */
1533 static bool VehicleModelSorter(const Vehicle * const &a, const Vehicle * const &b)
1535 int r = a->engine_type - b->engine_type;
1536 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1539 /** Sort vehicles by their value */
1540 static bool VehicleValueSorter(const Vehicle * const &a, const Vehicle * const &b)
1542 const Vehicle *u;
1543 Money diff = 0;
1545 for (u = a; u != nullptr; u = u->Next()) diff += u->value;
1546 for (u = b; u != nullptr; u = u->Next()) diff -= u->value;
1548 int r = ClampTo<int32_t>(diff);
1549 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1552 /** Sort vehicles by their length */
1553 static bool VehicleLengthSorter(const Vehicle * const &a, const Vehicle * const &b)
1555 int r = a->GetGroundVehicleCache()->cached_total_length - b->GetGroundVehicleCache()->cached_total_length;
1556 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1559 /** Sort vehicles by the time they can still live */
1560 static bool VehicleTimeToLiveSorter(const Vehicle * const &a, const Vehicle * const &b)
1562 int r = ClampTo<int32_t>((a->max_age - a->age) - (b->max_age - b->age));
1563 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1566 /** Sort vehicles by the timetable delay */
1567 static bool VehicleTimetableDelaySorter(const Vehicle * const &a, const Vehicle * const &b)
1569 int r = a->lateness_counter - b->lateness_counter;
1570 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1573 void InitializeGUI()
1575 MemSetT(&_grouping, 0);
1576 MemSetT(&_sorting, 0);
1580 * Assign a vehicle window a new vehicle
1581 * @param window_class WindowClass to search for
1582 * @param from_index the old vehicle ID
1583 * @param to_index the new vehicle ID
1585 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1587 Window *w = FindWindowById(window_class, from_index);
1588 if (w != nullptr) {
1589 /* Update window_number */
1590 w->window_number = to_index;
1591 if (w->viewport != nullptr) w->viewport->follow_vehicle = to_index;
1593 /* Update vehicle drag data */
1594 if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
1595 _thd.window_number = to_index;
1598 /* Notify the window. */
1599 w->InvalidateData(VIWD_AUTOREPLACE, false);
1604 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
1605 * @param from_index the old vehicle ID
1606 * @param to_index the new vehicle ID
1608 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
1610 ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
1611 ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
1612 ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
1613 ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
1614 ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
1617 static constexpr NWidgetPart _nested_vehicle_list[] = {
1618 NWidget(NWID_HORIZONTAL),
1619 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1620 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_CAPTION_SELECTION),
1621 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
1622 NWidget(NWID_HORIZONTAL),
1623 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION_SHARED_ORDERS),
1624 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_ORDER_VIEW), SetMinimalSize(61, 14), SetDataTip(STR_GOTO_ORDER_VIEW, STR_GOTO_ORDER_VIEW_TOOLTIP),
1625 EndContainer(),
1626 EndContainer(),
1627 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1628 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1629 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1630 EndContainer(),
1632 NWidget(NWID_HORIZONTAL),
1633 NWidget(NWID_VERTICAL, NC_EQUALSIZE),
1634 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VL_GROUP_ORDER), SetMinimalSize(0, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, STR_TOOLTIP_GROUP_ORDER),
1635 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(0, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1636 EndContainer(),
1637 NWidget(NWID_VERTICAL, NC_EQUALSIZE),
1638 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_GROUP_BY_PULLDOWN), SetMinimalSize(0, 12), SetFill(1, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
1639 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(0, 12), SetFill(1, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
1640 EndContainer(),
1641 NWidget(NWID_VERTICAL, NC_EQUALSIZE),
1642 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1643 NWidget(NWID_HORIZONTAL),
1644 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_FILTER_BY_CARGO_SEL),
1645 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_FILTER_BY_CARGO), SetMinimalSize(0, 12), SetFill(0, 1), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_FILTER_CRITERIA),
1646 EndContainer(),
1647 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1648 EndContainer(),
1649 EndContainer(),
1650 EndContainer(),
1652 NWidget(NWID_HORIZONTAL),
1653 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VL_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_VL_SCROLLBAR),
1654 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
1655 EndContainer(),
1657 NWidget(NWID_HORIZONTAL),
1658 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
1659 NWidget(NWID_HORIZONTAL),
1660 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
1661 SetDataTip(STR_JUST_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1662 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
1663 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
1664 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1665 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetAspect(WidgetDimensions::ASPECT_VEHICLE_FLAG), SetFill(0, 1),
1666 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1667 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetAspect(WidgetDimensions::ASPECT_VEHICLE_FLAG), SetFill(0, 1),
1668 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1669 EndContainer(),
1670 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1671 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1672 EndContainer(),
1673 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1674 EndContainer(),
1677 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, uint order_arrow_width, VehicleOrderID start)
1679 const Order *order = v->GetOrder(start);
1680 if (order == nullptr) return;
1682 bool rtl = _current_text_dir == TD_RTL;
1683 int l_offset = rtl ? 0 : order_arrow_width;
1684 int r_offset = rtl ? order_arrow_width : 0;
1685 int i = 0;
1686 VehicleOrderID oid = start;
1688 do {
1689 if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_JUST_RIGHT_ARROW, TC_BLACK, SA_LEFT, false, FS_SMALL);
1691 if (order->IsType(OT_GOTO_STATION)) {
1692 SetDParam(0, order->GetDestination());
1693 DrawString(left + l_offset, right - r_offset, y, STR_STATION_NAME, TC_BLACK, SA_LEFT, false, FS_SMALL);
1695 y += GetCharacterHeight(FS_SMALL);
1696 if (++i == 4) break;
1699 oid++;
1700 order = order->next;
1701 if (order == nullptr) {
1702 order = v->orders->GetFirstOrder();
1703 oid = 0;
1705 } while (oid != start);
1708 /** Draw small order list in the vehicle GUI, but without the little black arrow. This is used for shared order groups. */
1709 static void DrawSmallOrderList(const Order *order, int left, int right, int y, uint order_arrow_width)
1711 bool rtl = _current_text_dir == TD_RTL;
1712 int l_offset = rtl ? 0 : order_arrow_width;
1713 int r_offset = rtl ? order_arrow_width : 0;
1714 int i = 0;
1715 while (order != nullptr) {
1716 if (order->IsType(OT_GOTO_STATION)) {
1717 SetDParam(0, order->GetDestination());
1718 DrawString(left + l_offset, right - r_offset, y, STR_STATION_NAME, TC_BLACK, SA_LEFT, false, FS_SMALL);
1720 y += GetCharacterHeight(FS_SMALL);
1721 if (++i == 4) break;
1723 order = order->next;
1728 * Draws an image of a vehicle chain
1729 * @param v Front vehicle
1730 * @param r Rect to draw at
1731 * @param selection Selected vehicle to draw a frame around
1732 * @param skip Number of pixels to skip at the front (for scrolling)
1734 void DrawVehicleImage(const Vehicle *v, const Rect &r, VehicleID selection, EngineImageType image_type, int skip)
1736 switch (v->type) {
1737 case VEH_TRAIN: DrawTrainImage(Train::From(v), r, selection, image_type, skip); break;
1738 case VEH_ROAD: DrawRoadVehImage(v, r, selection, image_type, skip); break;
1739 case VEH_SHIP: DrawShipImage(v, r, selection, image_type); break;
1740 case VEH_AIRCRAFT: DrawAircraftImage(v, r, selection, image_type); break;
1741 default: NOT_REACHED();
1746 * Get the height of a vehicle in the vehicle list GUIs.
1747 * @param type the vehicle type to look at
1748 * @param divisor the resulting height must be dividable by this
1749 * @return the height
1751 uint GetVehicleListHeight(VehicleType type, uint divisor)
1753 /* Name + vehicle + profit */
1754 uint base = ScaleGUITrad(GetVehicleHeight(type)) + 2 * GetCharacterHeight(FS_SMALL) + WidgetDimensions::scaled.matrix.Vertical();
1755 /* Drawing of the 4 small orders + profit*/
1756 if (type >= VEH_SHIP) base = std::max(base, 6U * GetCharacterHeight(FS_SMALL) + WidgetDimensions::scaled.matrix.Vertical());
1758 if (divisor == 1) return base;
1760 /* Make sure the height is dividable by divisor */
1761 uint rem = base % divisor;
1762 return base + (rem == 0 ? 0 : divisor - rem);
1766 * Get width required for the formatted unit number display.
1767 * @param digits Number of digits required for unit number.
1768 * @return Required width in pixels.
1770 static int GetUnitNumberWidth(int digits)
1772 SetDParamMaxDigits(0, digits);
1773 return GetStringBoundingBox(STR_JUST_COMMA).width;
1777 * Draw all the vehicle list items.
1778 * @param selected_vehicle The vehicle that is to be highlighted.
1779 * @param line_height Height of a single item line.
1780 * @param r Rectangle with edge positions of the matrix widget.
1782 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1784 Rect ir = r.WithHeight(line_height).Shrink(WidgetDimensions::scaled.matrix, RectPadding::zero);
1785 bool rtl = _current_text_dir == TD_RTL;
1787 Dimension profit = GetSpriteSize(SPR_PROFIT_LOT);
1788 int text_offset = std::max<int>(profit.width, GetUnitNumberWidth(this->unitnumber_digits)) + WidgetDimensions::scaled.hsep_normal;
1789 Rect tr = ir.Indent(text_offset, rtl);
1791 bool show_orderlist = this->vli.vtype >= VEH_SHIP;
1792 Rect olr = ir.Indent(std::max(ScaleGUITrad(100) + text_offset, ir.Width() / 2), rtl);
1794 int image_left = (rtl && show_orderlist) ? olr.right : tr.left;
1795 int image_right = (!rtl && show_orderlist) ? olr.left : tr.right;
1797 int vehicle_button_x = rtl ? ir.right - profit.width : ir.left;
1799 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->vehgroups);
1800 for (auto it = first; it != last; ++it) {
1801 const GUIVehicleGroup &vehgroup = *it;
1803 SetDParam(0, vehgroup.GetDisplayProfitThisYear());
1804 SetDParam(1, vehgroup.GetDisplayProfitLastYear());
1805 DrawString(tr.left, tr.right, ir.bottom - GetCharacterHeight(FS_SMALL) - WidgetDimensions::scaled.framerect.bottom,
1806 TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_LIST_PROFIT_THIS_PERIOD_LAST_PERIOD : STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
1808 DrawVehicleProfitButton(vehgroup.GetOldestVehicleAge(), vehgroup.GetDisplayProfitLastYear(), vehgroup.NumVehicles(), vehicle_button_x, ir.top + GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal);
1810 switch (this->grouping) {
1811 case GB_NONE: {
1812 const Vehicle *v = vehgroup.GetSingleVehicle();
1814 if (HasBit(v->vehicle_flags, VF_PATHFINDER_LOST)) {
1815 DrawSprite(SPR_WARNING_SIGN, PAL_NONE, vehicle_button_x, ir.top + GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal + profit.height);
1818 DrawVehicleImage(v, {image_left, ir.top, image_right, ir.bottom}, selected_vehicle, EIT_IN_LIST, 0);
1820 if (_settings_client.gui.show_cargo_in_vehicle_lists) {
1821 /* Get the cargoes the vehicle can carry */
1822 CargoTypes vehicle_cargoes = 0;
1824 for (auto u = v; u != nullptr; u = u->Next()) {
1825 if (u->cargo_cap == 0) continue;
1827 SetBit(vehicle_cargoes, u->cargo_type);
1830 if (!v->name.empty()) {
1831 /* The vehicle got a name so we will print it and the cargoes */
1832 SetDParam(0, STR_VEHICLE_NAME);
1833 SetDParam(1, v->index);
1834 SetDParam(2, STR_VEHICLE_LIST_CARGO);
1835 SetDParam(3, vehicle_cargoes);
1836 DrawString(tr.left, tr.right, ir.top, STR_VEHICLE_LIST_NAME_AND_CARGO, TC_BLACK, SA_LEFT, false, FS_SMALL);
1837 } else if (v->group_id != DEFAULT_GROUP) {
1838 /* The vehicle has no name, but is member of a group, so print group name and the cargoes */
1839 SetDParam(0, STR_GROUP_NAME);
1840 SetDParam(1, v->group_id);
1841 SetDParam(2, STR_VEHICLE_LIST_CARGO);
1842 SetDParam(3, vehicle_cargoes);
1843 DrawString(tr.left, tr.right, ir.top, STR_VEHICLE_LIST_NAME_AND_CARGO, TC_BLACK, SA_LEFT, false, FS_SMALL);
1844 } else {
1845 /* The vehicle has no name, and is not a member of a group, so just print the cargoes */
1846 SetDParam(0, vehicle_cargoes);
1847 DrawString(tr.left, tr.right, ir.top, STR_VEHICLE_LIST_CARGO, TC_BLACK, SA_LEFT, false, FS_SMALL);
1849 } else if (!v->name.empty()) {
1850 /* The vehicle got a name so we will print it */
1851 SetDParam(0, v->index);
1852 DrawString(tr.left, tr.right, ir.top, STR_VEHICLE_NAME, TC_BLACK, SA_LEFT, false, FS_SMALL);
1853 } else if (v->group_id != DEFAULT_GROUP) {
1854 /* The vehicle has no name, but is member of a group, so print group name */
1855 SetDParam(0, v->group_id);
1856 DrawString(tr.left, tr.right, ir.top, STR_GROUP_NAME, TC_BLACK, SA_LEFT, false, FS_SMALL);
1859 if (show_orderlist) DrawSmallOrderList(v, olr.left, olr.right, ir.top + GetCharacterHeight(FS_SMALL), this->order_arrow_width, v->cur_real_order_index);
1861 TextColour tc;
1862 if (v->IsChainInDepot()) {
1863 tc = TC_BLUE;
1864 } else {
1865 tc = (v->age > v->max_age - CalendarTime::DAYS_IN_LEAP_YEAR) ? TC_RED : TC_BLACK;
1868 SetDParam(0, v->unitnumber);
1869 DrawString(ir.left, ir.right, ir.top + WidgetDimensions::scaled.framerect.top, STR_JUST_COMMA, tc);
1870 break;
1873 case GB_SHARED_ORDERS:
1874 assert(vehgroup.NumVehicles() > 0);
1876 for (int i = 0; i < static_cast<int>(vehgroup.NumVehicles()); ++i) {
1877 if (image_left + WidgetDimensions::scaled.hsep_wide * i >= image_right) break; // Break if there is no more space to draw any more vehicles anyway.
1878 DrawVehicleImage(vehgroup.vehicles_begin[i], {image_left + WidgetDimensions::scaled.hsep_wide * i, ir.top, image_right, ir.bottom}, selected_vehicle, EIT_IN_LIST, 0);
1881 if (show_orderlist) DrawSmallOrderList((vehgroup.vehicles_begin[0])->GetFirstOrder(), olr.left, olr.right, ir.top + GetCharacterHeight(FS_SMALL), this->order_arrow_width);
1883 SetDParam(0, vehgroup.NumVehicles());
1884 DrawString(ir.left, ir.right, ir.top + WidgetDimensions::scaled.framerect.top, STR_JUST_COMMA, TC_BLACK);
1885 break;
1887 default:
1888 NOT_REACHED();
1891 ir = ir.Translate(0, line_height);
1895 void BaseVehicleListWindow::UpdateSortingFromGrouping()
1897 /* Set up sorting. Make the window-specific _sorting variable
1898 * point to the correct global _sorting struct so we are freed
1899 * from having conditionals during window operation */
1900 switch (this->vli.vtype) {
1901 case VEH_TRAIN: this->sorting = &_sorting[this->grouping].train; break;
1902 case VEH_ROAD: this->sorting = &_sorting[this->grouping].roadveh; break;
1903 case VEH_SHIP: this->sorting = &_sorting[this->grouping].ship; break;
1904 case VEH_AIRCRAFT: this->sorting = &_sorting[this->grouping].aircraft; break;
1905 default: NOT_REACHED();
1907 this->vehgroups.SetSortFuncs(this->GetVehicleSorterFuncs());
1908 this->vehgroups.SetListing(*this->sorting);
1909 this->vehgroups.ForceRebuild();
1910 this->vehgroups.NeedResort();
1913 void BaseVehicleListWindow::UpdateVehicleGroupBy(GroupBy group_by)
1915 if (this->grouping != group_by) {
1916 /* Save the old sorting option, so that if we change the grouping option back later on,
1917 * UpdateSortingFromGrouping() will automatically restore the saved sorting option. */
1918 *this->sorting = this->vehgroups.GetListing();
1920 this->grouping = group_by;
1921 _grouping[this->vli.type][this->vli.vtype] = group_by;
1922 this->UpdateSortingFromGrouping();
1927 * Window for the (old) vehicle listing.
1929 * bitmask for w->window_number
1930 * 0-7 CompanyID (owner)
1931 * 8-10 window type (use flags in vehicle_gui.h)
1932 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
1933 * 16-31 StationID or OrderID depending on window type (bit 8-10)
1935 struct VehicleListWindow : public BaseVehicleListWindow {
1936 private:
1937 /** Enumeration of planes of the button row at the bottom. */
1938 enum ButtonPlanes {
1939 BP_SHOW_BUTTONS, ///< Show the buttons.
1940 BP_HIDE_BUTTONS, ///< Show the empty panel.
1943 /** Enumeration of planes of the title row at the top. */
1944 enum CaptionPlanes {
1945 BP_NORMAL, ///< Show shared orders caption and buttons.
1946 BP_SHARED_ORDERS, ///< Show the normal caption.
1949 public:
1950 VehicleListWindow(WindowDesc &desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
1952 this->CreateNestedTree();
1954 this->GetWidget<NWidgetStacked>(WID_VL_FILTER_BY_CARGO_SEL)->SetDisplayedPlane((this->vli.type == VL_SHARED_ORDERS) ? SZSP_NONE : 0);
1956 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1958 /* Set up the window widgets */
1959 this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
1961 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_CAPTION_SELECTION);
1962 if (this->vli.type == VL_SHARED_ORDERS) {
1963 this->GetWidget<NWidgetCore>(WID_VL_CAPTION_SHARED_ORDERS)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
1964 /* If we are in the shared orders window, then disable the group-by dropdown menu.
1965 * Remove this when the group-by dropdown menu has another option apart from grouping by shared orders. */
1966 this->SetWidgetDisabledState(WID_VL_GROUP_ORDER, true);
1967 this->SetWidgetDisabledState(WID_VL_GROUP_BY_PULLDOWN, true);
1968 nwi->SetDisplayedPlane(BP_SHARED_ORDERS);
1969 } else {
1970 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
1971 nwi->SetDisplayedPlane(BP_NORMAL);
1974 this->FinishInitNested(window_number);
1975 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1977 this->BuildVehicleList();
1978 this->SortVehicleList();
1981 ~VehicleListWindow()
1983 *this->sorting = this->vehgroups.GetListing();
1986 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1988 switch (widget) {
1989 case WID_VL_LIST:
1990 resize.height = GetVehicleListHeight(this->vli.vtype, 1);
1992 switch (this->vli.vtype) {
1993 case VEH_TRAIN:
1994 case VEH_ROAD:
1995 size.height = 6 * resize.height;
1996 break;
1997 case VEH_SHIP:
1998 case VEH_AIRCRAFT:
1999 size.height = 4 * resize.height;
2000 break;
2001 default: NOT_REACHED();
2003 break;
2005 case WID_VL_SORT_ORDER: {
2006 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
2007 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
2008 d.height += padding.height;
2009 size = maxdim(size, d);
2010 break;
2013 case WID_VL_GROUP_BY_PULLDOWN:
2014 size.width = GetStringListWidth(this->vehicle_group_by_names) + padding.width;
2015 break;
2017 case WID_VL_SORT_BY_PULLDOWN:
2018 size.width = GetStringListWidth(this->vehicle_group_none_sorter_names_calendar);
2019 size.width = std::max(size.width, GetStringListWidth(this->vehicle_group_none_sorter_names_wallclock));
2020 size.width = std::max(size.width, GetStringListWidth(this->vehicle_group_shared_orders_sorter_names_calendar));
2021 size.width = std::max(size.width, GetStringListWidth(this->vehicle_group_shared_orders_sorter_names_wallclock));
2022 size.width += padding.width;
2023 break;
2025 case WID_VL_FILTER_BY_CARGO:
2026 size.width = std::max(size.width, GetDropDownListDimension(this->BuildCargoDropDownList(true)).width + padding.width);
2027 break;
2029 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
2030 Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false, true);
2031 d.height += padding.height;
2032 d.width += padding.width;
2033 size = maxdim(size, d);
2034 break;
2039 void SetStringParameters(WidgetID widget) const override
2041 switch (widget) {
2042 case WID_VL_AVAILABLE_VEHICLES:
2043 SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
2044 break;
2046 case WID_VL_FILTER_BY_CARGO:
2047 SetDParam(0, this->GetCargoFilterLabel(this->cargo_filter_criteria));
2048 break;
2050 case WID_VL_CAPTION:
2051 case WID_VL_CAPTION_SHARED_ORDERS: {
2052 switch (this->vli.type) {
2053 case VL_SHARED_ORDERS: // Shared Orders
2054 SetDParam(0, this->vehicles.size());
2055 break;
2057 case VL_STANDARD: // Company Name
2058 SetDParam(0, STR_COMPANY_NAME);
2059 SetDParam(1, this->vli.index);
2060 SetDParam(3, this->vehicles.size());
2061 break;
2063 case VL_STATION_LIST: // Station/Waypoint Name
2064 SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
2065 SetDParam(1, this->vli.index);
2066 SetDParam(3, this->vehicles.size());
2067 break;
2069 case VL_DEPOT_LIST:
2070 SetDParam(0, STR_DEPOT_CAPTION);
2071 SetDParam(1, this->vli.vtype);
2072 SetDParam(2, this->vli.index);
2073 SetDParam(3, this->vehicles.size());
2074 break;
2075 default: NOT_REACHED();
2077 break;
2082 void DrawWidget(const Rect &r, WidgetID widget) const override
2084 switch (widget) {
2085 case WID_VL_SORT_ORDER:
2086 /* draw arrow pointing up/down for ascending/descending sorting */
2087 this->DrawSortButtonState(widget, this->vehgroups.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
2088 break;
2090 case WID_VL_LIST:
2091 this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
2092 break;
2096 void OnPaint() override
2098 this->BuildVehicleList();
2099 this->SortVehicleList();
2101 if (this->vehicles.empty() && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
2102 this->CloseChildWindows(WC_DROPDOWN_MENU);
2105 /* Hide the widgets that we will not use in this window
2106 * Some windows contains actions only fit for the owner */
2107 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
2108 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
2109 if (plane_to_show != nwi->shown_plane) {
2110 nwi->SetDisplayedPlane(plane_to_show);
2111 nwi->SetDirty(this);
2113 if (this->owner == _local_company) {
2114 this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
2115 this->SetWidgetsDisabledState(this->vehicles.empty(),
2116 WID_VL_MANAGE_VEHICLES_DROPDOWN,
2117 WID_VL_STOP_ALL,
2118 WID_VL_START_ALL);
2121 /* Set text of group by dropdown widget. */
2122 this->GetWidget<NWidgetCore>(WID_VL_GROUP_BY_PULLDOWN)->widget_data = std::data(this->vehicle_group_by_names)[this->grouping];
2124 /* Set text of sort by dropdown widget. */
2125 this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->GetVehicleSorterNames()[this->vehgroups.SortType()];
2127 this->GetWidget<NWidgetCore>(WID_VL_FILTER_BY_CARGO)->widget_data = this->GetCargoFilterLabel(this->cargo_filter_criteria);
2129 this->DrawWidgets();
2132 bool last_overlay_state;
2133 void OnMouseLoop() override
2135 if (last_overlay_state != ShowCargoIconOverlay()) {
2136 last_overlay_state = ShowCargoIconOverlay();
2137 this->SetDirty();
2141 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2143 switch (widget) {
2144 case WID_VL_ORDER_VIEW: // Open the shared orders window
2145 assert(this->vli.type == VL_SHARED_ORDERS);
2146 assert(!this->vehicles.empty());
2147 ShowOrdersWindow(this->vehicles[0]);
2148 break;
2150 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
2151 this->vehgroups.ToggleSortOrder();
2152 this->SetDirty();
2153 break;
2155 case WID_VL_GROUP_BY_PULLDOWN: // Select sorting criteria dropdown menu
2156 ShowDropDownMenu(this, this->vehicle_group_by_names, this->grouping, WID_VL_GROUP_BY_PULLDOWN, 0, 0);
2157 return;
2159 case WID_VL_SORT_BY_PULLDOWN: // Select sorting criteria dropdown menu
2160 ShowDropDownMenu(this, this->GetVehicleSorterNames(), this->vehgroups.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
2161 (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
2162 return;
2164 case WID_VL_FILTER_BY_CARGO: // Cargo filter dropdown
2165 ShowDropDownList(this, this->BuildCargoDropDownList(false), this->cargo_filter_criteria, widget);
2166 break;
2168 case WID_VL_LIST: { // Matrix to show vehicles
2169 auto it = this->vscroll->GetScrolledItemFromWidget(this->vehgroups, pt.y, this, WID_VL_LIST);
2170 if (it == this->vehgroups.end()) return; // click out of list bound
2172 const GUIVehicleGroup &vehgroup = *it;
2173 switch (this->grouping) {
2174 case GB_NONE: {
2175 const Vehicle *v = vehgroup.GetSingleVehicle();
2176 if (!VehicleClicked(v)) {
2177 if (_ctrl_pressed) {
2178 ShowCompanyGroupForVehicle(v);
2179 } else {
2180 ShowVehicleViewWindow(v);
2183 break;
2186 case GB_SHARED_ORDERS: {
2187 assert(vehgroup.NumVehicles() > 0);
2188 if (!VehicleClicked(vehgroup)) {
2189 const Vehicle *v = vehgroup.vehicles_begin[0];
2190 if (_ctrl_pressed) {
2191 ShowOrdersWindow(v);
2192 } else {
2193 if (vehgroup.NumVehicles() == 1) {
2194 ShowVehicleViewWindow(v);
2195 } else {
2196 ShowVehicleListWindow(v);
2200 break;
2203 default: NOT_REACHED();
2206 break;
2209 case WID_VL_AVAILABLE_VEHICLES:
2210 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
2211 break;
2213 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
2214 ShowDropDownList(this, this->BuildActionDropdownList(VehicleListIdentifier::UnPack(this->window_number).type == VL_STANDARD, false, true), 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
2215 break;
2218 case WID_VL_STOP_ALL:
2219 case WID_VL_START_ALL:
2220 Command<CMD_MASS_START_STOP>::Post(0, widget == WID_VL_START_ALL, true, this->vli);
2221 break;
2225 void OnDropdownSelect(WidgetID widget, int index) override
2227 switch (widget) {
2228 case WID_VL_GROUP_BY_PULLDOWN:
2229 this->UpdateVehicleGroupBy(static_cast<GroupBy>(index));
2230 break;
2232 case WID_VL_SORT_BY_PULLDOWN:
2233 this->vehgroups.SetSortType(index);
2234 break;
2236 case WID_VL_FILTER_BY_CARGO:
2237 this->SetCargoFilter(index);
2238 break;
2240 case WID_VL_MANAGE_VEHICLES_DROPDOWN:
2241 assert(!this->vehicles.empty());
2243 switch (index) {
2244 case ADI_REPLACE: // Replace window
2245 ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
2246 break;
2247 case ADI_SERVICE: // Send for servicing
2248 case ADI_DEPOT: // Send to Depots
2249 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Post(GetCmdSendToDepotMsg(this->vli.vtype), 0, DepotCommand::MassSend | (index == ADI_SERVICE ? DepotCommand::Service : DepotCommand::None), this->vli);
2250 break;
2252 case ADI_CREATE_GROUP: // Create group
2253 Command<CMD_ADD_VEHICLE_GROUP>::Post(CcAddVehicleNewGroup, NEW_GROUP, INVALID_VEHICLE, false, this->vli);
2254 break;
2256 default: NOT_REACHED();
2258 break;
2260 default: NOT_REACHED();
2262 this->SetDirty();
2265 void OnGameTick() override
2267 if (this->vehgroups.NeedResort()) {
2268 StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
2270 Debug(misc, 3, "Periodic resort {} list company {} at station {}", this->vli.vtype, this->owner, station);
2271 this->SetDirty();
2275 void OnResize() override
2277 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
2281 * Some data on this window has become invalid.
2282 * @param data Information about the changed data.
2283 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
2285 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
2287 if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
2288 /* Needs to be done in command-scope, so everything stays valid */
2289 this->vli.index = GB(data, 0, 20);
2290 this->window_number = this->vli.Pack();
2291 this->vehgroups.ForceRebuild();
2292 return;
2295 if (data == 0) {
2296 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
2297 this->vehgroups.ForceRebuild();
2298 } else {
2299 this->vehgroups.ForceResort();
2304 static WindowDesc _vehicle_list_other_desc(
2305 WDP_AUTO, "list_vehicles", 260, 246,
2306 WC_INVALID, WC_NONE,
2308 _nested_vehicle_list
2311 static WindowDesc _vehicle_list_train_desc(
2312 WDP_AUTO, "list_vehicles_train", 325, 246,
2313 WC_TRAINS_LIST, WC_NONE,
2315 _nested_vehicle_list
2318 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32_t unique_number)
2320 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
2322 WindowNumber num = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
2323 if (vehicle_type == VEH_TRAIN) {
2324 AllocateWindowDescFront<VehicleListWindow>(_vehicle_list_train_desc, num);
2325 } else {
2326 _vehicle_list_other_desc.cls = GetWindowClassForVehicleType(vehicle_type);
2327 AllocateWindowDescFront<VehicleListWindow>(_vehicle_list_other_desc, num);
2331 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
2333 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
2334 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
2335 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
2338 if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
2339 ShowCompanyGroup(company, vehicle_type);
2340 } else {
2341 ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
2345 void ShowVehicleListWindow(const Vehicle *v)
2347 ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
2350 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
2352 ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
2355 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
2357 uint16_t depot_airport_index;
2359 if (vehicle_type == VEH_AIRCRAFT) {
2360 depot_airport_index = GetStationIndex(depot_tile);
2361 } else {
2362 depot_airport_index = GetDepotIndex(depot_tile);
2364 ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
2368 /* Unified vehicle GUI - Vehicle Details Window */
2370 static_assert(WID_VD_DETAILS_CARGO_CARRIED == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO );
2371 static_assert(WID_VD_DETAILS_TRAIN_VEHICLES == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO );
2372 static_assert(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
2373 static_assert(WID_VD_DETAILS_TOTAL_CARGO == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS );
2375 /** Vehicle details widgets (other than train). */
2376 static constexpr NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
2377 NWidget(NWID_HORIZONTAL),
2378 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2379 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2380 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2381 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2382 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2383 EndContainer(),
2384 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
2385 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
2386 NWidget(NWID_HORIZONTAL),
2387 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
2388 SetDataTip(AWV_DECREASE, STR_NULL),
2389 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
2390 SetDataTip(AWV_INCREASE, STR_NULL),
2391 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
2392 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2393 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
2394 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2395 EndContainer(),
2398 /** Train details widgets. */
2399 static constexpr NWidgetPart _nested_train_vehicle_details_widgets[] = {
2400 NWidget(NWID_HORIZONTAL),
2401 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2402 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2403 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2404 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2405 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2406 EndContainer(),
2407 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
2408 NWidget(NWID_HORIZONTAL),
2409 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VD_MATRIX), SetResize(1, 1), SetMinimalSize(393, 45), SetMatrixDataTip(1, 0, STR_NULL), SetFill(1, 0), SetScrollbar(WID_VD_SCROLLBAR),
2410 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
2411 EndContainer(),
2412 NWidget(NWID_HORIZONTAL),
2413 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
2414 SetDataTip(AWV_DECREASE, STR_NULL),
2415 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
2416 SetDataTip(AWV_INCREASE, STR_NULL),
2417 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
2418 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2419 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
2420 EndContainer(),
2421 NWidget(NWID_HORIZONTAL),
2422 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
2423 SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2424 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
2425 SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2426 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
2427 SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2428 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
2429 SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2430 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2431 EndContainer(),
2435 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
2436 extern void DrawTrainDetails(const Train *v, const Rect &r, int vscroll_pos, uint16_t vscroll_cap, TrainDetailsWindowTabs det_tab);
2437 extern void DrawRoadVehDetails(const Vehicle *v, const Rect &r);
2438 extern void DrawShipDetails(const Vehicle *v, const Rect &r);
2439 extern void DrawAircraftDetails(const Aircraft *v, const Rect &r);
2441 static StringID _service_interval_dropdown_calendar[] = {
2442 STR_VEHICLE_DETAILS_DEFAULT,
2443 STR_VEHICLE_DETAILS_DAYS,
2444 STR_VEHICLE_DETAILS_PERCENT,
2447 static StringID _service_interval_dropdown_wallclock[] = {
2448 STR_VEHICLE_DETAILS_DEFAULT,
2449 STR_VEHICLE_DETAILS_MINUTES,
2450 STR_VEHICLE_DETAILS_PERCENT,
2453 /** Class for managing the vehicle details window. */
2454 struct VehicleDetailsWindow : Window {
2455 TrainDetailsWindowTabs tab; ///< For train vehicles: which tab is displayed.
2456 Scrollbar *vscroll;
2458 /** Initialize a newly created vehicle details window */
2459 VehicleDetailsWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc)
2461 const Vehicle *v = Vehicle::Get(window_number);
2463 this->CreateNestedTree();
2464 this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : nullptr);
2465 this->FinishInitNested(window_number);
2467 this->owner = v->owner;
2468 this->tab = TDW_TAB_CARGO;
2472 * Some data on this window has become invalid.
2473 * @param data Information about the changed data.
2474 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
2476 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
2478 if (data == VIWD_AUTOREPLACE) {
2479 /* Autoreplace replaced the vehicle.
2480 * Nothing to do for this window. */
2481 return;
2483 if (!gui_scope) return;
2484 const Vehicle *v = Vehicle::Get(this->window_number);
2485 if (v->type == VEH_ROAD) {
2486 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
2487 uint aimed_height = this->GetRoadVehDetailsHeight(v);
2488 /* If the number of articulated parts changes, the size of the window must change too. */
2489 if (aimed_height != nwid_info->current_y) {
2490 this->ReInit();
2496 * Gets the desired height for the road vehicle details panel.
2497 * @param v Road vehicle being shown.
2498 * @return Desired height in pixels.
2500 uint GetRoadVehDetailsHeight(const Vehicle *v)
2502 uint desired_height;
2503 if (v->HasArticulatedPart()) {
2504 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
2505 desired_height = ScaleGUITrad(15) + 3 * GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal * 2;
2506 /* Add space for the cargo amount for each part. */
2507 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
2508 if (u->cargo_cap != 0) desired_height += GetCharacterHeight(FS_NORMAL);
2510 } else {
2511 desired_height = 4 * GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal * 2;
2513 return desired_height;
2516 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2518 switch (widget) {
2519 case WID_VD_TOP_DETAILS: {
2520 Dimension dim = { 0, 0 };
2521 size.height = 4 * GetCharacterHeight(FS_NORMAL) + padding.height;
2523 for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
2524 static const StringID info_strings[] = {
2525 STR_VEHICLE_INFO_MAX_SPEED,
2526 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
2527 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
2528 STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR_MIN_PERFORMANCE,
2529 STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD_MIN_PERFORMANCE,
2530 STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
2532 for (const auto &info_string : info_strings) {
2533 dim = maxdim(dim, GetStringBoundingBox(info_string));
2535 SetDParam(0, STR_VEHICLE_INFO_AGE);
2536 dim = maxdim(dim, GetStringBoundingBox(TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_AGE_RUNNING_COST_PERIOD : STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
2537 size.width = dim.width + padding.width;
2538 break;
2541 case WID_VD_MIDDLE_DETAILS: {
2542 const Vehicle *v = Vehicle::Get(this->window_number);
2543 switch (v->type) {
2544 case VEH_ROAD:
2545 size.height = this->GetRoadVehDetailsHeight(v) + padding.height;
2546 break;
2548 case VEH_SHIP:
2549 size.height = 4 * GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal * 2 + padding.height;
2550 break;
2552 case VEH_AIRCRAFT:
2553 size.height = 5 * GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal * 2 + padding.height;
2554 break;
2556 default:
2557 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
2559 break;
2562 case WID_VD_MATRIX:
2563 resize.height = std::max<uint>(ScaleGUITrad(14), GetCharacterHeight(FS_NORMAL) + padding.height);
2564 size.height = 4 * resize.height;
2565 break;
2567 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2568 Dimension d = maxdim(GetStringListBoundingBox(_service_interval_dropdown_calendar), GetStringListBoundingBox(_service_interval_dropdown_wallclock));
2569 d.width += padding.width;
2570 d.height += padding.height;
2571 size = maxdim(size, d);
2572 break;
2575 case WID_VD_SERVICING_INTERVAL:
2576 SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
2578 /* Do we show the last serviced value as a date or minutes since service? */
2579 if (TimerGameEconomy::UsingWallclockUnits()) {
2580 SetDParam(1, STR_VEHICLE_DETAILS_LAST_SERVICE_MINUTES_AGO);
2581 /*/ Vehicle was last serviced at year 0, and we're at max year */
2582 SetDParamMaxValue(2, EconomyTime::MONTHS_IN_YEAR * EconomyTime::MAX_YEAR.base());
2583 } else {
2584 SetDParam(1, STR_VEHICLE_DETAILS_LAST_SERVICE_DATE);
2585 /*/ Vehicle was last serviced at year 0, and we're at max year */
2586 SetDParamMaxValue(2, TimerGameEconomy::DateAtStartOfYear(EconomyTime::MAX_YEAR));
2588 size.width = std::max(
2589 GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT).width,
2590 GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS).width
2591 ) + padding.width;
2592 size.height = GetCharacterHeight(FS_NORMAL) + padding.height;
2593 break;
2597 /** Checks whether service interval is enabled for the vehicle. */
2598 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
2600 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
2601 switch (vehicle_type) {
2602 default: NOT_REACHED();
2603 case VEH_TRAIN: return vds->servint_trains != 0;
2604 case VEH_ROAD: return vds->servint_roadveh != 0;
2605 case VEH_SHIP: return vds->servint_ships != 0;
2606 case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
2611 * Draw the details for the given vehicle at the position of the Details windows
2613 * @param v current vehicle
2614 * @param r the Rect to draw within
2615 * @param vscroll_pos Position of scrollbar (train only)
2616 * @param vscroll_cap Number of lines currently displayed (train only)
2617 * @param det_tab Selected details tab (train only)
2619 static void DrawVehicleDetails(const Vehicle *v, const Rect &r, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2621 switch (v->type) {
2622 case VEH_TRAIN: DrawTrainDetails(Train::From(v), r, vscroll_pos, vscroll_cap, det_tab); break;
2623 case VEH_ROAD: DrawRoadVehDetails(v, r); break;
2624 case VEH_SHIP: DrawShipDetails(v, r); break;
2625 case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), r); break;
2626 default: NOT_REACHED();
2630 void SetStringParameters(WidgetID widget) const override
2632 if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
2635 void DrawWidget(const Rect &r, WidgetID widget) const override
2637 const Vehicle *v = Vehicle::Get(this->window_number);
2639 switch (widget) {
2640 case WID_VD_TOP_DETAILS: {
2641 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2643 /* Draw running cost */
2644 SetDParam(1, TimerGameCalendar::DateToYear(v->age));
2645 SetDParam(0, (v->age + CalendarTime::DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
2646 SetDParam(2, TimerGameCalendar::DateToYear(v->max_age));
2647 SetDParam(3, v->GetDisplayRunningCost());
2648 DrawString(tr, TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_AGE_RUNNING_COST_PERIOD : STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
2649 tr.top += GetCharacterHeight(FS_NORMAL);
2651 /* Draw max speed */
2652 StringID string;
2653 if (v->type == VEH_TRAIN ||
2654 (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
2655 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2656 SetDParam(2, PackVelocity(v->GetDisplayMaxSpeed(), v->type));
2657 SetDParam(1, gcache->cached_power);
2658 SetDParam(0, gcache->cached_weight);
2659 SetDParam(3, gcache->cached_max_te);
2660 if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
2661 GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
2662 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
2663 } else {
2664 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
2666 } else {
2667 SetDParam(0, PackVelocity(v->GetDisplayMaxSpeed(), v->type));
2668 if (v->type == VEH_AIRCRAFT) {
2669 SetDParam(1, v->GetEngine()->GetAircraftTypeText());
2670 if (Aircraft::From(v)->GetRange() > 0) {
2671 SetDParam(2, Aircraft::From(v)->GetRange());
2672 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE_RANGE;
2673 } else {
2674 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE;
2676 } else {
2677 string = STR_VEHICLE_INFO_MAX_SPEED;
2680 DrawString(tr, string);
2681 tr.top += GetCharacterHeight(FS_NORMAL);
2683 /* Draw profit */
2684 SetDParam(0, v->GetDisplayProfitThisYear());
2685 SetDParam(1, v->GetDisplayProfitLastYear());
2686 if (v->IsGroundVehicle()) {
2687 SetDParam(2, v->GetDisplayMinPowerToWeight());
2688 DrawString(tr, TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD_MIN_PERFORMANCE : STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR_MIN_PERFORMANCE);
2689 } else {
2690 DrawString(tr, TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_INFO_PROFIT_THIS_PERIOD_LAST_PERIOD : STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2692 tr.top += GetCharacterHeight(FS_NORMAL);
2694 /* Draw breakdown & reliability */
2695 SetDParam(0, ToPercent16(v->reliability));
2696 SetDParam(1, v->breakdowns_since_last_service);
2697 DrawString(tr, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
2698 break;
2701 case WID_VD_MATRIX: {
2702 /* For trains only. */
2703 DrawVehicleDetails(v, r.Shrink(WidgetDimensions::scaled.matrix, RectPadding::zero).WithHeight(this->resize.step_height), this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->tab);
2704 break;
2707 case WID_VD_MIDDLE_DETAILS: {
2708 /* For other vehicles, at the place of the matrix. */
2709 bool rtl = _current_text_dir == TD_RTL;
2710 uint sprite_width = GetSingleVehicleWidth(v, EIT_IN_DETAILS) + WidgetDimensions::scaled.framerect.Horizontal();
2711 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2713 /* Articulated road vehicles use a complete line. */
2714 if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
2715 DrawVehicleImage(v, tr.WithHeight(ScaleGUITrad(GetVehicleHeight(v->type)), false), INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2716 } else {
2717 Rect sr = tr.WithWidth(sprite_width, rtl);
2718 DrawVehicleImage(v, sr.WithHeight(ScaleGUITrad(GetVehicleHeight(v->type)), false), INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2721 DrawVehicleDetails(v, tr.Indent(sprite_width, rtl), 0, 0, this->tab);
2722 break;
2725 case WID_VD_SERVICING_INTERVAL: {
2726 /* Draw service interval text */
2727 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2729 SetDParam(0, v->GetServiceInterval());
2731 /* We're using wallclock units. Show minutes since last serviced. */
2732 if (TimerGameEconomy::UsingWallclockUnits()) {
2733 int minutes_since_serviced = (TimerGameEconomy::date - v->date_of_last_service).base() / EconomyTime::DAYS_IN_ECONOMY_MONTH;
2734 SetDParam(1, STR_VEHICLE_DETAILS_LAST_SERVICE_MINUTES_AGO);
2735 SetDParam(2, minutes_since_serviced);
2736 DrawString(tr.left, tr.right, CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL)),
2737 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_MINUTES);
2738 break;
2741 /* We're using calendar dates. Show the date of last service. */
2742 SetDParam(1, STR_VEHICLE_DETAILS_LAST_SERVICE_DATE);
2743 SetDParam(2, v->date_of_last_service);
2744 DrawString(tr.left, tr.right, CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL)),
2745 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
2746 break;
2751 /** Repaint vehicle details window. */
2752 void OnPaint() override
2754 const Vehicle *v = Vehicle::Get(this->window_number);
2756 if (v->type == VEH_TRAIN) {
2757 this->LowerWidget(WID_VD_DETAILS_CARGO_CARRIED + this->tab);
2758 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2761 /* Disable service-scroller when interval is set to disabled */
2762 this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
2763 WID_VD_INCREASE_SERVICING_INTERVAL,
2764 WID_VD_DECREASE_SERVICING_INTERVAL);
2766 StringID str =
2767 !v->ServiceIntervalIsCustom() ? STR_VEHICLE_DETAILS_DEFAULT :
2768 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT :
2769 TimerGameEconomy::UsingWallclockUnits() ? STR_VEHICLE_DETAILS_MINUTES : STR_VEHICLE_DETAILS_DAYS;
2770 this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
2772 this->DrawWidgets();
2775 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2777 switch (widget) {
2778 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2779 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2780 const Vehicle *v = Vehicle::Get(this->window_number);
2781 int mod;
2782 if (!v->ServiceIntervalIsPercent() && TimerGameEconomy::UsingWallclockUnits()) {
2783 mod = _ctrl_pressed ? 1 : 5;
2784 } else {
2785 mod = _ctrl_pressed ? 5 : 10;
2788 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2789 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2790 if (mod == v->GetServiceInterval()) return;
2792 Command<CMD_CHANGE_SERVICE_INT>::Post(STR_ERROR_CAN_T_CHANGE_SERVICING, v->index, mod, true, v->ServiceIntervalIsPercent());
2793 break;
2796 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2797 const Vehicle *v = Vehicle::Get(this->window_number);
2798 ShowDropDownMenu(this,
2799 TimerGameEconomy::UsingWallclockUnits() ? _service_interval_dropdown_wallclock : _service_interval_dropdown_calendar,
2800 v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
2801 break;
2804 case WID_VD_DETAILS_CARGO_CARRIED:
2805 case WID_VD_DETAILS_TRAIN_VEHICLES:
2806 case WID_VD_DETAILS_CAPACITY_OF_EACH:
2807 case WID_VD_DETAILS_TOTAL_CARGO:
2808 this->SetWidgetsLoweredState(false,
2809 WID_VD_DETAILS_CARGO_CARRIED,
2810 WID_VD_DETAILS_TRAIN_VEHICLES,
2811 WID_VD_DETAILS_CAPACITY_OF_EACH,
2812 WID_VD_DETAILS_TOTAL_CARGO);
2814 this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
2815 this->SetDirty();
2816 break;
2820 bool OnTooltip([[maybe_unused]] Point pt, WidgetID widget, TooltipCloseCondition close_cond) override
2822 if (widget == WID_VD_INCREASE_SERVICING_INTERVAL || widget == WID_VD_DECREASE_SERVICING_INTERVAL) {
2823 const Vehicle *v = Vehicle::Get(this->window_number);
2824 StringID tool_tip;
2825 if (v->ServiceIntervalIsPercent()) {
2826 tool_tip = widget == WID_VD_INCREASE_SERVICING_INTERVAL ? STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP_PERCENT : STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP_PERCENT;
2827 } else if (TimerGameEconomy::UsingWallclockUnits()) {
2828 tool_tip = widget == WID_VD_INCREASE_SERVICING_INTERVAL ? STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP_MINUTES : STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP_MINUTES;
2829 } else {
2830 tool_tip = widget == WID_VD_INCREASE_SERVICING_INTERVAL ? STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP_DAYS : STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP_DAYS;
2832 GuiShowTooltips(this, tool_tip, close_cond);
2833 return true;
2836 return false;
2839 void OnDropdownSelect(WidgetID widget, int index) override
2841 switch (widget) {
2842 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2843 const Vehicle *v = Vehicle::Get(this->window_number);
2844 bool iscustom = index != 0;
2845 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2846 uint16_t interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2847 Command<CMD_CHANGE_SERVICE_INT>::Post(STR_ERROR_CAN_T_CHANGE_SERVICING, v->index, interval, iscustom, ispercent);
2848 break;
2853 void OnResize() override
2855 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
2856 if (nwi != nullptr) {
2857 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2862 /** Vehicle details window descriptor. */
2863 static WindowDesc _train_vehicle_details_desc(
2864 WDP_AUTO, "view_vehicle_details_train", 405, 178,
2865 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2867 _nested_train_vehicle_details_widgets
2870 /** Vehicle details window descriptor for other vehicles than a train. */
2871 static WindowDesc _nontrain_vehicle_details_desc(
2872 WDP_AUTO, "view_vehicle_details", 405, 113,
2873 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2875 _nested_nontrain_vehicle_details_widgets
2878 /** Shows the vehicle details window of the given vehicle. */
2879 static void ShowVehicleDetailsWindow(const Vehicle *v)
2881 CloseWindowById(WC_VEHICLE_ORDERS, v->index, false);
2882 CloseWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
2883 AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? _train_vehicle_details_desc : _nontrain_vehicle_details_desc, v->index);
2887 /* Unified vehicle GUI - Vehicle View Window */
2889 /** Vehicle view widgets. */
2890 static constexpr NWidgetPart _nested_vehicle_view_widgets[] = {
2891 NWidget(NWID_HORIZONTAL),
2892 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2893 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_RENAME), SetAspect(WidgetDimensions::ASPECT_RENAME), SetDataTip(SPR_RENAME, STR_NULL /* filled in later */),
2894 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2895 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_LOCATION), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetDataTip(SPR_GOTO_LOCATION, STR_NULL /* filled in later */),
2896 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
2897 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2898 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2899 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2900 EndContainer(),
2901 NWidget(NWID_HORIZONTAL),
2902 NWidget(WWT_PANEL, COLOUR_GREY),
2903 NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
2904 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1),
2905 EndContainer(),
2906 EndContainer(),
2907 NWidget(NWID_VERTICAL),
2908 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
2909 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2910 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2911 EndContainer(),
2912 /* For trains only, 'ignore signal' button. */
2913 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18),
2914 SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2915 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
2916 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
2917 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18),
2918 SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2919 EndContainer(),
2920 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
2921 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
2922 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
2923 EndContainer(),
2924 EndContainer(),
2925 NWidget(NWID_HORIZONTAL),
2926 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetResize(1, 0), SetFill(1, 0),
2927 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_ORDER_LOCATION), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetDataTip(SPR_GOTO_LOCATION, STR_VEHICLE_VIEW_ORDER_LOCATION_TOOLTIP),
2928 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2929 EndContainer(),
2932 /* Just to make sure, nobody has changed the vehicle type constants, as we are
2933 using them for array indexing in a number of places here. */
2934 static_assert(VEH_TRAIN == 0);
2935 static_assert(VEH_ROAD == 1);
2936 static_assert(VEH_SHIP == 2);
2937 static_assert(VEH_AIRCRAFT == 3);
2939 /** Zoom levels for vehicle views indexed by vehicle type. */
2940 static const ZoomLevel _vehicle_view_zoom_levels[] = {
2941 ZOOM_LVL_TRAIN,
2942 ZOOM_LVL_ROADVEH,
2943 ZOOM_LVL_SHIP,
2944 ZOOM_LVL_AIRCRAFT,
2947 /* Constants for geometry of vehicle view viewport */
2948 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2949 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2950 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
2952 /** Command indices for the _vehicle_command_translation_table. */
2953 enum VehicleCommandTranslation {
2954 VCT_CMD_START_STOP = 0,
2955 VCT_CMD_CLONE_VEH,
2956 VCT_CMD_TURN_AROUND,
2959 /** Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type. */
2960 static const StringID _vehicle_msg_translation_table[][4] = {
2961 { // VCT_CMD_START_STOP
2962 STR_ERROR_CAN_T_STOP_START_TRAIN,
2963 STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE,
2964 STR_ERROR_CAN_T_STOP_START_SHIP,
2965 STR_ERROR_CAN_T_STOP_START_AIRCRAFT
2967 { // VCT_CMD_CLONE_VEH
2968 STR_ERROR_CAN_T_BUY_TRAIN,
2969 STR_ERROR_CAN_T_BUY_ROAD_VEHICLE,
2970 STR_ERROR_CAN_T_BUY_SHIP,
2971 STR_ERROR_CAN_T_BUY_AIRCRAFT
2973 { // VCT_CMD_TURN_AROUND
2974 STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN,
2975 STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN,
2976 INVALID_STRING_ID, // invalid for ships
2977 INVALID_STRING_ID // invalid for aircraft
2982 * This is the Callback method after attempting to start/stop a vehicle
2983 * @param result the result of the start/stop command
2984 * @param veh_id Vehicle ID.
2986 void CcStartStopVehicle(Commands, const CommandCost &result, VehicleID veh_id, bool)
2988 if (result.Failed()) return;
2990 const Vehicle *v = Vehicle::GetIfValid(veh_id);
2991 if (v == nullptr || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2993 StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2994 Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
2995 AddTextEffect(msg, pt.x, pt.y, Ticks::DAY_TICKS, TE_RISING);
2999 * Executes #CMD_START_STOP_VEHICLE for given vehicle.
3000 * @param v Vehicle to start/stop
3001 * @param texteffect Should a texteffect be shown?
3003 void StartStopVehicle(const Vehicle *v, bool texteffect)
3005 assert(v->IsPrimaryVehicle());
3006 Command<CMD_START_STOP_VEHICLE>::Post(_vehicle_msg_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : nullptr, v->tile, v->index, false);
3009 /** Checks whether the vehicle may be refitted at the moment.*/
3010 static bool IsVehicleRefitable(const Vehicle *v)
3012 if (!v->IsStoppedInDepot()) return false;
3014 do {
3015 if (IsEngineRefittable(v->engine_type)) return true;
3016 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
3018 return false;
3021 /** Window manager class for viewing a vehicle. */
3022 struct VehicleViewWindow : Window {
3023 private:
3024 /** Display planes available in the vehicle view window. */
3025 enum PlaneSelections {
3026 SEL_DC_GOTO_DEPOT, ///< Display 'goto depot' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
3027 SEL_DC_CLONE, ///< Display 'clone vehicle' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
3029 SEL_RT_REFIT, ///< Display 'refit' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
3030 SEL_RT_TURN_AROUND, ///< Display 'turn around' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
3032 SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, ///< First plane of the #WID_VV_SELECT_DEPOT_CLONE stacked widget.
3033 SEL_RT_BASEPLANE = SEL_RT_REFIT, ///< First plane of the #WID_VV_SELECT_REFIT_TURN stacked widget.
3035 bool mouse_over_start_stop = false;
3038 * Display a plane in the window.
3039 * @param plane Plane to show.
3041 void SelectPlane(PlaneSelections plane)
3043 switch (plane) {
3044 case SEL_DC_GOTO_DEPOT:
3045 case SEL_DC_CLONE:
3046 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
3047 break;
3049 case SEL_RT_REFIT:
3050 case SEL_RT_TURN_AROUND:
3051 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
3052 break;
3054 default:
3055 NOT_REACHED();
3059 public:
3060 VehicleViewWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc)
3062 this->flags |= WF_DISABLE_VP_SCROLL;
3063 this->CreateNestedTree();
3065 /* Sprites for the 'send to depot' button indexed by vehicle type. */
3066 static const SpriteID vehicle_view_goto_depot_sprites[] = {
3067 SPR_SEND_TRAIN_TODEPOT,
3068 SPR_SEND_ROADVEH_TODEPOT,
3069 SPR_SEND_SHIP_TODEPOT,
3070 SPR_SEND_AIRCRAFT_TODEPOT,
3072 const Vehicle *v = Vehicle::Get(window_number);
3073 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
3075 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
3076 static const SpriteID vehicle_view_clone_sprites[] = {
3077 SPR_CLONE_TRAIN,
3078 SPR_CLONE_ROADVEH,
3079 SPR_CLONE_SHIP,
3080 SPR_CLONE_AIRCRAFT,
3082 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
3084 switch (v->type) {
3085 case VEH_TRAIN:
3086 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
3087 break;
3089 case VEH_ROAD:
3090 break;
3092 case VEH_SHIP:
3093 case VEH_AIRCRAFT:
3094 this->SelectPlane(SEL_RT_REFIT);
3095 break;
3097 default: NOT_REACHED();
3099 this->FinishInitNested(window_number);
3100 this->owner = v->owner;
3101 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, static_cast<VehicleID>(this->window_number), ScaleZoomGUI(_vehicle_view_zoom_levels[v->type]));
3103 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip = STR_VEHICLE_VIEW_TRAIN_STATUS_START_STOP_TOOLTIP + v->type;
3104 this->GetWidget<NWidgetCore>(WID_VV_RENAME)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
3105 this->GetWidget<NWidgetCore>(WID_VV_LOCATION)->tool_tip = STR_VEHICLE_VIEW_TRAIN_CENTER_TOOLTIP + v->type;
3106 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
3107 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
3108 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
3109 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
3110 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
3112 this->UpdateButtonStatus();
3115 void Close([[maybe_unused]] int data = 0) override
3117 CloseWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
3118 CloseWindowById(WC_VEHICLE_REFIT, this->window_number, false);
3119 CloseWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
3120 CloseWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
3121 this->Window::Close();
3124 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
3126 const Vehicle *v = Vehicle::Get(this->window_number);
3127 switch (widget) {
3128 case WID_VV_START_STOP:
3129 size.height = std::max<uint>({size.height, (uint)GetCharacterHeight(FS_NORMAL), GetScaledSpriteSize(SPR_WARNING_SIGN).height, GetScaledSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetScaledSpriteSize(SPR_FLAG_VEH_RUNNING).height}) + padding.height;
3130 break;
3132 case WID_VV_FORCE_PROCEED:
3133 if (v->type != VEH_TRAIN) {
3134 size.height = 0;
3135 size.width = 0;
3137 break;
3139 case WID_VV_VIEWPORT:
3140 size.width = VV_INITIAL_VIEWPORT_WIDTH;
3141 size.height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
3142 break;
3146 void OnPaint() override
3148 const Vehicle *v = Vehicle::Get(this->window_number);
3149 bool is_localcompany = v->owner == _local_company;
3150 bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
3152 this->SetWidgetDisabledState(WID_VV_RENAME, !is_localcompany);
3153 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
3154 this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
3155 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
3157 if (v->type == VEH_TRAIN) {
3158 this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
3159 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
3162 if (v->type == VEH_TRAIN || v->type == VEH_ROAD) {
3163 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
3166 this->SetWidgetDisabledState(WID_VV_ORDER_LOCATION, v->current_order.GetLocation(v) == INVALID_TILE);
3168 this->DrawWidgets();
3171 void SetStringParameters(WidgetID widget) const override
3173 if (widget != WID_VV_CAPTION) return;
3175 const Vehicle *v = Vehicle::Get(this->window_number);
3176 SetDParam(0, v->index);
3179 void DrawWidget(const Rect &r, WidgetID widget) const override
3181 if (widget != WID_VV_START_STOP) return;
3183 Vehicle *v = Vehicle::Get(this->window_number);
3184 StringID str;
3185 TextColour text_colour = TC_FROMSTRING;
3186 if (v->vehstatus & VS_CRASHED) {
3187 str = STR_VEHICLE_STATUS_CRASHED;
3188 } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
3189 str = STR_VEHICLE_STATUS_BROKEN_DOWN;
3190 } else if (v->vehstatus & VS_STOPPED && (!mouse_over_start_stop || v->IsStoppedInDepot())) {
3191 if (v->type == VEH_TRAIN) {
3192 if (v->cur_speed == 0) {
3193 if (Train::From(v)->gcache.cached_power == 0) {
3194 str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
3195 } else {
3196 str = STR_VEHICLE_STATUS_STOPPED;
3198 } else {
3199 SetDParam(0, PackVelocity(v->GetDisplaySpeed(), v->type));
3200 str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
3202 } else { // no train
3203 str = STR_VEHICLE_STATUS_STOPPED;
3205 } else if (v->IsInDepot() && v->IsWaitingForUnbunching()) {
3206 str = STR_VEHICLE_STATUS_WAITING_UNBUNCHING;
3207 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
3208 str = STR_VEHICLE_STATUS_TRAIN_STUCK;
3209 } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
3210 str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
3211 } else { // vehicle is in a "normal" state, show current order
3212 if (mouse_over_start_stop) {
3213 if (v->vehstatus & VS_STOPPED) {
3214 text_colour = TC_RED | TC_FORCED;
3215 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
3216 text_colour = TC_ORANGE | TC_FORCED;
3219 switch (v->current_order.GetType()) {
3220 case OT_GOTO_STATION: {
3221 SetDParam(0, v->current_order.GetDestination());
3222 SetDParam(1, PackVelocity(v->GetDisplaySpeed(), v->type));
3223 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_STATION_VEL : STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
3224 break;
3227 case OT_GOTO_DEPOT: {
3228 SetDParam(0, v->type);
3229 SetDParam(1, v->current_order.GetDestination());
3230 SetDParam(2, PackVelocity(v->GetDisplaySpeed(), v->type));
3231 if (v->current_order.GetDestination() == INVALID_DEPOT) {
3232 /* This case *only* happens when multiple nearest depot orders
3233 * follow each other (including an order list only one order: a
3234 * nearest depot order) and there are no reachable depots.
3235 * It is primarily to guard for the case that there is no
3236 * depot with index 0, which would be used as fallback for
3237 * evaluating the string in the status bar. */
3238 str = STR_EMPTY;
3239 } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
3240 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
3241 } else if (v->current_order.GetDepotActionType() & ODATFB_UNBUNCH) {
3242 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_SERVICE_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_UNBUNCH_VEL;
3243 } else {
3244 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_SERVICE_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
3246 break;
3249 case OT_LOADING:
3250 str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
3251 break;
3253 case OT_GOTO_WAYPOINT: {
3254 assert(v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP);
3255 SetDParam(0, v->current_order.GetDestination());
3256 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_WAYPOINT_VEL : STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
3257 SetDParam(1, PackVelocity(v->GetDisplaySpeed(), v->type));
3258 break;
3261 case OT_LEAVESTATION:
3262 if (v->type != VEH_AIRCRAFT) {
3263 str = STR_VEHICLE_STATUS_LEAVING;
3264 break;
3266 [[fallthrough]];
3267 default:
3268 if (v->GetNumManualOrders() == 0) {
3269 str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
3270 SetDParam(0, PackVelocity(v->GetDisplaySpeed(), v->type));
3271 } else {
3272 str = STR_EMPTY;
3274 break;
3278 /* Draw the flag plus orders. */
3279 bool rtl = (_current_text_dir == TD_RTL);
3280 uint icon_width = std::max({GetScaledSpriteSize(SPR_WARNING_SIGN).width, GetScaledSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetScaledSpriteSize(SPR_FLAG_VEH_RUNNING).width});
3281 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
3282 SpriteID image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : (HasBit(v->vehicle_flags, VF_PATHFINDER_LOST)) ? SPR_WARNING_SIGN : SPR_FLAG_VEH_RUNNING;
3283 DrawSpriteIgnorePadding(image, PAL_NONE, tr.WithWidth(icon_width, rtl), SA_CENTER);
3284 tr = tr.Indent(icon_width + WidgetDimensions::scaled.imgbtn.Horizontal(), rtl);
3285 DrawString(tr.left, tr.right, CenterBounds(tr.top, tr.bottom, GetCharacterHeight(FS_NORMAL)), str, text_colour, SA_HOR_CENTER);
3288 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
3290 const Vehicle *v = Vehicle::Get(this->window_number);
3292 switch (widget) {
3293 case WID_VV_RENAME: { // rename
3294 SetDParam(0, v->index);
3295 ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
3296 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
3297 break;
3300 case WID_VV_START_STOP: // start stop
3301 StartStopVehicle(v, false);
3302 break;
3304 case WID_VV_ORDER_LOCATION: {
3305 /* Scroll to current order destination */
3306 TileIndex tile = v->current_order.GetLocation(v);
3307 if (tile == INVALID_TILE) break;
3309 if (_ctrl_pressed) {
3310 ShowExtraViewportWindow(tile);
3311 } else {
3312 ScrollMainWindowToTile(tile);
3314 break;
3317 case WID_VV_LOCATION: // center main view
3318 if (_ctrl_pressed) {
3319 ShowExtraViewportWindow(TileVirtXY(v->x_pos, v->y_pos));
3320 } else {
3321 const Window *mainwindow = GetMainWindow();
3322 if (click_count > 1) {
3323 /* main window 'follows' vehicle */
3324 mainwindow->viewport->follow_vehicle = v->index;
3325 } else {
3326 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
3329 break;
3331 case WID_VV_GOTO_DEPOT: // goto hangar
3332 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Post(GetCmdSendToDepotMsg(v), v->index, _ctrl_pressed ? DepotCommand::Service : DepotCommand::None, {});
3333 break;
3334 case WID_VV_REFIT: // refit
3335 ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
3336 break;
3337 case WID_VV_SHOW_ORDERS: // show orders
3338 if (_ctrl_pressed) {
3339 ShowTimetableWindow(v);
3340 } else {
3341 ShowOrdersWindow(v);
3343 break;
3344 case WID_VV_SHOW_DETAILS: // show details
3345 if (_ctrl_pressed) {
3346 ShowCompanyGroupForVehicle(v);
3347 } else {
3348 ShowVehicleDetailsWindow(v);
3350 break;
3351 case WID_VV_CLONE: // clone vehicle
3352 /* Suppress the vehicle GUI when share-cloning.
3353 * There is no point to it except for starting the vehicle.
3354 * For starting the vehicle the player has to open the depot GUI, which is
3355 * most likely already open, but is also visible in the vehicle viewport. */
3356 Command<CMD_CLONE_VEHICLE>::Post(_vehicle_msg_translation_table[VCT_CMD_CLONE_VEH][v->type],
3357 _ctrl_pressed ? nullptr : CcCloneVehicle,
3358 v->tile, v->index, _ctrl_pressed);
3359 break;
3360 case WID_VV_TURN_AROUND: // turn around
3361 assert(v->IsGroundVehicle());
3362 if (v->type == VEH_ROAD) {
3363 Command<CMD_TURN_ROADVEH>::Post(_vehicle_msg_translation_table[VCT_CMD_TURN_AROUND][v->type], v->tile, v->index);
3364 } else {
3365 Command<CMD_REVERSE_TRAIN_DIRECTION>::Post(_vehicle_msg_translation_table[VCT_CMD_TURN_AROUND][v->type], v->tile, v->index, false);
3367 break;
3368 case WID_VV_FORCE_PROCEED: // force proceed
3369 assert(v->type == VEH_TRAIN);
3370 Command<CMD_FORCE_TRAIN_PROCEED>::Post(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL, v->tile, v->index);
3371 break;
3375 EventState OnHotkey(int hotkey) override
3377 /* If the hotkey is not for any widget in the UI (i.e. for honking) */
3378 if (hotkey == WID_VV_HONK_HORN) {
3379 const Window *mainwindow = GetMainWindow();
3380 const Vehicle *v = Vehicle::Get(window_number);
3381 /* Only play the sound if we're following this vehicle */
3382 if (mainwindow->viewport->follow_vehicle == v->index) {
3383 v->PlayLeaveStationSound(true);
3386 return Window::OnHotkey(hotkey);
3389 void OnQueryTextFinished(std::optional<std::string> str) override
3391 if (!str.has_value()) return;
3393 Command<CMD_RENAME_VEHICLE>::Post(STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(this->window_number)->type, this->window_number, *str);
3396 void OnMouseOver([[maybe_unused]] Point pt, WidgetID widget) override
3398 bool start_stop = widget == WID_VV_START_STOP;
3399 if (start_stop != mouse_over_start_stop) {
3400 mouse_over_start_stop = start_stop;
3401 this->SetWidgetDirty(WID_VV_START_STOP);
3405 void OnMouseWheel(int wheel) override
3407 if (_settings_client.gui.scrollwheel_scrolling != SWS_OFF) {
3408 DoZoomInOutWindow(wheel < 0 ? ZOOM_IN : ZOOM_OUT, this);
3412 void OnResize() override
3414 if (this->viewport != nullptr) {
3415 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
3416 nvp->UpdateViewportCoordinates(this);
3420 void UpdateButtonStatus()
3422 const Vehicle *v = Vehicle::Get(this->window_number);
3423 bool veh_stopped = v->IsStoppedInDepot();
3425 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
3426 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
3428 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
3429 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
3430 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
3431 this->SelectPlane(plane);
3432 this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
3434 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
3435 if (v->IsGroundVehicle()) {
3436 plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
3437 nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
3438 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
3439 this->SelectPlane(plane);
3440 this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
3446 * Some data on this window has become invalid.
3447 * @param data Information about the changed data.
3448 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
3450 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
3452 if (data == VIWD_AUTOREPLACE) {
3453 /* Autoreplace replaced the vehicle.
3454 * Nothing to do for this window. */
3455 return;
3458 this->UpdateButtonStatus();
3461 bool IsNewGRFInspectable() const override
3463 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3466 void ShowNewGRFInspectWindow() const override
3468 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3471 static inline HotkeyList hotkeys{"vehicleview", {
3472 Hotkey('H', "honk", WID_VV_HONK_HORN),
3476 /** Vehicle view window descriptor for all vehicles but trains. */
3477 static WindowDesc _vehicle_view_desc(
3478 WDP_AUTO, "view_vehicle", 250, 116,
3479 WC_VEHICLE_VIEW, WC_NONE,
3481 _nested_vehicle_view_widgets,
3482 &VehicleViewWindow::hotkeys
3486 * Vehicle view window descriptor for trains. Only minimum_height and
3487 * default_height are different for train view.
3489 static WindowDesc _train_view_desc(
3490 WDP_AUTO, "view_vehicle_train", 250, 134,
3491 WC_VEHICLE_VIEW, WC_NONE,
3493 _nested_vehicle_view_widgets,
3494 &VehicleViewWindow::hotkeys
3497 /** Shows the vehicle view window of the given vehicle. */
3498 void ShowVehicleViewWindow(const Vehicle *v)
3500 AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? _train_view_desc : _vehicle_view_desc, v->index);
3504 * Dispatch a "vehicle selected" event if any window waits for it.
3505 * @param v selected vehicle;
3506 * @return did any window accept vehicle selection?
3508 bool VehicleClicked(const Vehicle *v)
3510 assert(v != nullptr);
3511 if (!(_thd.place_mode & HT_VEHICLE)) return false;
3513 v = v->First();
3514 if (!v->IsPrimaryVehicle()) return false;
3516 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
3520 * Dispatch a "vehicle group selected" event if any window waits for it.
3521 * @param begin iterator to the start of the range of vehicles
3522 * @param end iterator to the end of the range of vehicles
3523 * @return did any window accept vehicle group selection?
3525 bool VehicleClicked(VehicleList::const_iterator begin, VehicleList::const_iterator end)
3527 assert(begin != end);
3528 if (!(_thd.place_mode & HT_VEHICLE)) return false;
3530 /* If there is only one vehicle in the group, act as if we clicked a single vehicle */
3531 if (begin + 1 == end) return _thd.GetCallbackWnd()->OnVehicleSelect(*begin);
3533 return _thd.GetCallbackWnd()->OnVehicleSelect(begin, end);
3537 * Dispatch a "vehicle group selected" event if any window waits for it.
3538 * @param vehgroup the GUIVehicleGroup representing the vehicle group
3539 * @return did any window accept vehicle group selection?
3541 bool VehicleClicked(const GUIVehicleGroup &vehgroup)
3543 return VehicleClicked(vehgroup.vehicles_begin, vehgroup.vehicles_end);
3546 void StopGlobalFollowVehicle(const Vehicle *v)
3548 Window *w = GetMainWindow();
3549 if (w->viewport->follow_vehicle == v->index) {
3550 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
3551 w->viewport->follow_vehicle = INVALID_VEHICLE;
3557 * This is the Callback method after the construction attempt of a primary vehicle
3558 * @param result indicates completion (or not) of the operation
3559 * @param new_veh_id ID of the new vehicle.
3561 void CcBuildPrimaryVehicle(Commands, const CommandCost &result, VehicleID new_veh_id, uint, uint16_t, CargoArray)
3563 if (result.Failed()) return;
3565 const Vehicle *v = Vehicle::Get(new_veh_id);
3566 ShowVehicleViewWindow(v);
3570 * Get the width of a vehicle (part) in pixels.
3571 * @param v Vehicle to get the width for.
3572 * @return Width of the vehicle.
3574 int GetSingleVehicleWidth(const Vehicle *v, EngineImageType image_type)
3576 switch (v->type) {
3577 case VEH_TRAIN:
3578 return Train::From(v)->GetDisplayImageWidth();
3580 case VEH_ROAD:
3581 return RoadVehicle::From(v)->GetDisplayImageWidth();
3583 default:
3584 bool rtl = _current_text_dir == TD_RTL;
3585 VehicleSpriteSeq seq;
3586 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
3587 Rect rec;
3588 seq.GetBounds(&rec);
3589 return UnScaleGUI(rec.Width());
3594 * Get the width of a vehicle (including all parts of the consist) in pixels.
3595 * @param v Vehicle to get the width for.
3596 * @return Width of the vehicle.
3598 int GetVehicleWidth(const Vehicle *v, EngineImageType image_type)
3600 if (v->type == VEH_TRAIN || v->type == VEH_ROAD) {
3601 int vehicle_width = 0;
3602 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
3603 vehicle_width += GetSingleVehicleWidth(u, image_type);
3605 return vehicle_width;
3606 } else {
3607 return GetSingleVehicleWidth(v, image_type);
3612 * Set the mouse cursor to look like a vehicle.
3613 * @param v Vehicle
3614 * @param image_type Type of vehicle image to use.
3616 void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type)
3618 bool rtl = _current_text_dir == TD_RTL;
3620 _cursor.sprites.clear();
3621 int total_width = 0;
3622 int y_offset = 0;
3623 bool rotor_seq = false; // Whether to draw the rotor of the vehicle in this step.
3624 bool is_ground_vehicle = v->IsGroundVehicle();
3626 while (v != nullptr) {
3627 if (total_width >= ScaleSpriteTrad(2 * (int)VEHICLEINFO_FULL_VEHICLE_WIDTH)) break;
3629 PaletteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
3630 VehicleSpriteSeq seq;
3632 if (rotor_seq) {
3633 GetCustomRotorSprite(Aircraft::From(v), image_type, &seq);
3634 if (!seq.IsValid()) seq.Set(SPR_ROTOR_STOPPED);
3635 y_offset = -ScaleSpriteTrad(5);
3636 } else {
3637 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
3640 int x_offs = 0;
3641 if (v->type == VEH_TRAIN) x_offs = Train::From(v)->GetCursorImageOffset();
3643 for (uint i = 0; i < seq.count; ++i) {
3644 PaletteID pal2 = (v->vehstatus & VS_CRASHED) || !seq.seq[i].pal ? pal : seq.seq[i].pal;
3645 _cursor.sprites.emplace_back(seq.seq[i].sprite, pal2, rtl ? (-total_width + x_offs) : (total_width + x_offs), y_offset);
3648 if (v->type == VEH_AIRCRAFT && v->subtype == AIR_HELICOPTER && !rotor_seq) {
3649 /* Draw rotor part in the next step. */
3650 rotor_seq = true;
3651 } else {
3652 total_width += GetSingleVehicleWidth(v, image_type);
3653 v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr;
3657 if (is_ground_vehicle) {
3658 /* Center trains and road vehicles on the front vehicle */
3659 int offs = (ScaleSpriteTrad(VEHICLEINFO_FULL_VEHICLE_WIDTH) - total_width) / 2;
3660 if (rtl) offs = -offs;
3661 for (auto &cs : _cursor.sprites) {
3662 cs.pos.x += offs;
3666 UpdateCursorSize();