4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file engine.cpp Base for all engine handling. */
13 #include "company_func.h"
14 #include "command_func.h"
15 #include "news_func.h"
18 #include "newgrf_engine.h"
19 #include "strings_func.h"
20 #include "core/random_func.hpp"
21 #include "window_func.h"
22 #include "date_func.h"
23 #include "autoreplace_gui.h"
24 #include "string_func.h"
26 #include "core/pool_func.hpp"
27 #include "engine_gui.h"
28 #include "engine_func.h"
29 #include "engine_base.h"
30 #include "company_base.h"
31 #include "vehicle_func.h"
32 #include "articulated_vehicles.h"
35 #include "table/strings.h"
36 #include "table/engines.h"
38 EnginePool
_engine_pool("Engine");
39 INSTANTIATE_POOL_METHODS(Engine
)
41 EngineOverrideManager _engine_mngr
;
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
;
50 * The railtypes that have been or never will be introduced, or
51 * an inverse bitmap of rail types that have to be introduced. */
52 static uint16 _introduced_railtypes
;
54 /** Number of engines of each vehicle type in original engine data */
55 const uint8 _engine_counts
[4] = {
56 lengthof(_orig_rail_vehicle_info
),
57 lengthof(_orig_road_vehicle_info
),
58 lengthof(_orig_ship_vehicle_info
),
59 lengthof(_orig_aircraft_vehicle_info
),
62 /** Offset of the first engine of each vehicle type in original engine data */
63 const uint8 _engine_offsets
[4] = {
65 lengthof(_orig_rail_vehicle_info
),
66 lengthof(_orig_rail_vehicle_info
) + lengthof(_orig_road_vehicle_info
),
67 lengthof(_orig_rail_vehicle_info
) + lengthof(_orig_road_vehicle_info
) + lengthof(_orig_ship_vehicle_info
),
70 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
));
72 const uint
EngineOverrideManager::NUM_DEFAULT_ENGINES
= _engine_counts
[VEH_TRAIN
] + _engine_counts
[VEH_ROAD
] + _engine_counts
[VEH_SHIP
] + _engine_counts
[VEH_AIRCRAFT
];
81 Engine::Engine(VehicleType type
, EngineID base
)
84 this->grf_prop
.local_id
= base
;
85 this->list_position
= base
;
87 /* Check if this base engine is within the original engine data range */
88 if (base
>= _engine_counts
[type
]) {
89 /* Set model life to maximum to make wagons available */
90 this->info
.base_life
= 0xFF;
91 /* Set road vehicle tractive effort to the default value */
92 if (type
== VEH_ROAD
) this->u
.road
.tractive_effort
= 0x4C;
93 /* Aircraft must have CT_INVALID as default, as there is no property */
94 if (type
== VEH_AIRCRAFT
) this->info
.cargo_type
= CT_INVALID
;
95 /* Set visual effect to the default value */
97 case VEH_TRAIN
: this->u
.rail
.visual_effect
= VE_DEFAULT
; break;
98 case VEH_ROAD
: this->u
.road
.visual_effect
= VE_DEFAULT
; break;
99 case VEH_SHIP
: this->u
.ship
.visual_effect
= VE_DEFAULT
; break;
100 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
102 /* Set cargo aging period to the default value. */
103 this->info
.cargo_age_period
= CARGO_AGING_TICKS
;
107 /* Copy the original engine info for this slot */
108 this->info
= _orig_engine_info
[_engine_offsets
[type
] + base
];
110 /* Copy the original engine data for this slot */
112 default: NOT_REACHED();
115 this->u
.rail
= _orig_rail_vehicle_info
[base
];
116 this->original_image_index
= this->u
.rail
.image_index
;
117 this->info
.string_id
= STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM
+ base
;
119 /* Set the default model life of original wagons to "infinite" */
120 if (this->u
.rail
.railveh_type
== RAILVEH_WAGON
) this->info
.base_life
= 0xFF;
125 this->u
.road
= _orig_road_vehicle_info
[base
];
126 this->original_image_index
= this->u
.road
.image_index
;
127 this->info
.string_id
= STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS
+ base
;
131 this->u
.ship
= _orig_ship_vehicle_info
[base
];
132 this->original_image_index
= this->u
.ship
.image_index
;
133 this->info
.string_id
= STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER
+ base
;
137 this->u
.air
= _orig_aircraft_vehicle_info
[base
];
138 this->original_image_index
= this->u
.air
.image_index
;
139 this->info
.string_id
= STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52
+ base
;
146 UnloadWagonOverrides(this);
151 * Checks whether the engine is a valid (non-articulated part of an) engine.
152 * @return true if enabled
154 bool Engine::IsEnabled() const
156 return this->info
.string_id
!= STR_NEWGRF_INVALID_ENGINE
&& HasBit(this->info
.climates
, _settings_game
.game_creation
.landscape
);
160 * Retrieve the GRF ID of the NewGRF the engine is tied to.
161 * This is the GRF providing the Action 3.
162 * @return GRF ID of the associated NewGRF.
164 uint32
Engine::GetGRFID() const
166 const GRFFile
*file
= this->GetGRF();
167 return file
== NULL
? 0 : file
->grfid
;
171 * Determines whether an engine can carry something.
172 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
173 * @return true if the vehicle can carry something.
175 bool Engine::CanCarryCargo() const
177 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
178 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
179 * for livery selection etc.
180 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
182 switch (this->type
) {
184 if (this->u
.rail
.capacity
== 0) return false;
188 if (this->u
.road
.capacity
== 0) return false;
195 default: NOT_REACHED();
197 return this->GetDefaultCargoType() != CT_INVALID
;
202 * Determines capacity of a given vehicle from scratch.
203 * For aircraft the main capacity is determined. Mail might be present as well.
204 * @param v Vehicle of interest; NULL in purchase list
205 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
208 uint
Engine::DetermineCapacity(const Vehicle
*v
, uint16
*mail_capacity
) const
210 assert(v
== NULL
|| this->index
== v
->engine_type
);
211 if (mail_capacity
!= NULL
) *mail_capacity
= 0;
213 if (!this->CanCarryCargo()) return 0;
215 bool new_multipliers
= HasBit(this->info
.misc_flags
, EF_NO_DEFAULT_CARGO_MULTIPLIER
);
216 CargoID default_cargo
= this->GetDefaultCargoType();
217 CargoID cargo_type
= (v
!= NULL
) ? v
->cargo_type
: default_cargo
;
219 if (mail_capacity
!= NULL
&& this->type
== VEH_AIRCRAFT
&& IsCargoInClass(cargo_type
, CC_PASSENGERS
)) {
220 *mail_capacity
= GetEngineProperty(this->index
, PROP_AIRCRAFT_MAIL_CAPACITY
, this->u
.air
.mail_capacity
, v
);
223 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
224 if (HasBit(this->info
.callback_mask
, CBM_VEHICLE_REFIT_CAPACITY
) &&
225 (new_multipliers
|| default_cargo
!= cargo_type
|| (v
!= NULL
&& v
->cargo_subtype
!= 0))) {
226 uint16 callback
= GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY
, 0, 0, this->index
, v
);
227 if (callback
!= CALLBACK_FAILED
) return callback
;
230 /* Get capacity according to property resp. CB */
232 uint extra_mail_cap
= 0;
233 switch (this->type
) {
235 capacity
= GetEngineProperty(this->index
, PROP_TRAIN_CARGO_CAPACITY
, this->u
.rail
.capacity
, v
);
237 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
238 if (v
== NULL
&& this->u
.rail
.railveh_type
== RAILVEH_MULTIHEAD
) capacity
+= this->u
.rail
.capacity
;
242 capacity
= GetEngineProperty(this->index
, PROP_ROADVEH_CARGO_CAPACITY
, this->u
.road
.capacity
, v
);
246 capacity
= GetEngineProperty(this->index
, PROP_SHIP_CARGO_CAPACITY
, this->u
.ship
.capacity
, v
);
250 capacity
= GetEngineProperty(this->index
, PROP_AIRCRAFT_PASSENGER_CAPACITY
, this->u
.air
.passenger_capacity
, v
);
251 if (!IsCargoInClass(cargo_type
, CC_PASSENGERS
)) {
252 extra_mail_cap
= GetEngineProperty(this->index
, PROP_AIRCRAFT_MAIL_CAPACITY
, this->u
.air
.mail_capacity
, v
);
254 if (!new_multipliers
&& cargo_type
== CT_MAIL
) return capacity
+ extra_mail_cap
;
255 default_cargo
= CT_PASSENGERS
; // Always use 'passengers' wrt. cargo multipliers
258 default: NOT_REACHED();
261 if (!new_multipliers
) {
262 /* Use the passenger multiplier for mail as well */
263 capacity
+= extra_mail_cap
;
267 /* Apply multipliers depending on cargo- and vehicletype. */
268 if (new_multipliers
|| (this->type
!= VEH_SHIP
&& default_cargo
!= cargo_type
)) {
269 uint16 default_multiplier
= new_multipliers
? 0x100 : CargoSpec::Get(default_cargo
)->multiplier
;
270 uint16 cargo_multiplier
= CargoSpec::Get(cargo_type
)->multiplier
;
271 capacity
*= cargo_multiplier
;
272 if (extra_mail_cap
> 0) {
273 uint mail_multiplier
= CargoSpec::Get(CT_MAIL
)->multiplier
;
274 capacity
+= (default_multiplier
* extra_mail_cap
* cargo_multiplier
+ mail_multiplier
/ 2) / mail_multiplier
;
276 capacity
= (capacity
+ default_multiplier
/ 2) / default_multiplier
;
283 * Return how much the running costs of this engine are.
284 * @return Yearly running cost of the engine.
286 Money
Engine::GetRunningCost() const
290 switch (this->type
) {
292 base_price
= this->u
.road
.running_cost_class
;
293 if (base_price
== INVALID_PRICE
) return 0;
294 cost_factor
= GetEngineProperty(this->index
, PROP_ROADVEH_RUNNING_COST_FACTOR
, this->u
.road
.running_cost
);
298 base_price
= this->u
.rail
.running_cost_class
;
299 if (base_price
== INVALID_PRICE
) return 0;
300 cost_factor
= GetEngineProperty(this->index
, PROP_TRAIN_RUNNING_COST_FACTOR
, this->u
.rail
.running_cost
);
304 base_price
= PR_RUNNING_SHIP
;
305 cost_factor
= GetEngineProperty(this->index
, PROP_SHIP_RUNNING_COST_FACTOR
, this->u
.ship
.running_cost
);
309 base_price
= PR_RUNNING_AIRCRAFT
;
310 cost_factor
= GetEngineProperty(this->index
, PROP_AIRCRAFT_RUNNING_COST_FACTOR
, this->u
.air
.running_cost
);
313 default: NOT_REACHED();
316 return GetPrice(base_price
, cost_factor
, this->GetGRF(), -8);
320 * Return how much a new engine costs.
321 * @return Cost of the engine.
323 Money
Engine::GetCost() const
327 switch (this->type
) {
329 base_price
= PR_BUILD_VEHICLE_ROAD
;
330 cost_factor
= GetEngineProperty(this->index
, PROP_ROADVEH_COST_FACTOR
, this->u
.road
.cost_factor
);
334 if (this->u
.rail
.railveh_type
== RAILVEH_WAGON
) {
335 base_price
= PR_BUILD_VEHICLE_WAGON
;
336 cost_factor
= GetEngineProperty(this->index
, PROP_TRAIN_COST_FACTOR
, this->u
.rail
.cost_factor
);
338 base_price
= PR_BUILD_VEHICLE_TRAIN
;
339 cost_factor
= GetEngineProperty(this->index
, PROP_TRAIN_COST_FACTOR
, this->u
.rail
.cost_factor
);
344 base_price
= PR_BUILD_VEHICLE_SHIP
;
345 cost_factor
= GetEngineProperty(this->index
, PROP_SHIP_COST_FACTOR
, this->u
.ship
.cost_factor
);
349 base_price
= PR_BUILD_VEHICLE_AIRCRAFT
;
350 cost_factor
= GetEngineProperty(this->index
, PROP_AIRCRAFT_COST_FACTOR
, this->u
.air
.cost_factor
);
353 default: NOT_REACHED();
356 return GetPrice(base_price
, cost_factor
, this->GetGRF(), -8);
360 * Returns max speed of the engine for display purposes
361 * @return max speed in km-ish/h
363 uint
Engine::GetDisplayMaxSpeed() const
365 switch (this->type
) {
367 return GetEngineProperty(this->index
, PROP_TRAIN_SPEED
, this->u
.rail
.max_speed
);
370 uint max_speed
= GetEngineProperty(this->index
, PROP_ROADVEH_SPEED
, 0);
371 return (max_speed
!= 0) ? max_speed
* 2 : this->u
.road
.max_speed
/ 2;
375 return GetEngineProperty(this->index
, PROP_SHIP_SPEED
, this->u
.ship
.max_speed
) / 2;
378 uint max_speed
= GetEngineProperty(this->index
, PROP_AIRCRAFT_SPEED
, 0);
379 if (max_speed
!= 0) {
380 return (max_speed
* 128) / 10;
382 return this->u
.air
.max_speed
;
385 default: NOT_REACHED();
390 * Returns the power of the engine for display
391 * and sorting purposes.
392 * Only trains and road vehicles have power
393 * @return power in display units hp
395 uint
Engine::GetPower() const
397 /* Only trains and road vehicles have 'power'. */
398 switch (this->type
) {
400 return GetEngineProperty(this->index
, PROP_TRAIN_POWER
, this->u
.rail
.power
);
402 return GetEngineProperty(this->index
, PROP_ROADVEH_POWER
, this->u
.road
.power
) * 10;
404 default: NOT_REACHED();
409 * Returns the weight of the engine for display purposes.
410 * For dual-headed train-engines this is the weight of both heads
411 * @return weight in display units metric tons
413 uint
Engine::GetDisplayWeight() const
415 /* Only trains and road vehicles have 'weight'. */
416 switch (this->type
) {
418 return GetEngineProperty(this->index
, PROP_TRAIN_WEIGHT
, this->u
.rail
.weight
) << (this->u
.rail
.railveh_type
== RAILVEH_MULTIHEAD
? 1 : 0);
420 return GetEngineProperty(this->index
, PROP_ROADVEH_WEIGHT
, this->u
.road
.weight
) / 4;
422 default: NOT_REACHED();
427 * Returns the tractive effort of the engine for display purposes.
428 * For dual-headed train-engines this is the tractive effort of both heads
429 * @return tractive effort in display units kN
431 uint
Engine::GetDisplayMaxTractiveEffort() const
433 /* Only trains and road vehicles have 'tractive effort'. */
434 switch (this->type
) {
436 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index
, PROP_TRAIN_TRACTIVE_EFFORT
, this->u
.rail
.tractive_effort
)) / 256;
438 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index
, PROP_ROADVEH_TRACTIVE_EFFORT
, this->u
.road
.tractive_effort
)) / 256;
440 default: NOT_REACHED();
445 * Returns the vehicle's (not model's!) life length in days.
446 * @return the life length
448 Date
Engine::GetLifeLengthInDays() const
450 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
451 return (this->info
.lifelength
+ _settings_game
.vehicle
.extend_vehicle_life
) * DAYS_IN_LEAP_YEAR
;
455 * Get the range of an aircraft type.
456 * @return Range of the aircraft type in tiles or 0 if unlimited range.
458 uint16
Engine::GetRange() const
460 switch (this->type
) {
462 return GetEngineProperty(this->index
, PROP_AIRCRAFT_RANGE
, this->u
.air
.max_range
);
464 default: NOT_REACHED();
469 * Initializes the EngineOverrideManager with the default engines.
471 void EngineOverrideManager::ResetToDefaultMapping()
474 for (VehicleType type
= VEH_TRAIN
; type
<= VEH_AIRCRAFT
; type
++) {
475 for (uint internal_id
= 0; internal_id
< _engine_counts
[type
]; internal_id
++) {
476 EngineIDMapping
*eid
= this->Append();
478 eid
->grfid
= INVALID_GRFID
;
479 eid
->internal_id
= internal_id
;
480 eid
->substitute_id
= internal_id
;
486 * Looks up an EngineID in the EngineOverrideManager
487 * @param type Vehicle type
488 * @param grf_local_id The local id in the newgrf
489 * @param grfid The GrfID that defines the scope of grf_local_id.
490 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
491 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
492 * @return The engine ID if present, or INVALID_ENGINE if not.
494 EngineID
EngineOverrideManager::GetID(VehicleType type
, uint16 grf_local_id
, uint32 grfid
)
496 const EngineIDMapping
*end
= this->End();
498 for (const EngineIDMapping
*eid
= this->Begin(); eid
!= end
; eid
++, index
++) {
499 if (eid
->type
== type
&& eid
->grfid
== grfid
&& eid
->internal_id
== grf_local_id
) {
503 return INVALID_ENGINE
;
507 * Tries to reset the engine mapping to match the current NewGRF configuration.
508 * This is only possible when there are currently no vehicles in the game.
509 * @return false if resetting failed due to present vehicles.
511 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
514 FOR_ALL_VEHICLES(v
) {
515 if (IsCompanyBuildableVehicleType(v
)) return false;
518 /* Reset the engines, they will get new EngineIDs */
519 _engine_mngr
.ResetToDefaultMapping();
526 * Initialise the engine pool with the data from the original vehicles.
530 DeleteWindowByClass(WC_ENGINE_PREVIEW
);
531 _engine_pool
.CleanPool();
533 assert(_engine_mngr
.Length() >= _engine_mngr
.NUM_DEFAULT_ENGINES
);
534 const EngineIDMapping
*end
= _engine_mngr
.End();
536 for (const EngineIDMapping
*eid
= _engine_mngr
.Begin(); eid
!= end
; eid
++, index
++) {
537 /* Assert is safe; there won't be more than 256 original vehicles
538 * in any case, and we just cleaned the pool. */
539 assert(Engine::CanAllocateItem());
540 const Engine
*e
= new Engine(eid
->type
, eid
->internal_id
);
541 assert(e
->index
== index
);
544 _introduced_railtypes
= 0;
548 * Check whether the railtypes should be introduced.
550 static void CheckRailIntroduction()
552 /* All railtypes have been introduced. */
553 if (_introduced_railtypes
== UINT16_MAX
|| Company::GetPoolSize() == 0) return;
555 /* We need to find the railtypes that are known to all companies. */
556 RailTypes rts
= (RailTypes
)UINT16_MAX
;
558 /* We are at, or past the introduction date of the rail. */
560 FOR_ALL_COMPANIES(c
) {
561 c
->avail_railtypes
= AddDateIntroducedRailTypes(c
->avail_railtypes
, _date
);
562 rts
&= c
->avail_railtypes
;
565 _introduced_railtypes
|= rts
;
568 void ShowEnginePreviewWindow(EngineID engine
);
571 * Determine whether an engine type is a wagon (and not a loco).
572 * @param index %Engine getting queried.
573 * @return Whether the queried engine is a wagon.
575 static bool IsWagon(EngineID index
)
577 const Engine
*e
= Engine::Get(index
);
578 return e
->type
== VEH_TRAIN
&& e
->u
.rail
.railveh_type
== RAILVEH_WAGON
;
582 * Update #reliability of engine \a e, (if needed) update the engine GUIs.
583 * @param e %Engine to update.
585 static void CalcEngineReliability(Engine
*e
)
589 /* Check for early retirement */
590 if (e
->company_avail
!= 0 && !_settings_game
.vehicle
.never_expire_vehicles
&& e
->info
.base_life
!= 0xFF) {
591 int retire_early
= e
->info
.retire_early
;
592 uint retire_early_max_age
= max(0, e
->duration_phase_1
+ e
->duration_phase_2
- retire_early
* 12);
593 if (retire_early
!= 0 && age
>= retire_early_max_age
) {
594 /* Early retirement is enabled and we're past the date... */
595 e
->company_avail
= 0;
596 AddRemoveEngineFromAutoreplaceAndBuildWindows(e
->type
);
600 if (age
< e
->duration_phase_1
) {
601 uint start
= e
->reliability_start
;
602 e
->reliability
= age
* (e
->reliability_max
- start
) / e
->duration_phase_1
+ start
;
603 } else if ((age
-= e
->duration_phase_1
) < e
->duration_phase_2
|| _settings_game
.vehicle
.never_expire_vehicles
|| e
->info
.base_life
== 0xFF) {
604 /* We are at the peak of this engines life. It will have max reliability.
605 * This is also true if the engines never expire. They will not go bad over time */
606 e
->reliability
= e
->reliability_max
;
607 } else if ((age
-= e
->duration_phase_2
) < e
->duration_phase_3
) {
608 uint max
= e
->reliability_max
;
609 e
->reliability
= (int)age
* (int)(e
->reliability_final
- max
) / e
->duration_phase_3
+ max
;
611 /* time's up for this engine.
612 * We will now completely retire this design */
613 e
->company_avail
= 0;
614 e
->reliability
= e
->reliability_final
;
615 /* Kick this engine out of the lists */
616 AddRemoveEngineFromAutoreplaceAndBuildWindows(e
->type
);
618 SetWindowClassesDirty(WC_BUILD_VEHICLE
); // Update to show the new reliability
619 SetWindowClassesDirty(WC_REPLACE_VEHICLE
);
622 /** Compute the value for #_year_engine_aging_stops. */
623 void SetYearEngineAgingStops()
625 /* Determine last engine aging year, default to 2050 as previously. */
626 _year_engine_aging_stops
= 2050;
630 const EngineInfo
*ei
= &e
->info
;
632 /* Exclude certain engines */
633 if (!HasBit(ei
->climates
, _settings_game
.game_creation
.landscape
)) continue;
634 if (e
->type
== VEH_TRAIN
&& e
->u
.rail
.railveh_type
== RAILVEH_WAGON
) continue;
636 /* Base year ending date on half the model life */
638 ConvertDateToYMD(ei
->base_intro
+ (ei
->lifelength
* DAYS_IN_LEAP_YEAR
) / 2, &ymd
);
640 _year_engine_aging_stops
= max(_year_engine_aging_stops
, ymd
.year
);
645 * Start/initialise one engine.
646 * @param e The engine to initialise.
647 * @param aging_date The date used for age calculations.
649 void StartupOneEngine(Engine
*e
, Date aging_date
)
651 const EngineInfo
*ei
= &e
->info
;
655 e
->company_avail
= 0;
657 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
658 * of engines in early starting games.
659 * Note: TTDP uses fixed 1922 */
661 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
;
662 if (e
->intro_date
<= _date
) {
663 e
->age
= (aging_date
- e
->intro_date
) >> 5;
664 e
->company_avail
= (CompanyMask
)-1;
665 e
->flags
|= ENGINE_AVAILABLE
;
668 e
->reliability_start
= GB(r
, 16, 14) + 0x7AE0;
670 e
->reliability_max
= GB(r
, 0, 14) + 0xBFFF;
671 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()
696 /* Aging of vehicles stops, so account for that when starting late */
697 const Date aging_date
= min(_date
, ConvertYMDToDate(_year_engine_aging_stops
, 0, 1));
700 StartupOneEngine(e
, aging_date
);
703 /* Update the bitmasks for the vehicle lists */
705 FOR_ALL_COMPANIES(c
) {
706 c
->avail_railtypes
= GetCompanyRailtypes(c
->index
);
707 c
->avail_roadtypes
= GetCompanyRoadtypes(c
->index
);
710 /* Rail types that are invalid or never introduced are marked as
711 * being introduced upon start. That way we can easily check whether
712 * there is any date related introduction that is still going to
713 * happen somewhere in the future. */
714 for (RailType rt
= RAILTYPE_BEGIN
; rt
!= RAILTYPE_END
; rt
++) {
715 const RailtypeInfo
*rti
= GetRailTypeInfo(rt
);
716 if (rti
->label
!= 0 && IsInsideMM(rti
->introduction_date
, 0, MAX_DAY
)) continue;
718 SetBit(_introduced_railtypes
, rt
);
721 CheckRailIntroduction();
723 /* Invalidate any open purchase lists */
724 InvalidateWindowClassesData(WC_BUILD_VEHICLE
);
728 * Company \a company accepts engine \a eid for preview.
729 * @param eid Engine being accepted (is under preview).
730 * @param company Current company previewing the engine.
732 static void AcceptEnginePreview(EngineID eid
, CompanyID company
)
734 Engine
*e
= Engine::Get(eid
);
735 Company
*c
= Company::Get(company
);
737 SetBit(e
->company_avail
, company
);
738 if (e
->type
== VEH_TRAIN
) {
739 assert(e
->u
.rail
.railtype
< RAILTYPE_END
);
740 c
->avail_railtypes
= AddDateIntroducedRailTypes(c
->avail_railtypes
| GetRailTypeInfo(e
->u
.rail
.railtype
)->introduces_railtypes
, _date
);
741 } else if (e
->type
== VEH_ROAD
) {
742 SetBit(c
->avail_roadtypes
, HasBit(e
->info
.misc_flags
, EF_ROAD_TRAM
) ? ROADTYPE_TRAM
: ROADTYPE_ROAD
);
745 e
->preview_company
= INVALID_COMPANY
;
746 e
->preview_asked
= (CompanyMask
)-1;
747 if (company
== _local_company
) {
748 AddRemoveEngineFromAutoreplaceAndBuildWindows(e
->type
);
751 /* Update the toolbar. */
752 if (e
->type
== VEH_ROAD
) InvalidateWindowData(WC_BUILD_TOOLBAR
, TRANSPORT_ROAD
);
753 if (e
->type
== VEH_SHIP
) InvalidateWindowData(WC_BUILD_TOOLBAR
, TRANSPORT_WATER
);
755 /* Notify preview window, that it might want to close.
756 * Note: We cannot directly close the window.
757 * In singleplayer this function is called from the preview window, so
758 * we have to use the GUI-scope scheduling of InvalidateWindowData.
760 InvalidateWindowData(WC_ENGINE_PREVIEW
, eid
);
764 * Get the best company for an engine preview.
765 * @param e Engine to preview.
766 * @return Best company if it exists, #INVALID_COMPANY otherwise.
768 static CompanyID
GetPreviewCompany(Engine
*e
)
770 CompanyID best_company
= INVALID_COMPANY
;
772 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
773 uint32 cargomask
= e
->type
!= VEH_TRAIN
? GetUnionOfArticulatedRefitMasks(e
->index
, true) : (uint32
)-1;
775 int32 best_hist
= -1;
777 FOR_ALL_COMPANIES(c
) {
778 if (c
->block_preview
== 0 && !HasBit(e
->preview_asked
, c
->index
) &&
779 c
->old_economy
[0].performance_history
> best_hist
) {
781 /* Check whether the company uses similar vehicles */
783 FOR_ALL_VEHICLES(v
) {
784 if (v
->owner
!= c
->index
|| v
->type
!= e
->type
) continue;
785 if (!v
->GetEngine()->CanCarryCargo() || !HasBit(cargomask
, v
->cargo_type
)) continue;
787 best_hist
= c
->old_economy
[0].performance_history
;
788 best_company
= c
->index
;
798 * Checks if a vehicle type is disabled for all/ai companies.
799 * @param type The vehicle type which shall be checked.
800 * @param ai If true, check if the type is disabled for AI companies, otherwise check if
801 * the vehicle type is disabled for human companies.
802 * @return Whether or not a vehicle type is disabled.
804 static bool IsVehicleTypeDisabled(VehicleType type
, bool ai
)
807 case VEH_TRAIN
: return _settings_game
.vehicle
.max_trains
== 0 || (ai
&& _settings_game
.ai
.ai_disable_veh_train
);
808 case VEH_ROAD
: return _settings_game
.vehicle
.max_roadveh
== 0 || (ai
&& _settings_game
.ai
.ai_disable_veh_roadveh
);
809 case VEH_SHIP
: return _settings_game
.vehicle
.max_ships
== 0 || (ai
&& _settings_game
.ai
.ai_disable_veh_ship
);
810 case VEH_AIRCRAFT
: return _settings_game
.vehicle
.max_aircraft
== 0 || (ai
&& _settings_game
.ai
.ai_disable_veh_aircraft
);
812 default: NOT_REACHED();
816 /** Daily check to offer an exclusive engine preview to the companies. */
817 void EnginesDailyLoop()
819 CheckRailIntroduction();
821 if (_cur_year
>= _year_engine_aging_stops
) return;
825 EngineID i
= e
->index
;
826 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) {
827 if (e
->preview_company
!= INVALID_COMPANY
) {
828 if (!--e
->preview_wait
) {
829 DeleteWindowById(WC_ENGINE_PREVIEW
, i
);
830 e
->preview_company
= INVALID_COMPANY
;
832 } else if (CountBits(e
->preview_asked
) < MAX_COMPANIES
) {
833 e
->preview_company
= GetPreviewCompany(e
);
835 if (e
->preview_company
== INVALID_COMPANY
) {
836 e
->preview_asked
= (CompanyMask
)-1;
840 SetBit(e
->preview_asked
, e
->preview_company
);
841 e
->preview_wait
= 20;
842 /* AIs are intentionally not skipped for preview even if they cannot build a certain
843 * vehicle type. This is done to not give poor performing human companies an "unfair"
844 * boost that they wouldn't have gotten against other human companies. The check on
845 * the line below is just to make AIs not notice that they have a preview if they
846 * cannot build the vehicle. */
847 if (!IsVehicleTypeDisabled(e
->type
, true)) AI::NewEvent(e
->preview_company
, new ScriptEventEnginePreview(i
));
848 if (IsInteractiveCompany(e
->preview_company
)) ShowEnginePreviewWindow(i
);
855 * Accept an engine prototype. XXX - it is possible that the top-company
856 * changes while you are waiting to accept the offer? Then it becomes invalid
858 * @param flags operation to perform
859 * @param p1 engine-prototype offered
862 * @return the cost of this operation or an error
864 CommandCost
CmdWantEnginePreview(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
866 Engine
*e
= Engine::GetIfValid(p1
);
867 if (e
== NULL
|| e
->preview_company
!= _current_company
) return CMD_ERROR
;
869 if (flags
& DC_EXEC
) AcceptEnginePreview(p1
, _current_company
);
871 return CommandCost();
875 * An engine has become available for general use.
876 * Also handle the exclusive engine preview contract.
877 * @param e Engine generally available as of now.
879 static void NewVehicleAvailable(Engine
*e
)
883 EngineID index
= e
->index
;
885 /* In case the company didn't build the vehicle during the intro period,
886 * prevent that company from getting future intro periods for a while. */
887 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) {
888 FOR_ALL_COMPANIES(c
) {
889 uint block_preview
= c
->block_preview
;
891 if (!HasBit(e
->company_avail
, c
->index
)) continue;
893 /* We assume the user did NOT build it.. prove me wrong ;) */
894 c
->block_preview
= 20;
896 FOR_ALL_VEHICLES(v
) {
897 if (v
->type
== VEH_TRAIN
|| v
->type
== VEH_ROAD
|| v
->type
== VEH_SHIP
||
898 (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->IsNormalAircraft())) {
899 if (v
->owner
== c
->index
&& v
->engine_type
== index
) {
900 /* The user did prove me wrong, so restore old value */
901 c
->block_preview
= block_preview
;
909 e
->flags
= (e
->flags
& ~ENGINE_EXCLUSIVE_PREVIEW
) | ENGINE_AVAILABLE
;
910 AddRemoveEngineFromAutoreplaceAndBuildWindows(e
->type
);
912 /* Now available for all companies */
913 e
->company_avail
= (CompanyMask
)-1;
915 /* Do not introduce new rail wagons */
916 if (IsWagon(index
)) return;
918 if (e
->type
== VEH_TRAIN
) {
919 /* maybe make another rail type available */
920 RailType railtype
= e
->u
.rail
.railtype
;
921 assert(railtype
< RAILTYPE_END
);
922 FOR_ALL_COMPANIES(c
) c
->avail_railtypes
= AddDateIntroducedRailTypes(c
->avail_railtypes
| GetRailTypeInfo(e
->u
.rail
.railtype
)->introduces_railtypes
, _date
);
923 } else if (e
->type
== VEH_ROAD
) {
924 /* maybe make another road type available */
925 FOR_ALL_COMPANIES(c
) SetBit(c
->avail_roadtypes
, HasBit(e
->info
.misc_flags
, EF_ROAD_TRAM
) ? ROADTYPE_TRAM
: ROADTYPE_ROAD
);
928 /* Only broadcast event if AIs are able to build this vehicle type. */
929 if (!IsVehicleTypeDisabled(e
->type
, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index
));
931 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
932 if (!IsVehicleTypeDisabled(e
->type
, false)) {
933 SetDParam(0, GetEngineCategoryName(index
));
935 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE
, NT_NEW_VEHICLES
, NF_VEHICLE
, NR_ENGINE
, index
);
938 /* Update the toolbar. */
939 if (e
->type
== VEH_ROAD
) InvalidateWindowData(WC_BUILD_TOOLBAR
, TRANSPORT_ROAD
);
940 if (e
->type
== VEH_SHIP
) InvalidateWindowData(WC_BUILD_TOOLBAR
, TRANSPORT_WATER
);
942 /* Close pending preview windows */
943 DeleteWindowById(WC_ENGINE_PREVIEW
, index
);
946 /** Monthly update of the availability, reliability, and preview offers of the engines. */
947 void EnginesMonthlyLoop()
949 if (_cur_year
< _year_engine_aging_stops
) {
952 /* Age the vehicle */
953 if ((e
->flags
& ENGINE_AVAILABLE
) && e
->age
!= MAX_DAY
) {
955 CalcEngineReliability(e
);
958 /* Do not introduce invalid engines */
959 if (!e
->IsEnabled()) continue;
961 if (!(e
->flags
& ENGINE_AVAILABLE
) && _date
>= (e
->intro_date
+ DAYS_IN_YEAR
)) {
962 /* Introduce it to all companies */
963 NewVehicleAvailable(e
);
964 } else if (!(e
->flags
& (ENGINE_AVAILABLE
| ENGINE_EXCLUSIVE_PREVIEW
)) && _date
>= e
->intro_date
) {
965 /* Introduction date has passed...
966 * Check if it is allowed to build this vehicle type at all
967 * based on the current game settings. If not, it does not
968 * make sense to show the preview dialog to any company. */
969 if (IsVehicleTypeDisabled(e
->type
, false)) continue;
971 /* Do not introduce new rail wagons */
972 if (IsWagon(e
->index
)) continue;
974 /* Show preview dialog to one of the companies. */
975 e
->flags
|= ENGINE_EXCLUSIVE_PREVIEW
;
976 e
->preview_company
= INVALID_COMPANY
;
977 e
->preview_asked
= 0;
981 InvalidateWindowClassesData(WC_BUILD_VEHICLE
); // rebuild the purchase list (esp. when sorted by reliability)
986 * Is \a name still free as name for an engine?
987 * @param name New name of an engine.
988 * @return \c false if the name is being used already, else \c true.
990 static bool IsUniqueEngineName(const char *name
)
995 if (e
->name
!= NULL
&& strcmp(e
->name
, name
) == 0) return false;
1003 * @param tile unused
1004 * @param flags operation to perform
1005 * @param p1 engine ID to rename
1007 * @param text the new name or an empty string when resetting to the default
1008 * @return the cost of this operation or an error
1010 CommandCost
CmdRenameEngine(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1012 Engine
*e
= Engine::GetIfValid(p1
);
1013 if (e
== NULL
) return CMD_ERROR
;
1015 bool reset
= StrEmpty(text
);
1018 if (Utf8StringLength(text
) >= MAX_LENGTH_ENGINE_NAME_CHARS
) return CMD_ERROR
;
1019 if (!IsUniqueEngineName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1022 if (flags
& DC_EXEC
) {
1028 e
->name
= strdup(text
);
1031 MarkWholeScreenDirty();
1034 return CommandCost();
1039 * Check if an engine is buildable.
1040 * @param engine index of the engine to check.
1041 * @param type the type the engine should be.
1042 * @param company index of the company.
1043 * @return True if an engine is valid, of the specified type, and buildable by
1044 * the given company.
1046 bool IsEngineBuildable(EngineID engine
, VehicleType type
, CompanyID company
)
1048 const Engine
*e
= Engine::GetIfValid(engine
);
1050 /* check if it's an engine that is in the engine array */
1051 if (e
== NULL
) return false;
1053 /* check if it's an engine of specified type */
1054 if (e
->type
!= type
) return false;
1056 /* check if it's available ... */
1057 if (company
== OWNER_DEITY
) {
1058 /* ... for any company (preview does not count) */
1059 if (!(e
->flags
& ENGINE_AVAILABLE
) || e
->company_avail
== 0) return false;
1061 /* ... for this company */
1062 if (!HasBit(e
->company_avail
, company
)) return false;
1065 if (!e
->IsEnabled()) return false;
1067 if (type
== VEH_TRAIN
&& company
!= OWNER_DEITY
) {
1068 /* Check if the rail type is available to this company */
1069 const Company
*c
= Company::Get(company
);
1070 if (((GetRailTypeInfo(e
->u
.rail
.railtype
))->compatible_railtypes
& c
->avail_railtypes
) == 0) return false;
1077 * Check if an engine is refittable.
1078 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1079 * @param engine index of the engine to check.
1080 * @return true if the engine is refittable.
1082 bool IsEngineRefittable(EngineID engine
)
1084 const Engine
*e
= Engine::GetIfValid(engine
);
1086 /* check if it's an engine that is in the engine array */
1087 if (e
== NULL
) return false;
1089 if (!e
->CanCarryCargo()) return false;
1091 const EngineInfo
*ei
= &e
->info
;
1092 if (ei
->refit_mask
== 0) return false;
1094 /* Are there suffixes?
1095 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1096 if (HasBit(ei
->callback_mask
, CBM_VEHICLE_CARGO_SUFFIX
)) return true;
1098 /* Is there any cargo except the default cargo? */
1099 CargoID default_cargo
= e
->GetDefaultCargoType();
1100 return default_cargo
!= CT_INVALID
&& ei
->refit_mask
!= 1U << default_cargo
;
1104 * Check for engines that have an appropriate availability.
1109 Date min_date
= INT32_MAX
;
1111 FOR_ALL_ENGINES(e
) {
1112 if (!e
->IsEnabled()) continue;
1114 /* We have an available engine... yay! */
1115 if ((e
->flags
& ENGINE_AVAILABLE
) != 0 && e
->company_avail
!= 0) return;
1117 /* Okay, try to find the earliest date. */
1118 min_date
= min(min_date
, e
->info
.base_intro
);
1121 if (min_date
< INT32_MAX
) {
1122 SetDParam(0, min_date
);
1123 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET
, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION
, WL_WARNING
);
1125 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL
, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION
, WL_WARNING
);