Codechange: Use cached town, station, industry names for list window sorting
[openttd-github.git] / src / build_vehicle_gui.cpp
blobc3252f7b9e414d2b1055c5e23e55653c0fdc0e38
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 build_vehicle_gui.cpp GUI for building vehicles. */
10 #include "stdafx.h"
11 #include "engine_base.h"
12 #include "engine_func.h"
13 #include "station_base.h"
14 #include "network/network.h"
15 #include "articulated_vehicles.h"
16 #include "textbuf_gui.h"
17 #include "command_func.h"
18 #include "company_func.h"
19 #include "vehicle_gui.h"
20 #include "newgrf_engine.h"
21 #include "newgrf_text.h"
22 #include "group.h"
23 #include "string_func.h"
24 #include "strings_func.h"
25 #include "window_func.h"
26 #include "date_func.h"
27 #include "vehicle_func.h"
28 #include "widgets/dropdown_func.h"
29 #include "engine_gui.h"
30 #include "cargotype.h"
31 #include "core/geometry_func.hpp"
32 #include "autoreplace_func.h"
34 #include "widgets/build_vehicle_widget.h"
36 #include "table/strings.h"
38 #include "safeguards.h"
40 /**
41 * Get the height of a single 'entry' in the engine lists.
42 * @param type the vehicle type to get the height of
43 * @return the height for the entry
45 uint GetEngineListHeight(VehicleType type)
47 return max<uint>(FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM, GetVehicleImageCellSize(type, EIT_PURCHASE).height);
50 static const NWidgetPart _nested_build_vehicle_widgets[] = {
51 NWidget(NWID_HORIZONTAL),
52 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
53 NWidget(WWT_CAPTION, COLOUR_GREY, WID_BV_CAPTION), SetDataTip(STR_WHITE_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
54 NWidget(WWT_SHADEBOX, COLOUR_GREY),
55 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
56 NWidget(WWT_STICKYBOX, COLOUR_GREY),
57 EndContainer(),
58 NWidget(WWT_PANEL, COLOUR_GREY),
59 NWidget(NWID_VERTICAL),
60 NWidget(NWID_HORIZONTAL),
61 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_SORT_ASCENDING_DESCENDING), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
62 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_BV_SORT_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
63 EndContainer(),
64 NWidget(NWID_HORIZONTAL),
65 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BV_SHOW_HIDDEN_ENGINES),
66 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_BV_CARGO_FILTER_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_FILTER_CRITERIA),
67 EndContainer(),
68 EndContainer(),
69 EndContainer(),
70 /* Vehicle list. */
71 NWidget(NWID_HORIZONTAL),
72 NWidget(WWT_MATRIX, COLOUR_GREY, WID_BV_LIST), SetResize(1, 1), SetFill(1, 0), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_BV_SCROLLBAR),
73 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_BV_SCROLLBAR),
74 EndContainer(),
75 /* Panel with details. */
76 NWidget(WWT_PANEL, COLOUR_GREY, WID_BV_PANEL), SetMinimalSize(240, 122), SetResize(1, 0), EndContainer(),
77 /* Build/rename buttons, resize button. */
78 NWidget(NWID_HORIZONTAL),
79 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_BV_BUILD_SEL),
80 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_BUILD), SetResize(1, 0), SetFill(1, 0),
81 EndContainer(),
82 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_SHOW_HIDE), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
83 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_BV_RENAME), SetResize(1, 0), SetFill(1, 0),
84 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
85 EndContainer(),
88 /** Special cargo filter criteria */
89 static const CargoID CF_ANY = CT_NO_REFIT; ///< Show all vehicles independent of carried cargo (i.e. no filtering)
90 static const CargoID CF_NONE = CT_INVALID; ///< Show only vehicles which do not carry cargo (e.g. train engines)
92 bool _engine_sort_direction; ///< \c false = descending, \c true = ascending.
93 byte _engine_sort_last_criteria[] = {0, 0, 0, 0}; ///< Last set sort criteria, for each vehicle type.
94 bool _engine_sort_last_order[] = {false, false, false, false}; ///< Last set direction of the sort order, for each vehicle type.
95 bool _engine_sort_show_hidden_engines[] = {false, false, false, false}; ///< Last set 'show hidden engines' setting for each vehicle type.
96 static CargoID _engine_sort_last_cargo_criteria[] = {CF_ANY, CF_ANY, CF_ANY, CF_ANY}; ///< Last set filter criteria, for each vehicle type.
98 /**
99 * Determines order of engines by engineID
100 * @param a first engine to compare
101 * @param b second engine to compare
102 * @return for descending order: returns true if a < b. Vice versa for ascending order
104 static bool EngineNumberSorter(const EngineID &a, const EngineID &b)
106 int r = Engine::Get(a)->list_position - Engine::Get(b)->list_position;
108 return _engine_sort_direction ? r > 0 : r < 0;
112 * Determines order of engines by introduction date
113 * @param a first engine to compare
114 * @param b second engine to compare
115 * @return for descending order: returns true if a < b. Vice versa for ascending order
117 static bool EngineIntroDateSorter(const EngineID &a, const EngineID &b)
119 const int va = Engine::Get(a)->intro_date;
120 const int vb = Engine::Get(b)->intro_date;
121 const int r = va - vb;
123 /* Use EngineID to sort instead since we want consistent sorting */
124 if (r == 0) return EngineNumberSorter(a, b);
125 return _engine_sort_direction ? r > 0 : r < 0;
129 * Determines order of engines by name
130 * @param a first engine to compare
131 * @param b second engine to compare
132 * @return for descending order: returns true if a < b. Vice versa for ascending order
134 static bool EngineNameSorter(const EngineID &a, const EngineID &b)
136 static EngineID last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE };
137 static char last_name[2][64] = { "\0", "\0" };
139 if (a != last_engine[0]) {
140 last_engine[0] = a;
141 SetDParam(0, a);
142 GetString(last_name[0], STR_ENGINE_NAME, lastof(last_name[0]));
145 if (b != last_engine[1]) {
146 last_engine[1] = b;
147 SetDParam(0, b);
148 GetString(last_name[1], STR_ENGINE_NAME, lastof(last_name[1]));
151 int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
153 /* Use EngineID to sort instead since we want consistent sorting */
154 if (r == 0) return EngineNumberSorter(a, b);
155 return _engine_sort_direction ? r > 0 : r < 0;
159 * Determines order of engines by reliability
160 * @param a first engine to compare
161 * @param b second engine to compare
162 * @return for descending order: returns true if a < b. Vice versa for ascending order
164 static bool EngineReliabilitySorter(const EngineID &a, const EngineID &b)
166 const int va = Engine::Get(a)->reliability;
167 const int vb = Engine::Get(b)->reliability;
168 const int r = va - vb;
170 /* Use EngineID to sort instead since we want consistent sorting */
171 if (r == 0) return EngineNumberSorter(a, b);
172 return _engine_sort_direction ? r > 0 : r < 0;
176 * Determines order of engines by purchase cost
177 * @param a first engine to compare
178 * @param b second engine to compare
179 * @return for descending order: returns true if a < b. Vice versa for ascending order
181 static bool EngineCostSorter(const EngineID &a, const EngineID &b)
183 Money va = Engine::Get(a)->GetCost();
184 Money vb = Engine::Get(b)->GetCost();
185 int r = ClampToI32(va - vb);
187 /* Use EngineID to sort instead since we want consistent sorting */
188 if (r == 0) return EngineNumberSorter(a, b);
189 return _engine_sort_direction ? r > 0 : r < 0;
193 * Determines order of engines by speed
194 * @param a first engine to compare
195 * @param b second engine to compare
196 * @return for descending order: returns true if a < b. Vice versa for ascending order
198 static bool EngineSpeedSorter(const EngineID &a, const EngineID &b)
200 int va = Engine::Get(a)->GetDisplayMaxSpeed();
201 int vb = Engine::Get(b)->GetDisplayMaxSpeed();
202 int r = va - vb;
204 /* Use EngineID to sort instead since we want consistent sorting */
205 if (r == 0) return EngineNumberSorter(a, b);
206 return _engine_sort_direction ? r > 0 : r < 0;
210 * Determines order of engines by power
211 * @param a first engine to compare
212 * @param b second engine to compare
213 * @return for descending order: returns true if a < b. Vice versa for ascending order
215 static bool EnginePowerSorter(const EngineID &a, const EngineID &b)
217 int va = Engine::Get(a)->GetPower();
218 int vb = Engine::Get(b)->GetPower();
219 int r = va - vb;
221 /* Use EngineID to sort instead since we want consistent sorting */
222 if (r == 0) return EngineNumberSorter(a, b);
223 return _engine_sort_direction ? r > 0 : r < 0;
227 * Determines order of engines by tractive effort
228 * @param a first engine to compare
229 * @param b second engine to compare
230 * @return for descending order: returns true if a < b. Vice versa for ascending order
232 static bool EngineTractiveEffortSorter(const EngineID &a, const EngineID &b)
234 int va = Engine::Get(a)->GetDisplayMaxTractiveEffort();
235 int vb = Engine::Get(b)->GetDisplayMaxTractiveEffort();
236 int r = va - vb;
238 /* Use EngineID to sort instead since we want consistent sorting */
239 if (r == 0) return EngineNumberSorter(a, b);
240 return _engine_sort_direction ? r > 0 : r < 0;
244 * Determines order of engines by running costs
245 * @param a first engine to compare
246 * @param b second engine to compare
247 * @return for descending order: returns true if a < b. Vice versa for ascending order
249 static bool EngineRunningCostSorter(const EngineID &a, const EngineID &b)
251 Money va = Engine::Get(a)->GetRunningCost();
252 Money vb = Engine::Get(b)->GetRunningCost();
253 int r = ClampToI32(va - vb);
255 /* Use EngineID to sort instead since we want consistent sorting */
256 if (r == 0) return EngineNumberSorter(a, b);
257 return _engine_sort_direction ? r > 0 : r < 0;
261 * Determines order of engines by running costs
262 * @param a first engine to compare
263 * @param b second engine to compare
264 * @return for descending order: returns true if a < b. Vice versa for ascending order
266 static bool EnginePowerVsRunningCostSorter(const EngineID &a, const EngineID &b)
268 const Engine *e_a = Engine::Get(a);
269 const Engine *e_b = Engine::Get(b);
270 uint p_a = e_a->GetPower();
271 uint p_b = e_b->GetPower();
272 Money r_a = e_a->GetRunningCost();
273 Money r_b = e_b->GetRunningCost();
274 /* Check if running cost is zero in one or both engines.
275 * If only one of them is zero then that one has higher value,
276 * else if both have zero cost then compare powers. */
277 if (r_a == 0) {
278 if (r_b == 0) {
279 /* If it is ambiguous which to return go with their ID */
280 if (p_a == p_b) return EngineNumberSorter(a, b);
281 return _engine_sort_direction != (p_a < p_b);
283 return !_engine_sort_direction;
285 if (r_b == 0) return _engine_sort_direction;
286 /* Using double for more precision when comparing close values.
287 * This shouldn't have any major effects in performance nor in keeping
288 * the game in sync between players since it's used in GUI only in client side */
289 double v_a = (double)p_a / (double)r_a;
290 double v_b = (double)p_b / (double)r_b;
291 /* Use EngineID to sort if both have same power/running cost,
292 * since we want consistent sorting.
293 * Also if both have no power then sort with reverse of running cost to simulate
294 * previous sorting behaviour for wagons. */
295 if (v_a == 0 && v_b == 0) return !EngineRunningCostSorter(a, b);
296 if (v_a == v_b) return EngineNumberSorter(a, b);
297 return _engine_sort_direction != (v_a < v_b);
300 /* Train sorting functions */
303 * Determines order of train engines by capacity
304 * @param a first engine to compare
305 * @param b second engine to compare
306 * @return for descending order: returns true if a < b. Vice versa for ascending order
308 static bool TrainEngineCapacitySorter(const EngineID &a, const EngineID &b)
310 const RailVehicleInfo *rvi_a = RailVehInfo(a);
311 const RailVehicleInfo *rvi_b = RailVehInfo(b);
313 int va = GetTotalCapacityOfArticulatedParts(a) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
314 int vb = GetTotalCapacityOfArticulatedParts(b) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
315 int r = va - vb;
317 /* Use EngineID to sort instead since we want consistent sorting */
318 if (r == 0) return EngineNumberSorter(a, b);
319 return _engine_sort_direction ? r > 0 : r < 0;
323 * Determines order of train engines by engine / wagon
324 * @param a first engine to compare
325 * @param b second engine to compare
326 * @return for descending order: returns true if a < b. Vice versa for ascending order
328 static bool TrainEnginesThenWagonsSorter(const EngineID &a, const EngineID &b)
330 int val_a = (RailVehInfo(a)->railveh_type == RAILVEH_WAGON ? 1 : 0);
331 int val_b = (RailVehInfo(b)->railveh_type == RAILVEH_WAGON ? 1 : 0);
332 int r = val_a - val_b;
334 /* Use EngineID to sort instead since we want consistent sorting */
335 if (r == 0) return EngineNumberSorter(a, b);
336 return _engine_sort_direction ? r > 0 : r < 0;
339 /* Road vehicle sorting functions */
342 * Determines order of road vehicles by capacity
343 * @param a first engine to compare
344 * @param b second engine to compare
345 * @return for descending order: returns true if a < b. Vice versa for ascending order
347 static bool RoadVehEngineCapacitySorter(const EngineID &a, const EngineID &b)
349 int va = GetTotalCapacityOfArticulatedParts(a);
350 int vb = GetTotalCapacityOfArticulatedParts(b);
351 int r = va - vb;
353 /* Use EngineID to sort instead since we want consistent sorting */
354 if (r == 0) return EngineNumberSorter(a, b);
355 return _engine_sort_direction ? r > 0 : r < 0;
358 /* Ship vehicle sorting functions */
361 * Determines order of ships by capacity
362 * @param a first engine to compare
363 * @param b second engine to compare
364 * @return for descending order: returns true if a < b. Vice versa for ascending order
366 static bool ShipEngineCapacitySorter(const EngineID &a, const EngineID &b)
368 const Engine *e_a = Engine::Get(a);
369 const Engine *e_b = Engine::Get(b);
371 int va = e_a->GetDisplayDefaultCapacity();
372 int vb = e_b->GetDisplayDefaultCapacity();
373 int r = va - vb;
375 /* Use EngineID to sort instead since we want consistent sorting */
376 if (r == 0) return EngineNumberSorter(a, b);
377 return _engine_sort_direction ? r > 0 : r < 0;
380 /* Aircraft sorting functions */
383 * Determines order of aircraft by cargo
384 * @param a first engine to compare
385 * @param b second engine to compare
386 * @return for descending order: returns true if a < b. Vice versa for ascending order
388 static bool AircraftEngineCargoSorter(const EngineID &a, const EngineID &b)
390 const Engine *e_a = Engine::Get(a);
391 const Engine *e_b = Engine::Get(b);
393 uint16 mail_a, mail_b;
394 int va = e_a->GetDisplayDefaultCapacity(&mail_a);
395 int vb = e_b->GetDisplayDefaultCapacity(&mail_b);
396 int r = va - vb;
398 if (r == 0) {
399 /* The planes have the same passenger capacity. Check mail capacity instead */
400 r = mail_a - mail_b;
402 if (r == 0) {
403 /* Use EngineID to sort instead since we want consistent sorting */
404 return EngineNumberSorter(a, b);
407 return _engine_sort_direction ? r > 0 : r < 0;
411 * Determines order of aircraft by range.
412 * @param a first engine to compare
413 * @param b second engine to compare
414 * @return for descending order: returns true if a < b. Vice versa for ascending order
416 static bool AircraftRangeSorter(const EngineID &a, const EngineID &b)
418 uint16 r_a = Engine::Get(a)->GetRange();
419 uint16 r_b = Engine::Get(b)->GetRange();
421 int r = r_a - r_b;
423 /* Use EngineID to sort instead since we want consistent sorting */
424 if (r == 0) return EngineNumberSorter(a, b);
425 return _engine_sort_direction ? r > 0 : r < 0;
428 /** Sort functions for the vehicle sort criteria, for each vehicle type. */
429 EngList_SortTypeFunction * const _engine_sort_functions[][11] = {{
430 /* Trains */
431 &EngineNumberSorter,
432 &EngineCostSorter,
433 &EngineSpeedSorter,
434 &EnginePowerSorter,
435 &EngineTractiveEffortSorter,
436 &EngineIntroDateSorter,
437 &EngineNameSorter,
438 &EngineRunningCostSorter,
439 &EnginePowerVsRunningCostSorter,
440 &EngineReliabilitySorter,
441 &TrainEngineCapacitySorter,
442 }, {
443 /* Road vehicles */
444 &EngineNumberSorter,
445 &EngineCostSorter,
446 &EngineSpeedSorter,
447 &EnginePowerSorter,
448 &EngineTractiveEffortSorter,
449 &EngineIntroDateSorter,
450 &EngineNameSorter,
451 &EngineRunningCostSorter,
452 &EnginePowerVsRunningCostSorter,
453 &EngineReliabilitySorter,
454 &RoadVehEngineCapacitySorter,
455 }, {
456 /* Ships */
457 &EngineNumberSorter,
458 &EngineCostSorter,
459 &EngineSpeedSorter,
460 &EngineIntroDateSorter,
461 &EngineNameSorter,
462 &EngineRunningCostSorter,
463 &EngineReliabilitySorter,
464 &ShipEngineCapacitySorter,
465 }, {
466 /* Aircraft */
467 &EngineNumberSorter,
468 &EngineCostSorter,
469 &EngineSpeedSorter,
470 &EngineIntroDateSorter,
471 &EngineNameSorter,
472 &EngineRunningCostSorter,
473 &EngineReliabilitySorter,
474 &AircraftEngineCargoSorter,
475 &AircraftRangeSorter,
478 /** Dropdown menu strings for the vehicle sort criteria. */
479 const StringID _engine_sort_listing[][12] = {{
480 /* Trains */
481 STR_SORT_BY_ENGINE_ID,
482 STR_SORT_BY_COST,
483 STR_SORT_BY_MAX_SPEED,
484 STR_SORT_BY_POWER,
485 STR_SORT_BY_TRACTIVE_EFFORT,
486 STR_SORT_BY_INTRO_DATE,
487 STR_SORT_BY_NAME,
488 STR_SORT_BY_RUNNING_COST,
489 STR_SORT_BY_POWER_VS_RUNNING_COST,
490 STR_SORT_BY_RELIABILITY,
491 STR_SORT_BY_CARGO_CAPACITY,
492 INVALID_STRING_ID
493 }, {
494 /* Road vehicles */
495 STR_SORT_BY_ENGINE_ID,
496 STR_SORT_BY_COST,
497 STR_SORT_BY_MAX_SPEED,
498 STR_SORT_BY_POWER,
499 STR_SORT_BY_TRACTIVE_EFFORT,
500 STR_SORT_BY_INTRO_DATE,
501 STR_SORT_BY_NAME,
502 STR_SORT_BY_RUNNING_COST,
503 STR_SORT_BY_POWER_VS_RUNNING_COST,
504 STR_SORT_BY_RELIABILITY,
505 STR_SORT_BY_CARGO_CAPACITY,
506 INVALID_STRING_ID
507 }, {
508 /* Ships */
509 STR_SORT_BY_ENGINE_ID,
510 STR_SORT_BY_COST,
511 STR_SORT_BY_MAX_SPEED,
512 STR_SORT_BY_INTRO_DATE,
513 STR_SORT_BY_NAME,
514 STR_SORT_BY_RUNNING_COST,
515 STR_SORT_BY_RELIABILITY,
516 STR_SORT_BY_CARGO_CAPACITY,
517 INVALID_STRING_ID
518 }, {
519 /* Aircraft */
520 STR_SORT_BY_ENGINE_ID,
521 STR_SORT_BY_COST,
522 STR_SORT_BY_MAX_SPEED,
523 STR_SORT_BY_INTRO_DATE,
524 STR_SORT_BY_NAME,
525 STR_SORT_BY_RUNNING_COST,
526 STR_SORT_BY_RELIABILITY,
527 STR_SORT_BY_CARGO_CAPACITY,
528 STR_SORT_BY_RANGE,
529 INVALID_STRING_ID
532 /** Cargo filter functions */
533 static bool CDECL CargoFilter(const EngineID *eid, const CargoID cid)
535 if (cid == CF_ANY) return true;
536 CargoTypes refit_mask = GetUnionOfArticulatedRefitMasks(*eid, true) & _standard_cargo_mask;
537 return (cid == CF_NONE ? refit_mask == 0 : HasBit(refit_mask, cid));
540 static GUIEngineList::FilterFunction * const _filter_funcs[] = {
541 &CargoFilter,
544 static int DrawCargoCapacityInfo(int left, int right, int y, EngineID engine, TestedEngineDetails &te)
546 CargoArray cap;
547 CargoTypes refits;
548 GetArticulatedVehicleCargoesAndRefits(engine, &cap, &refits, te.cargo, te.capacity);
550 for (CargoID c = 0; c < NUM_CARGO; c++) {
551 if (cap[c] == 0) continue;
553 SetDParam(0, c);
554 SetDParam(1, cap[c]);
555 SetDParam(2, HasBit(refits, c) ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
556 DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
557 y += FONT_HEIGHT_NORMAL;
560 return y;
563 /* Draw rail wagon specific details */
564 static int DrawRailWagonPurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi, TestedEngineDetails &te)
566 const Engine *e = Engine::Get(engine_number);
568 /* Purchase cost */
569 if (te.cost != 0) {
570 SetDParam(0, e->GetCost() + te.cost);
571 SetDParam(1, te.cost);
572 DrawString(left, right, y, STR_PURCHASE_INFO_COST_REFIT);
573 } else {
574 SetDParam(0, e->GetCost());
575 DrawString(left, right, y, STR_PURCHASE_INFO_COST);
577 y += FONT_HEIGHT_NORMAL;
579 /* Wagon weight - (including cargo) */
580 uint weight = e->GetDisplayWeight();
581 SetDParam(0, weight);
582 uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(te.cargo)->weight * te.capacity / 16 : 0);
583 SetDParam(1, cargo_weight + weight);
584 DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT);
585 y += FONT_HEIGHT_NORMAL;
587 /* Wagon speed limit, displayed if above zero */
588 if (_settings_game.vehicle.wagon_speed_limits) {
589 uint max_speed = e->GetDisplayMaxSpeed();
590 if (max_speed > 0) {
591 SetDParam(0, max_speed);
592 DrawString(left, right, y, STR_PURCHASE_INFO_SPEED);
593 y += FONT_HEIGHT_NORMAL;
597 /* Running cost */
598 if (rvi->running_cost_class != INVALID_PRICE) {
599 SetDParam(0, e->GetRunningCost());
600 DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
601 y += FONT_HEIGHT_NORMAL;
604 return y;
607 /* Draw locomotive specific details */
608 static int DrawRailEnginePurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi, TestedEngineDetails &te)
610 const Engine *e = Engine::Get(engine_number);
612 /* Purchase Cost - Engine weight */
613 if (te.cost != 0) {
614 SetDParam(0, e->GetCost() + te.cost);
615 SetDParam(1, te.cost);
616 SetDParam(2, e->GetDisplayWeight());
617 DrawString(left, right, y, STR_PURCHASE_INFO_COST_REFIT_WEIGHT);
618 } else {
619 SetDParam(0, e->GetCost());
620 SetDParam(1, e->GetDisplayWeight());
621 DrawString(left, right, y, STR_PURCHASE_INFO_COST_WEIGHT);
623 y += FONT_HEIGHT_NORMAL;
625 /* Max speed - Engine power */
626 SetDParam(0, e->GetDisplayMaxSpeed());
627 SetDParam(1, e->GetPower());
628 DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER);
629 y += FONT_HEIGHT_NORMAL;
631 /* Max tractive effort - not applicable if old acceleration or maglev */
632 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && GetRailTypeInfo(rvi->railtype)->acceleration_type != 2) {
633 SetDParam(0, e->GetDisplayMaxTractiveEffort());
634 DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE);
635 y += FONT_HEIGHT_NORMAL;
638 /* Running cost */
639 if (rvi->running_cost_class != INVALID_PRICE) {
640 SetDParam(0, e->GetRunningCost());
641 DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
642 y += FONT_HEIGHT_NORMAL;
645 /* Powered wagons power - Powered wagons extra weight */
646 if (rvi->pow_wag_power != 0) {
647 SetDParam(0, rvi->pow_wag_power);
648 SetDParam(1, rvi->pow_wag_weight);
649 DrawString(left, right, y, STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT);
650 y += FONT_HEIGHT_NORMAL;
653 return y;
656 /* Draw road vehicle specific details */
657 static int DrawRoadVehPurchaseInfo(int left, int right, int y, EngineID engine_number, TestedEngineDetails &te)
659 const Engine *e = Engine::Get(engine_number);
661 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
662 /* Purchase Cost */
663 if (te.cost != 0) {
664 SetDParam(0, e->GetCost() + te.cost);
665 SetDParam(1, te.cost);
666 DrawString(left, right, y, STR_PURCHASE_INFO_COST_REFIT);
667 } else {
668 SetDParam(0, e->GetCost());
669 DrawString(left, right, y, STR_PURCHASE_INFO_COST);
671 y += FONT_HEIGHT_NORMAL;
673 /* Road vehicle weight - (including cargo) */
674 int16 weight = e->GetDisplayWeight();
675 SetDParam(0, weight);
676 uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(te.cargo)->weight * te.capacity / 16 : 0);
677 SetDParam(1, cargo_weight + weight);
678 DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT);
679 y += FONT_HEIGHT_NORMAL;
681 /* Max speed - Engine power */
682 SetDParam(0, e->GetDisplayMaxSpeed());
683 SetDParam(1, e->GetPower());
684 DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER);
685 y += FONT_HEIGHT_NORMAL;
687 /* Max tractive effort */
688 SetDParam(0, e->GetDisplayMaxTractiveEffort());
689 DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE);
690 y += FONT_HEIGHT_NORMAL;
691 } else {
692 /* Purchase cost - Max speed */
693 if (te.cost != 0) {
694 SetDParam(0, e->GetCost() + te.cost);
695 SetDParam(1, te.cost);
696 SetDParam(2, e->GetDisplayMaxSpeed());
697 DrawString(left, right, y, STR_PURCHASE_INFO_COST_REFIT_SPEED);
698 } else {
699 SetDParam(0, e->GetCost());
700 SetDParam(1, e->GetDisplayMaxSpeed());
701 DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
703 y += FONT_HEIGHT_NORMAL;
706 /* Running cost */
707 SetDParam(0, e->GetRunningCost());
708 DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
709 y += FONT_HEIGHT_NORMAL;
711 return y;
714 /* Draw ship specific details */
715 static int DrawShipPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable, TestedEngineDetails &te)
717 const Engine *e = Engine::Get(engine_number);
719 /* Purchase cost - Max speed */
720 uint raw_speed = e->GetDisplayMaxSpeed();
721 uint ocean_speed = e->u.ship.ApplyWaterClassSpeedFrac(raw_speed, true);
722 uint canal_speed = e->u.ship.ApplyWaterClassSpeedFrac(raw_speed, false);
724 if (ocean_speed == canal_speed) {
725 if (te.cost != 0) {
726 SetDParam(0, e->GetCost() + te.cost);
727 SetDParam(1, te.cost);
728 SetDParam(2, ocean_speed);
729 DrawString(left, right, y, STR_PURCHASE_INFO_COST_REFIT_SPEED);
730 } else {
731 SetDParam(0, e->GetCost());
732 SetDParam(1, ocean_speed);
733 DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
735 y += FONT_HEIGHT_NORMAL;
736 } else {
737 if (te.cost != 0) {
738 SetDParam(0, e->GetCost() + te.cost);
739 SetDParam(1, te.cost);
740 DrawString(left, right, y, STR_PURCHASE_INFO_COST_REFIT);
741 } else {
742 SetDParam(0, e->GetCost());
743 DrawString(left, right, y, STR_PURCHASE_INFO_COST);
745 y += FONT_HEIGHT_NORMAL;
747 SetDParam(0, ocean_speed);
748 DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_OCEAN);
749 y += FONT_HEIGHT_NORMAL;
751 SetDParam(0, canal_speed);
752 DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_CANAL);
753 y += FONT_HEIGHT_NORMAL;
756 /* Cargo type + capacity */
757 SetDParam(0, te.cargo);
758 SetDParam(1, te.capacity);
759 SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
760 DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
761 y += FONT_HEIGHT_NORMAL;
763 /* Running cost */
764 SetDParam(0, e->GetRunningCost());
765 DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
766 y += FONT_HEIGHT_NORMAL;
768 return y;
772 * Draw aircraft specific details in the buy window.
773 * @param left Left edge of the window to draw in.
774 * @param right Right edge of the window to draw in.
775 * @param y Top of the area to draw in.
776 * @param engine_number Engine to display.
777 * @param refittable If set, the aircraft can be refitted.
778 * @return Bottom of the used area.
780 static int DrawAircraftPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable, TestedEngineDetails &te)
782 const Engine *e = Engine::Get(engine_number);
784 /* Purchase cost - Max speed */
785 if (te.cost != 0) {
786 SetDParam(0, e->GetCost() + te.cost);
787 SetDParam(1, te.cost);
788 SetDParam(2, e->GetDisplayMaxSpeed());
789 DrawString(left, right, y, STR_PURCHASE_INFO_COST_REFIT_SPEED);
790 } else {
791 SetDParam(0, e->GetCost());
792 SetDParam(1, e->GetDisplayMaxSpeed());
793 DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
795 y += FONT_HEIGHT_NORMAL;
797 /* Cargo capacity */
798 if (te.mail_capacity > 0) {
799 SetDParam(0, te.cargo);
800 SetDParam(1, te.capacity);
801 SetDParam(2, CT_MAIL);
802 SetDParam(3, te.mail_capacity);
803 DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_CAPACITY);
804 } else {
805 /* Note, if the default capacity is selected by the refit capacity
806 * callback, then the capacity shown is likely to be incorrect. */
807 SetDParam(0, te.cargo);
808 SetDParam(1, te.capacity);
809 SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
810 DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
812 y += FONT_HEIGHT_NORMAL;
814 /* Running cost */
815 SetDParam(0, e->GetRunningCost());
816 DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
817 y += FONT_HEIGHT_NORMAL;
819 /* Aircraft type */
820 SetDParam(0, e->GetAircraftTypeText());
821 DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_TYPE);
822 y += FONT_HEIGHT_NORMAL;
824 /* Aircraft range, if available. */
825 uint16 range = e->GetRange();
826 if (range != 0) {
827 SetDParam(0, range);
828 DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_RANGE);
829 y += FONT_HEIGHT_NORMAL;
832 return y;
836 * Display additional text from NewGRF in the purchase information window
837 * @param left Left border of text bounding box
838 * @param right Right border of text bounding box
839 * @param y Top border of text bounding box
840 * @param engine Engine to query the additional purchase information for
841 * @return Bottom border of text bounding box
843 static uint ShowAdditionalText(int left, int right, int y, EngineID engine)
845 uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, nullptr);
846 if (callback == CALLBACK_FAILED || callback == 0x400) return y;
847 const GRFFile *grffile = Engine::Get(engine)->GetGRF();
848 if (callback > 0x400) {
849 ErrorUnknownCallbackResult(grffile->grfid, CBID_VEHICLE_ADDITIONAL_TEXT, callback);
850 return y;
853 StartTextRefStackUsage(grffile, 6);
854 uint result = DrawStringMultiLine(left, right, y, INT32_MAX, GetGRFStringID(grffile->grfid, 0xD000 + callback), TC_BLACK);
855 StopTextRefStackUsage();
856 return result;
860 * Draw the purchase info details of a vehicle at a given location.
861 * @param left,right,y location where to draw the info
862 * @param engine_number the engine of which to draw the info of
863 * @return y after drawing all the text
865 int DrawVehiclePurchaseInfo(int left, int right, int y, EngineID engine_number, TestedEngineDetails &te)
867 const Engine *e = Engine::Get(engine_number);
868 YearMonthDay ymd;
869 ConvertDateToYMD(e->intro_date, &ymd);
870 bool refittable = IsArticulatedVehicleRefittable(engine_number);
871 bool articulated_cargo = false;
873 switch (e->type) {
874 default: NOT_REACHED();
875 case VEH_TRAIN:
876 if (e->u.rail.railveh_type == RAILVEH_WAGON) {
877 y = DrawRailWagonPurchaseInfo(left, right, y, engine_number, &e->u.rail, te);
878 } else {
879 y = DrawRailEnginePurchaseInfo(left, right, y, engine_number, &e->u.rail, te);
881 articulated_cargo = true;
882 break;
884 case VEH_ROAD:
885 y = DrawRoadVehPurchaseInfo(left, right, y, engine_number, te);
886 articulated_cargo = true;
887 break;
889 case VEH_SHIP:
890 y = DrawShipPurchaseInfo(left, right, y, engine_number, refittable, te);
891 break;
893 case VEH_AIRCRAFT:
894 y = DrawAircraftPurchaseInfo(left, right, y, engine_number, refittable, te);
895 break;
898 if (articulated_cargo) {
899 /* Cargo type + capacity, or N/A */
900 int new_y = DrawCargoCapacityInfo(left, right, y, engine_number, te);
902 if (new_y == y) {
903 SetDParam(0, CT_INVALID);
904 SetDParam(2, STR_EMPTY);
905 DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
906 y += FONT_HEIGHT_NORMAL;
907 } else {
908 y = new_y;
912 /* Draw details that apply to all types except rail wagons. */
913 if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
914 /* Design date - Life length */
915 SetDParam(0, ymd.year);
916 SetDParam(1, e->GetLifeLengthInDays() / DAYS_IN_LEAP_YEAR);
917 DrawString(left, right, y, STR_PURCHASE_INFO_DESIGNED_LIFE);
918 y += FONT_HEIGHT_NORMAL;
920 /* Reliability */
921 SetDParam(0, ToPercent16(e->reliability));
922 DrawString(left, right, y, STR_PURCHASE_INFO_RELIABILITY);
923 y += FONT_HEIGHT_NORMAL;
926 if (refittable) y = ShowRefitOptionsList(left, right, y, engine_number);
928 /* Additional text from NewGRF */
929 y = ShowAdditionalText(left, right, y, engine_number);
931 /* The NewGRF's name which the vehicle comes from */
932 const GRFConfig *config = GetGRFConfig(e->GetGRFID());
933 if (_settings_client.gui.show_newgrf_name && config != nullptr)
935 DrawString(left, right, y, config->GetName(), TC_BLACK);
936 y += FONT_HEIGHT_NORMAL;
939 return y;
943 * Engine drawing loop
944 * @param type Type of vehicle (VEH_*)
945 * @param l The left most location of the list
946 * @param r The right most location of the list
947 * @param y The top most location of the list
948 * @param eng_list What engines to draw
949 * @param min where to start in the list
950 * @param max where in the list to end
951 * @param selected_id what engine to highlight as selected, if any
952 * @param show_count Whether to show the amount of engines or not
953 * @param selected_group the group to list the engines of
955 void DrawEngineList(VehicleType type, int l, int r, int y, const GUIEngineList *eng_list, uint16 min, uint16 max, EngineID selected_id, bool show_count, GroupID selected_group)
957 static const int sprite_y_offsets[] = { -1, -1, -2, -2 };
959 /* Obligatory sanity checks! */
960 assert(max <= eng_list->size());
962 bool rtl = _current_text_dir == TD_RTL;
963 int step_size = GetEngineListHeight(type);
964 int sprite_left = GetVehicleImageCellSize(type, EIT_PURCHASE).extend_left;
965 int sprite_right = GetVehicleImageCellSize(type, EIT_PURCHASE).extend_right;
966 int sprite_width = sprite_left + sprite_right;
968 int sprite_x = rtl ? r - sprite_right - 1 : l + sprite_left + 1;
969 int sprite_y_offset = sprite_y_offsets[type] + step_size / 2;
971 Dimension replace_icon = {0, 0};
972 int count_width = 0;
973 if (show_count) {
974 replace_icon = GetSpriteSize(SPR_GROUP_REPLACE_ACTIVE);
975 SetDParamMaxDigits(0, 3, FS_SMALL);
976 count_width = GetStringBoundingBox(STR_TINY_BLACK_COMA).width;
979 int text_left = l + (rtl ? WD_FRAMERECT_LEFT + replace_icon.width + 8 + count_width : sprite_width + WD_FRAMETEXT_LEFT);
980 int text_right = r - (rtl ? sprite_width + WD_FRAMETEXT_RIGHT : WD_FRAMERECT_RIGHT + replace_icon.width + 8 + count_width);
981 int replace_icon_left = rtl ? l + WD_FRAMERECT_LEFT : r - WD_FRAMERECT_RIGHT - replace_icon.width;
982 int count_left = l;
983 int count_right = rtl ? text_left : r - WD_FRAMERECT_RIGHT - replace_icon.width - 8;
985 int normal_text_y_offset = (step_size - FONT_HEIGHT_NORMAL) / 2;
986 int small_text_y_offset = step_size - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1;
987 int replace_icon_y_offset = (step_size - replace_icon.height) / 2 - 1;
989 for (; min < max; min++, y += step_size) {
990 const EngineID engine = (*eng_list)[min];
991 /* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_company here. */
992 const uint num_engines = GetGroupNumEngines(_local_company, selected_group, engine);
994 const Engine *e = Engine::Get(engine);
995 bool hidden = HasBit(e->company_hidden, _local_company);
996 StringID str = hidden ? STR_HIDDEN_ENGINE_NAME : STR_ENGINE_NAME;
997 TextColour tc = (engine == selected_id) ? TC_WHITE : (TC_NO_SHADE | (hidden ? TC_GREY : TC_BLACK));
999 SetDParam(0, engine);
1000 DrawString(text_left, text_right, y + normal_text_y_offset, str, tc);
1001 DrawVehicleEngine(l, r, sprite_x, y + sprite_y_offset, engine, (show_count && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_company), EIT_PURCHASE);
1002 if (show_count) {
1003 SetDParam(0, num_engines);
1004 DrawString(count_left, count_right, y + small_text_y_offset, STR_TINY_BLACK_COMA, TC_FROMSTRING, SA_RIGHT | SA_FORCE);
1005 if (EngineHasReplacementForCompany(Company::Get(_local_company), engine, selected_group)) DrawSprite(SPR_GROUP_REPLACE_ACTIVE, num_engines == 0 ? PALETTE_CRASH : PAL_NONE, replace_icon_left, y + replace_icon_y_offset);
1011 * Display the dropdown for the vehicle sort criteria.
1012 * @param w Parent window (holds the dropdown button).
1013 * @param vehicle_type %Vehicle type being sorted.
1014 * @param selected Currently selected sort criterium.
1015 * @param button Widget button.
1017 void DisplayVehicleSortDropDown(Window *w, VehicleType vehicle_type, int selected, int button)
1019 uint32 hidden_mask = 0;
1020 /* Disable sorting by power or tractive effort when the original acceleration model for road vehicles is being used. */
1021 if (vehicle_type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) {
1022 SetBit(hidden_mask, 3); // power
1023 SetBit(hidden_mask, 4); // tractive effort
1024 SetBit(hidden_mask, 8); // power by running costs
1026 /* Disable sorting by tractive effort when the original acceleration model for trains is being used. */
1027 if (vehicle_type == VEH_TRAIN && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
1028 SetBit(hidden_mask, 4); // tractive effort
1030 ShowDropDownMenu(w, _engine_sort_listing[vehicle_type], selected, button, 0, hidden_mask);
1033 /** GUI for building vehicles. */
1034 struct BuildVehicleWindow : Window {
1035 VehicleType vehicle_type; ///< Type of vehicles shown in the window.
1036 union {
1037 RailType railtype; ///< Rail type to show, or #INVALID_RAILTYPE.
1038 RoadType roadtype; ///< Road type to show, or #INVALID_ROADTYPE.
1039 } filter; ///< Filter to apply.
1040 bool descending_sort_order; ///< Sort direction, @see _engine_sort_direction
1041 byte sort_criteria; ///< Current sort criterium.
1042 bool show_hidden_engines; ///< State of the 'show hidden engines' button.
1043 bool listview_mode; ///< If set, only display the available vehicles and do not show a 'build' button.
1044 EngineID sel_engine; ///< Currently selected engine, or #INVALID_ENGINE
1045 EngineID rename_engine; ///< Engine being renamed.
1046 GUIEngineList eng_list;
1047 CargoID cargo_filter[NUM_CARGO + 2]; ///< Available cargo filters; CargoID or CF_ANY or CF_NONE
1048 StringID cargo_filter_texts[NUM_CARGO + 3]; ///< Texts for filter_cargo, terminated by INVALID_STRING_ID
1049 byte cargo_filter_criteria; ///< Selected cargo filter
1050 int details_height; ///< Minimal needed height of the details panels (found so far).
1051 Scrollbar *vscroll;
1052 TestedEngineDetails te; ///< Tested cost and capacity after refit.
1054 void SetBuyVehicleText()
1056 NWidgetCore *widget = this->GetWidget<NWidgetCore>(WID_BV_BUILD);
1058 bool refit = this->sel_engine != INVALID_ENGINE && this->cargo_filter[this->cargo_filter_criteria] != CF_ANY && this->cargo_filter[this->cargo_filter_criteria] != CF_NONE;
1059 if (refit) refit = Engine::Get(this->sel_engine)->GetDefaultCargoType() != this->cargo_filter[this->cargo_filter_criteria];
1061 if (refit) {
1062 widget->widget_data = STR_BUY_VEHICLE_TRAIN_BUY_REFIT_VEHICLE_BUTTON + this->vehicle_type;
1063 widget->tool_tip = STR_BUY_VEHICLE_TRAIN_BUY_REFIT_VEHICLE_TOOLTIP + this->vehicle_type;
1064 } else {
1065 widget->widget_data = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_BUTTON + this->vehicle_type;
1066 widget->tool_tip = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_TOOLTIP + this->vehicle_type;
1070 BuildVehicleWindow(WindowDesc *desc, TileIndex tile, VehicleType type) : Window(desc)
1072 this->vehicle_type = type;
1073 this->listview_mode = tile == INVALID_TILE;
1074 this->window_number = this->listview_mode ? (int)type : tile;
1076 this->sel_engine = INVALID_ENGINE;
1078 this->sort_criteria = _engine_sort_last_criteria[type];
1079 this->descending_sort_order = _engine_sort_last_order[type];
1080 this->show_hidden_engines = _engine_sort_show_hidden_engines[type];
1082 this->UpdateFilterByTile();
1084 this->CreateNestedTree();
1086 this->vscroll = this->GetScrollbar(WID_BV_SCROLLBAR);
1088 /* If we are just viewing the list of vehicles, we do not need the Build button.
1089 * So we just hide it, and enlarge the Rename button by the now vacant place. */
1090 if (this->listview_mode) this->GetWidget<NWidgetStacked>(WID_BV_BUILD_SEL)->SetDisplayedPlane(SZSP_NONE);
1092 /* disable renaming engines in network games if you are not the server */
1093 this->SetWidgetDisabledState(WID_BV_RENAME, _networking && !_network_server);
1095 NWidgetCore *widget = this->GetWidget<NWidgetCore>(WID_BV_LIST);
1096 widget->tool_tip = STR_BUY_VEHICLE_TRAIN_LIST_TOOLTIP + type;
1098 widget = this->GetWidget<NWidgetCore>(WID_BV_SHOW_HIDE);
1099 widget->tool_tip = STR_BUY_VEHICLE_TRAIN_HIDE_SHOW_TOGGLE_TOOLTIP + type;
1101 widget = this->GetWidget<NWidgetCore>(WID_BV_RENAME);
1102 widget->widget_data = STR_BUY_VEHICLE_TRAIN_RENAME_BUTTON + type;
1103 widget->tool_tip = STR_BUY_VEHICLE_TRAIN_RENAME_TOOLTIP + type;
1105 widget = this->GetWidget<NWidgetCore>(WID_BV_SHOW_HIDDEN_ENGINES);
1106 widget->widget_data = STR_SHOW_HIDDEN_ENGINES_VEHICLE_TRAIN + type;
1107 widget->tool_tip = STR_SHOW_HIDDEN_ENGINES_VEHICLE_TRAIN_TOOLTIP + type;
1108 widget->SetLowered(this->show_hidden_engines);
1110 this->details_height = ((this->vehicle_type == VEH_TRAIN) ? 10 : 9) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1112 this->FinishInitNested(tile == INVALID_TILE ? (int)type : tile);
1114 this->owner = (tile != INVALID_TILE) ? GetTileOwner(tile) : _local_company;
1116 this->eng_list.ForceRebuild();
1117 this->GenerateBuildList(); // generate the list, since we need it in the next line
1118 /* Select the first engine in the list as default when opening the window */
1119 if (this->eng_list.size() > 0) {
1120 this->SelectEngine(this->eng_list[0]);
1121 } else {
1122 this->SelectEngine(INVALID_ENGINE);
1126 /** Set the filter type according to the depot type */
1127 void UpdateFilterByTile()
1129 switch (this->vehicle_type) {
1130 default: NOT_REACHED();
1131 case VEH_TRAIN:
1132 if (this->listview_mode) {
1133 this->filter.railtype = INVALID_RAILTYPE;
1134 } else {
1135 this->filter.railtype = GetRailType(this->window_number);
1137 break;
1139 case VEH_ROAD:
1140 if (this->listview_mode) {
1141 this->filter.roadtype = INVALID_ROADTYPE;
1142 } else {
1143 this->filter.roadtype = GetRoadTypeRoad(this->window_number);
1144 if (this->filter.roadtype == INVALID_ROADTYPE) {
1145 this->filter.roadtype = GetRoadTypeTram(this->window_number);
1148 break;
1150 case VEH_SHIP:
1151 case VEH_AIRCRAFT:
1152 break;
1156 /** Populate the filter list and set the cargo filter criteria. */
1157 void SetCargoFilterArray()
1159 uint filter_items = 0;
1161 /* Add item for disabling filtering. */
1162 this->cargo_filter[filter_items] = CF_ANY;
1163 this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_ALL_TYPES;
1164 filter_items++;
1166 /* Add item for vehicles not carrying anything, e.g. train engines.
1167 * This could also be useful for eyecandy vehicles of other types, but is likely too confusing for joe, */
1168 if (this->vehicle_type == VEH_TRAIN) {
1169 this->cargo_filter[filter_items] = CF_NONE;
1170 this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_NONE;
1171 filter_items++;
1174 /* Collect available cargo types for filtering. */
1175 const CargoSpec *cs;
1176 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1177 this->cargo_filter[filter_items] = cs->Index();
1178 this->cargo_filter_texts[filter_items] = cs->name;
1179 filter_items++;
1182 /* Terminate the filter list. */
1183 this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
1185 /* If not found, the cargo criteria will be set to all cargoes. */
1186 this->cargo_filter_criteria = 0;
1188 /* Find the last cargo filter criteria. */
1189 for (uint i = 0; i < filter_items; i++) {
1190 if (this->cargo_filter[i] == _engine_sort_last_cargo_criteria[this->vehicle_type]) {
1191 this->cargo_filter_criteria = i;
1192 break;
1196 this->eng_list.SetFilterFuncs(_filter_funcs);
1197 this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
1200 void SelectEngine(EngineID engine)
1202 CargoID cargo = this->cargo_filter[this->cargo_filter_criteria];
1203 if (cargo == CF_ANY) cargo = CF_NONE;
1205 this->sel_engine = engine;
1206 this->SetBuyVehicleText();
1208 if (this->sel_engine == INVALID_ENGINE) return;
1210 const Engine *e = Engine::Get(this->sel_engine);
1211 if (!e->CanCarryCargo()) {
1212 this->te.cost = 0;
1213 this->te.cargo = CT_INVALID;
1214 return;
1217 if (!this->listview_mode) {
1218 /* Query for cost and refitted capacity */
1219 CommandCost ret = DoCommand(this->window_number, this->sel_engine | (cargo << 24), 0, DC_QUERY_COST, GetCmdBuildVeh(this->vehicle_type), nullptr);
1220 if (ret.Succeeded()) {
1221 this->te.cost = ret.GetCost() - e->GetCost();
1222 this->te.capacity = _returned_refit_capacity;
1223 this->te.mail_capacity = _returned_mail_refit_capacity;
1224 this->te.cargo = (cargo == CT_INVALID) ? e->GetDefaultCargoType() : cargo;
1225 return;
1229 /* Purchase test was not possible or failed, fill in the defaults instead. */
1230 this->te.cost = 0;
1231 this->te.capacity = e->GetDisplayDefaultCapacity(&this->te.mail_capacity);
1232 this->te.cargo = e->GetDefaultCargoType();
1235 void OnInit() override
1237 this->SetCargoFilterArray();
1240 /** Filter the engine list against the currently selected cargo filter */
1241 void FilterEngineList()
1243 this->eng_list.Filter(this->cargo_filter[this->cargo_filter_criteria]);
1244 if (0 == this->eng_list.size()) { // no engine passed through the filter, invalidate the previously selected engine
1245 this->SelectEngine(INVALID_ENGINE);
1246 } else if (std::find(this->eng_list.begin(), this->eng_list.end(), this->sel_engine) == this->eng_list.end()) { // previously selected engine didn't pass the filter, select the first engine of the list
1247 this->SelectEngine(this->eng_list[0]);
1251 /** Filter a single engine */
1252 bool FilterSingleEngine(EngineID eid)
1254 CargoID filter_type = this->cargo_filter[this->cargo_filter_criteria];
1255 return (filter_type == CF_ANY || CargoFilter(&eid, filter_type));
1258 /* Figure out what train EngineIDs to put in the list */
1259 void GenerateBuildTrainList()
1261 EngineID sel_id = INVALID_ENGINE;
1262 int num_engines = 0;
1263 int num_wagons = 0;
1265 this->eng_list.clear();
1267 /* Make list of all available train engines and wagons.
1268 * Also check to see if the previously selected engine is still available,
1269 * and if not, reset selection to INVALID_ENGINE. This could be the case
1270 * when engines become obsolete and are removed */
1271 for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
1272 if (!this->show_hidden_engines && e->IsHidden(_local_company)) continue;
1273 EngineID eid = e->index;
1274 const RailVehicleInfo *rvi = &e->u.rail;
1276 if (this->filter.railtype != INVALID_RAILTYPE && !HasPowerOnRail(rvi->railtype, this->filter.railtype)) continue;
1277 if (!IsEngineBuildable(eid, VEH_TRAIN, _local_company)) continue;
1279 /* Filter now! So num_engines and num_wagons is valid */
1280 if (!FilterSingleEngine(eid)) continue;
1282 this->eng_list.push_back(eid);
1284 if (rvi->railveh_type != RAILVEH_WAGON) {
1285 num_engines++;
1286 } else {
1287 num_wagons++;
1290 if (eid == this->sel_engine) sel_id = eid;
1293 this->SelectEngine(sel_id);
1295 /* make engines first, and then wagons, sorted by selected sort_criteria */
1296 _engine_sort_direction = false;
1297 EngList_Sort(&this->eng_list, TrainEnginesThenWagonsSorter);
1299 /* and then sort engines */
1300 _engine_sort_direction = this->descending_sort_order;
1301 EngList_SortPartial(&this->eng_list, _engine_sort_functions[0][this->sort_criteria], 0, num_engines);
1303 /* and finally sort wagons */
1304 EngList_SortPartial(&this->eng_list, _engine_sort_functions[0][this->sort_criteria], num_engines, num_wagons);
1307 /* Figure out what road vehicle EngineIDs to put in the list */
1308 void GenerateBuildRoadVehList()
1310 EngineID sel_id = INVALID_ENGINE;
1312 this->eng_list.clear();
1314 for (const Engine *e : Engine::IterateType(VEH_ROAD)) {
1315 if (!this->show_hidden_engines && e->IsHidden(_local_company)) continue;
1316 EngineID eid = e->index;
1317 if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue;
1318 if (this->filter.roadtype != INVALID_ROADTYPE && !HasPowerOnRoad(e->u.road.roadtype, this->filter.roadtype)) continue;
1320 this->eng_list.push_back(eid);
1322 if (eid == this->sel_engine) sel_id = eid;
1324 this->SelectEngine(sel_id);
1327 /* Figure out what ship EngineIDs to put in the list */
1328 void GenerateBuildShipList()
1330 EngineID sel_id = INVALID_ENGINE;
1331 this->eng_list.clear();
1333 for (const Engine *e : Engine::IterateType(VEH_SHIP)) {
1334 if (!this->show_hidden_engines && e->IsHidden(_local_company)) continue;
1335 EngineID eid = e->index;
1336 if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue;
1337 this->eng_list.push_back(eid);
1339 if (eid == this->sel_engine) sel_id = eid;
1341 this->SelectEngine(sel_id);
1344 /* Figure out what aircraft EngineIDs to put in the list */
1345 void GenerateBuildAircraftList()
1347 EngineID sel_id = INVALID_ENGINE;
1349 this->eng_list.clear();
1351 const Station *st = this->listview_mode ? nullptr : Station::GetByTile(this->window_number);
1353 /* Make list of all available planes.
1354 * Also check to see if the previously selected plane is still available,
1355 * and if not, reset selection to INVALID_ENGINE. This could be the case
1356 * when planes become obsolete and are removed */
1357 for (const Engine *e : Engine::IterateType(VEH_AIRCRAFT)) {
1358 if (!this->show_hidden_engines && e->IsHidden(_local_company)) continue;
1359 EngineID eid = e->index;
1360 if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue;
1361 /* First VEH_END window_numbers are fake to allow a window open for all different types at once */
1362 if (!this->listview_mode && !CanVehicleUseStation(eid, st)) continue;
1364 this->eng_list.push_back(eid);
1365 if (eid == this->sel_engine) sel_id = eid;
1368 this->SelectEngine(sel_id);
1371 /* Generate the list of vehicles */
1372 void GenerateBuildList()
1374 if (!this->eng_list.NeedRebuild()) return;
1376 /* Update filter type in case the road/railtype of the depot got converted */
1377 this->UpdateFilterByTile();
1379 switch (this->vehicle_type) {
1380 default: NOT_REACHED();
1381 case VEH_TRAIN:
1382 this->GenerateBuildTrainList();
1383 this->eng_list.shrink_to_fit();
1384 this->eng_list.RebuildDone();
1385 return; // trains should not reach the last sorting
1386 case VEH_ROAD:
1387 this->GenerateBuildRoadVehList();
1388 break;
1389 case VEH_SHIP:
1390 this->GenerateBuildShipList();
1391 break;
1392 case VEH_AIRCRAFT:
1393 this->GenerateBuildAircraftList();
1394 break;
1397 this->FilterEngineList();
1399 _engine_sort_direction = this->descending_sort_order;
1400 EngList_Sort(&this->eng_list, _engine_sort_functions[this->vehicle_type][this->sort_criteria]);
1402 this->eng_list.shrink_to_fit();
1403 this->eng_list.RebuildDone();
1406 void OnClick(Point pt, int widget, int click_count) override
1408 switch (widget) {
1409 case WID_BV_SORT_ASCENDING_DESCENDING:
1410 this->descending_sort_order ^= true;
1411 _engine_sort_last_order[this->vehicle_type] = this->descending_sort_order;
1412 this->eng_list.ForceRebuild();
1413 this->SetDirty();
1414 break;
1416 case WID_BV_SHOW_HIDDEN_ENGINES:
1417 this->show_hidden_engines ^= true;
1418 _engine_sort_show_hidden_engines[this->vehicle_type] = this->show_hidden_engines;
1419 this->eng_list.ForceRebuild();
1420 this->SetWidgetLoweredState(widget, this->show_hidden_engines);
1421 this->SetDirty();
1422 break;
1424 case WID_BV_LIST: {
1425 uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_BV_LIST);
1426 size_t num_items = this->eng_list.size();
1427 this->SelectEngine((i < num_items) ? this->eng_list[i] : INVALID_ENGINE);
1428 this->SetDirty();
1429 if (_ctrl_pressed) {
1430 this->OnClick(pt, WID_BV_SHOW_HIDE, 1);
1431 } else if (click_count > 1 && !this->listview_mode) {
1432 this->OnClick(pt, WID_BV_BUILD, 1);
1434 break;
1437 case WID_BV_SORT_DROPDOWN: // Select sorting criteria dropdown menu
1438 DisplayVehicleSortDropDown(this, this->vehicle_type, this->sort_criteria, WID_BV_SORT_DROPDOWN);
1439 break;
1441 case WID_BV_CARGO_FILTER_DROPDOWN: // Select cargo filtering criteria dropdown menu
1442 ShowDropDownMenu(this, this->cargo_filter_texts, this->cargo_filter_criteria, WID_BV_CARGO_FILTER_DROPDOWN, 0, 0);
1443 break;
1445 case WID_BV_SHOW_HIDE: {
1446 const Engine *e = (this->sel_engine == INVALID_ENGINE) ? nullptr : Engine::Get(this->sel_engine);
1447 if (e != nullptr) {
1448 DoCommandP(0, 0, this->sel_engine | (e->IsHidden(_current_company) ? 0 : (1u << 31)), CMD_SET_VEHICLE_VISIBILITY);
1450 break;
1453 case WID_BV_BUILD: {
1454 EngineID sel_eng = this->sel_engine;
1455 if (sel_eng != INVALID_ENGINE) {
1456 CommandCallback *callback = (this->vehicle_type == VEH_TRAIN && RailVehInfo(sel_eng)->railveh_type == RAILVEH_WAGON) ? CcBuildWagon : CcBuildPrimaryVehicle;
1457 CargoID cargo = this->cargo_filter[this->cargo_filter_criteria];
1458 if (cargo == CF_ANY) cargo = CF_NONE;
1459 DoCommandP(this->window_number, sel_eng | (cargo << 24), 0, GetCmdBuildVeh(this->vehicle_type), callback);
1461 break;
1464 case WID_BV_RENAME: {
1465 EngineID sel_eng = this->sel_engine;
1466 if (sel_eng != INVALID_ENGINE) {
1467 this->rename_engine = sel_eng;
1468 SetDParam(0, sel_eng);
1469 ShowQueryString(STR_ENGINE_NAME, STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
1471 break;
1477 * Some data on this window has become invalid.
1478 * @param data Information about the changed data.
1479 * @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.
1481 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1483 if (!gui_scope) return;
1484 /* When switching to original acceleration model for road vehicles, clear the selected sort criteria if it is not available now. */
1485 if (this->vehicle_type == VEH_ROAD &&
1486 _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL &&
1487 this->sort_criteria > 7) {
1488 this->sort_criteria = 0;
1489 _engine_sort_last_criteria[VEH_ROAD] = 0;
1491 this->eng_list.ForceRebuild();
1494 void SetStringParameters(int widget) const override
1496 switch (widget) {
1497 case WID_BV_CAPTION:
1498 if (this->vehicle_type == VEH_TRAIN && !this->listview_mode) {
1499 const RailtypeInfo *rti = GetRailTypeInfo(this->filter.railtype);
1500 SetDParam(0, rti->strings.build_caption);
1501 } else if (this->vehicle_type == VEH_ROAD && !this->listview_mode) {
1502 const RoadTypeInfo *rti = GetRoadTypeInfo(this->filter.roadtype);
1503 SetDParam(0, rti->strings.build_caption);
1504 } else {
1505 SetDParam(0, (this->listview_mode ? STR_VEHICLE_LIST_AVAILABLE_TRAINS : STR_BUY_VEHICLE_TRAIN_ALL_CAPTION) + this->vehicle_type);
1507 break;
1509 case WID_BV_SORT_DROPDOWN:
1510 SetDParam(0, _engine_sort_listing[this->vehicle_type][this->sort_criteria]);
1511 break;
1513 case WID_BV_CARGO_FILTER_DROPDOWN:
1514 SetDParam(0, this->cargo_filter_texts[this->cargo_filter_criteria]);
1515 break;
1517 case WID_BV_SHOW_HIDE: {
1518 const Engine *e = (this->sel_engine == INVALID_ENGINE) ? nullptr : Engine::Get(this->sel_engine);
1519 if (e != nullptr && e->IsHidden(_local_company)) {
1520 SetDParam(0, STR_BUY_VEHICLE_TRAIN_SHOW_TOGGLE_BUTTON + this->vehicle_type);
1521 } else {
1522 SetDParam(0, STR_BUY_VEHICLE_TRAIN_HIDE_TOGGLE_BUTTON + this->vehicle_type);
1524 break;
1529 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1531 switch (widget) {
1532 case WID_BV_LIST:
1533 resize->height = GetEngineListHeight(this->vehicle_type);
1534 size->height = 3 * resize->height;
1535 size->width = max(size->width, GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_left + GetVehicleImageCellSize(this->vehicle_type, EIT_PURCHASE).extend_right + 165);
1536 break;
1538 case WID_BV_PANEL:
1539 size->height = this->details_height;
1540 break;
1542 case WID_BV_SORT_ASCENDING_DESCENDING: {
1543 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1544 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1545 d.height += padding.height;
1546 *size = maxdim(*size, d);
1547 break;
1550 case WID_BV_BUILD:
1551 *size = GetStringBoundingBox(STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_BUTTON + this->vehicle_type);
1552 *size = maxdim(*size, GetStringBoundingBox(STR_BUY_VEHICLE_TRAIN_BUY_REFIT_VEHICLE_BUTTON + this->vehicle_type));
1553 size->width += padding.width;
1554 size->height += padding.height;
1555 break;
1557 case WID_BV_SHOW_HIDE:
1558 *size = GetStringBoundingBox(STR_BUY_VEHICLE_TRAIN_HIDE_TOGGLE_BUTTON + this->vehicle_type);
1559 *size = maxdim(*size, GetStringBoundingBox(STR_BUY_VEHICLE_TRAIN_SHOW_TOGGLE_BUTTON + this->vehicle_type));
1560 size->width += padding.width;
1561 size->height += padding.height;
1562 break;
1566 void DrawWidget(const Rect &r, int widget) const override
1568 switch (widget) {
1569 case WID_BV_LIST:
1570 DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, &this->eng_list, this->vscroll->GetPosition(), min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (uint)this->eng_list.size()), this->sel_engine, false, DEFAULT_GROUP);
1571 break;
1573 case WID_BV_SORT_ASCENDING_DESCENDING:
1574 this->DrawSortButtonState(WID_BV_SORT_ASCENDING_DESCENDING, this->descending_sort_order ? SBS_DOWN : SBS_UP);
1575 break;
1579 void OnPaint() override
1581 this->GenerateBuildList();
1582 this->vscroll->SetCount((uint)this->eng_list.size());
1584 this->SetWidgetsDisabledState(this->sel_engine == INVALID_ENGINE, WID_BV_SHOW_HIDE, WID_BV_BUILD, WID_BV_RENAME, WIDGET_LIST_END);
1586 this->DrawWidgets();
1588 if (!this->IsShaded()) {
1589 int needed_height = this->details_height;
1590 /* Draw details panels. */
1591 if (this->sel_engine != INVALID_ENGINE) {
1592 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_BV_PANEL);
1593 int text_end = DrawVehiclePurchaseInfo(nwi->pos_x + WD_FRAMETEXT_LEFT, nwi->pos_x + nwi->current_x - WD_FRAMETEXT_RIGHT,
1594 nwi->pos_y + WD_FRAMERECT_TOP, this->sel_engine, this->te);
1595 needed_height = max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM);
1597 if (needed_height != this->details_height) { // Details window are not high enough, enlarge them.
1598 int resize = needed_height - this->details_height;
1599 this->details_height = needed_height;
1600 this->ReInit(0, resize);
1601 return;
1606 void OnQueryTextFinished(char *str) override
1608 if (str == nullptr) return;
1610 DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN_TYPE + this->vehicle_type), nullptr, str);
1613 void OnDropdownSelect(int widget, int index) override
1615 switch (widget) {
1616 case WID_BV_SORT_DROPDOWN:
1617 if (this->sort_criteria != index) {
1618 this->sort_criteria = index;
1619 _engine_sort_last_criteria[this->vehicle_type] = this->sort_criteria;
1620 this->eng_list.ForceRebuild();
1622 break;
1624 case WID_BV_CARGO_FILTER_DROPDOWN: // Select a cargo filter criteria
1625 if (this->cargo_filter_criteria != index) {
1626 this->cargo_filter_criteria = index;
1627 _engine_sort_last_cargo_criteria[this->vehicle_type] = this->cargo_filter[this->cargo_filter_criteria];
1628 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1629 this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
1630 this->eng_list.ForceRebuild();
1631 this->SelectEngine(this->sel_engine);
1633 break;
1635 this->SetDirty();
1638 void OnResize() override
1640 this->vscroll->SetCapacityFromWidget(this, WID_BV_LIST);
1644 static WindowDesc _build_vehicle_desc(
1645 WDP_AUTO, "build_vehicle", 240, 268,
1646 WC_BUILD_VEHICLE, WC_NONE,
1647 WDF_CONSTRUCTION,
1648 _nested_build_vehicle_widgets, lengthof(_nested_build_vehicle_widgets)
1651 void ShowBuildVehicleWindow(TileIndex tile, VehicleType type)
1653 /* We want to be able to open both Available Train as Available Ships,
1654 * so if tile == INVALID_TILE (Available XXX Window), use 'type' as unique number.
1655 * As it always is a low value, it won't collide with any real tile
1656 * number. */
1657 uint num = (tile == INVALID_TILE) ? (int)type : tile;
1659 assert(IsCompanyBuildableVehicleType(type));
1661 DeleteWindowById(WC_BUILD_VEHICLE, num);
1663 new BuildVehicleWindow(&_build_vehicle_desc, tile, type);