Update: Translations from eints
[openttd-github.git] / src / engine.cpp
blob79bff97e15223c742c916d50ca6750726b6e6bc1
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 engine.cpp Base for all engine handling. */
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "command_func.h"
13 #include "news_func.h"
14 #include "aircraft.h"
15 #include "newgrf.h"
16 #include "newgrf_engine.h"
17 #include "strings_func.h"
18 #include "core/random_func.hpp"
19 #include "window_func.h"
20 #include "autoreplace_gui.h"
21 #include "string_func.h"
22 #include "ai/ai.hpp"
23 #include "core/pool_func.hpp"
24 #include "engine_gui.h"
25 #include "engine_func.h"
26 #include "engine_base.h"
27 #include "company_base.h"
28 #include "vehicle_func.h"
29 #include "articulated_vehicles.h"
30 #include "error.h"
31 #include "engine_base.h"
32 #include "timer/timer.h"
33 #include "timer/timer_game_tick.h"
34 #include "timer/timer_game_calendar.h"
36 #include "table/strings.h"
37 #include "table/engines.h"
39 #include "safeguards.h"
41 EnginePool _engine_pool("Engine");
42 INSTANTIATE_POOL_METHODS(Engine)
44 EngineOverrideManager _engine_mngr;
46 /**
47 * Year that engine aging stops. Engines will not reduce in reliability
48 * and no more engines will be introduced
50 static TimerGameCalendar::Year _year_engine_aging_stops;
52 /** Number of engines of each vehicle type in original engine data */
53 const uint8_t _engine_counts[4] = {
54 lengthof(_orig_rail_vehicle_info),
55 lengthof(_orig_road_vehicle_info),
56 lengthof(_orig_ship_vehicle_info),
57 lengthof(_orig_aircraft_vehicle_info),
60 /** Offset of the first engine of each vehicle type in original engine data */
61 const uint8_t _engine_offsets[4] = {
63 lengthof(_orig_rail_vehicle_info),
64 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
65 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
68 static_assert(lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info) + lengthof(_orig_aircraft_vehicle_info) == lengthof(_orig_engine_info));
70 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
72 Engine::Engine(VehicleType type, EngineID base)
74 this->type = type;
75 this->grf_prop.local_id = base;
76 this->list_position = base;
77 this->preview_company = INVALID_COMPANY;
78 this->display_last_variant = INVALID_ENGINE;
80 /* Check if this base engine is within the original engine data range */
81 if (base >= _engine_counts[type]) {
82 /* 'power' defaults to zero, so we also have to default to 'wagon' */
83 if (type == VEH_TRAIN) this->u.rail.railveh_type = RAILVEH_WAGON;
84 /* Set model life to maximum to make wagons available */
85 this->info.base_life = 0xFF;
86 /* Set road vehicle tractive effort to the default value */
87 if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
88 /* Aircraft must have INVALID_CARGO as default, as there is no property */
89 if (type == VEH_AIRCRAFT) this->info.cargo_type = INVALID_CARGO;
90 /* Ships must have a non-zero acceleration. */
91 if (type == VEH_SHIP) this->u.ship.acceleration = 1;
92 /* Set visual effect to the default value */
93 switch (type) {
94 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
95 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
96 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
97 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
99 /* Set cargo aging period to the default value. */
100 this->info.cargo_age_period = Ticks::CARGO_AGING_TICKS;
101 /* Not a variant */
102 this->info.variant_id = INVALID_ENGINE;
103 return;
106 /* Copy the original engine info for this slot */
107 this->info = _orig_engine_info[_engine_offsets[type] + base];
109 /* Copy the original engine data for this slot */
110 switch (type) {
111 default: NOT_REACHED();
113 case VEH_TRAIN:
114 this->u.rail = _orig_rail_vehicle_info[base];
115 this->original_image_index = this->u.rail.image_index;
116 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
118 /* Set the default model life of original wagons to "infinite" */
119 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
121 break;
123 case VEH_ROAD:
124 this->u.road = _orig_road_vehicle_info[base];
125 this->original_image_index = this->u.road.image_index;
126 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
127 break;
129 case VEH_SHIP:
130 this->u.ship = _orig_ship_vehicle_info[base];
131 this->original_image_index = this->u.ship.image_index;
132 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
133 break;
135 case VEH_AIRCRAFT:
136 this->u.air = _orig_aircraft_vehicle_info[base];
137 this->original_image_index = this->u.air.image_index;
138 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
139 break;
144 * Checks whether the engine is a valid (non-articulated part of an) engine.
145 * @return true if enabled
147 bool Engine::IsEnabled() const
149 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
153 * Retrieve the GRF ID of the NewGRF the engine is tied to.
154 * This is the GRF providing the Action 3.
155 * @return GRF ID of the associated NewGRF.
157 uint32_t Engine::GetGRFID() const
159 const GRFFile *file = this->GetGRF();
160 return file == nullptr ? 0 : file->grfid;
164 * Determines whether an engine can carry something.
165 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
166 * @return true if the vehicle can carry something.
168 bool Engine::CanCarryCargo() const
170 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
171 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
172 * for livery selection etc.
173 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
175 switch (this->type) {
176 case VEH_TRAIN:
177 if (this->u.rail.capacity == 0) return false;
178 break;
180 case VEH_ROAD:
181 if (this->u.road.capacity == 0) return false;
182 break;
184 case VEH_SHIP:
185 case VEH_AIRCRAFT:
186 break;
188 default: NOT_REACHED();
190 return IsValidCargoID(this->GetDefaultCargoType());
195 * Determines capacity of a given vehicle from scratch.
196 * For aircraft the main capacity is determined. Mail might be present as well.
197 * @param v Vehicle of interest; nullptr in purchase list
198 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
199 * @return Capacity
201 uint Engine::DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity) const
203 assert(v == nullptr || this->index == v->engine_type);
204 if (mail_capacity != nullptr) *mail_capacity = 0;
206 if (!this->CanCarryCargo()) return 0;
208 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
209 CargoID default_cargo = this->GetDefaultCargoType();
210 CargoID cargo_type = (v != nullptr) ? v->cargo_type : default_cargo;
212 if (mail_capacity != nullptr && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
213 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
216 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
217 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
218 (new_multipliers || default_cargo != cargo_type || (v != nullptr && v->cargo_subtype != 0))) {
219 uint16_t callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
220 if (callback != CALLBACK_FAILED) return callback;
223 /* Get capacity according to property resp. CB */
224 uint capacity;
225 uint extra_mail_cap = 0;
226 switch (this->type) {
227 case VEH_TRAIN:
228 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
230 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
231 if (v == nullptr && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
232 break;
234 case VEH_ROAD:
235 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
236 break;
238 case VEH_SHIP:
239 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
240 break;
242 case VEH_AIRCRAFT:
243 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
244 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
245 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
247 if (IsValidCargoID(GetCargoIDByLabel(CT_MAIL))) {
248 if (!new_multipliers && cargo_type == GetCargoIDByLabel(CT_MAIL)) return capacity + extra_mail_cap;
250 default_cargo = GetCargoIDByLabel(CT_PASSENGERS); // Always use 'passengers' wrt. cargo multipliers
251 break;
253 default: NOT_REACHED();
256 if (!new_multipliers) {
257 /* Use the passenger multiplier for mail as well */
258 capacity += extra_mail_cap;
259 extra_mail_cap = 0;
262 /* Apply multipliers depending on cargo- and vehicletype. */
263 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
264 uint16_t default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
265 uint16_t cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
266 capacity *= cargo_multiplier;
267 if (extra_mail_cap > 0 && IsValidCargoID(GetCargoIDByLabel(CT_MAIL))) {
268 uint mail_multiplier = CargoSpec::Get(GetCargoIDByLabel(CT_MAIL))->multiplier;
269 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
271 capacity = (capacity + default_multiplier / 2) / default_multiplier;
274 return capacity;
278 * Return how much the running costs of this engine are.
279 * @return Yearly running cost of the engine.
281 Money Engine::GetRunningCost() const
283 Price base_price;
284 uint cost_factor;
285 switch (this->type) {
286 case VEH_ROAD:
287 base_price = this->u.road.running_cost_class;
288 if (base_price == INVALID_PRICE) return 0;
289 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
290 break;
292 case VEH_TRAIN:
293 base_price = this->u.rail.running_cost_class;
294 if (base_price == INVALID_PRICE) return 0;
295 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
296 break;
298 case VEH_SHIP:
299 base_price = PR_RUNNING_SHIP;
300 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
301 break;
303 case VEH_AIRCRAFT:
304 base_price = PR_RUNNING_AIRCRAFT;
305 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
306 break;
308 default: NOT_REACHED();
311 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
315 * Return how much a new engine costs.
316 * @return Cost of the engine.
318 Money Engine::GetCost() const
320 Price base_price;
321 uint cost_factor;
322 switch (this->type) {
323 case VEH_ROAD:
324 base_price = PR_BUILD_VEHICLE_ROAD;
325 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
326 break;
328 case VEH_TRAIN:
329 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
330 base_price = PR_BUILD_VEHICLE_WAGON;
331 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
332 } else {
333 base_price = PR_BUILD_VEHICLE_TRAIN;
334 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
336 break;
338 case VEH_SHIP:
339 base_price = PR_BUILD_VEHICLE_SHIP;
340 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
341 break;
343 case VEH_AIRCRAFT:
344 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
345 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
346 break;
348 default: NOT_REACHED();
351 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
355 * Returns max speed of the engine for display purposes
356 * @return max speed in km-ish/h
358 uint Engine::GetDisplayMaxSpeed() const
360 switch (this->type) {
361 case VEH_TRAIN:
362 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
364 case VEH_ROAD: {
365 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
366 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
369 case VEH_SHIP:
370 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
372 case VEH_AIRCRAFT: {
373 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
374 if (max_speed != 0) {
375 return (max_speed * 128) / 10;
377 return this->u.air.max_speed;
380 default: NOT_REACHED();
385 * Returns the power of the engine for display
386 * and sorting purposes.
387 * Only trains and road vehicles have power
388 * @return power in display units hp
390 uint Engine::GetPower() const
392 /* Only trains and road vehicles have 'power'. */
393 switch (this->type) {
394 case VEH_TRAIN:
395 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
396 case VEH_ROAD:
397 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
399 default: NOT_REACHED();
404 * Returns the weight of the engine for display purposes.
405 * For dual-headed train-engines this is the weight of both heads
406 * @return weight in display units metric tons
408 uint Engine::GetDisplayWeight() const
410 /* Only trains and road vehicles have 'weight'. */
411 switch (this->type) {
412 case VEH_TRAIN:
413 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
414 case VEH_ROAD:
415 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
417 default: NOT_REACHED();
422 * Returns the tractive effort of the engine for display purposes.
423 * For dual-headed train-engines this is the tractive effort of both heads
424 * @return tractive effort in display units kN
426 uint Engine::GetDisplayMaxTractiveEffort() const
428 /* Only trains and road vehicles have 'tractive effort'. */
429 switch (this->type) {
430 case VEH_TRAIN:
431 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
432 case VEH_ROAD:
433 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
435 default: NOT_REACHED();
440 * Returns the vehicle's (not model's!) life length in days.
441 * @return the life length
443 TimerGameCalendar::Date Engine::GetLifeLengthInDays() const
445 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
446 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life).base() * CalendarTime::DAYS_IN_LEAP_YEAR;
450 * Get the range of an aircraft type.
451 * @return Range of the aircraft type in tiles or 0 if unlimited range.
453 uint16_t Engine::GetRange() const
455 switch (this->type) {
456 case VEH_AIRCRAFT:
457 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
459 default: NOT_REACHED();
464 * Get the name of the aircraft type for display purposes.
465 * @return Aircraft type string.
467 StringID Engine::GetAircraftTypeText() const
469 switch (this->type) {
470 case VEH_AIRCRAFT:
471 switch (this->u.air.subtype) {
472 case AIR_HELI: return STR_LIVERY_HELICOPTER;
473 case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
474 case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
475 default: NOT_REACHED();
478 default: NOT_REACHED();
483 * Check whether the engine variant chain is hidden in the GUI for the given company.
484 * @param c Company to check.
485 * @return \c true iff the engine variant chain is hidden in the GUI for the given company.
487 bool Engine::IsVariantHidden(CompanyID c) const
489 /* In case company is spectator. */
490 if (c >= MAX_COMPANIES) return false;
492 /* Shortcut if this engine is explicitly hidden. */
493 if (this->IsHidden(c)) return true;
495 /* Check for hidden parent variants. This is a bit convoluted as we must check hidden status of
496 * the last display variant rather than the actual parent variant. */
497 const Engine *re = this;
498 const Engine *ve = re->GetDisplayVariant();
499 while (!(ve->IsHidden(c)) && re->info.variant_id != INVALID_ENGINE) {
500 re = Engine::Get(re->info.variant_id);
501 ve = re->GetDisplayVariant();
503 return ve->IsHidden(c);
507 * Initializes the #EngineOverrideManager with the default engines.
509 void EngineOverrideManager::ResetToDefaultMapping()
511 this->clear();
512 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
513 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
514 EngineIDMapping &eid = this->emplace_back();
515 eid.type = type;
516 eid.grfid = INVALID_GRFID;
517 eid.internal_id = internal_id;
518 eid.substitute_id = internal_id;
524 * Looks up an EngineID in the EngineOverrideManager
525 * @param type Vehicle type
526 * @param grf_local_id The local id in the newgrf
527 * @param grfid The GrfID that defines the scope of grf_local_id.
528 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
529 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
530 * @return The engine ID if present, or INVALID_ENGINE if not.
532 EngineID EngineOverrideManager::GetID(VehicleType type, uint16_t grf_local_id, uint32_t grfid)
534 EngineID index = 0;
535 for (const EngineIDMapping &eid : *this) {
536 if (eid.type == type && eid.grfid == grfid && eid.internal_id == grf_local_id) {
537 return index;
539 index++;
541 return INVALID_ENGINE;
545 * Tries to reset the engine mapping to match the current NewGRF configuration.
546 * This is only possible when there are currently no vehicles in the game.
547 * @return false if resetting failed due to present vehicles.
549 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
551 for (const Vehicle *v : Vehicle::Iterate()) {
552 if (IsCompanyBuildableVehicleType(v)) return false;
555 /* Reset the engines, they will get new EngineIDs */
556 _engine_mngr.ResetToDefaultMapping();
557 ReloadNewGRFData();
559 return true;
563 * Initialise the engine pool with the data from the original vehicles.
565 void SetupEngines()
567 CloseWindowByClass(WC_ENGINE_PREVIEW);
568 _engine_pool.CleanPool();
570 assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES);
571 [[maybe_unused]] uint index = 0;
572 for (const EngineIDMapping &eid : _engine_mngr) {
573 /* Assert is safe; there won't be more than 256 original vehicles
574 * in any case, and we just cleaned the pool. */
575 assert(Engine::CanAllocateItem());
576 [[maybe_unused]] const Engine *e = new Engine(eid.type, eid.internal_id);
577 assert(e->index == index);
578 index++;
582 void ShowEnginePreviewWindow(EngineID engine);
585 * Determine whether an engine type is a wagon (and not a loco).
586 * @param index %Engine getting queried.
587 * @return Whether the queried engine is a wagon.
589 static bool IsWagon(EngineID index)
591 const Engine *e = Engine::Get(index);
592 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
596 * Ensure engine is not set as the last used variant for any other engine.
597 * @param engine_id Engine being removed.
598 * @param type Type of engine.
600 static void ClearLastVariant(EngineID engine_id, VehicleType type)
602 for (Engine *e : Engine::IterateType(type)) {
603 if (e->display_last_variant == engine_id) e->display_last_variant = INVALID_ENGINE;
608 * Update #Engine::reliability and (if needed) update the engine GUIs.
609 * @param e %Engine to update.
611 void CalcEngineReliability(Engine *e, bool new_month)
613 /* Get source engine for reliability age. This is normally our engine unless variant reliability syncing is requested. */
614 Engine *re = e;
615 while (re->info.variant_id != INVALID_ENGINE && HasFlag(re->info.extra_flags, ExtraEngineFlags::SyncReliability)) {
616 re = Engine::Get(re->info.variant_id);
619 uint32_t age = re->age;
620 if (new_month && re->index > e->index && age != INT32_MAX) age++; /* parent variant's age has not yet updated. */
622 /* Check for early retirement */
623 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
624 int retire_early = e->info.retire_early;
625 uint retire_early_max_age = std::max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
626 if (retire_early != 0 && age >= retire_early_max_age) {
627 /* Early retirement is enabled and we're past the date... */
628 e->company_avail = 0;
629 ClearLastVariant(e->index, e->type);
630 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
634 if (age < e->duration_phase_1) {
635 uint start = e->reliability_start;
636 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
637 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
638 /* We are at the peak of this engines life. It will have max reliability.
639 * This is also true if the engines never expire. They will not go bad over time */
640 e->reliability = e->reliability_max;
641 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
642 uint max = e->reliability_max;
643 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
644 } else {
645 /* time's up for this engine.
646 * We will now completely retire this design */
647 e->company_avail = 0;
648 e->reliability = e->reliability_final;
649 /* Kick this engine out of the lists */
650 ClearLastVariant(e->index, e->type);
651 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
656 /** Compute the value for #_year_engine_aging_stops. */
657 void SetYearEngineAgingStops()
659 /* Determine last engine aging year, default to 2050 as previously. */
660 _year_engine_aging_stops = 2050;
662 for (const Engine *e : Engine::Iterate()) {
663 const EngineInfo *ei = &e->info;
665 /* Exclude certain engines */
666 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
667 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
669 /* Base year ending date on half the model life */
670 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(ei->base_intro + (ei->lifelength.base() * CalendarTime::DAYS_IN_LEAP_YEAR) / 2);
672 _year_engine_aging_stops = std::max(_year_engine_aging_stops, ymd.year);
677 * Start/initialise one engine.
678 * @param e The engine to initialise.
679 * @param aging_date The date used for age calculations.
680 * @param seed Random seed.
682 void StartupOneEngine(Engine *e, const TimerGameCalendar::YearMonthDay &aging_ymd, uint32_t seed)
684 const EngineInfo *ei = &e->info;
686 e->age = 0;
687 e->flags = 0;
688 e->company_avail = 0;
689 e->company_hidden = 0;
691 /* Vehicles with the same base_intro date shall be introduced at the same time.
692 * Make sure they use the same randomisation of the date. */
693 SavedRandomSeeds saved_seeds;
694 SaveRandomSeeds(&saved_seeds);
695 SetRandomSeed(_settings_game.game_creation.generation_seed ^ seed ^
696 ei->base_intro.base() ^
697 e->type ^
698 e->GetGRFID());
699 uint32_t r = Random();
701 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
702 * of engines in early starting games.
703 * Note: TTDP uses fixed 1922 */
704 e->intro_date = ei->base_intro <= TimerGameCalendar::ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : (TimerGameCalendar::Date)GB(r, 0, 9) + ei->base_intro;
705 if (e->intro_date <= TimerGameCalendar::date) {
706 TimerGameCalendar::YearMonthDay intro_ymd = TimerGameCalendar::ConvertDateToYMD(e->intro_date);
707 int aging_months = aging_ymd.year.base() * 12 + aging_ymd.month;
708 int intro_months = intro_ymd.year.base() * 12 + intro_ymd.month;
709 if (intro_ymd.day > 1) intro_months++; // Engines are introduced at the first month start at/after intro date.
710 e->age = aging_months - intro_months;
711 e->company_avail = MAX_UVALUE(CompanyMask);
712 e->flags |= ENGINE_AVAILABLE;
715 /* Get parent variant index for syncing reliability via random seed. */
716 const Engine *re = e;
717 while (re->info.variant_id != INVALID_ENGINE && HasFlag(re->info.extra_flags, ExtraEngineFlags::SyncReliability)) {
718 re = Engine::Get(re->info.variant_id);
721 SetRandomSeed(_settings_game.game_creation.generation_seed ^ seed ^
722 (re->index << 16) ^ (re->info.base_intro.base() << 12) ^ (re->info.decay_speed << 8) ^
723 (re->info.lifelength.base() << 4) ^ re->info.retire_early ^
724 e->type ^
725 e->GetGRFID());
727 /* Base reliability defined as a percentage of UINT16_MAX. */
728 const uint16_t RELIABILITY_START = UINT16_MAX * 48 / 100;
729 const uint16_t RELIABILITY_MAX = UINT16_MAX * 75 / 100;
730 const uint16_t RELIABILITY_FINAL = UINT16_MAX * 25 / 100;
732 static_assert(RELIABILITY_START == 0x7AE0);
733 static_assert(RELIABILITY_MAX == 0xBFFF);
734 static_assert(RELIABILITY_FINAL == 0x3FFF);
736 r = Random();
737 /* 14 bits gives a value between 0 and 16383, which is up to an additional 25%p reliability on top of the base reliability. */
738 e->reliability_start = GB(r, 16, 14) + RELIABILITY_START;
739 e->reliability_max = GB(r, 0, 14) + RELIABILITY_MAX;
741 r = Random();
742 e->reliability_final = GB(r, 16, 14) + RELIABILITY_FINAL;
744 e->duration_phase_1 = GB(r, 0, 5) + 7;
745 e->duration_phase_2 = std::max(0, int(GB(r, 5, 4)) + ei->base_life.base() * 12 - 96);
746 e->duration_phase_3 = GB(r, 9, 7) + 120;
748 RestoreRandomSeeds(saved_seeds);
750 e->reliability_spd_dec = ei->decay_speed << 2;
752 /* prevent certain engines from ever appearing. */
753 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
754 e->flags |= ENGINE_AVAILABLE;
755 e->company_avail = 0;
760 * Start/initialise all our engines. Must be called whenever there are changes
761 * to the NewGRF config.
763 void StartupEngines()
765 /* Aging of vehicles stops, so account for that when starting late */
766 const TimerGameCalendar::Date aging_date = std::min(TimerGameCalendar::date, TimerGameCalendar::ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
767 TimerGameCalendar::YearMonthDay aging_ymd = TimerGameCalendar::ConvertDateToYMD(aging_date);
768 uint32_t seed = Random();
770 for (Engine *e : Engine::Iterate()) {
771 StartupOneEngine(e, aging_ymd, seed);
773 for (Engine *e : Engine::Iterate()) {
774 CalcEngineReliability(e, false);
777 /* Update the bitmasks for the vehicle lists */
778 for (Company *c : Company::Iterate()) {
779 c->avail_railtypes = GetCompanyRailTypes(c->index);
780 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
783 /* Invalidate any open purchase lists */
784 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
786 SetWindowClassesDirty(WC_BUILD_VEHICLE);
787 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
791 * Allows engine \a eid to be used by a company \a company.
792 * @param eid The engine to enable.
793 * @param company The company to allow using the engine.
795 static void EnableEngineForCompany(EngineID eid, CompanyID company)
797 Engine *e = Engine::Get(eid);
798 Company *c = Company::Get(company);
800 SetBit(e->company_avail, company);
801 if (e->type == VEH_TRAIN) {
802 c->avail_railtypes = GetCompanyRailTypes(c->index);
803 } else if (e->type == VEH_ROAD) {
804 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
807 if (company == _local_company) {
808 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
810 /* Update the toolbar. */
811 InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
812 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
813 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
814 if (e->type == VEH_AIRCRAFT) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_AIR);
819 * Forbids engine \a eid to be used by a company \a company.
820 * @param eid The engine to disable.
821 * @param company The company to forbid using the engine.
823 static void DisableEngineForCompany(EngineID eid, CompanyID company)
825 Engine *e = Engine::Get(eid);
826 Company *c = Company::Get(company);
828 ClrBit(e->company_avail, company);
829 if (e->type == VEH_TRAIN) {
830 c->avail_railtypes = GetCompanyRailTypes(c->index);
831 } else if (e->type == VEH_ROAD) {
832 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
835 if (company == _local_company) {
836 ClearLastVariant(e->index, e->type);
837 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
842 * Company \a company accepts engine \a eid for preview.
843 * @param eid Engine being accepted (is under preview).
844 * @param company Current company previewing the engine.
845 * @param recursion_depth Recursion depth to avoid infinite loop.
847 static void AcceptEnginePreview(EngineID eid, CompanyID company, int recursion_depth = 0)
849 Engine *e = Engine::Get(eid);
851 e->preview_company = INVALID_COMPANY;
852 e->preview_asked = MAX_UVALUE(CompanyMask);
854 EnableEngineForCompany(eid, company);
856 /* Notify preview window, that it might want to close.
857 * Note: We cannot directly close the window.
858 * In singleplayer this function is called from the preview window, so
859 * we have to use the GUI-scope scheduling of InvalidateWindowData.
861 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
863 /* Don't search for variants to include if we are 10 levels deep already. */
864 if (recursion_depth >= 10) return;
866 /* Find variants to be included in preview. */
867 for (Engine *ve : Engine::IterateType(e->type)) {
868 if (ve->index != eid && ve->info.variant_id == eid && HasFlag(ve->info.extra_flags, ExtraEngineFlags::JoinPreview)) {
869 AcceptEnginePreview(ve->index, company, recursion_depth + 1);
875 * Get the best company for an engine preview.
876 * @param e Engine to preview.
877 * @return Best company if it exists, #INVALID_COMPANY otherwise.
879 static CompanyID GetPreviewCompany(Engine *e)
881 CompanyID best_company = INVALID_COMPANY;
883 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
884 CargoTypes cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : ALL_CARGOTYPES;
886 int32_t best_hist = -1;
887 for (const Company *c : Company::Iterate()) {
888 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
889 c->old_economy[0].performance_history > best_hist) {
891 /* Check whether the company uses similar vehicles */
892 for (const Vehicle *v : Vehicle::Iterate()) {
893 if (v->owner != c->index || v->type != e->type) continue;
894 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
896 best_hist = c->old_economy[0].performance_history;
897 best_company = c->index;
898 break;
903 return best_company;
907 * Checks if a vehicle type is disabled for all/ai companies.
908 * @param type The vehicle type which shall be checked.
909 * @param ai If true, check if the type is disabled for AI companies, otherwise check if
910 * the vehicle type is disabled for human companies.
911 * @return Whether or not a vehicle type is disabled.
913 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
915 switch (type) {
916 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
917 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
918 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
919 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
921 default: NOT_REACHED();
925 /** Daily check to offer an exclusive engine preview to the companies. */
926 static IntervalTimer<TimerGameCalendar> _calendar_engines_daily({TimerGameCalendar::DAY, TimerGameCalendar::Priority::ENGINE}, [](auto)
928 for (Company *c : Company::Iterate()) {
929 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, TimerGameCalendar::date);
930 c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes, TimerGameCalendar::date);
933 if (TimerGameCalendar::year >= _year_engine_aging_stops) return;
935 for (Engine *e : Engine::Iterate()) {
936 EngineID i = e->index;
937 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
938 if (e->preview_company != INVALID_COMPANY) {
939 if (!--e->preview_wait) {
940 CloseWindowById(WC_ENGINE_PREVIEW, i);
941 e->preview_company = INVALID_COMPANY;
943 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
944 e->preview_company = GetPreviewCompany(e);
946 if (e->preview_company == INVALID_COMPANY) {
947 e->preview_asked = MAX_UVALUE(CompanyMask);
948 continue;
951 SetBit(e->preview_asked, e->preview_company);
952 e->preview_wait = 20;
953 /* AIs are intentionally not skipped for preview even if they cannot build a certain
954 * vehicle type. This is done to not give poor performing human companies an "unfair"
955 * boost that they wouldn't have gotten against other human companies. The check on
956 * the line below is just to make AIs not notice that they have a preview if they
957 * cannot build the vehicle. */
958 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
959 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
966 * Clear the 'hidden' flag for all engines of a new company.
967 * @param cid Company being created.
969 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
971 for (Engine *e : Engine::Iterate()) {
972 SB(e->company_hidden, cid, 1, 0);
977 * Set the visibility of an engine.
978 * @param flags Operation to perform.
979 * @param engine_id Engine id..
980 * @param hide Set for hidden, unset for visible.
981 * @return The cost of this operation or an error.
983 CommandCost CmdSetVehicleVisibility(DoCommandFlag flags, EngineID engine_id, bool hide)
985 Engine *e = Engine::GetIfValid(engine_id);
986 if (e == nullptr || _current_company >= MAX_COMPANIES) return CMD_ERROR;
987 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
989 if ((flags & DC_EXEC) != 0) {
990 AssignBit(e->company_hidden, _current_company, hide);
991 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
994 return CommandCost();
998 * Accept an engine prototype. XXX - it is possible that the top-company
999 * changes while you are waiting to accept the offer? Then it becomes invalid
1000 * @param flags operation to perform
1001 * @param engine_id engine-prototype offered
1002 * @return the cost of this operation or an error
1004 CommandCost CmdWantEnginePreview(DoCommandFlag flags, EngineID engine_id)
1006 Engine *e = Engine::GetIfValid(engine_id);
1007 if (e == nullptr || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
1009 if (flags & DC_EXEC) AcceptEnginePreview(engine_id, _current_company);
1011 return CommandCost();
1015 * Allow or forbid a specific company to use an engine
1016 * @param flags operation to perform
1017 * @param engine_id engine id
1018 * @param company_id Company to allow/forbid the use of an engine.
1019 * @param allow false to forbid, true to allow.
1020 * @return the cost of this operation or an error
1022 CommandCost CmdEngineCtrl(DoCommandFlag flags, EngineID engine_id, CompanyID company_id, bool allow)
1024 if (_current_company != OWNER_DEITY) return CMD_ERROR;
1026 if (!Engine::IsValidID(engine_id) || !Company::IsValidID(company_id)) return CMD_ERROR;
1028 if (flags & DC_EXEC) {
1029 if (allow) {
1030 EnableEngineForCompany(engine_id, company_id);
1031 } else {
1032 DisableEngineForCompany(engine_id, company_id);
1036 return CommandCost();
1040 * An engine has become available for general use.
1041 * Also handle the exclusive engine preview contract.
1042 * @param e Engine generally available as of now.
1044 static void NewVehicleAvailable(Engine *e)
1046 EngineID index = e->index;
1048 /* In case the company didn't build the vehicle during the intro period,
1049 * prevent that company from getting future intro periods for a while. */
1050 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
1051 for (Company *c : Company::Iterate()) {
1052 uint block_preview = c->block_preview;
1054 if (!HasBit(e->company_avail, c->index)) continue;
1056 /* We assume the user did NOT build it.. prove me wrong ;) */
1057 c->block_preview = 20;
1059 for (const Vehicle *v : Vehicle::Iterate()) {
1060 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
1061 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
1062 if (v->owner == c->index && v->engine_type == index) {
1063 /* The user did prove me wrong, so restore old value */
1064 c->block_preview = block_preview;
1065 break;
1072 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
1073 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
1075 /* Now available for all companies */
1076 e->company_avail = MAX_UVALUE(CompanyMask);
1078 /* Do not introduce new rail wagons */
1079 if (IsWagon(index)) return;
1081 if (e->type == VEH_TRAIN) {
1082 /* maybe make another rail type available */
1083 assert(e->u.rail.railtype < RAILTYPE_END);
1084 for (Company *c : Company::Iterate()) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, TimerGameCalendar::date);
1085 } else if (e->type == VEH_ROAD) {
1086 /* maybe make another road type available */
1087 assert(e->u.road.roadtype < ROADTYPE_END);
1088 for (Company *c : Company::Iterate()) c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes | GetRoadTypeInfo(e->u.road.roadtype)->introduces_roadtypes, TimerGameCalendar::date);
1091 /* Only broadcast event if AIs are able to build this vehicle type. */
1092 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
1094 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
1095 if (!IsVehicleTypeDisabled(e->type, false) && !HasFlag(e->info.extra_flags, ExtraEngineFlags::NoNews)) {
1096 SetDParam(0, GetEngineCategoryName(index));
1097 SetDParam(1, PackEngineNameDParam(index, EngineNameContext::PreviewNews));
1098 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
1101 /* Update the toolbar. */
1102 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
1103 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
1104 if (e->type == VEH_AIRCRAFT) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_AIR);
1106 /* Close pending preview windows */
1107 CloseWindowById(WC_ENGINE_PREVIEW, index);
1110 /** Monthly update of the availability, reliability, and preview offers of the engines. */
1111 void CalendarEnginesMonthlyLoop()
1113 if (TimerGameCalendar::year < _year_engine_aging_stops) {
1114 bool refresh = false;
1115 for (Engine *e : Engine::Iterate()) {
1116 /* Age the vehicle */
1117 if ((e->flags & ENGINE_AVAILABLE) && e->age != INT32_MAX) {
1118 e->age++;
1119 CalcEngineReliability(e, true);
1120 refresh = true;
1123 /* Do not introduce invalid engines */
1124 if (!e->IsEnabled()) continue;
1126 if (!(e->flags & ENGINE_AVAILABLE) && TimerGameCalendar::date >= (e->intro_date + CalendarTime::DAYS_IN_YEAR)) {
1127 /* Introduce it to all companies */
1128 NewVehicleAvailable(e);
1129 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && TimerGameCalendar::date >= e->intro_date) {
1130 /* Introduction date has passed...
1131 * Check if it is allowed to build this vehicle type at all
1132 * based on the current game settings. If not, it does not
1133 * make sense to show the preview dialog to any company. */
1134 if (IsVehicleTypeDisabled(e->type, false)) continue;
1136 /* Do not introduce new rail wagons */
1137 if (IsWagon(e->index)) continue;
1139 /* Engine has no preview */
1140 if (HasFlag(e->info.extra_flags, ExtraEngineFlags::NoPreview)) continue;
1142 /* Show preview dialog to one of the companies. */
1143 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
1144 e->preview_company = INVALID_COMPANY;
1145 e->preview_asked = 0;
1149 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
1151 if (refresh) {
1152 SetWindowClassesDirty(WC_BUILD_VEHICLE);
1153 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
1158 static IntervalTimer<TimerGameCalendar> _calendar_engines_monthly({TimerGameCalendar::MONTH, TimerGameCalendar::Priority::ENGINE}, [](auto)
1160 CalendarEnginesMonthlyLoop();
1164 * Is \a name still free as name for an engine?
1165 * @param name New name of an engine.
1166 * @return \c false if the name is being used already, else \c true.
1168 static bool IsUniqueEngineName(const std::string &name)
1170 for (const Engine *e : Engine::Iterate()) {
1171 if (!e->name.empty() && e->name == name) return false;
1174 return true;
1178 * Rename an engine.
1179 * @param flags operation to perform
1180 * @param engine_id engine ID to rename
1181 * @param text the new name or an empty string when resetting to the default
1182 * @return the cost of this operation or an error
1184 CommandCost CmdRenameEngine(DoCommandFlag flags, EngineID engine_id, const std::string &text)
1186 Engine *e = Engine::GetIfValid(engine_id);
1187 if (e == nullptr) return CMD_ERROR;
1189 bool reset = text.empty();
1191 if (!reset) {
1192 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1193 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1196 if (flags & DC_EXEC) {
1197 if (reset) {
1198 e->name.clear();
1199 } else {
1200 e->name = text;
1203 MarkWholeScreenDirty();
1206 return CommandCost();
1211 * Check if an engine is buildable.
1212 * @param engine index of the engine to check.
1213 * @param type the type the engine should be.
1214 * @param company index of the company.
1215 * @return True if an engine is valid, of the specified type, and buildable by
1216 * the given company.
1218 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1220 const Engine *e = Engine::GetIfValid(engine);
1222 /* check if it's an engine that is in the engine array */
1223 if (e == nullptr) return false;
1225 /* check if it's an engine of specified type */
1226 if (e->type != type) return false;
1228 /* check if it's available ... */
1229 if (company == OWNER_DEITY) {
1230 /* ... for any company (preview does not count) */
1231 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1232 } else {
1233 /* ... for this company */
1234 if (!HasBit(e->company_avail, company)) return false;
1237 if (!e->IsEnabled()) return false;
1239 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1240 /* Check if the rail type is available to this company */
1241 const Company *c = Company::Get(company);
1242 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1244 if (type == VEH_ROAD && company != OWNER_DEITY) {
1245 /* Check if the road type is available to this company */
1246 const Company *c = Company::Get(company);
1247 if ((GetRoadTypeInfo(e->u.road.roadtype)->powered_roadtypes & c->avail_roadtypes) == ROADTYPES_NONE) return false;
1250 return true;
1254 * Check if an engine is refittable.
1255 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1256 * @param engine index of the engine to check.
1257 * @return true if the engine is refittable.
1259 bool IsEngineRefittable(EngineID engine)
1261 const Engine *e = Engine::GetIfValid(engine);
1263 /* check if it's an engine that is in the engine array */
1264 if (e == nullptr) return false;
1266 if (!e->CanCarryCargo()) return false;
1268 const EngineInfo *ei = &e->info;
1269 if (ei->refit_mask == 0) return false;
1271 /* Are there suffixes?
1272 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1273 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1275 /* Is there any cargo except the default cargo? */
1276 CargoID default_cargo = e->GetDefaultCargoType();
1277 CargoTypes default_cargo_mask = 0;
1278 SetBit(default_cargo_mask, default_cargo);
1279 return IsValidCargoID(default_cargo) && ei->refit_mask != default_cargo_mask;
1283 * Check for engines that have an appropriate availability.
1285 void CheckEngines()
1287 TimerGameCalendar::Date min_date = INT32_MAX;
1289 for (const Engine *e : Engine::Iterate()) {
1290 if (!e->IsEnabled()) continue;
1292 /* Don't consider train wagons, we need a powered engine available. */
1293 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
1295 /* We have an available engine... yay! */
1296 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1298 /* Okay, try to find the earliest date. */
1299 min_date = std::min(min_date, e->info.base_intro);
1302 if (min_date < INT32_MAX) {
1303 SetDParam(0, min_date);
1304 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1305 } else {
1306 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);