Add: INR currency (#8136)
[openttd-github.git] / src / engine.cpp
blobc3e9329fb75c14fd986936b0d6d57c51d02e3271
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 assert_compile(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 name(nullptr),
71 overrides_count(0),
72 overrides(nullptr)
76 Engine::Engine(VehicleType type, EngineID base)
78 this->type = type;
79 this->grf_prop.local_id = base;
80 this->list_position = base;
81 this->preview_company = INVALID_COMPANY;
83 /* Check if this base engine is within the original engine data range */
84 if (base >= _engine_counts[type]) {
85 /* Set model life to maximum to make wagons available */
86 this->info.base_life = 0xFF;
87 /* Set road vehicle tractive effort to the default value */
88 if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
89 /* Aircraft must have CT_INVALID as default, as there is no property */
90 if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
91 /* Set visual effect to the default value */
92 switch (type) {
93 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
94 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
95 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
96 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
98 /* Set cargo aging period to the default value. */
99 this->info.cargo_age_period = CARGO_AGING_TICKS;
100 return;
103 /* Copy the original engine info for this slot */
104 this->info = _orig_engine_info[_engine_offsets[type] + base];
106 /* Copy the original engine data for this slot */
107 switch (type) {
108 default: NOT_REACHED();
110 case VEH_TRAIN:
111 this->u.rail = _orig_rail_vehicle_info[base];
112 this->original_image_index = this->u.rail.image_index;
113 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
115 /* Set the default model life of original wagons to "infinite" */
116 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
118 break;
120 case VEH_ROAD:
121 this->u.road = _orig_road_vehicle_info[base];
122 this->original_image_index = this->u.road.image_index;
123 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
124 break;
126 case VEH_SHIP:
127 this->u.ship = _orig_ship_vehicle_info[base];
128 this->original_image_index = this->u.ship.image_index;
129 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
130 break;
132 case VEH_AIRCRAFT:
133 this->u.air = _orig_aircraft_vehicle_info[base];
134 this->original_image_index = this->u.air.image_index;
135 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
136 break;
140 Engine::~Engine()
142 UnloadWagonOverrides(this);
143 free(this->name);
147 * Checks whether the engine is a valid (non-articulated part of an) engine.
148 * @return true if enabled
150 bool Engine::IsEnabled() const
152 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
156 * Retrieve the GRF ID of the NewGRF the engine is tied to.
157 * This is the GRF providing the Action 3.
158 * @return GRF ID of the associated NewGRF.
160 uint32 Engine::GetGRFID() const
162 const GRFFile *file = this->GetGRF();
163 return file == nullptr ? 0 : file->grfid;
167 * Determines whether an engine can carry something.
168 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
169 * @return true if the vehicle can carry something.
171 bool Engine::CanCarryCargo() const
173 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
174 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
175 * for livery selection etc.
176 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
178 switch (this->type) {
179 case VEH_TRAIN:
180 if (this->u.rail.capacity == 0) return false;
181 break;
183 case VEH_ROAD:
184 if (this->u.road.capacity == 0) return false;
185 break;
187 case VEH_SHIP:
188 case VEH_AIRCRAFT:
189 break;
191 default: NOT_REACHED();
193 return this->GetDefaultCargoType() != CT_INVALID;
198 * Determines capacity of a given vehicle from scratch.
199 * For aircraft the main capacity is determined. Mail might be present as well.
200 * @param v Vehicle of interest; nullptr in purchase list
201 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
202 * @return Capacity
204 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
206 assert(v == nullptr || this->index == v->engine_type);
207 if (mail_capacity != nullptr) *mail_capacity = 0;
209 if (!this->CanCarryCargo()) return 0;
211 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
212 CargoID default_cargo = this->GetDefaultCargoType();
213 CargoID cargo_type = (v != nullptr) ? v->cargo_type : default_cargo;
215 if (mail_capacity != nullptr && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
216 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
219 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
220 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
221 (new_multipliers || default_cargo != cargo_type || (v != nullptr && v->cargo_subtype != 0))) {
222 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
223 if (callback != CALLBACK_FAILED) return callback;
226 /* Get capacity according to property resp. CB */
227 uint capacity;
228 uint extra_mail_cap = 0;
229 switch (this->type) {
230 case VEH_TRAIN:
231 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
233 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
234 if (v == nullptr && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
235 break;
237 case VEH_ROAD:
238 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
239 break;
241 case VEH_SHIP:
242 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
243 break;
245 case VEH_AIRCRAFT:
246 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
247 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
248 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
250 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
251 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
252 break;
254 default: NOT_REACHED();
257 if (!new_multipliers) {
258 /* Use the passenger multiplier for mail as well */
259 capacity += extra_mail_cap;
260 extra_mail_cap = 0;
263 /* Apply multipliers depending on cargo- and vehicletype. */
264 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
265 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
266 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
267 capacity *= cargo_multiplier;
268 if (extra_mail_cap > 0) {
269 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
270 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
272 capacity = (capacity + default_multiplier / 2) / default_multiplier;
275 return capacity;
279 * Return how much the running costs of this engine are.
280 * @return Yearly running cost of the engine.
282 Money Engine::GetRunningCost() const
284 Price base_price;
285 uint cost_factor;
286 switch (this->type) {
287 case VEH_ROAD:
288 base_price = this->u.road.running_cost_class;
289 if (base_price == INVALID_PRICE) return 0;
290 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
291 break;
293 case VEH_TRAIN:
294 base_price = this->u.rail.running_cost_class;
295 if (base_price == INVALID_PRICE) return 0;
296 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
297 break;
299 case VEH_SHIP:
300 base_price = PR_RUNNING_SHIP;
301 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
302 break;
304 case VEH_AIRCRAFT:
305 base_price = PR_RUNNING_AIRCRAFT;
306 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
307 break;
309 default: NOT_REACHED();
312 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
316 * Return how much a new engine costs.
317 * @return Cost of the engine.
319 Money Engine::GetCost() const
321 Price base_price;
322 uint cost_factor;
323 switch (this->type) {
324 case VEH_ROAD:
325 base_price = PR_BUILD_VEHICLE_ROAD;
326 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
327 break;
329 case VEH_TRAIN:
330 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
331 base_price = PR_BUILD_VEHICLE_WAGON;
332 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
333 } else {
334 base_price = PR_BUILD_VEHICLE_TRAIN;
335 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
337 break;
339 case VEH_SHIP:
340 base_price = PR_BUILD_VEHICLE_SHIP;
341 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
342 break;
344 case VEH_AIRCRAFT:
345 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
346 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
347 break;
349 default: NOT_REACHED();
352 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
356 * Returns max speed of the engine for display purposes
357 * @return max speed in km-ish/h
359 uint Engine::GetDisplayMaxSpeed() const
361 switch (this->type) {
362 case VEH_TRAIN:
363 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
365 case VEH_ROAD: {
366 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
367 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
370 case VEH_SHIP:
371 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
373 case VEH_AIRCRAFT: {
374 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
375 if (max_speed != 0) {
376 return (max_speed * 128) / 10;
378 return this->u.air.max_speed;
381 default: NOT_REACHED();
386 * Returns the power of the engine for display
387 * and sorting purposes.
388 * Only trains and road vehicles have power
389 * @return power in display units hp
391 uint Engine::GetPower() const
393 /* Only trains and road vehicles have 'power'. */
394 switch (this->type) {
395 case VEH_TRAIN:
396 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
397 case VEH_ROAD:
398 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
400 default: NOT_REACHED();
405 * Returns the weight of the engine for display purposes.
406 * For dual-headed train-engines this is the weight of both heads
407 * @return weight in display units metric tons
409 uint Engine::GetDisplayWeight() const
411 /* Only trains and road vehicles have 'weight'. */
412 switch (this->type) {
413 case VEH_TRAIN:
414 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
415 case VEH_ROAD:
416 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
418 default: NOT_REACHED();
423 * Returns the tractive effort of the engine for display purposes.
424 * For dual-headed train-engines this is the tractive effort of both heads
425 * @return tractive effort in display units kN
427 uint Engine::GetDisplayMaxTractiveEffort() const
429 /* Only trains and road vehicles have 'tractive effort'. */
430 switch (this->type) {
431 case VEH_TRAIN:
432 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256 / 1000;
433 case VEH_ROAD:
434 return (GROUND_ACCELERATION * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256 / 1000;
436 default: NOT_REACHED();
441 * Returns the vehicle's (not model's!) life length in days.
442 * @return the life length
444 Date Engine::GetLifeLengthInDays() const
446 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
447 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
451 * Get the range of an aircraft type.
452 * @return Range of the aircraft type in tiles or 0 if unlimited range.
454 uint16 Engine::GetRange() const
456 switch (this->type) {
457 case VEH_AIRCRAFT:
458 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
460 default: NOT_REACHED();
465 * Get the name of the aircraft type for display purposes.
466 * @return Aircraft type string.
468 StringID Engine::GetAircraftTypeText() const
470 switch (this->type) {
471 case VEH_AIRCRAFT:
472 switch (this->u.air.subtype) {
473 case AIR_HELI: return STR_LIVERY_HELICOPTER;
474 case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
475 case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
476 default: NOT_REACHED();
479 default: NOT_REACHED();
484 * Initializes the #EngineOverrideManager with the default engines.
486 void EngineOverrideManager::ResetToDefaultMapping()
488 this->clear();
489 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
490 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
491 /*C++17: EngineIDMapping &eid = */ this->emplace_back();
492 EngineIDMapping &eid = this->back();
493 eid.type = type;
494 eid.grfid = INVALID_GRFID;
495 eid.internal_id = internal_id;
496 eid.substitute_id = internal_id;
502 * Looks up an EngineID in the EngineOverrideManager
503 * @param type Vehicle type
504 * @param grf_local_id The local id in the newgrf
505 * @param grfid The GrfID that defines the scope of grf_local_id.
506 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
507 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
508 * @return The engine ID if present, or INVALID_ENGINE if not.
510 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
512 EngineID index = 0;
513 for (const EngineIDMapping &eid : *this) {
514 if (eid.type == type && eid.grfid == grfid && eid.internal_id == grf_local_id) {
515 return index;
517 index++;
519 return INVALID_ENGINE;
523 * Tries to reset the engine mapping to match the current NewGRF configuration.
524 * This is only possible when there are currently no vehicles in the game.
525 * @return false if resetting failed due to present vehicles.
527 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
529 for (const Vehicle *v : Vehicle::Iterate()) {
530 if (IsCompanyBuildableVehicleType(v)) return false;
533 /* Reset the engines, they will get new EngineIDs */
534 _engine_mngr.ResetToDefaultMapping();
535 ReloadNewGRFData();
537 return true;
541 * Initialise the engine pool with the data from the original vehicles.
543 void SetupEngines()
545 DeleteWindowByClass(WC_ENGINE_PREVIEW);
546 _engine_pool.CleanPool();
548 assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES);
549 uint index = 0;
550 for (const EngineIDMapping &eid : _engine_mngr) {
551 /* Assert is safe; there won't be more than 256 original vehicles
552 * in any case, and we just cleaned the pool. */
553 assert(Engine::CanAllocateItem());
554 const Engine *e = new Engine(eid.type, eid.internal_id);
555 assert(e->index == index);
556 index++;
560 void ShowEnginePreviewWindow(EngineID engine);
563 * Determine whether an engine type is a wagon (and not a loco).
564 * @param index %Engine getting queried.
565 * @return Whether the queried engine is a wagon.
567 static bool IsWagon(EngineID index)
569 const Engine *e = Engine::Get(index);
570 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
574 * Update #Engine::reliability and (if needed) update the engine GUIs.
575 * @param e %Engine to update.
577 static void CalcEngineReliability(Engine *e)
579 uint age = e->age;
581 /* Check for early retirement */
582 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
583 int retire_early = e->info.retire_early;
584 uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
585 if (retire_early != 0 && age >= retire_early_max_age) {
586 /* Early retirement is enabled and we're past the date... */
587 e->company_avail = 0;
588 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
592 if (age < e->duration_phase_1) {
593 uint start = e->reliability_start;
594 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
595 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
596 /* We are at the peak of this engines life. It will have max reliability.
597 * This is also true if the engines never expire. They will not go bad over time */
598 e->reliability = e->reliability_max;
599 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
600 uint max = e->reliability_max;
601 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
602 } else {
603 /* time's up for this engine.
604 * We will now completely retire this design */
605 e->company_avail = 0;
606 e->reliability = e->reliability_final;
607 /* Kick this engine out of the lists */
608 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
610 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
611 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
614 /** Compute the value for #_year_engine_aging_stops. */
615 void SetYearEngineAgingStops()
617 /* Determine last engine aging year, default to 2050 as previously. */
618 _year_engine_aging_stops = 2050;
620 for (const Engine *e : Engine::Iterate()) {
621 const EngineInfo *ei = &e->info;
623 /* Exclude certain engines */
624 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
625 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
627 /* Base year ending date on half the model life */
628 YearMonthDay ymd;
629 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
631 _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
636 * Start/initialise one engine.
637 * @param e The engine to initialise.
638 * @param aging_date The date used for age calculations.
640 void StartupOneEngine(Engine *e, Date aging_date)
642 const EngineInfo *ei = &e->info;
644 e->age = 0;
645 e->flags = 0;
646 e->company_avail = 0;
647 e->company_hidden = 0;
649 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
650 * of engines in early starting games.
651 * Note: TTDP uses fixed 1922 */
652 SavedRandomSeeds saved_seeds;
653 SaveRandomSeeds(&saved_seeds);
654 SetRandomSeed(_settings_game.game_creation.generation_seed ^
655 ei->base_intro ^
656 e->type ^
657 e->GetGRFID());
658 uint32 r = Random();
660 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;
661 if (e->intro_date <= _date) {
662 e->age = (aging_date - e->intro_date) >> 5;
663 e->company_avail = (CompanyMask)-1;
664 e->flags |= ENGINE_AVAILABLE;
667 e->reliability_start = GB(r, 16, 14) + 0x7AE0;
668 r = Random();
669 e->reliability_max = GB(r, 0, 14) + 0xBFFF;
670 e->reliability_final = GB(r, 16, 14) + 0x3FFF;
672 r = Random();
673 e->duration_phase_1 = GB(r, 0, 5) + 7;
674 e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
675 e->duration_phase_3 = GB(r, 9, 7) + 120;
677 e->reliability_spd_dec = ei->decay_speed << 2;
679 RestoreRandomSeeds(saved_seeds);
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 = 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 != nullptr && strcmp(e->name, name) == 0) 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 free(e->name);
1102 if (reset) {
1103 e->name = nullptr;
1104 } else {
1105 e->name = stredup(text);
1108 MarkWholeScreenDirty();
1111 return CommandCost();
1116 * Check if an engine is buildable.
1117 * @param engine index of the engine to check.
1118 * @param type the type the engine should be.
1119 * @param company index of the company.
1120 * @return True if an engine is valid, of the specified type, and buildable by
1121 * the given company.
1123 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1125 const Engine *e = Engine::GetIfValid(engine);
1127 /* check if it's an engine that is in the engine array */
1128 if (e == nullptr) return false;
1130 /* check if it's an engine of specified type */
1131 if (e->type != type) return false;
1133 /* check if it's available ... */
1134 if (company == OWNER_DEITY) {
1135 /* ... for any company (preview does not count) */
1136 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1137 } else {
1138 /* ... for this company */
1139 if (!HasBit(e->company_avail, company)) return false;
1142 if (!e->IsEnabled()) return false;
1144 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1145 /* Check if the rail type is available to this company */
1146 const Company *c = Company::Get(company);
1147 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1149 if (type == VEH_ROAD && company != OWNER_DEITY) {
1150 /* Check if the road type is available to this company */
1151 const Company *c = Company::Get(company);
1152 if ((GetRoadTypeInfo(e->u.road.roadtype)->powered_roadtypes & c->avail_roadtypes) == ROADTYPES_NONE) return false;
1155 return true;
1159 * Check if an engine is refittable.
1160 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1161 * @param engine index of the engine to check.
1162 * @return true if the engine is refittable.
1164 bool IsEngineRefittable(EngineID engine)
1166 const Engine *e = Engine::GetIfValid(engine);
1168 /* check if it's an engine that is in the engine array */
1169 if (e == nullptr) return false;
1171 if (!e->CanCarryCargo()) return false;
1173 const EngineInfo *ei = &e->info;
1174 if (ei->refit_mask == 0) return false;
1176 /* Are there suffixes?
1177 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1178 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1180 /* Is there any cargo except the default cargo? */
1181 CargoID default_cargo = e->GetDefaultCargoType();
1182 CargoTypes default_cargo_mask = 0;
1183 SetBit(default_cargo_mask, default_cargo);
1184 return default_cargo != CT_INVALID && ei->refit_mask != default_cargo_mask;
1188 * Check for engines that have an appropriate availability.
1190 void CheckEngines()
1192 Date min_date = INT32_MAX;
1194 for (const Engine *e : Engine::Iterate()) {
1195 if (!e->IsEnabled()) continue;
1197 /* We have an available engine... yay! */
1198 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1200 /* Okay, try to find the earliest date. */
1201 min_date = min(min_date, e->info.base_intro);
1204 if (min_date < INT32_MAX) {
1205 SetDParam(0, min_date);
1206 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1207 } else {
1208 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);