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"
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 template<> Engine::Pool
Engine::PoolItem::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
];
80 Engine::Engine(VehicleType type
, EngineID base
)
83 this->grf_prop
.local_id
= base
;
84 this->list_position
= base
;
86 /* Check if this base engine is within the original engine data range */
87 if (base
>= _engine_counts
[type
]) {
88 /* Set model life to maximum to make wagons available */
89 this->info
.base_life
= 0xFF;
90 /* Set road vehicle tractive effort to the default value */
91 if (type
== VEH_ROAD
) this->u
.road
.tractive_effort
= 0x4C;
92 /* Aircraft must have CT_INVALID as default, as there is no property */
93 if (type
== VEH_AIRCRAFT
) this->info
.cargo_type
= CT_INVALID
;
94 /* Set visual effect to the default value */
96 case VEH_TRAIN
: this->u
.rail
.visual_effect
= VE_DEFAULT
; break;
97 case VEH_ROAD
: this->u
.road
.visual_effect
= VE_DEFAULT
; break;
98 case VEH_SHIP
: this->u
.ship
.visual_effect
= VE_DEFAULT
; break;
99 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
101 /* Set cargo aging period to the default value. */
102 this->info
.cargo_age_period
= CARGO_AGING_TICKS
;
106 /* Copy the original engine info for this slot */
107 this->info
= _orig_engine_info
[_engine_offsets
[type
] + base
];
109 /* Copy the original engine data for this slot */
111 default: NOT_REACHED();
114 this->u
.rail
= _orig_rail_vehicle_info
[base
];
115 this->original_image_index
= this->u
.rail
.image_index
;
116 this->info
.string_id
= STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM
+ base
;
118 /* Set the default model life of original wagons to "infinite" */
119 if (this->u
.rail
.railveh_type
== RAILVEH_WAGON
) this->info
.base_life
= 0xFF;
124 this->u
.road
= _orig_road_vehicle_info
[base
];
125 this->original_image_index
= this->u
.road
.image_index
;
126 this->info
.string_id
= STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS
+ base
;
130 this->u
.ship
= _orig_ship_vehicle_info
[base
];
131 this->original_image_index
= this->u
.ship
.image_index
;
132 this->info
.string_id
= STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER
+ base
;
136 this->u
.air
= _orig_aircraft_vehicle_info
[base
];
137 this->original_image_index
= this->u
.air
.image_index
;
138 this->info
.string_id
= STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52
+ base
;
145 UnloadWagonOverrides(this);
149 * Checks whether the engine is a valid (non-articulated part of an) engine.
150 * @return true if enabled
152 bool Engine::IsEnabled() const
154 return this->info
.string_id
!= STR_NEWGRF_INVALID_ENGINE
&& HasBit(this->info
.climates
, _settings_game
.game_creation
.landscape
);
158 * Retrieve the GRF ID of the NewGRF the engine is tied to.
159 * This is the GRF providing the Action 3.
160 * @return GRF ID of the associated NewGRF.
162 uint32
Engine::GetGRFID() const
164 const GRFFile
*file
= this->GetGRF();
165 return file
== NULL
? 0 : file
->grfid
;
169 * Determines whether an engine can carry something.
170 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
171 * @return true if the vehicle can carry something.
173 bool Engine::CanCarryCargo() const
175 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
176 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
177 * for livery selection etc.
178 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
180 switch (this->type
) {
182 if (this->u
.rail
.capacity
== 0) return false;
186 if (this->u
.road
.capacity
== 0) return false;
193 default: NOT_REACHED();
195 return this->GetDefaultCargoType() != CT_INVALID
;
200 * Determines capacity of a given vehicle from scratch.
201 * For aircraft the main capacity is determined. Mail might be present as well.
202 * @param v Vehicle of interest; NULL in purchase list
203 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
206 uint
Engine::DetermineCapacity(const Vehicle
*v
, uint16
*mail_capacity
) const
208 assert(v
== NULL
|| this->index
== v
->engine_type
);
209 if (mail_capacity
!= NULL
) *mail_capacity
= 0;
211 if (!this->CanCarryCargo()) return 0;
213 bool new_multipliers
= HasBit(this->info
.misc_flags
, EF_NO_DEFAULT_CARGO_MULTIPLIER
);
214 CargoID default_cargo
= this->GetDefaultCargoType();
215 CargoID cargo_type
= (v
!= NULL
) ? v
->cargo_type
: default_cargo
;
217 if (mail_capacity
!= NULL
&& this->type
== VEH_AIRCRAFT
&& IsCargoInClass(cargo_type
, CC_PASSENGERS
)) {
218 *mail_capacity
= GetEngineProperty(this->index
, PROP_AIRCRAFT_MAIL_CAPACITY
, this->u
.air
.mail_capacity
, v
);
221 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
222 if (HasBit(this->info
.callback_mask
, CBM_VEHICLE_REFIT_CAPACITY
) &&
223 (new_multipliers
|| default_cargo
!= cargo_type
|| (v
!= NULL
&& v
->cargo_subtype
!= 0))) {
224 uint16 callback
= GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY
, 0, 0, this->index
, v
);
225 if (callback
!= CALLBACK_FAILED
) return callback
;
228 /* Get capacity according to property resp. CB */
230 uint extra_mail_cap
= 0;
231 switch (this->type
) {
233 capacity
= GetEngineProperty(this->index
, PROP_TRAIN_CARGO_CAPACITY
, this->u
.rail
.capacity
, v
);
235 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
236 if (v
== NULL
&& this->u
.rail
.railveh_type
== RAILVEH_MULTIHEAD
) capacity
+= this->u
.rail
.capacity
;
240 capacity
= GetEngineProperty(this->index
, PROP_ROADVEH_CARGO_CAPACITY
, this->u
.road
.capacity
, v
);
244 capacity
= GetEngineProperty(this->index
, PROP_SHIP_CARGO_CAPACITY
, this->u
.ship
.capacity
, v
);
248 capacity
= GetEngineProperty(this->index
, PROP_AIRCRAFT_PASSENGER_CAPACITY
, this->u
.air
.passenger_capacity
, v
);
249 if (!IsCargoInClass(cargo_type
, CC_PASSENGERS
)) {
250 extra_mail_cap
= GetEngineProperty(this->index
, PROP_AIRCRAFT_MAIL_CAPACITY
, this->u
.air
.mail_capacity
, v
);
252 if (!new_multipliers
&& cargo_type
== CT_MAIL
) return capacity
+ extra_mail_cap
;
253 default_cargo
= CT_PASSENGERS
; // Always use 'passengers' wrt. cargo multipliers
256 default: NOT_REACHED();
259 if (!new_multipliers
) {
260 /* Use the passenger multiplier for mail as well */
261 capacity
+= extra_mail_cap
;
265 /* Apply multipliers depending on cargo- and vehicletype. */
266 if (new_multipliers
|| (this->type
!= VEH_SHIP
&& default_cargo
!= cargo_type
)) {
267 uint16 default_multiplier
= new_multipliers
? 0x100 : CargoSpec::Get(default_cargo
)->multiplier
;
268 uint16 cargo_multiplier
= CargoSpec::Get(cargo_type
)->multiplier
;
269 capacity
*= cargo_multiplier
;
270 if (extra_mail_cap
> 0) {
271 uint mail_multiplier
= CargoSpec::Get(CT_MAIL
)->multiplier
;
272 capacity
+= (default_multiplier
* extra_mail_cap
* cargo_multiplier
+ mail_multiplier
/ 2) / mail_multiplier
;
274 capacity
= (capacity
+ default_multiplier
/ 2) / default_multiplier
;
281 * Return how much the running costs of this engine are.
282 * @return Yearly running cost of the engine.
284 Money
Engine::GetRunningCost() const
288 switch (this->type
) {
290 base_price
= this->u
.road
.running_cost_class
;
291 if (base_price
== INVALID_PRICE
) return 0;
292 cost_factor
= GetEngineProperty(this->index
, PROP_ROADVEH_RUNNING_COST_FACTOR
, this->u
.road
.running_cost
);
296 base_price
= this->u
.rail
.running_cost_class
;
297 if (base_price
== INVALID_PRICE
) return 0;
298 cost_factor
= GetEngineProperty(this->index
, PROP_TRAIN_RUNNING_COST_FACTOR
, this->u
.rail
.running_cost
);
302 base_price
= PR_RUNNING_SHIP
;
303 cost_factor
= GetEngineProperty(this->index
, PROP_SHIP_RUNNING_COST_FACTOR
, this->u
.ship
.running_cost
);
307 base_price
= PR_RUNNING_AIRCRAFT
;
308 cost_factor
= GetEngineProperty(this->index
, PROP_AIRCRAFT_RUNNING_COST_FACTOR
, this->u
.air
.running_cost
);
311 default: NOT_REACHED();
314 return GetPrice(base_price
, cost_factor
, this->GetGRF(), -8);
318 * Return how much a new engine costs.
319 * @return Cost of the engine.
321 Money
Engine::GetCost() const
325 switch (this->type
) {
327 base_price
= PR_BUILD_VEHICLE_ROAD
;
328 cost_factor
= GetEngineProperty(this->index
, PROP_ROADVEH_COST_FACTOR
, this->u
.road
.cost_factor
);
332 if (this->u
.rail
.railveh_type
== RAILVEH_WAGON
) {
333 base_price
= PR_BUILD_VEHICLE_WAGON
;
334 cost_factor
= GetEngineProperty(this->index
, PROP_TRAIN_COST_FACTOR
, this->u
.rail
.cost_factor
);
336 base_price
= PR_BUILD_VEHICLE_TRAIN
;
337 cost_factor
= GetEngineProperty(this->index
, PROP_TRAIN_COST_FACTOR
, this->u
.rail
.cost_factor
);
342 base_price
= PR_BUILD_VEHICLE_SHIP
;
343 cost_factor
= GetEngineProperty(this->index
, PROP_SHIP_COST_FACTOR
, this->u
.ship
.cost_factor
);
347 base_price
= PR_BUILD_VEHICLE_AIRCRAFT
;
348 cost_factor
= GetEngineProperty(this->index
, PROP_AIRCRAFT_COST_FACTOR
, this->u
.air
.cost_factor
);
351 default: NOT_REACHED();
354 return GetPrice(base_price
, cost_factor
, this->GetGRF(), -8);
358 * Returns max speed of the engine for display purposes
359 * @return max speed in km-ish/h
361 uint
Engine::GetDisplayMaxSpeed() const
363 switch (this->type
) {
365 return GetEngineProperty(this->index
, PROP_TRAIN_SPEED
, this->u
.rail
.max_speed
);
368 uint max_speed
= GetEngineProperty(this->index
, PROP_ROADVEH_SPEED
, 0);
369 return (max_speed
!= 0) ? max_speed
* 2 : this->u
.road
.max_speed
/ 2;
373 return GetEngineProperty(this->index
, PROP_SHIP_SPEED
, this->u
.ship
.max_speed
) / 2;
376 uint max_speed
= GetEngineProperty(this->index
, PROP_AIRCRAFT_SPEED
, 0);
377 if (max_speed
!= 0) {
378 return (max_speed
* 128) / 10;
380 return this->u
.air
.max_speed
;
383 default: NOT_REACHED();
388 * Returns the power of the engine for display
389 * and sorting purposes.
390 * Only trains and road vehicles have power
391 * @return power in display units hp
393 uint
Engine::GetPower() const
395 /* Only trains and road vehicles have 'power'. */
396 switch (this->type
) {
398 return GetEngineProperty(this->index
, PROP_TRAIN_POWER
, this->u
.rail
.power
);
400 return GetEngineProperty(this->index
, PROP_ROADVEH_POWER
, this->u
.road
.power
) * 10;
402 default: NOT_REACHED();
407 * Returns the weight of the engine for display purposes.
408 * For dual-headed train-engines this is the weight of both heads
409 * @return weight in display units metric tons
411 uint
Engine::GetDisplayWeight() const
413 /* Only trains and road vehicles have 'weight'. */
414 switch (this->type
) {
416 return GetEngineProperty(this->index
, PROP_TRAIN_WEIGHT
, this->u
.rail
.weight
) << (this->u
.rail
.railveh_type
== RAILVEH_MULTIHEAD
? 1 : 0);
418 return GetEngineProperty(this->index
, PROP_ROADVEH_WEIGHT
, this->u
.road
.weight
) / 4;
420 default: NOT_REACHED();
425 * Returns the tractive effort of the engine for display purposes.
426 * For dual-headed train-engines this is the tractive effort of both heads
427 * @return tractive effort in display units kN
429 uint
Engine::GetDisplayMaxTractiveEffort() const
431 /* Only trains and road vehicles have 'tractive effort'. */
432 switch (this->type
) {
434 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index
, PROP_TRAIN_TRACTIVE_EFFORT
, this->u
.rail
.tractive_effort
)) / 256;
436 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index
, PROP_ROADVEH_TRACTIVE_EFFORT
, this->u
.road
.tractive_effort
)) / 256;
438 default: NOT_REACHED();
443 * Returns the vehicle's (not model's!) life length in days.
444 * @return the life length
446 Date
Engine::GetLifeLengthInDays() const
448 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
449 return (this->info
.lifelength
+ _settings_game
.vehicle
.extend_vehicle_life
) * DAYS_IN_LEAP_YEAR
;
453 * Get the range of an aircraft type.
454 * @return Range of the aircraft type in tiles or 0 if unlimited range.
456 uint16
Engine::GetRange() const
458 switch (this->type
) {
460 return GetEngineProperty(this->index
, PROP_AIRCRAFT_RANGE
, this->u
.air
.max_range
);
462 default: NOT_REACHED();
467 * Initializes the EngineOverrideManager with the default engines.
469 void EngineOverrideManager::ResetToDefaultMapping()
472 for (VehicleType type
= VEH_TRAIN
; type
<= VEH_AIRCRAFT
; type
++) {
473 for (uint internal_id
= 0; internal_id
< _engine_counts
[type
]; internal_id
++) {
474 EngineIDMapping
*eid
= this->Append();
476 eid
->grfid
= INVALID_GRFID
;
477 eid
->internal_id
= internal_id
;
478 eid
->substitute_id
= internal_id
;
484 * Looks up an EngineID in the EngineOverrideManager
485 * @param type Vehicle type
486 * @param grf_local_id The local id in the newgrf
487 * @param grfid The GrfID that defines the scope of grf_local_id.
488 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
489 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
490 * @return The engine ID if present, or INVALID_ENGINE if not.
492 EngineID
EngineOverrideManager::GetID(VehicleType type
, uint16 grf_local_id
, uint32 grfid
)
494 const EngineIDMapping
*end
= this->End();
496 for (const EngineIDMapping
*eid
= this->Begin(); eid
!= end
; eid
++, index
++) {
497 if (eid
->type
== type
&& eid
->grfid
== grfid
&& eid
->internal_id
== grf_local_id
) {
501 return INVALID_ENGINE
;
505 * Tries to reset the engine mapping to match the current NewGRF configuration.
506 * This is only possible when there are currently no vehicles in the game.
507 * @return false if resetting failed due to present vehicles.
509 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
512 FOR_ALL_VEHICLES(v
) {
513 if (IsCompanyBuildableVehicleType(v
)) return false;
516 /* Reset the engines, they will get new EngineIDs */
517 _engine_mngr
.ResetToDefaultMapping();
524 * Initialise the engine pool with the data from the original vehicles.
528 DeleteWindowByClass(WC_ENGINE_PREVIEW
);
529 Engine::pool
.CleanPool();
531 assert(_engine_mngr
.Length() >= _engine_mngr
.NUM_DEFAULT_ENGINES
);
532 const EngineIDMapping
*end
= _engine_mngr
.End();
534 for (const EngineIDMapping
*eid
= _engine_mngr
.Begin(); eid
!= end
; eid
++, index
++) {
535 /* Assert is safe; there won't be more than 256 original vehicles
536 * in any case, and we just cleaned the pool. */
537 assert(Engine::CanAllocateItem());
538 const Engine
*e
= new Engine(eid
->type
, eid
->internal_id
);
539 assert(e
->index
== index
);
542 _introduced_railtypes
= 0;
546 * Check whether the railtypes should be introduced.
548 static void CheckRailIntroduction()
550 /* All railtypes have been introduced. */
551 if (_introduced_railtypes
== UINT16_MAX
|| Company::GetPoolSize() == 0) return;
553 /* We need to find the railtypes that are known to all companies. */
554 RailTypes rts
= (RailTypes
)UINT16_MAX
;
556 /* We are at, or past the introduction date of the rail. */
558 FOR_ALL_COMPANIES(c
) {
559 c
->avail_railtypes
= AddDateIntroducedRailTypes(c
->avail_railtypes
, _date
);
560 rts
&= c
->avail_railtypes
;
563 _introduced_railtypes
|= rts
;
566 void ShowEnginePreviewWindow(EngineID engine
);
569 * Determine whether an engine type is a wagon (and not a loco).
570 * @param index %Engine getting queried.
571 * @return Whether the queried engine is a wagon.
573 static bool IsWagon(EngineID index
)
575 const Engine
*e
= Engine::Get(index
);
576 return e
->type
== VEH_TRAIN
&& e
->u
.rail
.railveh_type
== RAILVEH_WAGON
;
580 * Update #reliability of engine \a e.
581 * @param e %EngineState to update.
582 * @param ei %EngineInfo for the engine.
584 static void CalcEngineReliability (EngineState
*e
, const EngineInfo
*ei
)
588 /* Check for early retirement */
589 if (e
->company_avail
!= 0 && !_settings_game
.vehicle
.never_expire_vehicles
&& ei
->base_life
!= 0xFF) {
590 int retire_early
= ei
->retire_early
;
591 uint retire_early_max_age
= max(0, e
->duration_phase_1
+ e
->duration_phase_2
- retire_early
* 12);
592 if (retire_early
!= 0 && age
>= retire_early_max_age
) {
593 /* Early retirement is enabled and we're past the date... */
594 e
->company_avail
= 0;
598 if (age
< e
->duration_phase_1
) {
599 uint start
= e
->reliability_start
;
600 e
->reliability
= age
* (e
->reliability_max
- start
) / e
->duration_phase_1
+ start
;
601 } else if ((age
-= e
->duration_phase_1
) < e
->duration_phase_2
|| _settings_game
.vehicle
.never_expire_vehicles
|| ei
->base_life
== 0xFF) {
602 /* We are at the peak of this engines life. It will have max reliability.
603 * This is also true if the engines never expire. They will not go bad over time */
604 e
->reliability
= e
->reliability_max
;
605 } else if ((age
-= e
->duration_phase_2
) < e
->duration_phase_3
) {
606 uint max
= e
->reliability_max
;
607 e
->reliability
= (int)age
* (int)(e
->reliability_final
- max
) / e
->duration_phase_3
+ max
;
609 /* time's up for this engine.
610 * We will now completely retire this design */
611 e
->company_avail
= 0;
612 e
->reliability
= e
->reliability_final
;
616 /** Compute the value for #_year_engine_aging_stops. */
617 void SetYearEngineAgingStops()
619 /* Determine last engine aging year, default to 2050 as previously. */
620 _year_engine_aging_stops
= 2050;
624 const EngineInfo
*ei
= &e
->info
;
626 /* Exclude certain engines */
627 if (!HasBit(ei
->climates
, _settings_game
.game_creation
.landscape
)) continue;
628 if (e
->type
== VEH_TRAIN
&& e
->u
.rail
.railveh_type
== RAILVEH_WAGON
) continue;
630 /* Base year ending date on half the model life */
632 ConvertDateToYMD(ei
->base_intro
+ (ei
->lifelength
* DAYS_IN_LEAP_YEAR
) / 2, &ymd
);
634 _year_engine_aging_stops
= max(_year_engine_aging_stops
, ymd
.year
);
639 * Reset or initialise the variable data of an engine.
640 * @param ei Engine info.
641 * @param aging_date The date used for age calculations.
643 void EngineState::reset (const EngineInfo
*ei
, Date aging_date
)
647 this->company_avail
= 0;
648 this->company_hidden
= 0;
650 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
651 * of engines in early starting games.
652 * Note: TTDP uses fixed 1922 */
654 this->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
;
655 if (this->intro_date
<= _date
) {
656 this->age
= (aging_date
- this->intro_date
) >> 5;
657 this->company_avail
= (CompanyMask
)-1;
658 this->flags
|= ENGINE_AVAILABLE
;
661 this->reliability_start
= GB(r
, 16, 14) + 0x7AE0;
663 this->reliability_max
= GB(r
, 0, 14) + 0xBFFF;
664 this->reliability_final
= GB(r
, 16, 14) + 0x3FFF;
667 this->duration_phase_1
= GB(r
, 0, 5) + 7;
668 this->duration_phase_2
= GB(r
, 5, 4) + ei
->base_life
* 12 - 96;
669 this->duration_phase_3
= GB(r
, 9, 7) + 120;
671 this->reliability_spd_dec
= ei
->decay_speed
<< 2;
673 CalcEngineReliability (this, ei
);
675 /* prevent certain engines from ever appearing. */
676 if (!HasBit(ei
->climates
, _settings_game
.game_creation
.landscape
)) {
677 this->flags
|= ENGINE_AVAILABLE
;
678 this->company_avail
= 0;
683 * Start/initialise all our engines. Must be called whenever there are changes
684 * to the NewGRF config.
686 void StartupEngines()
689 /* Aging of vehicles stops, so account for that when starting late */
690 const Date aging_date
= min(_date
, ConvertYMDToDate(_year_engine_aging_stops
, 0, 1));
693 e
->reset (&e
->info
, aging_date
);
696 /* Update the bitmasks for the vehicle lists */
698 FOR_ALL_COMPANIES(c
) {
699 c
->avail_railtypes
= GetCompanyRailtypes(c
->index
);
700 c
->avail_roadtypes
= GetCompanyRoadtypes(c
->index
);
703 /* Rail types that are invalid or never introduced are marked as
704 * being introduced upon start. That way we can easily check whether
705 * there is any date related introduction that is still going to
706 * happen somewhere in the future. */
707 for (RailType rt
= RAILTYPE_BEGIN
; rt
!= RAILTYPE_END
; rt
++) {
708 const RailtypeInfo
*rti
= GetRailTypeInfo(rt
);
709 if (rti
->label
!= 0 && IsInsideMM(rti
->introduction_date
, 0, MAX_DAY
)) continue;
711 SetBit(_introduced_railtypes
, rt
);
714 CheckRailIntroduction();
716 SetWindowClassesDirty(WC_BUILD_VEHICLE
); // Update to show the new reliability
717 SetWindowClassesDirty(WC_REPLACE_VEHICLE
);
719 /* Invalidate any open purchase lists */
720 InvalidateWindowClassesData(WC_BUILD_VEHICLE
);
721 InvalidateWindowClassesData(WC_REPLACE_VEHICLE
);
725 * Company \a company accepts engine \a eid for preview.
726 * @param eid Engine being accepted (is under preview).
727 * @param company Current company previewing the engine.
729 static void AcceptEnginePreview(EngineID eid
, CompanyID company
)
731 Engine
*e
= Engine::Get(eid
);
732 Company
*c
= Company::Get(company
);
734 SetBit(e
->company_avail
, company
);
735 if (e
->type
== VEH_TRAIN
) {
736 assert(e
->u
.rail
.railtype
< RAILTYPE_END
);
737 c
->avail_railtypes
= AddDateIntroducedRailTypes(c
->avail_railtypes
| GetRailTypeInfo(e
->u
.rail
.railtype
)->introduces_railtypes
, _date
);
738 } else if (e
->type
== VEH_ROAD
) {
739 SetBit(c
->avail_roadtypes
, HasBit(e
->info
.misc_flags
, EF_ROAD_TRAM
) ? ROADTYPE_TRAM
: ROADTYPE_ROAD
);
742 e
->preview_company
= INVALID_COMPANY
;
743 e
->preview_asked
= (CompanyMask
)-1;
744 if (company
== _local_company
) {
745 AddRemoveEngineFromAutoreplaceAndBuildWindows(e
->type
);
748 /* Update the toolbar. */
749 if (e
->type
== VEH_ROAD
) InvalidateWindowData(WC_BUILD_TOOLBAR
, TRANSPORT_ROAD
);
750 if (e
->type
== VEH_SHIP
) InvalidateWindowData(WC_BUILD_TOOLBAR
, TRANSPORT_WATER
);
752 /* Notify preview window, that it might want to close.
753 * Note: We cannot directly close the window.
754 * In singleplayer this function is called from the preview window, so
755 * we have to use the GUI-scope scheduling of InvalidateWindowData.
757 InvalidateWindowData(WC_ENGINE_PREVIEW
, eid
);
761 * Get the best company for an engine preview.
762 * @param e Engine to preview.
763 * @return Best company if it exists, #INVALID_COMPANY otherwise.
765 static CompanyID
GetPreviewCompany(Engine
*e
)
767 CompanyID best_company
= INVALID_COMPANY
;
769 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
770 uint32 cargomask
= e
->type
!= VEH_TRAIN
? GetUnionOfArticulatedRefitMasks(e
->index
, true) : (uint32
)-1;
772 int32 best_hist
= -1;
774 FOR_ALL_COMPANIES(c
) {
775 if (c
->block_preview
== 0 && !HasBit(e
->preview_asked
, c
->index
) &&
776 c
->old_economy
[0].performance_history
> best_hist
) {
778 /* Check whether the company uses similar vehicles */
780 FOR_ALL_VEHICLES(v
) {
781 if (v
->owner
!= c
->index
|| v
->type
!= e
->type
) continue;
782 if (!v
->GetEngine()->CanCarryCargo() || !HasBit(cargomask
, v
->cargo_type
)) continue;
784 best_hist
= c
->old_economy
[0].performance_history
;
785 best_company
= c
->index
;
795 * Checks if a vehicle type is disabled for all/ai companies.
796 * @param type The vehicle type which shall be checked.
797 * @param ai If true, check if the type is disabled for AI companies, otherwise check if
798 * the vehicle type is disabled for human companies.
799 * @return Whether or not a vehicle type is disabled.
801 static bool IsVehicleTypeDisabled(VehicleType type
, bool ai
)
804 case VEH_TRAIN
: return _settings_game
.vehicle
.max_trains
== 0 || (ai
&& _settings_game
.ai
.ai_disable_veh_train
);
805 case VEH_ROAD
: return _settings_game
.vehicle
.max_roadveh
== 0 || (ai
&& _settings_game
.ai
.ai_disable_veh_roadveh
);
806 case VEH_SHIP
: return _settings_game
.vehicle
.max_ships
== 0 || (ai
&& _settings_game
.ai
.ai_disable_veh_ship
);
807 case VEH_AIRCRAFT
: return _settings_game
.vehicle
.max_aircraft
== 0 || (ai
&& _settings_game
.ai
.ai_disable_veh_aircraft
);
809 default: NOT_REACHED();
813 /** Daily check to offer an exclusive engine preview to the companies. */
814 void EnginesDailyLoop()
816 CheckRailIntroduction();
818 if (_cur_year
>= _year_engine_aging_stops
) return;
822 EngineID i
= e
->index
;
823 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) {
824 if (e
->preview_company
!= INVALID_COMPANY
) {
825 if (!--e
->preview_wait
) {
826 DeleteWindowById(WC_ENGINE_PREVIEW
, i
);
827 e
->preview_company
= INVALID_COMPANY
;
829 } else if (CountBits(e
->preview_asked
) < MAX_COMPANIES
) {
830 e
->preview_company
= GetPreviewCompany(e
);
832 if (e
->preview_company
== INVALID_COMPANY
) {
833 e
->preview_asked
= (CompanyMask
)-1;
837 SetBit(e
->preview_asked
, e
->preview_company
);
838 e
->preview_wait
= 20;
839 /* AIs are intentionally not skipped for preview even if they cannot build a certain
840 * vehicle type. This is done to not give poor performing human companies an "unfair"
841 * boost that they wouldn't have gotten against other human companies. The check on
842 * the line below is just to make AIs not notice that they have a preview if they
843 * cannot build the vehicle. */
844 if (!IsVehicleTypeDisabled(e
->type
, true)) AI::NewEvent(e
->preview_company
, new ScriptEventEnginePreview(i
));
845 if (IsInteractiveCompany(e
->preview_company
)) ShowEnginePreviewWindow(i
);
852 * Clear the 'hidden' flag for all engines of a new company.
853 * @param cid Company being created.
855 void ClearEnginesHiddenFlagOfCompany(CompanyID cid
)
859 SB(e
->company_hidden
, cid
, 1, 0);
864 * Set the visibility of an engine.
865 * @param tile Unused.
866 * @param flags Operation to perform.
868 * @param p2 Bit 31: 0=visible, 1=hidden, other bits for the #EngineID.
869 * @param text Unused.
870 * @return The cost of this operation or an error.
872 CommandCost
CmdSetVehicleVisibility(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
874 Engine
*e
= Engine::GetIfValid(GB(p2
, 0, 31));
875 if (e
== NULL
|| _current_company
>= MAX_COMPANIES
) return CMD_ERROR
;
876 if ((e
->flags
& ENGINE_AVAILABLE
) == 0 || !HasBit(e
->company_avail
, _current_company
)) return CMD_ERROR
;
878 if ((flags
& DC_EXEC
) != 0) {
879 SB(e
->company_hidden
, _current_company
, 1, GB(p2
, 31, 1));
880 AddRemoveEngineFromAutoreplaceAndBuildWindows(e
->type
);
883 return CommandCost();
887 * Accept an engine prototype. XXX - it is possible that the top-company
888 * changes while you are waiting to accept the offer? Then it becomes invalid
890 * @param flags operation to perform
891 * @param p1 engine-prototype offered
894 * @return the cost of this operation or an error
896 CommandCost
CmdWantEnginePreview(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
898 Engine
*e
= Engine::GetIfValid(p1
);
899 if (e
== NULL
|| e
->preview_company
!= _current_company
) return CMD_ERROR
;
901 if (flags
& DC_EXEC
) AcceptEnginePreview(p1
, _current_company
);
903 return CommandCost();
907 * An engine has become available for general use.
908 * Also handle the exclusive engine preview contract.
909 * @param e Engine generally available as of now.
911 static void NewVehicleAvailable(Engine
*e
)
915 EngineID index
= e
->index
;
917 /* In case the company didn't build the vehicle during the intro period,
918 * prevent that company from getting future intro periods for a while. */
919 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) {
920 FOR_ALL_COMPANIES(c
) {
921 uint block_preview
= c
->block_preview
;
923 if (!HasBit(e
->company_avail
, c
->index
)) continue;
925 /* We assume the user did NOT build it.. prove me wrong ;) */
926 c
->block_preview
= 20;
928 FOR_ALL_VEHICLES(v
) {
929 if (v
->type
== VEH_TRAIN
|| v
->type
== VEH_ROAD
|| v
->type
== VEH_SHIP
||
930 (v
->type
== VEH_AIRCRAFT
&& Aircraft::From(v
)->IsNormalAircraft())) {
931 if (v
->owner
== c
->index
&& v
->engine_type
== index
) {
932 /* The user did prove me wrong, so restore old value */
933 c
->block_preview
= block_preview
;
941 e
->flags
= (e
->flags
& ~ENGINE_EXCLUSIVE_PREVIEW
) | ENGINE_AVAILABLE
;
942 AddRemoveEngineFromAutoreplaceAndBuildWindows(e
->type
);
944 /* Now available for all companies */
945 e
->company_avail
= (CompanyMask
)-1;
947 /* Do not introduce new rail wagons */
948 if (IsWagon(index
)) return;
950 if (e
->type
== VEH_TRAIN
) {
951 /* maybe make another rail type available */
952 RailType railtype
= e
->u
.rail
.railtype
;
953 assert(railtype
< RAILTYPE_END
);
954 FOR_ALL_COMPANIES(c
) c
->avail_railtypes
= AddDateIntroducedRailTypes(c
->avail_railtypes
| GetRailTypeInfo(e
->u
.rail
.railtype
)->introduces_railtypes
, _date
);
955 } else if (e
->type
== VEH_ROAD
) {
956 /* maybe make another road type available */
957 FOR_ALL_COMPANIES(c
) SetBit(c
->avail_roadtypes
, HasBit(e
->info
.misc_flags
, EF_ROAD_TRAM
) ? ROADTYPE_TRAM
: ROADTYPE_ROAD
);
960 /* Only broadcast event if AIs are able to build this vehicle type. */
961 if (!IsVehicleTypeDisabled(e
->type
, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index
));
963 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
964 if (!IsVehicleTypeDisabled(e
->type
, false)) {
965 SetDParam(0, GetEngineCategoryName(index
));
967 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE
, NT_NEW_VEHICLES
, NF_VEHICLE
, NR_ENGINE
, index
);
970 /* Update the toolbar. */
971 if (e
->type
== VEH_ROAD
) InvalidateWindowData(WC_BUILD_TOOLBAR
, TRANSPORT_ROAD
);
972 if (e
->type
== VEH_SHIP
) InvalidateWindowData(WC_BUILD_TOOLBAR
, TRANSPORT_WATER
);
974 /* Close pending preview windows */
975 DeleteWindowById(WC_ENGINE_PREVIEW
, index
);
978 /** Monthly update of the availability, reliability, and preview offers of the engines. */
979 void EnginesMonthlyLoop()
981 if (_cur_year
< _year_engine_aging_stops
) {
984 /* Age the vehicle */
985 if ((e
->flags
& ENGINE_AVAILABLE
) && e
->age
!= MAX_DAY
) {
987 CalcEngineReliability (e
, &e
->info
);
990 /* Do not introduce invalid engines */
991 if (!e
->IsEnabled()) continue;
993 if (!(e
->flags
& ENGINE_AVAILABLE
) && _date
>= (e
->intro_date
+ DAYS_IN_YEAR
)) {
994 /* Introduce it to all companies */
995 NewVehicleAvailable(e
);
996 } else if (!(e
->flags
& (ENGINE_AVAILABLE
| ENGINE_EXCLUSIVE_PREVIEW
)) && _date
>= e
->intro_date
) {
997 /* Introduction date has passed...
998 * Check if it is allowed to build this vehicle type at all
999 * based on the current game settings. If not, it does not
1000 * make sense to show the preview dialog to any company. */
1001 if (IsVehicleTypeDisabled(e
->type
, false)) continue;
1003 /* Do not introduce new rail wagons */
1004 if (IsWagon(e
->index
)) continue;
1006 /* Show preview dialog to one of the companies. */
1007 e
->flags
|= ENGINE_EXCLUSIVE_PREVIEW
;
1008 e
->preview_company
= INVALID_COMPANY
;
1009 e
->preview_asked
= 0;
1013 SetWindowClassesDirty(WC_BUILD_VEHICLE
); // Update to show the new reliability
1014 SetWindowClassesDirty(WC_REPLACE_VEHICLE
);
1016 InvalidateWindowClassesData(WC_BUILD_VEHICLE
); // rebuild the purchase list (esp. when sorted by reliability)
1017 InvalidateWindowClassesData(WC_REPLACE_VEHICLE
);
1022 * Is \a name still free as name for an engine?
1023 * @param name New name of an engine.
1024 * @return \c false if the name is being used already, else \c true.
1026 static bool IsUniqueEngineName(const char *name
)
1030 FOR_ALL_ENGINES(e
) {
1031 if (e
->name
!= NULL
&& strcmp(e
->name
, name
) == 0) return false;
1039 * @param tile unused
1040 * @param flags operation to perform
1041 * @param p1 engine ID to rename
1043 * @param text the new name or an empty string when resetting to the default
1044 * @return the cost of this operation or an error
1046 CommandCost
CmdRenameEngine(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1048 Engine
*e
= Engine::GetIfValid(p1
);
1049 if (e
== NULL
) return CMD_ERROR
;
1051 bool reset
= StrEmpty(text
);
1054 if (Utf8StringLength(text
) >= MAX_LENGTH_ENGINE_NAME_CHARS
) return CMD_ERROR
;
1055 if (!IsUniqueEngineName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1058 if (flags
& DC_EXEC
) {
1064 e
->name
= xstrdup(text
);
1067 MarkWholeScreenDirty();
1070 return CommandCost();
1075 * Check if an engine is buildable.
1076 * @param engine index of the engine to check.
1077 * @param type the type the engine should be.
1078 * @param company index of the company.
1079 * @return True if an engine is valid, of the specified type, and buildable by
1080 * the given company.
1082 bool IsEngineBuildable(EngineID engine
, VehicleType type
, CompanyID company
)
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 /* check if it's an engine of specified type */
1090 if (e
->type
!= type
) return false;
1092 /* check if it's available ... */
1093 if (company
== OWNER_DEITY
) {
1094 /* ... for any company (preview does not count) */
1095 if (!(e
->flags
& ENGINE_AVAILABLE
) || e
->company_avail
== 0) return false;
1097 /* ... for this company */
1098 if (!HasBit(e
->company_avail
, company
)) return false;
1101 if (!e
->IsEnabled()) return false;
1103 if (type
== VEH_TRAIN
&& company
!= OWNER_DEITY
) {
1104 /* Check if the rail type is available to this company */
1105 const Company
*c
= Company::Get(company
);
1106 if (((GetRailTypeInfo(e
->u
.rail
.railtype
))->compatible_railtypes
& c
->avail_railtypes
) == 0) return false;
1113 * Check if an engine is refittable.
1114 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1115 * @param engine index of the engine to check.
1116 * @return true if the engine is refittable.
1118 bool IsEngineRefittable(EngineID engine
)
1120 const Engine
*e
= Engine::GetIfValid(engine
);
1122 /* check if it's an engine that is in the engine array */
1123 if (e
== NULL
) return false;
1125 if (!e
->CanCarryCargo()) return false;
1127 const EngineInfo
*ei
= &e
->info
;
1128 if (ei
->refit_mask
== 0) return false;
1130 /* Are there suffixes?
1131 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1132 if (HasBit(ei
->callback_mask
, CBM_VEHICLE_CARGO_SUFFIX
)) return true;
1134 /* Is there any cargo except the default cargo? */
1135 CargoID default_cargo
= e
->GetDefaultCargoType();
1136 return default_cargo
!= CT_INVALID
&& ei
->refit_mask
!= 1U << default_cargo
;
1140 * Check for engines that have an appropriate availability.
1145 Date min_date
= INT32_MAX
;
1147 FOR_ALL_ENGINES(e
) {
1148 if (!e
->IsEnabled()) continue;
1150 /* We have an available engine... yay! */
1151 if ((e
->flags
& ENGINE_AVAILABLE
) != 0 && e
->company_avail
!= 0) return;
1153 /* Okay, try to find the earliest date. */
1154 min_date
= min(min_date
, e
->info
.base_intro
);
1157 if (min_date
< INT32_MAX
) {
1158 SetDParam(0, min_date
);
1159 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET
, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION
, WL_WARNING
);
1161 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL
, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION
, WL_WARNING
);