Fix incorrect tile and trackdir in reserve through program execution
[openttd-joker.git] / src / engine.cpp
blob55042820af8a8f625026be5b95bde5b32f18864c
1 /* $Id: engine.cpp 25640 2013-07-31 07:30:18Z alberth $ */
3 /*
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/>.
8 */
10 /** @file engine.cpp Base for all engine handling. */
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "command_func.h"
15 #include "news_func.h"
16 #include "aircraft.h"
17 #include "newgrf.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"
25 #include "ai/ai.hpp"
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"
33 #include "settings_type.h"
34 #include "error.h"
36 #include "table/strings.h"
37 #include "table/engines.h"
39 #include "safeguards.h"
41 EnginePool _engine_pool("Engine");
42 INSTANTIATE_POOL_METHODS(Engine)
44 EngineOverrideManager _engine_mngr;
46 /**
47 * Year that engine aging stops. Engines will not reduce in reliability
48 * and no more engines will be introduced
50 static Year _year_engine_aging_stops;
52 /** Number of engines of each vehicle type in original engine data */
53 const uint8 _engine_counts[4] = {
54 lengthof(_orig_rail_vehicle_info),
55 lengthof(_orig_road_vehicle_info),
56 lengthof(_orig_ship_vehicle_info),
57 lengthof(_orig_aircraft_vehicle_info),
60 /** Offset of the first engine of each vehicle type in original engine data */
61 const uint8 _engine_offsets[4] = {
63 lengthof(_orig_rail_vehicle_info),
64 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
65 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
68 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));
70 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
72 Engine::Engine() :
73 name(NULL),
74 overrides_count(0),
75 overrides(NULL)
79 Engine::Engine(VehicleType type, EngineID base)
81 this->type = type;
82 this->grf_prop.local_id = base;
83 this->list_position = base;
84 this->preview_company = INVALID_COMPANY;
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 */
95 switch (type) {
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;
103 return;
106 /* Copy the original engine info for this slot */
107 this->info = _orig_engine_info[_engine_offsets[type] + base];
109 /* Copy the original engine data for this slot */
110 switch (type) {
111 default: NOT_REACHED();
113 case VEH_TRAIN:
114 this->u.rail = _orig_rail_vehicle_info[base];
115 this->original_image_index = this->u.rail.image_index;
116 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
118 /* Set the default model life of original wagons to "infinite" */
119 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
121 break;
123 case VEH_ROAD:
124 this->u.road = _orig_road_vehicle_info[base];
125 this->original_image_index = this->u.road.image_index;
126 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
127 break;
129 case VEH_SHIP:
130 this->u.ship = _orig_ship_vehicle_info[base];
131 this->original_image_index = this->u.ship.image_index;
132 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
133 break;
135 case VEH_AIRCRAFT:
136 this->u.air = _orig_aircraft_vehicle_info[base];
137 this->original_image_index = this->u.air.image_index;
138 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
139 break;
143 Engine::~Engine()
145 UnloadWagonOverrides(this);
146 free(this->name);
150 * Checks whether the engine is a valid (non-articulated part of an) engine.
151 * @return true if enabled
153 bool Engine::IsEnabled() const
155 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
159 * Retrieve the GRF ID of the NewGRF the engine is tied to.
160 * This is the GRF providing the Action 3.
161 * @return GRF ID of the associated NewGRF.
163 uint32 Engine::GetGRFID() const
165 const GRFFile *file = this->GetGRF();
166 return file == NULL ? 0 : file->grfid;
170 * Determines whether an engine can carry something.
171 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
172 * @return true if the vehicle can carry something.
174 bool Engine::CanCarryCargo() const
176 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
177 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
178 * for livery selection etc.
179 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
181 switch (this->type) {
182 case VEH_TRAIN:
183 if (this->u.rail.capacity == 0) return false;
184 break;
186 case VEH_ROAD:
187 if (this->u.road.capacity == 0) return false;
188 break;
190 case VEH_SHIP:
191 case VEH_AIRCRAFT:
192 break;
194 default: NOT_REACHED();
196 return this->GetDefaultCargoType() != CT_INVALID;
201 * Determines capacity of a given vehicle from scratch.
202 * For aircraft the main capacity is determined. Mail might be present as well.
203 * @param v Vehicle of interest; NULL in purchase list
204 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
205 * @return Capacity
207 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
209 assert(v == NULL || this->index == v->engine_type);
210 if (mail_capacity != NULL) *mail_capacity = 0;
212 if (!this->CanCarryCargo()) return 0;
214 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
215 CargoID default_cargo = this->GetDefaultCargoType();
216 CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
218 if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
219 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
222 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
223 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
224 (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
225 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
226 if (callback != CALLBACK_FAILED) return callback;
229 /* Get capacity according to property resp. CB */
230 uint capacity;
231 uint extra_mail_cap = 0;
232 switch (this->type) {
233 case VEH_TRAIN:
234 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
236 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
237 if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
238 break;
240 case VEH_ROAD:
241 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
242 break;
244 case VEH_SHIP:
245 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
246 break;
248 case VEH_AIRCRAFT:
249 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
250 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
251 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
253 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
254 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
255 break;
257 default: NOT_REACHED();
260 if (!new_multipliers) {
261 /* Use the passenger multiplier for mail as well */
262 capacity += extra_mail_cap;
263 extra_mail_cap = 0;
266 /* Apply multipliers depending on cargo- and vehicletype. */
267 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
268 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
269 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
270 capacity *= cargo_multiplier;
271 if (extra_mail_cap > 0) {
272 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
273 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
275 capacity = (capacity + default_multiplier / 2) / default_multiplier;
278 return capacity;
282 * Return display value of how much the running costs of this engine are.
283 * @return Yearly running cost of the engine.
285 Money Engine::GetDisplayRunningCost() const
287 return this->GetRunningCost() * _settings_game.economy.daylength;
291 * Return how much the running costs of this engine are.
292 * @return Yearly running cost of the engine.
294 Money Engine::GetRunningCost() const
296 Price base_price;
297 uint cost_factor;
298 switch (this->type) {
299 case VEH_ROAD:
300 base_price = this->u.road.running_cost_class;
301 if (base_price == INVALID_PRICE) return 0;
302 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
303 break;
305 case VEH_TRAIN:
306 base_price = this->u.rail.running_cost_class;
307 if (base_price == INVALID_PRICE) return 0;
308 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
309 break;
311 case VEH_SHIP:
312 base_price = PR_RUNNING_SHIP;
313 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
314 break;
316 case VEH_AIRCRAFT:
317 base_price = PR_RUNNING_AIRCRAFT;
318 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
319 break;
321 default: NOT_REACHED();
324 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
328 * Return how much a new engine costs.
329 * @return Cost of the engine.
331 Money Engine::GetCost() const
333 Price base_price;
334 uint cost_factor;
335 switch (this->type) {
336 case VEH_ROAD:
337 base_price = PR_BUILD_VEHICLE_ROAD;
338 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
339 break;
341 case VEH_TRAIN:
342 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
343 base_price = PR_BUILD_VEHICLE_WAGON;
344 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
345 } else {
346 base_price = PR_BUILD_VEHICLE_TRAIN;
347 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
349 break;
351 case VEH_SHIP:
352 base_price = PR_BUILD_VEHICLE_SHIP;
353 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
354 break;
356 case VEH_AIRCRAFT:
357 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
358 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
359 break;
361 default: NOT_REACHED();
364 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
368 * Returns max speed of the engine for display purposes
369 * @return max speed in km-ish/h
371 uint Engine::GetDisplayMaxSpeed() const
373 switch (this->type) {
374 case VEH_TRAIN:
375 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
377 case VEH_ROAD: {
378 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
379 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
382 case VEH_SHIP:
383 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
385 case VEH_AIRCRAFT: {
386 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
387 if (max_speed != 0) {
388 return (max_speed * 128) / 10;
390 return this->u.air.max_speed;
393 default: NOT_REACHED();
398 * Returns the power of the engine for display
399 * and sorting purposes.
400 * Only trains and road vehicles have power
401 * @return power in display units hp
403 uint Engine::GetPower() const
405 /* Only trains and road vehicles have 'power'. */
406 switch (this->type) {
407 case VEH_TRAIN:
408 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
409 case VEH_ROAD:
410 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
412 default: NOT_REACHED();
417 * Returns the weight of the engine for display purposes.
418 * For dual-headed train-engines this is the weight of both heads
419 * @return weight in display units metric tons
421 uint Engine::GetDisplayWeight() const
423 /* Only trains and road vehicles have 'weight'. */
424 switch (this->type) {
425 case VEH_TRAIN:
426 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
427 case VEH_ROAD:
428 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
430 default: NOT_REACHED();
435 * Returns the tractive effort of the engine for display purposes.
436 * For dual-headed train-engines this is the tractive effort of both heads
437 * @return tractive effort in display units kN
439 uint Engine::GetDisplayMaxTractiveEffort() const
441 /* Only trains and road vehicles have 'tractive effort'. */
442 switch (this->type) {
443 case VEH_TRAIN:
444 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
445 case VEH_ROAD:
446 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
448 default: NOT_REACHED();
453 * Returns the vehicle's (not model's!) life length in days.
454 * @return the life length
456 Date Engine::GetLifeLengthInDays() const
458 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
459 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
463 * Get the range of an aircraft type.
464 * @return Range of the aircraft type in tiles or 0 if unlimited range.
466 uint16 Engine::GetRange() const
468 switch (this->type) {
469 case VEH_AIRCRAFT:
470 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
472 default: NOT_REACHED();
477 * Get the name of the aircraft type for display purposes.
478 * @return Aircraft type string.
480 StringID Engine::GetAircraftTypeText() const
482 switch (this->type) {
483 case VEH_AIRCRAFT:
484 switch (this->u.air.subtype) {
485 case AIR_HELI: return STR_LIVERY_HELICOPTER;
486 case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
487 case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
488 default: NOT_REACHED();
491 default: NOT_REACHED();
496 * Initializes the #EngineOverrideManager with the default engines.
498 void EngineOverrideManager::ResetToDefaultMapping()
500 this->Clear();
501 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
502 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
503 EngineIDMapping *eid = this->Append();
504 eid->type = type;
505 eid->grfid = INVALID_GRFID;
506 eid->internal_id = internal_id;
507 eid->substitute_id = internal_id;
513 * Looks up an EngineID in the EngineOverrideManager
514 * @param type Vehicle type
515 * @param grf_local_id The local id in the newgrf
516 * @param grfid The GrfID that defines the scope of grf_local_id.
517 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
518 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
519 * @return The engine ID if present, or INVALID_ENGINE if not.
521 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
523 const EngineIDMapping *end = this->End();
524 EngineID index = 0;
525 for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
526 if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
527 return index;
530 return INVALID_ENGINE;
534 * Tries to reset the engine mapping to match the current NewGRF configuration.
535 * This is only possible when there are currently no vehicles in the game.
536 * @return false if resetting failed due to present vehicles.
538 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
540 const Vehicle *v;
541 FOR_ALL_VEHICLES(v) {
542 if (IsCompanyBuildableVehicleType(v)) return false;
545 /* Reset the engines, they will get new EngineIDs */
546 _engine_mngr.ResetToDefaultMapping();
547 ReloadNewGRFData();
549 return true;
553 * Initialise the engine pool with the data from the original vehicles.
555 void SetupEngines()
557 DeleteWindowByClass(WC_ENGINE_PREVIEW);
558 _engine_pool.CleanPool();
560 assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
561 const EngineIDMapping *end = _engine_mngr.End();
562 uint index = 0;
563 for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
564 /* Assert is safe; there won't be more than 256 original vehicles
565 * in any case, and we just cleaned the pool. */
566 assert(Engine::CanAllocateItem());
567 const Engine *e = new Engine(eid->type, eid->internal_id);
568 assert(e->index == index);
572 void ShowEnginePreviewWindow(EngineID engine);
575 * Determine whether an engine type is a wagon (and not a loco).
576 * @param index %Engine getting queried.
577 * @return Whether the queried engine is a wagon.
579 static bool IsWagon(EngineID index)
581 const Engine *e = Engine::Get(index);
582 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
586 * Update #reliability of engine \a e, (if needed) update the engine GUIs.
587 * @param e %Engine to update.
589 static void CalcEngineReliability(Engine *e)
591 uint age = e->age;
593 /* Check for early retirement */
594 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
595 int retire_early = e->info.retire_early;
596 uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
597 if (retire_early != 0 && age >= retire_early_max_age) {
598 /* Early retirement is enabled and we're past the date... */
599 e->company_avail = 0;
600 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
604 if (age < e->duration_phase_1) {
605 uint start = e->reliability_start;
606 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
607 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
608 /* We are at the peak of this engines life. It will have max reliability.
609 * This is also true if the engines never expire. They will not go bad over time */
610 e->reliability = e->reliability_max;
611 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
612 uint max = e->reliability_max;
613 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
614 } else {
615 /* time's up for this engine.
616 * We will now completely retire this design */
617 e->company_avail = 0;
618 e->reliability = e->reliability_final;
619 /* Kick this engine out of the lists */
620 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
622 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
623 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
626 /** Compute the value for #_year_engine_aging_stops. */
627 void SetYearEngineAgingStops()
629 /* Determine last engine aging year, default to 2050 as previously. */
630 _year_engine_aging_stops = 2050;
632 const Engine *e;
633 FOR_ALL_ENGINES(e) {
634 const EngineInfo *ei = &e->info;
636 /* Exclude certain engines */
637 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
638 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
640 /* Base year ending date on half the model life */
641 YearMonthDay ymd;
642 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
644 _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
649 * Start/initialise one engine.
650 * @param e The engine to initialise.
651 * @param aging_date The date used for age calculations.
653 void StartupOneEngine(Engine *e, Date aging_date)
655 const EngineInfo *ei = &e->info;
657 e->age = 0;
658 e->flags = 0;
659 e->company_avail = 0;
660 e->company_hidden = 0;
662 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
663 * of engines in early starting games.
664 * Note: TTDP uses fixed 1922 */
665 uint32 r = Random();
666 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;
667 if (e->intro_date <= _date) {
668 e->age = (aging_date - e->intro_date) >> 5;
669 e->company_avail = (CompanyMask)-1;
670 e->flags |= ENGINE_AVAILABLE;
673 e->reliability_start = GB(r, 16, 14) + 0x7AE0;
674 r = Random();
675 e->reliability_max = GB(r, 0, 14) + 0xBFFF;
676 e->reliability_final = GB(r, 16, 14) + 0x3FFF;
678 r = Random();
679 e->duration_phase_1 = GB(r, 0, 5) + 7;
680 e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
681 e->duration_phase_3 = GB(r, 9, 7) + 120;
683 e->reliability_spd_dec = ei->decay_speed << 2;
685 CalcEngineReliability(e);
687 /* prevent certain engines from ever appearing. */
688 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
689 e->flags |= ENGINE_AVAILABLE;
690 e->company_avail = 0;
695 * Start/initialise all our engines. Must be called whenever there are changes
696 * to the NewGRF config.
698 void StartupEngines()
700 Engine *e;
701 /* Aging of vehicles stops, so account for that when starting late */
702 const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
704 FOR_ALL_ENGINES(e) {
705 StartupOneEngine(e, aging_date);
708 /* Update the bitmasks for the vehicle lists */
709 Company *c;
710 FOR_ALL_COMPANIES(c) {
711 c->avail_railtypes = GetCompanyRailtypes(c->index);
712 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
715 /* Invalidate any open purchase lists */
716 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
720 * Company \a company accepts engine \a eid for preview.
721 * @param eid Engine being accepted (is under preview).
722 * @param company Current company previewing the engine.
724 static void AcceptEnginePreview(EngineID eid, CompanyID company)
726 Engine *e = Engine::Get(eid);
727 Company *c = Company::Get(company);
729 SetBit(e->company_avail, company);
730 if (e->type == VEH_TRAIN) {
731 assert(e->u.rail.railtype < RAILTYPE_END);
732 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
733 } else if (e->type == VEH_ROAD) {
734 SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
737 e->preview_company = INVALID_COMPANY;
738 e->preview_asked = (CompanyMask)-1;
739 if (company == _local_company) {
740 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
743 /* Update the toolbar. */
744 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
745 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
747 /* Notify preview window, that it might want to close.
748 * Note: We cannot directly close the window.
749 * In singleplayer this function is called from the preview window, so
750 * we have to use the GUI-scope scheduling of InvalidateWindowData.
752 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
756 * Get the best company for an engine preview.
757 * @param e Engine to preview.
758 * @return Best company if it exists, #INVALID_COMPANY otherwise.
760 static CompanyID GetPreviewCompany(Engine *e)
762 CompanyID best_company = INVALID_COMPANY;
764 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
765 uint32 cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : (uint32)-1;
767 int32 best_hist = -1;
768 const Company *c;
769 FOR_ALL_COMPANIES(c) {
770 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
771 c->old_economy[0].performance_history > best_hist) {
773 /* Check whether the company uses similar vehicles */
774 Vehicle *v;
775 FOR_ALL_VEHICLES(v) {
776 if (v->owner != c->index || v->type != e->type) continue;
777 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
779 best_hist = c->old_economy[0].performance_history;
780 best_company = c->index;
781 break;
786 return best_company;
790 * Checks if a vehicle type is disabled for all/ai companies.
791 * @param type The vehicle type which shall be checked.
792 * @param ai If true, check if the type is disabled for AI companies, otherwise check if
793 * the vehicle type is disabled for human companies.
794 * @return Whether or not a vehicle type is disabled.
796 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
798 switch (type) {
799 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
800 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
801 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
802 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
804 default: NOT_REACHED();
808 /** Daily check to offer an exclusive engine preview to the companies. */
809 void EnginesDailyLoop()
811 Company *c;
812 FOR_ALL_COMPANIES(c) {
813 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
816 if (_cur_year >= _year_engine_aging_stops) return;
818 Engine *e;
819 FOR_ALL_ENGINES(e) {
820 EngineID i = e->index;
821 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
822 if (e->preview_company != INVALID_COMPANY) {
823 if (!--e->preview_wait) {
824 DeleteWindowById(WC_ENGINE_PREVIEW, i);
825 e->preview_company = INVALID_COMPANY;
827 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
828 e->preview_company = GetPreviewCompany(e);
830 if (e->preview_company == INVALID_COMPANY) {
831 e->preview_asked = (CompanyMask)-1;
832 continue;
835 SetBit(e->preview_asked, e->preview_company);
836 e->preview_wait = 20;
837 /* AIs are intentionally not skipped for preview even if they cannot build a certain
838 * vehicle type. This is done to not give poor performing human companies an "unfair"
839 * boost that they wouldn't have gotten against other human companies. The check on
840 * the line below is just to make AIs not notice that they have a preview if they
841 * cannot build the vehicle. */
842 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
843 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
850 * Clear the 'hidden' flag for all engines of a new company.
851 * @param cid Company being created.
853 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
855 Engine *e;
856 FOR_ALL_ENGINES(e) {
857 SB(e->company_hidden, cid, 1, 0);
862 * Set the visibility of an engine.
863 * @param tile Unused.
864 * @param flags Operation to perform.
865 * @param p1 Unused.
866 * @param p2 Bit 31: 0=visible, 1=hidden, other bits for the #EngineID.
867 * @param text Unused.
868 * @return The cost of this operation or an error.
870 CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
872 Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
873 if (e == NULL || _current_company >= MAX_COMPANIES) return CMD_ERROR;
874 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
876 if ((flags & DC_EXEC) != 0) {
877 SB(e->company_hidden, _current_company, 1, GB(p2, 31, 1));
878 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
881 return CommandCost();
885 * Accept an engine prototype. XXX - it is possible that the top-company
886 * changes while you are waiting to accept the offer? Then it becomes invalid
887 * @param tile unused
888 * @param flags operation to perform
889 * @param p1 engine-prototype offered
890 * @param p2 unused
891 * @param text unused
892 * @return the cost of this operation or an error
894 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
896 Engine *e = Engine::GetIfValid(p1);
897 if (e == NULL || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
899 if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
901 return CommandCost();
905 * An engine has become available for general use.
906 * Also handle the exclusive engine preview contract.
907 * @param e Engine generally available as of now.
909 static void NewVehicleAvailable(Engine *e)
911 Vehicle *v;
912 Company *c;
913 EngineID index = e->index;
915 /* In case the company didn't build the vehicle during the intro period,
916 * prevent that company from getting future intro periods for a while. */
917 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
918 FOR_ALL_COMPANIES(c) {
919 uint block_preview = c->block_preview;
921 if (!HasBit(e->company_avail, c->index)) continue;
923 /* We assume the user did NOT build it.. prove me wrong ;) */
924 c->block_preview = 20;
926 FOR_ALL_VEHICLES(v) {
927 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
928 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
929 if (v->owner == c->index && v->engine_type == index) {
930 /* The user did prove me wrong, so restore old value */
931 c->block_preview = block_preview;
932 break;
939 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
940 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
942 /* Now available for all companies */
943 e->company_avail = (CompanyMask)-1;
945 /* Do not introduce new rail wagons */
946 if (IsWagon(index)) return;
948 if (e->type == VEH_TRAIN) {
949 /* maybe make another rail type available */
950 RailType railtype = e->u.rail.railtype;
951 assert(railtype < RAILTYPE_END);
952 FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
953 } else if (e->type == VEH_ROAD) {
954 /* maybe make another road type available */
955 FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
958 /* Only broadcast event if AIs are able to build this vehicle type. */
959 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
961 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
962 if (!IsVehicleTypeDisabled(e->type, false)) {
963 SetDParam(0, GetEngineCategoryName(index));
964 SetDParam(1, index);
965 AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
968 /* Update the toolbar. */
969 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
970 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
972 /* Close pending preview windows */
973 DeleteWindowById(WC_ENGINE_PREVIEW, index);
976 /** Monthly update of the availability, reliability, and preview offers of the engines. */
977 void EnginesMonthlyLoop()
979 if (_cur_year < _year_engine_aging_stops) {
980 Engine *e;
981 FOR_ALL_ENGINES(e) {
982 /* Age the vehicle */
983 if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
984 e->age++;
985 CalcEngineReliability(e);
988 /* Do not introduce invalid engines */
989 if (!e->IsEnabled()) continue;
991 if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
992 /* Introduce it to all companies */
993 NewVehicleAvailable(e);
994 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
995 /* Introduction date has passed...
996 * Check if it is allowed to build this vehicle type at all
997 * based on the current game settings. If not, it does not
998 * make sense to show the preview dialog to any company. */
999 if (IsVehicleTypeDisabled(e->type, false)) continue;
1001 /* Do not introduce new rail wagons */
1002 if (IsWagon(e->index)) continue;
1004 /* Show preview dialog to one of the companies. */
1005 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
1006 e->preview_company = INVALID_COMPANY;
1007 e->preview_asked = 0;
1011 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
1016 * Is \a name still free as name for an engine?
1017 * @param name New name of an engine.
1018 * @return \c false if the name is being used already, else \c true.
1020 static bool IsUniqueEngineName(const char *name)
1022 const Engine *e;
1024 FOR_ALL_ENGINES(e) {
1025 if (e->name != NULL && strcmp(e->name, name) == 0) return false;
1028 return true;
1032 * Rename an engine.
1033 * @param tile unused
1034 * @param flags operation to perform
1035 * @param p1 engine ID to rename
1036 * @param p2 unused
1037 * @param text the new name or an empty string when resetting to the default
1038 * @return the cost of this operation or an error
1040 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1042 Engine *e = Engine::GetIfValid(p1);
1043 if (e == NULL) return CMD_ERROR;
1045 bool reset = StrEmpty(text);
1047 if (!reset) {
1048 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1049 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1052 if (flags & DC_EXEC) {
1053 free(e->name);
1055 if (reset) {
1056 e->name = NULL;
1057 } else {
1058 e->name = stredup(text);
1061 MarkWholeScreenDirty();
1064 return CommandCost();
1069 * Check if an engine is buildable.
1070 * @param engine index of the engine to check.
1071 * @param type the type the engine should be.
1072 * @param company index of the company.
1073 * @return True if an engine is valid, of the specified type, and buildable by
1074 * the given company.
1076 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1078 const Engine *e = Engine::GetIfValid(engine);
1080 /* check if it's an engine that is in the engine array */
1081 if (e == NULL) return false;
1083 /* check if it's an engine of specified type */
1084 if (e->type != type) return false;
1086 /* check if it's available ... */
1087 if (company == OWNER_DEITY) {
1088 /* ... for any company (preview does not count) */
1089 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1090 } else {
1091 /* ... for this company */
1092 if (!HasBit(e->company_avail, company)) return false;
1095 if (!e->IsEnabled()) return false;
1097 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1098 /* Check if the rail type is available to this company */
1099 const Company *c = Company::Get(company);
1100 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1103 return true;
1107 * Check if an engine is refittable.
1108 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1109 * @param engine index of the engine to check.
1110 * @return true if the engine is refittable.
1112 bool IsEngineRefittable(EngineID engine)
1114 const Engine *e = Engine::GetIfValid(engine);
1116 /* check if it's an engine that is in the engine array */
1117 if (e == NULL) return false;
1119 if (!e->CanCarryCargo()) return false;
1121 const EngineInfo *ei = &e->info;
1122 if (ei->refit_mask == 0) return false;
1124 /* Are there suffixes?
1125 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1126 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1128 /* Is there any cargo except the default cargo? */
1129 CargoID default_cargo = e->GetDefaultCargoType();
1130 return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
1134 * Check for engines that have an appropriate availability.
1136 void CheckEngines()
1138 const Engine *e;
1139 Date min_date = INT32_MAX;
1141 FOR_ALL_ENGINES(e) {
1142 if (!e->IsEnabled()) continue;
1144 /* We have an available engine... yay! */
1145 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1147 /* Okay, try to find the earliest date. */
1148 min_date = min(min_date, e->info.base_intro);
1151 if (min_date < INT32_MAX) {
1152 SetDParam(0, min_date);
1153 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1154 } else {
1155 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);