Add: Towns can build tunnels (#8473)
[openttd-github.git] / src / engine.cpp
blob2681b8fa62aa86d99c7d732b80355d861f945e6a
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 "date_func.h"
21 #include "autoreplace_gui.h"
22 #include "string_func.h"
23 #include "ai/ai.hpp"
24 #include "core/pool_func.hpp"
25 #include "engine_gui.h"
26 #include "engine_func.h"
27 #include "engine_base.h"
28 #include "company_base.h"
29 #include "vehicle_func.h"
30 #include "articulated_vehicles.h"
31 #include "error.h"
33 #include "table/strings.h"
34 #include "table/engines.h"
36 #include "safeguards.h"
38 EnginePool _engine_pool("Engine");
39 INSTANTIATE_POOL_METHODS(Engine)
41 EngineOverrideManager _engine_mngr;
43 /**
44 * Year that engine aging stops. Engines will not reduce in reliability
45 * and no more engines will be introduced
47 static Year _year_engine_aging_stops;
49 /** Number of engines of each vehicle type in original engine data */
50 const uint8 _engine_counts[4] = {
51 lengthof(_orig_rail_vehicle_info),
52 lengthof(_orig_road_vehicle_info),
53 lengthof(_orig_ship_vehicle_info),
54 lengthof(_orig_aircraft_vehicle_info),
57 /** Offset of the first engine of each vehicle type in original engine data */
58 const uint8 _engine_offsets[4] = {
60 lengthof(_orig_rail_vehicle_info),
61 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
62 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
65 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));
67 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
69 Engine::Engine() :
70 overrides_count(0),
71 overrides(nullptr)
75 Engine::Engine(VehicleType type, EngineID base)
77 this->type = type;
78 this->grf_prop.local_id = base;
79 this->list_position = base;
80 this->preview_company = INVALID_COMPANY;
82 /* Check if this base engine is within the original engine data range */
83 if (base >= _engine_counts[type]) {
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 CT_INVALID as default, as there is no property */
89 if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
90 /* Set visual effect to the default value */
91 switch (type) {
92 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
93 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
94 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
95 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
97 /* Set cargo aging period to the default value. */
98 this->info.cargo_age_period = CARGO_AGING_TICKS;
99 return;
102 /* Copy the original engine info for this slot */
103 this->info = _orig_engine_info[_engine_offsets[type] + base];
105 /* Copy the original engine data for this slot */
106 switch (type) {
107 default: NOT_REACHED();
109 case VEH_TRAIN:
110 this->u.rail = _orig_rail_vehicle_info[base];
111 this->original_image_index = this->u.rail.image_index;
112 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
114 /* Set the default model life of original wagons to "infinite" */
115 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
117 break;
119 case VEH_ROAD:
120 this->u.road = _orig_road_vehicle_info[base];
121 this->original_image_index = this->u.road.image_index;
122 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
123 break;
125 case VEH_SHIP:
126 this->u.ship = _orig_ship_vehicle_info[base];
127 this->original_image_index = this->u.ship.image_index;
128 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
129 break;
131 case VEH_AIRCRAFT:
132 this->u.air = _orig_aircraft_vehicle_info[base];
133 this->original_image_index = this->u.air.image_index;
134 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
135 break;
139 Engine::~Engine()
141 UnloadWagonOverrides(this);
145 * Checks whether the engine is a valid (non-articulated part of an) engine.
146 * @return true if enabled
148 bool Engine::IsEnabled() const
150 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
154 * Retrieve the GRF ID of the NewGRF the engine is tied to.
155 * This is the GRF providing the Action 3.
156 * @return GRF ID of the associated NewGRF.
158 uint32 Engine::GetGRFID() const
160 const GRFFile *file = this->GetGRF();
161 return file == nullptr ? 0 : file->grfid;
165 * Determines whether an engine can carry something.
166 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
167 * @return true if the vehicle can carry something.
169 bool Engine::CanCarryCargo() const
171 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
172 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
173 * for livery selection etc.
174 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
176 switch (this->type) {
177 case VEH_TRAIN:
178 if (this->u.rail.capacity == 0) return false;
179 break;
181 case VEH_ROAD:
182 if (this->u.road.capacity == 0) return false;
183 break;
185 case VEH_SHIP:
186 case VEH_AIRCRAFT:
187 break;
189 default: NOT_REACHED();
191 return this->GetDefaultCargoType() != CT_INVALID;
196 * Determines capacity of a given vehicle from scratch.
197 * For aircraft the main capacity is determined. Mail might be present as well.
198 * @param v Vehicle of interest; nullptr in purchase list
199 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
200 * @return Capacity
202 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
204 assert(v == nullptr || this->index == v->engine_type);
205 if (mail_capacity != nullptr) *mail_capacity = 0;
207 if (!this->CanCarryCargo()) return 0;
209 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
210 CargoID default_cargo = this->GetDefaultCargoType();
211 CargoID cargo_type = (v != nullptr) ? v->cargo_type : default_cargo;
213 if (mail_capacity != nullptr && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
214 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
217 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
218 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
219 (new_multipliers || default_cargo != cargo_type || (v != nullptr && v->cargo_subtype != 0))) {
220 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
221 if (callback != CALLBACK_FAILED) return callback;
224 /* Get capacity according to property resp. CB */
225 uint capacity;
226 uint extra_mail_cap = 0;
227 switch (this->type) {
228 case VEH_TRAIN:
229 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
231 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
232 if (v == nullptr && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
233 break;
235 case VEH_ROAD:
236 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
237 break;
239 case VEH_SHIP:
240 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
241 break;
243 case VEH_AIRCRAFT:
244 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
245 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
246 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
248 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
249 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
250 break;
252 default: NOT_REACHED();
255 if (!new_multipliers) {
256 /* Use the passenger multiplier for mail as well */
257 capacity += extra_mail_cap;
258 extra_mail_cap = 0;
261 /* Apply multipliers depending on cargo- and vehicletype. */
262 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
263 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
264 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
265 capacity *= cargo_multiplier;
266 if (extra_mail_cap > 0) {
267 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
268 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
270 capacity = (capacity + default_multiplier / 2) / default_multiplier;
273 return capacity;
277 * Return how much the running costs of this engine are.
278 * @return Yearly running cost of the engine.
280 Money Engine::GetRunningCost() const
282 Price base_price;
283 uint cost_factor;
284 switch (this->type) {
285 case VEH_ROAD:
286 base_price = this->u.road.running_cost_class;
287 if (base_price == INVALID_PRICE) return 0;
288 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
289 break;
291 case VEH_TRAIN:
292 base_price = this->u.rail.running_cost_class;
293 if (base_price == INVALID_PRICE) return 0;
294 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
295 break;
297 case VEH_SHIP:
298 base_price = PR_RUNNING_SHIP;
299 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
300 break;
302 case VEH_AIRCRAFT:
303 base_price = PR_RUNNING_AIRCRAFT;
304 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
305 break;
307 default: NOT_REACHED();
310 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
314 * Return how much a new engine costs.
315 * @return Cost of the engine.
317 Money Engine::GetCost() const
319 Price base_price;
320 uint cost_factor;
321 switch (this->type) {
322 case VEH_ROAD:
323 base_price = PR_BUILD_VEHICLE_ROAD;
324 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
325 break;
327 case VEH_TRAIN:
328 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
329 base_price = PR_BUILD_VEHICLE_WAGON;
330 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
331 } else {
332 base_price = PR_BUILD_VEHICLE_TRAIN;
333 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
335 break;
337 case VEH_SHIP:
338 base_price = PR_BUILD_VEHICLE_SHIP;
339 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
340 break;
342 case VEH_AIRCRAFT:
343 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
344 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
345 break;
347 default: NOT_REACHED();
350 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
354 * Returns max speed of the engine for display purposes
355 * @return max speed in km-ish/h
357 uint Engine::GetDisplayMaxSpeed() const
359 switch (this->type) {
360 case VEH_TRAIN:
361 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
363 case VEH_ROAD: {
364 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
365 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
368 case VEH_SHIP:
369 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
371 case VEH_AIRCRAFT: {
372 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
373 if (max_speed != 0) {
374 return (max_speed * 128) / 10;
376 return this->u.air.max_speed;
379 default: NOT_REACHED();
384 * Returns the power of the engine for display
385 * and sorting purposes.
386 * Only trains and road vehicles have power
387 * @return power in display units hp
389 uint Engine::GetPower() const
391 /* Only trains and road vehicles have 'power'. */
392 switch (this->type) {
393 case VEH_TRAIN:
394 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
395 case VEH_ROAD:
396 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
398 default: NOT_REACHED();
403 * Returns the weight of the engine for display purposes.
404 * For dual-headed train-engines this is the weight of both heads
405 * @return weight in display units metric tons
407 uint Engine::GetDisplayWeight() const
409 /* Only trains and road vehicles have 'weight'. */
410 switch (this->type) {
411 case VEH_TRAIN:
412 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
413 case VEH_ROAD:
414 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
416 default: NOT_REACHED();
421 * Returns the tractive effort of the engine for display purposes.
422 * For dual-headed train-engines this is the tractive effort of both heads
423 * @return tractive effort in display units kN
425 uint Engine::GetDisplayMaxTractiveEffort() const
427 /* Only trains and road vehicles have 'tractive effort'. */
428 switch (this->type) {
429 case VEH_TRAIN:
430 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256 / 1000;
431 case VEH_ROAD:
432 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256 / 1000;
434 default: NOT_REACHED();
439 * Returns the vehicle's (not model's!) life length in days.
440 * @return the life length
442 Date Engine::GetLifeLengthInDays() const
444 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
445 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
449 * Get the range of an aircraft type.
450 * @return Range of the aircraft type in tiles or 0 if unlimited range.
452 uint16 Engine::GetRange() const
454 switch (this->type) {
455 case VEH_AIRCRAFT:
456 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
458 default: NOT_REACHED();
463 * Get the name of the aircraft type for display purposes.
464 * @return Aircraft type string.
466 StringID Engine::GetAircraftTypeText() const
468 switch (this->type) {
469 case VEH_AIRCRAFT:
470 switch (this->u.air.subtype) {
471 case AIR_HELI: return STR_LIVERY_HELICOPTER;
472 case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
473 case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
474 default: NOT_REACHED();
477 default: NOT_REACHED();
482 * Initializes the #EngineOverrideManager with the default engines.
484 void EngineOverrideManager::ResetToDefaultMapping()
486 this->clear();
487 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
488 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
489 EngineIDMapping &eid = this->emplace_back();
490 eid.type = type;
491 eid.grfid = INVALID_GRFID;
492 eid.internal_id = internal_id;
493 eid.substitute_id = internal_id;
499 * Looks up an EngineID in the EngineOverrideManager
500 * @param type Vehicle type
501 * @param grf_local_id The local id in the newgrf
502 * @param grfid The GrfID that defines the scope of grf_local_id.
503 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
504 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
505 * @return The engine ID if present, or INVALID_ENGINE if not.
507 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
509 EngineID index = 0;
510 for (const EngineIDMapping &eid : *this) {
511 if (eid.type == type && eid.grfid == grfid && eid.internal_id == grf_local_id) {
512 return index;
514 index++;
516 return INVALID_ENGINE;
520 * Tries to reset the engine mapping to match the current NewGRF configuration.
521 * This is only possible when there are currently no vehicles in the game.
522 * @return false if resetting failed due to present vehicles.
524 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
526 for (const Vehicle *v : Vehicle::Iterate()) {
527 if (IsCompanyBuildableVehicleType(v)) return false;
530 /* Reset the engines, they will get new EngineIDs */
531 _engine_mngr.ResetToDefaultMapping();
532 ReloadNewGRFData();
534 return true;
538 * Initialise the engine pool with the data from the original vehicles.
540 void SetupEngines()
542 DeleteWindowByClass(WC_ENGINE_PREVIEW);
543 _engine_pool.CleanPool();
545 assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES);
546 uint index = 0;
547 for (const EngineIDMapping &eid : _engine_mngr) {
548 /* Assert is safe; there won't be more than 256 original vehicles
549 * in any case, and we just cleaned the pool. */
550 assert(Engine::CanAllocateItem());
551 const Engine *e = new Engine(eid.type, eid.internal_id);
552 assert(e->index == index);
553 index++;
557 void ShowEnginePreviewWindow(EngineID engine);
560 * Determine whether an engine type is a wagon (and not a loco).
561 * @param index %Engine getting queried.
562 * @return Whether the queried engine is a wagon.
564 static bool IsWagon(EngineID index)
566 const Engine *e = Engine::Get(index);
567 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
571 * Update #Engine::reliability and (if needed) update the engine GUIs.
572 * @param e %Engine to update.
574 static void CalcEngineReliability(Engine *e)
576 uint age = e->age;
578 /* Check for early retirement */
579 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
580 int retire_early = e->info.retire_early;
581 uint retire_early_max_age = std::max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
582 if (retire_early != 0 && age >= retire_early_max_age) {
583 /* Early retirement is enabled and we're past the date... */
584 e->company_avail = 0;
585 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
589 if (age < e->duration_phase_1) {
590 uint start = e->reliability_start;
591 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
592 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
593 /* We are at the peak of this engines life. It will have max reliability.
594 * This is also true if the engines never expire. They will not go bad over time */
595 e->reliability = e->reliability_max;
596 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
597 uint max = e->reliability_max;
598 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
599 } else {
600 /* time's up for this engine.
601 * We will now completely retire this design */
602 e->company_avail = 0;
603 e->reliability = e->reliability_final;
604 /* Kick this engine out of the lists */
605 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
607 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
608 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
611 /** Compute the value for #_year_engine_aging_stops. */
612 void SetYearEngineAgingStops()
614 /* Determine last engine aging year, default to 2050 as previously. */
615 _year_engine_aging_stops = 2050;
617 for (const Engine *e : Engine::Iterate()) {
618 const EngineInfo *ei = &e->info;
620 /* Exclude certain engines */
621 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
622 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
624 /* Base year ending date on half the model life */
625 YearMonthDay ymd;
626 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
628 _year_engine_aging_stops = std::max(_year_engine_aging_stops, ymd.year);
633 * Start/initialise one engine.
634 * @param e The engine to initialise.
635 * @param aging_date The date used for age calculations.
637 void StartupOneEngine(Engine *e, Date aging_date)
639 const EngineInfo *ei = &e->info;
641 e->age = 0;
642 e->flags = 0;
643 e->company_avail = 0;
644 e->company_hidden = 0;
646 /* Vehicles with the same base_intro date shall be introduced at the same time.
647 * Make sure they use the same randomisation of the date. */
648 SavedRandomSeeds saved_seeds;
649 SaveRandomSeeds(&saved_seeds);
650 SetRandomSeed(_settings_game.game_creation.generation_seed ^
651 ei->base_intro ^
652 e->type ^
653 e->GetGRFID());
654 uint32 r = Random();
656 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
657 * of engines in early starting games.
658 * Note: TTDP uses fixed 1922 */
659 e->intro_date = ei->base_intro <= ConvertYMDToDate(_settings_game.game_creation.starting_year + 2, 0, 1) ? ei->base_intro : (Date)GB(r, 0, 9) + ei->base_intro;
660 if (e->intro_date <= _date) {
661 e->age = (aging_date - e->intro_date) >> 5;
662 e->company_avail = (CompanyMask)-1;
663 e->flags |= ENGINE_AVAILABLE;
666 RestoreRandomSeeds(saved_seeds);
668 r = Random();
669 e->reliability_start = GB(r, 16, 14) + 0x7AE0;
670 e->reliability_max = GB(r, 0, 14) + 0xBFFF;
672 r = Random();
673 e->reliability_final = GB(r, 16, 14) + 0x3FFF;
674 e->duration_phase_1 = GB(r, 0, 5) + 7;
675 e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
676 e->duration_phase_3 = GB(r, 9, 7) + 120;
678 e->reliability_spd_dec = ei->decay_speed << 2;
680 CalcEngineReliability(e);
682 /* prevent certain engines from ever appearing. */
683 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
684 e->flags |= ENGINE_AVAILABLE;
685 e->company_avail = 0;
690 * Start/initialise all our engines. Must be called whenever there are changes
691 * to the NewGRF config.
693 void StartupEngines()
695 /* Aging of vehicles stops, so account for that when starting late */
696 const Date aging_date = std::min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
698 for (Engine *e : Engine::Iterate()) {
699 StartupOneEngine(e, aging_date);
702 /* Update the bitmasks for the vehicle lists */
703 for (Company *c : Company::Iterate()) {
704 c->avail_railtypes = GetCompanyRailtypes(c->index);
705 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
708 /* Invalidate any open purchase lists */
709 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
713 * Allows engine \a eid to be used by a company \a company.
714 * @param eid The engine to enable.
715 * @param company The company to allow using the engine.
717 static void EnableEngineForCompany(EngineID eid, CompanyID company)
719 Engine *e = Engine::Get(eid);
720 Company *c = Company::Get(company);
722 SetBit(e->company_avail, company);
723 if (e->type == VEH_TRAIN) {
724 assert(e->u.rail.railtype < RAILTYPE_END);
725 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
726 } else if (e->type == VEH_ROAD) {
727 assert(e->u.road.roadtype < ROADTYPE_END);
728 c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes | GetRoadTypeInfo(e->u.road.roadtype)->introduces_roadtypes, _date);
731 if (company == _local_company) {
732 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
734 /* Update the toolbar. */
735 InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
736 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
737 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
742 * Forbids engine \a eid to be used by a company \a company.
743 * @param eid The engine to disable.
744 * @param company The company to forbid using the engine.
746 static void DisableEngineForCompany(EngineID eid, CompanyID company)
748 Engine *e = Engine::Get(eid);
750 ClrBit(e->company_avail, company);
752 if (company == _local_company) {
753 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
758 * Company \a company accepts engine \a eid for preview.
759 * @param eid Engine being accepted (is under preview).
760 * @param company Current company previewing the engine.
762 static void AcceptEnginePreview(EngineID eid, CompanyID company)
764 Engine *e = Engine::Get(eid);
766 e->preview_company = INVALID_COMPANY;
767 e->preview_asked = (CompanyMask)-1;
769 EnableEngineForCompany(eid, company);
771 /* Notify preview window, that it might want to close.
772 * Note: We cannot directly close the window.
773 * In singleplayer this function is called from the preview window, so
774 * we have to use the GUI-scope scheduling of InvalidateWindowData.
776 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
780 * Get the best company for an engine preview.
781 * @param e Engine to preview.
782 * @return Best company if it exists, #INVALID_COMPANY otherwise.
784 static CompanyID GetPreviewCompany(Engine *e)
786 CompanyID best_company = INVALID_COMPANY;
788 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
789 CargoTypes cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : ALL_CARGOTYPES;
791 int32 best_hist = -1;
792 for (const Company *c : Company::Iterate()) {
793 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
794 c->old_economy[0].performance_history > best_hist) {
796 /* Check whether the company uses similar vehicles */
797 for (const Vehicle *v : Vehicle::Iterate()) {
798 if (v->owner != c->index || v->type != e->type) continue;
799 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
801 best_hist = c->old_economy[0].performance_history;
802 best_company = c->index;
803 break;
808 return best_company;
812 * Checks if a vehicle type is disabled for all/ai companies.
813 * @param type The vehicle type which shall be checked.
814 * @param ai If true, check if the type is disabled for AI companies, otherwise check if
815 * the vehicle type is disabled for human companies.
816 * @return Whether or not a vehicle type is disabled.
818 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
820 switch (type) {
821 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
822 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
823 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
824 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
826 default: NOT_REACHED();
830 /** Daily check to offer an exclusive engine preview to the companies. */
831 void EnginesDailyLoop()
833 for (Company *c : Company::Iterate()) {
834 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
835 c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes, _date);
838 if (_cur_year >= _year_engine_aging_stops) return;
840 for (Engine *e : Engine::Iterate()) {
841 EngineID i = e->index;
842 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
843 if (e->preview_company != INVALID_COMPANY) {
844 if (!--e->preview_wait) {
845 DeleteWindowById(WC_ENGINE_PREVIEW, i);
846 e->preview_company = INVALID_COMPANY;
848 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
849 e->preview_company = GetPreviewCompany(e);
851 if (e->preview_company == INVALID_COMPANY) {
852 e->preview_asked = (CompanyMask)-1;
853 continue;
856 SetBit(e->preview_asked, e->preview_company);
857 e->preview_wait = 20;
858 /* AIs are intentionally not skipped for preview even if they cannot build a certain
859 * vehicle type. This is done to not give poor performing human companies an "unfair"
860 * boost that they wouldn't have gotten against other human companies. The check on
861 * the line below is just to make AIs not notice that they have a preview if they
862 * cannot build the vehicle. */
863 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
864 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
871 * Clear the 'hidden' flag for all engines of a new company.
872 * @param cid Company being created.
874 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
876 for (Engine *e : Engine::Iterate()) {
877 SB(e->company_hidden, cid, 1, 0);
882 * Set the visibility of an engine.
883 * @param tile Unused.
884 * @param flags Operation to perform.
885 * @param p1 Unused.
886 * @param p2 Bit 31: 0=visible, 1=hidden, other bits for the #EngineID.
887 * @param text Unused.
888 * @return The cost of this operation or an error.
890 CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
892 Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
893 if (e == nullptr || _current_company >= MAX_COMPANIES) return CMD_ERROR;
894 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
896 if ((flags & DC_EXEC) != 0) {
897 SB(e->company_hidden, _current_company, 1, GB(p2, 31, 1));
898 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
901 return CommandCost();
905 * Accept an engine prototype. XXX - it is possible that the top-company
906 * changes while you are waiting to accept the offer? Then it becomes invalid
907 * @param tile unused
908 * @param flags operation to perform
909 * @param p1 engine-prototype offered
910 * @param p2 unused
911 * @param text unused
912 * @return the cost of this operation or an error
914 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
916 Engine *e = Engine::GetIfValid(p1);
917 if (e == nullptr || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
919 if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
921 return CommandCost();
925 * Allow or forbid a specific company to use an engine
926 * @param tile unused
927 * @param flags operation to perform
928 * @param p1 engine id
929 * @param p2 various bitstuffed elements
930 * - p2 = (bit 0 - 7) - Company to allow/forbid the use of an engine.
931 * - p2 = (bit 31) - 0 to forbid, 1 to allow.
932 * @param text unused
933 * @return the cost of this operation or an error
935 CommandCost CmdEngineCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
937 if (_current_company != OWNER_DEITY) return CMD_ERROR;
938 EngineID engine_id = (EngineID)p1;
939 CompanyID company_id = (CompanyID)GB(p2, 0, 8);
940 bool allow = HasBit(p2, 31);
942 if (!Engine::IsValidID(engine_id) || !Company::IsValidID(company_id)) return CMD_ERROR;
944 if (flags & DC_EXEC) {
945 if (allow) {
946 EnableEngineForCompany(engine_id, company_id);
947 } else {
948 DisableEngineForCompany(engine_id, company_id);
952 return CommandCost();
956 * An engine has become available for general use.
957 * Also handle the exclusive engine preview contract.
958 * @param e Engine generally available as of now.
960 static void NewVehicleAvailable(Engine *e)
962 EngineID index = e->index;
964 /* In case the company didn't build the vehicle during the intro period,
965 * prevent that company from getting future intro periods for a while. */
966 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
967 for (Company *c : Company::Iterate()) {
968 uint block_preview = c->block_preview;
970 if (!HasBit(e->company_avail, c->index)) continue;
972 /* We assume the user did NOT build it.. prove me wrong ;) */
973 c->block_preview = 20;
975 for (const Vehicle *v : Vehicle::Iterate()) {
976 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
977 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
978 if (v->owner == c->index && v->engine_type == index) {
979 /* The user did prove me wrong, so restore old value */
980 c->block_preview = block_preview;
981 break;
988 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
989 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
991 /* Now available for all companies */
992 e->company_avail = (CompanyMask)-1;
994 /* Do not introduce new rail wagons */
995 if (IsWagon(index)) return;
997 if (e->type == VEH_TRAIN) {
998 /* maybe make another rail type available */
999 RailType railtype = e->u.rail.railtype;
1000 assert(railtype < RAILTYPE_END);
1001 for (Company *c : Company::Iterate()) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
1002 } else if (e->type == VEH_ROAD) {
1003 /* maybe make another road type available */
1004 assert(e->u.road.roadtype < ROADTYPE_END);
1005 for (Company* c : Company::Iterate()) c->avail_roadtypes = AddDateIntroducedRoadTypes(c->avail_roadtypes | GetRoadTypeInfo(e->u.road.roadtype)->introduces_roadtypes, _date);
1008 /* Only broadcast event if AIs are able to build this vehicle type. */
1009 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
1011 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
1012 if (!IsVehicleTypeDisabled(e->type, false)) {
1013 SetDParam(0, GetEngineCategoryName(index));
1014 SetDParam(1, index);
1015 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
1018 /* Update the toolbar. */
1019 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
1020 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
1022 /* Close pending preview windows */
1023 DeleteWindowById(WC_ENGINE_PREVIEW, index);
1026 /** Monthly update of the availability, reliability, and preview offers of the engines. */
1027 void EnginesMonthlyLoop()
1029 if (_cur_year < _year_engine_aging_stops) {
1030 for (Engine *e : Engine::Iterate()) {
1031 /* Age the vehicle */
1032 if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
1033 e->age++;
1034 CalcEngineReliability(e);
1037 /* Do not introduce invalid engines */
1038 if (!e->IsEnabled()) continue;
1040 if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
1041 /* Introduce it to all companies */
1042 NewVehicleAvailable(e);
1043 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
1044 /* Introduction date has passed...
1045 * Check if it is allowed to build this vehicle type at all
1046 * based on the current game settings. If not, it does not
1047 * make sense to show the preview dialog to any company. */
1048 if (IsVehicleTypeDisabled(e->type, false)) continue;
1050 /* Do not introduce new rail wagons */
1051 if (IsWagon(e->index)) continue;
1053 /* Show preview dialog to one of the companies. */
1054 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
1055 e->preview_company = INVALID_COMPANY;
1056 e->preview_asked = 0;
1060 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
1065 * Is \a name still free as name for an engine?
1066 * @param name New name of an engine.
1067 * @return \c false if the name is being used already, else \c true.
1069 static bool IsUniqueEngineName(const char *name)
1071 for (const Engine *e : Engine::Iterate()) {
1072 if (!e->name.empty() && e->name == name) return false;
1075 return true;
1079 * Rename an engine.
1080 * @param tile unused
1081 * @param flags operation to perform
1082 * @param p1 engine ID to rename
1083 * @param p2 unused
1084 * @param text the new name or an empty string when resetting to the default
1085 * @return the cost of this operation or an error
1087 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1089 Engine *e = Engine::GetIfValid(p1);
1090 if (e == nullptr) return CMD_ERROR;
1092 bool reset = StrEmpty(text);
1094 if (!reset) {
1095 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1096 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1099 if (flags & DC_EXEC) {
1100 if (reset) {
1101 e->name.clear();
1102 } else {
1103 e->name = text;
1106 MarkWholeScreenDirty();
1109 return CommandCost();
1114 * Check if an engine is buildable.
1115 * @param engine index of the engine to check.
1116 * @param type the type the engine should be.
1117 * @param company index of the company.
1118 * @return True if an engine is valid, of the specified type, and buildable by
1119 * the given company.
1121 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1123 const Engine *e = Engine::GetIfValid(engine);
1125 /* check if it's an engine that is in the engine array */
1126 if (e == nullptr) return false;
1128 /* check if it's an engine of specified type */
1129 if (e->type != type) return false;
1131 /* check if it's available ... */
1132 if (company == OWNER_DEITY) {
1133 /* ... for any company (preview does not count) */
1134 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1135 } else {
1136 /* ... for this company */
1137 if (!HasBit(e->company_avail, company)) return false;
1140 if (!e->IsEnabled()) return false;
1142 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1143 /* Check if the rail type is available to this company */
1144 const Company *c = Company::Get(company);
1145 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1147 if (type == VEH_ROAD && company != OWNER_DEITY) {
1148 /* Check if the road type is available to this company */
1149 const Company *c = Company::Get(company);
1150 if ((GetRoadTypeInfo(e->u.road.roadtype)->powered_roadtypes & c->avail_roadtypes) == ROADTYPES_NONE) return false;
1153 return true;
1157 * Check if an engine is refittable.
1158 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1159 * @param engine index of the engine to check.
1160 * @return true if the engine is refittable.
1162 bool IsEngineRefittable(EngineID engine)
1164 const Engine *e = Engine::GetIfValid(engine);
1166 /* check if it's an engine that is in the engine array */
1167 if (e == nullptr) return false;
1169 if (!e->CanCarryCargo()) return false;
1171 const EngineInfo *ei = &e->info;
1172 if (ei->refit_mask == 0) return false;
1174 /* Are there suffixes?
1175 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1176 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1178 /* Is there any cargo except the default cargo? */
1179 CargoID default_cargo = e->GetDefaultCargoType();
1180 CargoTypes default_cargo_mask = 0;
1181 SetBit(default_cargo_mask, default_cargo);
1182 return default_cargo != CT_INVALID && ei->refit_mask != default_cargo_mask;
1186 * Check for engines that have an appropriate availability.
1188 void CheckEngines()
1190 Date min_date = INT32_MAX;
1192 for (const Engine *e : Engine::Iterate()) {
1193 if (!e->IsEnabled()) continue;
1195 /* We have an available engine... yay! */
1196 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1198 /* Okay, try to find the earliest date. */
1199 min_date = std::min(min_date, e->info.base_intro);
1202 if (min_date < INT32_MAX) {
1203 SetDParam(0, min_date);
1204 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1205 } else {
1206 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);