Inline GfxMainBlitterViewport
[openttd/fttd.git] / src / engine.cpp
blob2ebd66471266cac416952b77fa006aa0baaa9ebb
1 /* $Id$ */
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.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 "error.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;
43 /**
44 * Year that engine aging stops. Engines will not reduce in reliability
45 * and no more engines will be introduced
47 static Year _year_engine_aging_stops;
49 /** Number of engines of each vehicle type in original engine data */
50 const uint8 _engine_counts[4] = {
51 lengthof(_orig_rail_vehicle_info),
52 lengthof(_orig_road_vehicle_info),
53 lengthof(_orig_ship_vehicle_info),
54 lengthof(_orig_aircraft_vehicle_info),
57 /** Offset of the first engine of each vehicle type in original engine data */
58 const uint8 _engine_offsets[4] = {
60 lengthof(_orig_rail_vehicle_info),
61 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
62 lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
65 assert_compile(lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info) + lengthof(_orig_aircraft_vehicle_info) == lengthof(_orig_engine_info));
67 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
69 Engine::Engine() :
70 overrides_count(0),
71 overrides(NULL)
75 Engine::Engine(VehicleType type, EngineID base)
77 this->type = type;
78 this->grf_prop.local_id = base;
79 this->list_position = base;
80 this->preview_company = INVALID_COMPANY;
82 /* Check if this base engine is within the original engine data range */
83 if (base >= _engine_counts[type]) {
84 /* Set model life to maximum to make wagons available */
85 this->info.base_life = 0xFF;
86 /* Set road vehicle tractive effort to the default value */
87 if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
88 /* Aircraft must have CT_INVALID as default, as there is no property */
89 if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
90 /* Set visual effect to the default value */
91 switch (type) {
92 case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
93 case VEH_ROAD: this->u.road.visual_effect = VE_DEFAULT; break;
94 case VEH_SHIP: this->u.ship.visual_effect = VE_DEFAULT; break;
95 default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
97 /* Set cargo aging period to the default value. */
98 this->info.cargo_age_period = CARGO_AGING_TICKS;
99 return;
102 /* Copy the original engine info for this slot */
103 this->info = _orig_engine_info[_engine_offsets[type] + base];
105 /* Copy the original engine data for this slot */
106 switch (type) {
107 default: NOT_REACHED();
109 case VEH_TRAIN:
110 this->u.rail = _orig_rail_vehicle_info[base];
111 this->original_image_index = this->u.rail.image_index;
112 this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
114 /* Set the default model life of original wagons to "infinite" */
115 if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
117 break;
119 case VEH_ROAD:
120 this->u.road = _orig_road_vehicle_info[base];
121 this->original_image_index = this->u.road.image_index;
122 this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
123 break;
125 case VEH_SHIP:
126 this->u.ship = _orig_ship_vehicle_info[base];
127 this->original_image_index = this->u.ship.image_index;
128 this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
129 break;
131 case VEH_AIRCRAFT:
132 this->u.air = _orig_aircraft_vehicle_info[base];
133 this->original_image_index = this->u.air.image_index;
134 this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
135 break;
139 Engine::~Engine()
141 UnloadWagonOverrides(this);
145 * Checks whether the engine is a valid (non-articulated part of an) engine.
146 * @return true if enabled
148 bool Engine::IsEnabled() const
150 return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
154 * Retrieve the GRF ID of the NewGRF the engine is tied to.
155 * This is the GRF providing the Action 3.
156 * @return GRF ID of the associated NewGRF.
158 uint32 Engine::GetGRFID() const
160 const GRFFile *file = this->GetGRF();
161 return file == NULL ? 0 : file->grfid;
165 * Determines whether an engine can carry something.
166 * A vehicle cannot carry anything if its capacity is zero, or none of the possible cargoes is available in the climate.
167 * @return true if the vehicle can carry something.
169 bool Engine::CanCarryCargo() const
171 /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
172 * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
173 * for livery selection etc.
174 * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
176 switch (this->type) {
177 case VEH_TRAIN:
178 if (this->u.rail.capacity == 0) return false;
179 break;
181 case VEH_ROAD:
182 if (this->u.road.capacity == 0) return false;
183 break;
185 case VEH_SHIP:
186 case VEH_AIRCRAFT:
187 break;
189 default: NOT_REACHED();
191 return this->GetDefaultCargoType() != CT_INVALID;
196 * Determines capacity of a given vehicle from scratch.
197 * For aircraft the main capacity is determined. Mail might be present as well.
198 * @param v Vehicle of interest; NULL in purchase list
199 * @param mail_capacity returns secondary cargo (mail) capacity of aircraft
200 * @return Capacity
202 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
204 assert(v == NULL || this->index == v->engine_type);
205 if (mail_capacity != NULL) *mail_capacity = 0;
207 if (!this->CanCarryCargo()) return 0;
209 bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
210 CargoID default_cargo = this->GetDefaultCargoType();
211 CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
213 if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
214 *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
217 /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
218 if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
219 (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
220 uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
221 if (callback != CALLBACK_FAILED) return callback;
224 /* Get capacity according to property resp. CB */
225 uint capacity;
226 uint extra_mail_cap = 0;
227 switch (this->type) {
228 case VEH_TRAIN:
229 capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
231 /* In purchase list add the capacity of the second head. Always use the plain property for this. */
232 if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
233 break;
235 case VEH_ROAD:
236 capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity, v);
237 break;
239 case VEH_SHIP:
240 capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity, v);
241 break;
243 case VEH_AIRCRAFT:
244 capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
245 if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
246 extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
248 if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
249 default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
250 break;
252 default: NOT_REACHED();
255 if (!new_multipliers) {
256 /* Use the passenger multiplier for mail as well */
257 capacity += extra_mail_cap;
258 extra_mail_cap = 0;
261 /* Apply multipliers depending on cargo- and vehicletype. */
262 if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
263 uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
264 uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
265 capacity *= cargo_multiplier;
266 if (extra_mail_cap > 0) {
267 uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
268 capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
270 capacity = (capacity + default_multiplier / 2) / default_multiplier;
273 return capacity;
277 * Return how much the running costs of this engine are.
278 * @return Yearly running cost of the engine.
280 Money Engine::GetRunningCost() const
282 Price base_price;
283 uint cost_factor;
284 switch (this->type) {
285 case VEH_ROAD:
286 base_price = this->u.road.running_cost_class;
287 if (base_price == INVALID_PRICE) return 0;
288 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
289 break;
291 case VEH_TRAIN:
292 base_price = this->u.rail.running_cost_class;
293 if (base_price == INVALID_PRICE) return 0;
294 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
295 break;
297 case VEH_SHIP:
298 base_price = PR_RUNNING_SHIP;
299 cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
300 break;
302 case VEH_AIRCRAFT:
303 base_price = PR_RUNNING_AIRCRAFT;
304 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
305 break;
307 default: NOT_REACHED();
310 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
314 * Return how much a new engine costs.
315 * @return Cost of the engine.
317 Money Engine::GetCost() const
319 Price base_price;
320 uint cost_factor;
321 switch (this->type) {
322 case VEH_ROAD:
323 base_price = PR_BUILD_VEHICLE_ROAD;
324 cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
325 break;
327 case VEH_TRAIN:
328 if (this->u.rail.railveh_type == RAILVEH_WAGON) {
329 base_price = PR_BUILD_VEHICLE_WAGON;
330 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
331 } else {
332 base_price = PR_BUILD_VEHICLE_TRAIN;
333 cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
335 break;
337 case VEH_SHIP:
338 base_price = PR_BUILD_VEHICLE_SHIP;
339 cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
340 break;
342 case VEH_AIRCRAFT:
343 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
344 cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
345 break;
347 default: NOT_REACHED();
350 return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
354 * Returns max speed of the engine for display purposes
355 * @return max speed in km-ish/h
357 uint Engine::GetDisplayMaxSpeed() const
359 switch (this->type) {
360 case VEH_TRAIN:
361 return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
363 case VEH_ROAD: {
364 uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
365 return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
368 case VEH_SHIP:
369 return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
371 case VEH_AIRCRAFT: {
372 uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
373 if (max_speed != 0) {
374 return (max_speed * 128) / 10;
376 return this->u.air.max_speed;
379 default: NOT_REACHED();
384 * Returns the power of the engine for display
385 * and sorting purposes.
386 * Only trains and road vehicles have power
387 * @return power in display units hp
389 uint Engine::GetPower() const
391 /* Only trains and road vehicles have 'power'. */
392 switch (this->type) {
393 case VEH_TRAIN:
394 return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
395 case VEH_ROAD:
396 return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
398 default: NOT_REACHED();
403 * Returns the weight of the engine for display purposes.
404 * For dual-headed train-engines this is the weight of both heads
405 * @return weight in display units metric tons
407 uint Engine::GetDisplayWeight() const
409 /* Only trains and road vehicles have 'weight'. */
410 switch (this->type) {
411 case VEH_TRAIN:
412 return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
413 case VEH_ROAD:
414 return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
416 default: NOT_REACHED();
421 * Returns the tractive effort of the engine for display purposes.
422 * For dual-headed train-engines this is the tractive effort of both heads
423 * @return tractive effort in display units kN
425 uint Engine::GetDisplayMaxTractiveEffort() const
427 /* Only trains and road vehicles have 'tractive effort'. */
428 switch (this->type) {
429 case VEH_TRAIN:
430 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
431 case VEH_ROAD:
432 return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
434 default: NOT_REACHED();
439 * Returns the vehicle's (not model's!) life length in days.
440 * @return the life length
442 Date Engine::GetLifeLengthInDays() const
444 /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
445 return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
449 * Get the range of an aircraft type.
450 * @return Range of the aircraft type in tiles or 0 if unlimited range.
452 uint16 Engine::GetRange() const
454 switch (this->type) {
455 case VEH_AIRCRAFT:
456 return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
458 default: NOT_REACHED();
463 * Get the name of the aircraft type for display purposes.
464 * @return Aircraft type string.
466 StringID Engine::GetAircraftTypeText() const
468 switch (this->type) {
469 case VEH_AIRCRAFT:
470 switch (this->u.air.subtype) {
471 case AIR_HELI: return STR_LIVERY_HELICOPTER;
472 case AIR_CTOL: return STR_LIVERY_SMALL_PLANE;
473 case AIR_CTOL | AIR_FAST: return STR_LIVERY_LARGE_PLANE;
474 default: NOT_REACHED();
477 default: NOT_REACHED();
482 * Initializes the #EngineOverrideManager with the default engines.
484 void EngineOverrideManager::ResetToDefaultMapping()
486 this->Clear();
487 for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
488 for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
489 EngineIDMapping *eid = this->Append();
490 eid->type = type;
491 eid->grfid = INVALID_GRFID;
492 eid->internal_id = internal_id;
493 eid->substitute_id = internal_id;
499 * Looks up an EngineID in the EngineOverrideManager
500 * @param type Vehicle type
501 * @param grf_local_id The local id in the newgrf
502 * @param grfid The GrfID that defines the scope of grf_local_id.
503 * If a newgrf overrides the engines of another newgrf, the "scope grfid" is the ID of the overridden newgrf.
504 * If dynnamic_engines is disabled, all newgrf share the same ID scope identified by INVALID_GRFID.
505 * @return The engine ID if present, or INVALID_ENGINE if not.
507 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
509 const EngineIDMapping *end = this->End();
510 EngineID index = 0;
511 for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
512 if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
513 return index;
516 return INVALID_ENGINE;
520 * Tries to reset the engine mapping to match the current NewGRF configuration.
521 * This is only possible when there are currently no vehicles in the game.
522 * @return false if resetting failed due to present vehicles.
524 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
526 const Vehicle *v;
527 FOR_ALL_VEHICLES(v) {
528 if (IsCompanyBuildableVehicleType(v)) return false;
531 /* Reset the engines, they will get new EngineIDs */
532 _engine_mngr.ResetToDefaultMapping();
533 ReloadNewGRFData();
535 return true;
539 * Initialise the engine pool with the data from the original vehicles.
541 void SetupEngines()
543 DeleteWindowByClass(WC_ENGINE_PREVIEW);
544 Engine::pool.CleanPool();
546 assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
547 const EngineIDMapping *end = _engine_mngr.End();
548 uint index = 0;
549 for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
550 /* Assert is safe; there won't be more than 256 original vehicles
551 * in any case, and we just cleaned the pool. */
552 assert(Engine::CanAllocateItem());
553 const Engine *e = new Engine(eid->type, eid->internal_id);
554 assert(e->index == index);
558 void ShowEnginePreviewWindow(EngineID engine);
561 * Determine whether an engine type is a wagon (and not a loco).
562 * @param index %Engine getting queried.
563 * @return Whether the queried engine is a wagon.
565 static bool IsWagon(EngineID index)
567 const Engine *e = Engine::Get(index);
568 return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
572 * Update #reliability of engine \a e.
573 * @param e %EngineState to update.
574 * @param ei %EngineInfo for the engine.
576 static void CalcEngineReliability (EngineState *e, const EngineInfo *ei)
578 uint age = e->age;
580 /* Check for early retirement */
581 if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && ei->base_life != 0xFF) {
582 int retire_early = ei->retire_early;
583 uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
584 if (retire_early != 0 && age >= retire_early_max_age) {
585 /* Early retirement is enabled and we're past the date... */
586 e->company_avail = 0;
590 if (age < e->duration_phase_1) {
591 uint start = e->reliability_start;
592 e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
593 } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || ei->base_life == 0xFF) {
594 /* We are at the peak of this engines life. It will have max reliability.
595 * This is also true if the engines never expire. They will not go bad over time */
596 e->reliability = e->reliability_max;
597 } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
598 uint max = e->reliability_max;
599 e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
600 } else {
601 /* time's up for this engine.
602 * We will now completely retire this design */
603 e->company_avail = 0;
604 e->reliability = e->reliability_final;
608 /** Compute the value for #_year_engine_aging_stops. */
609 void SetYearEngineAgingStops()
611 /* Determine last engine aging year, default to 2050 as previously. */
612 _year_engine_aging_stops = 2050;
614 const Engine *e;
615 FOR_ALL_ENGINES(e) {
616 const EngineInfo *ei = &e->info;
618 /* Exclude certain engines */
619 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
620 if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
622 /* Base year ending date on half the model life */
623 YearMonthDay ymd;
624 ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
626 _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
631 * Reset or initialise the variable data of an engine.
632 * @param ei Engine info.
633 * @param aging_date The date used for age calculations.
635 void EngineState::reset (const EngineInfo *ei, Date aging_date)
637 this->age = 0;
638 this->flags = 0;
639 this->company_avail = 0;
640 this->company_hidden = 0;
642 /* Don't randomise the start-date in the first two years after gamestart to ensure availability
643 * of engines in early starting games.
644 * Note: TTDP uses fixed 1922 */
645 uint32 r = Random();
646 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;
647 if (this->intro_date <= _date) {
648 this->age = (aging_date - this->intro_date) >> 5;
649 this->company_avail = (CompanyMask)-1;
650 this->flags |= ENGINE_AVAILABLE;
653 this->reliability_start = GB(r, 16, 14) + 0x7AE0;
654 r = Random();
655 this->reliability_max = GB(r, 0, 14) + 0xBFFF;
656 this->reliability_final = GB(r, 16, 14) + 0x3FFF;
658 r = Random();
659 this->duration_phase_1 = GB(r, 0, 5) + 7;
660 this->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
661 this->duration_phase_3 = GB(r, 9, 7) + 120;
663 this->reliability_spd_dec = ei->decay_speed << 2;
665 CalcEngineReliability (this, ei);
667 /* prevent certain engines from ever appearing. */
668 if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
669 this->flags |= ENGINE_AVAILABLE;
670 this->company_avail = 0;
675 * Start/initialise all our engines. Must be called whenever there are changes
676 * to the NewGRF config.
678 void StartupEngines()
680 Engine *e;
681 /* Aging of vehicles stops, so account for that when starting late */
682 const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
684 FOR_ALL_ENGINES(e) {
685 e->reset (&e->info, aging_date);
688 /* Update the bitmasks for the vehicle lists */
689 Company *c;
690 FOR_ALL_COMPANIES(c) {
691 c->avail_railtypes = GetCompanyRailtypes(c->index);
692 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
695 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
696 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
698 /* Invalidate any open purchase lists */
699 InvalidateWindowClassesData(WC_BUILD_VEHICLE);
700 InvalidateWindowClassesData(WC_REPLACE_VEHICLE);
704 * Company \a company accepts engine \a eid for preview.
705 * @param eid Engine being accepted (is under preview).
706 * @param company Current company previewing the engine.
708 static void AcceptEnginePreview(EngineID eid, CompanyID company)
710 Engine *e = Engine::Get(eid);
711 Company *c = Company::Get(company);
713 SetBit(e->company_avail, company);
714 if (e->type == VEH_TRAIN) {
715 assert(e->u.rail.railtype < RAILTYPE_END);
716 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
717 } else if (e->type == VEH_ROAD) {
718 SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
721 e->preview_company = INVALID_COMPANY;
722 e->preview_asked = (CompanyMask)-1;
723 if (company == _local_company) {
724 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
727 /* Update the toolbar. */
728 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
729 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
731 /* Notify preview window, that it might want to close.
732 * Note: We cannot directly close the window.
733 * In singleplayer this function is called from the preview window, so
734 * we have to use the GUI-scope scheduling of InvalidateWindowData.
736 InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
740 * Get the best company for an engine preview.
741 * @param e Engine to preview.
742 * @return Best company if it exists, #INVALID_COMPANY otherwise.
744 static CompanyID GetPreviewCompany(Engine *e)
746 CompanyID best_company = INVALID_COMPANY;
748 /* For trains the cargomask has no useful meaning, since you can attach other wagons */
749 uint32 cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : (uint32)-1;
751 int32 best_hist = -1;
752 const Company *c;
753 FOR_ALL_COMPANIES(c) {
754 if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
755 c->old_economy[0].performance_history > best_hist) {
757 /* Check whether the company uses similar vehicles */
758 Vehicle *v;
759 FOR_ALL_VEHICLES(v) {
760 if (v->owner != c->index || v->type != e->type) continue;
761 if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
763 best_hist = c->old_economy[0].performance_history;
764 best_company = c->index;
765 break;
770 return best_company;
774 * Checks if a vehicle type is disabled for all/ai companies.
775 * @param type The vehicle type which shall be checked.
776 * @param ai If true, check if the type is disabled for AI companies, otherwise check if
777 * the vehicle type is disabled for human companies.
778 * @return Whether or not a vehicle type is disabled.
780 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
782 switch (type) {
783 case VEH_TRAIN: return _settings_game.vehicle.max_trains == 0 || (ai && _settings_game.ai.ai_disable_veh_train);
784 case VEH_ROAD: return _settings_game.vehicle.max_roadveh == 0 || (ai && _settings_game.ai.ai_disable_veh_roadveh);
785 case VEH_SHIP: return _settings_game.vehicle.max_ships == 0 || (ai && _settings_game.ai.ai_disable_veh_ship);
786 case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
788 default: NOT_REACHED();
792 /** Daily check to offer an exclusive engine preview to the companies. */
793 void EnginesDailyLoop()
795 Company *c;
796 FOR_ALL_COMPANIES(c) {
797 c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
800 if (_cur_year >= _year_engine_aging_stops) return;
802 Engine *e;
803 FOR_ALL_ENGINES(e) {
804 EngineID i = e->index;
805 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
806 if (e->preview_company != INVALID_COMPANY) {
807 if (!--e->preview_wait) {
808 DeleteWindowById(WC_ENGINE_PREVIEW, i);
809 e->preview_company = INVALID_COMPANY;
811 } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
812 e->preview_company = GetPreviewCompany(e);
814 if (e->preview_company == INVALID_COMPANY) {
815 e->preview_asked = (CompanyMask)-1;
816 continue;
819 SetBit(e->preview_asked, e->preview_company);
820 e->preview_wait = 20;
821 /* AIs are intentionally not skipped for preview even if they cannot build a certain
822 * vehicle type. This is done to not give poor performing human companies an "unfair"
823 * boost that they wouldn't have gotten against other human companies. The check on
824 * the line below is just to make AIs not notice that they have a preview if they
825 * cannot build the vehicle. */
826 if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
827 if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
834 * Clear the 'hidden' flag for all engines of a new company.
835 * @param cid Company being created.
837 void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
839 Engine *e;
840 FOR_ALL_ENGINES(e) {
841 SB(e->company_hidden, cid, 1, 0);
846 * Set the visibility of an engine.
847 * @param tile Unused.
848 * @param flags Operation to perform.
849 * @param p1 Unused.
850 * @param p2 Bit 31: 0=visible, 1=hidden, other bits for the #EngineID.
851 * @param text Unused.
852 * @return The cost of this operation or an error.
854 CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
856 Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
857 if (e == NULL || _current_company >= MAX_COMPANIES) return CMD_ERROR;
858 if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
860 if ((flags & DC_EXEC) != 0) {
861 SB(e->company_hidden, _current_company, 1, GB(p2, 31, 1));
862 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
865 return CommandCost();
869 * Accept an engine prototype. XXX - it is possible that the top-company
870 * changes while you are waiting to accept the offer? Then it becomes invalid
871 * @param tile unused
872 * @param flags operation to perform
873 * @param p1 engine-prototype offered
874 * @param p2 unused
875 * @param text unused
876 * @return the cost of this operation or an error
878 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
880 Engine *e = Engine::GetIfValid(p1);
881 if (e == NULL || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
883 if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
885 return CommandCost();
889 * An engine has become available for general use.
890 * Also handle the exclusive engine preview contract.
891 * @param e Engine generally available as of now.
893 static void NewVehicleAvailable(Engine *e)
895 Vehicle *v;
896 Company *c;
897 EngineID index = e->index;
899 /* In case the company didn't build the vehicle during the intro period,
900 * prevent that company from getting future intro periods for a while. */
901 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
902 FOR_ALL_COMPANIES(c) {
903 uint block_preview = c->block_preview;
905 if (!HasBit(e->company_avail, c->index)) continue;
907 /* We assume the user did NOT build it.. prove me wrong ;) */
908 c->block_preview = 20;
910 FOR_ALL_VEHICLES(v) {
911 if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
912 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
913 if (v->owner == c->index && v->engine_type == index) {
914 /* The user did prove me wrong, so restore old value */
915 c->block_preview = block_preview;
916 break;
923 e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
924 AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
926 /* Now available for all companies */
927 e->company_avail = (CompanyMask)-1;
929 /* Do not introduce new rail wagons */
930 if (IsWagon(index)) return;
932 if (e->type == VEH_TRAIN) {
933 /* maybe make another rail type available */
934 RailType railtype = e->u.rail.railtype;
935 assert(railtype < RAILTYPE_END);
936 FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
937 } else if (e->type == VEH_ROAD) {
938 /* maybe make another road type available */
939 FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
942 /* Only broadcast event if AIs are able to build this vehicle type. */
943 if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
945 /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
946 if (!IsVehicleTypeDisabled(e->type, false)) {
947 AddNewsItem<EngineNewsItem> (index);
950 /* Update the toolbar. */
951 if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
952 if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
954 /* Close pending preview windows */
955 DeleteWindowById(WC_ENGINE_PREVIEW, index);
958 /** Monthly update of the availability, reliability, and preview offers of the engines. */
959 void EnginesMonthlyLoop()
961 if (_cur_year < _year_engine_aging_stops) {
962 Engine *e;
963 FOR_ALL_ENGINES(e) {
964 /* Age the vehicle */
965 if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
966 e->age++;
967 CalcEngineReliability (e, &e->info);
970 /* Do not introduce invalid engines */
971 if (!e->IsEnabled()) continue;
973 if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
974 /* Introduce it to all companies */
975 NewVehicleAvailable(e);
976 } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
977 /* Introduction date has passed...
978 * Check if it is allowed to build this vehicle type at all
979 * based on the current game settings. If not, it does not
980 * make sense to show the preview dialog to any company. */
981 if (IsVehicleTypeDisabled(e->type, false)) continue;
983 /* Do not introduce new rail wagons */
984 if (IsWagon(e->index)) continue;
986 /* Show preview dialog to one of the companies. */
987 e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
988 e->preview_company = INVALID_COMPANY;
989 e->preview_asked = 0;
993 SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
994 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
996 InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
997 InvalidateWindowClassesData(WC_REPLACE_VEHICLE);
1002 * Is \a name still free as name for an engine?
1003 * @param name New name of an engine.
1004 * @return \c false if the name is being used already, else \c true.
1006 static bool IsUniqueEngineName(const char *name)
1008 const Engine *e;
1010 FOR_ALL_ENGINES(e) {
1011 if (e->name != NULL && strcmp(e->name, name) == 0) return false;
1014 return true;
1018 * Rename an engine.
1019 * @param tile unused
1020 * @param flags operation to perform
1021 * @param p1 engine ID to rename
1022 * @param p2 unused
1023 * @param text the new name or an empty string when resetting to the default
1024 * @return the cost of this operation or an error
1026 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1028 Engine *e = Engine::GetIfValid(p1);
1029 if (e == NULL) return CMD_ERROR;
1031 bool reset = StrEmpty(text);
1033 if (!reset) {
1034 if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
1035 if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1038 if (flags & DC_EXEC) {
1039 free(e->name);
1041 if (reset) {
1042 e->name = NULL;
1043 } else {
1044 e->name = xstrdup(text);
1047 MarkWholeScreenDirty();
1050 return CommandCost();
1055 * Check if an engine is buildable.
1056 * @param engine index of the engine to check.
1057 * @param type the type the engine should be.
1058 * @param company index of the company.
1059 * @return True if an engine is valid, of the specified type, and buildable by
1060 * the given company.
1062 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
1064 const Engine *e = Engine::GetIfValid(engine);
1066 /* check if it's an engine that is in the engine array */
1067 if (e == NULL) return false;
1069 /* check if it's an engine of specified type */
1070 if (e->type != type) return false;
1072 /* check if it's available ... */
1073 if (company == OWNER_DEITY) {
1074 /* ... for any company (preview does not count) */
1075 if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
1076 } else {
1077 /* ... for this company */
1078 if (!HasBit(e->company_avail, company)) return false;
1081 if (!e->IsEnabled()) return false;
1083 if (type == VEH_TRAIN && company != OWNER_DEITY) {
1084 /* Check if the rail type is available to this company */
1085 const Company *c = Company::Get(company);
1086 if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
1089 return true;
1093 * Check if an engine is refittable.
1094 * Note: Likely you want to use IsArticulatedVehicleRefittable().
1095 * @param engine index of the engine to check.
1096 * @return true if the engine is refittable.
1098 bool IsEngineRefittable(EngineID engine)
1100 const Engine *e = Engine::GetIfValid(engine);
1102 /* check if it's an engine that is in the engine array */
1103 if (e == NULL) return false;
1105 if (!e->CanCarryCargo()) return false;
1107 const EngineInfo *ei = &e->info;
1108 if (ei->refit_mask == 0) return false;
1110 /* Are there suffixes?
1111 * Note: This does not mean the suffixes are actually available for every consist at any time. */
1112 if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
1114 /* Is there any cargo except the default cargo? */
1115 CargoID default_cargo = e->GetDefaultCargoType();
1116 return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
1120 * Check for engines that have an appropriate availability.
1122 void CheckEngines()
1124 const Engine *e;
1125 Date min_date = INT32_MAX;
1127 FOR_ALL_ENGINES(e) {
1128 if (!e->IsEnabled()) continue;
1130 /* We have an available engine... yay! */
1131 if ((e->flags & ENGINE_AVAILABLE) != 0 && e->company_avail != 0) return;
1133 /* Okay, try to find the earliest date. */
1134 min_date = min(min_date, e->info.base_intro);
1137 if (min_date < INT32_MAX) {
1138 SetDParam(0, min_date);
1139 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_YET, STR_ERROR_NO_VEHICLES_AVAILABLE_YET_EXPLANATION, WL_WARNING);
1140 } else {
1141 ShowErrorMessage(STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL, STR_ERROR_NO_VEHICLES_AVAILABLE_AT_ALL_EXPLANATION, WL_WARNING);