# engine.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "company_func.h"
    00014 #include "command_func.h"
    00015 #include "news_func.h"
    00016 #include "aircraft.h"
    00017 #include "newgrf.h"
    00018 #include "newgrf_engine.h"
    00019 #include "strings_func.h"
    00020 #include "core/random_func.hpp"
    00021 #include "window_func.h"
    00022 #include "date_func.h"
    00023 #include "autoreplace_gui.h"
    00024 #include "string_func.h"
    00025 #include "ai/ai.hpp"
    00026 #include "core/pool_func.hpp"
    00027 #include "engine_gui.h"
    00028 #include "engine_func.h"
    00029 #include "engine_base.h"
    00030 #include "company_base.h"
    00031 #include "vehicle_func.h"
    00032 #include "articulated_vehicles.h"
    00033
    00034 #include "table/strings.h"
    00035 #include "table/engines.h"
    00036
    00037 EnginePool _engine_pool("Engine");
    00038 INSTANTIATE_POOL_METHODS(Engine)
    00039
    00040 EngineOverrideManager _engine_mngr;
    00041
    00046 static Year _year_engine_aging_stops;
    00047
    00051 static uint16 _introduced_railtypes;
    00052
    00054 const uint8 _engine_counts[4] = {
    00055   lengthof(_orig_rail_vehicle_info),
    00056   lengthof(_orig_road_vehicle_info),
    00057   lengthof(_orig_ship_vehicle_info),
    00058   lengthof(_orig_aircraft_vehicle_info),
    00059 };
    00060
    00062 const uint8 _engine_offsets[4] = {
    00063   0,
    00064   lengthof(_orig_rail_vehicle_info),
    00065   lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info),
    00066   lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
    00067 };
    00068
    00069 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));
    00070
    00071 const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
    00072
    00073 Engine::Engine() :
    00074   name(NULL),
    00075   overrides_count(0),
    00076   overrides(NULL)
    00077 {
    00078 }
    00079
    00080 Engine::Engine(VehicleType type, EngineID base)
    00081 {
    00082   this->type = type;
    00083   this->grf_prop.local_id = base;
    00084   this->list_position = base;
    00085
    00086   /* Check if this base engine is within the original engine data range */
    00087   if (base >= _engine_counts[type]) {
    00088     /* Set model life to maximum to make wagons available */
    00089     this->info.base_life = 0xFF;
    00090     /* Set road vehicle tractive effort to the default value */
    00091     if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
    00092     /* Aircraft must have CT_INVALID as default, as there is no property */
    00093     if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
    00094     /* Set visual effect to the default value */
    00095     switch (type) {
    00096       case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
    00097       case VEH_ROAD:  this->u.road.visual_effect = VE_DEFAULT; break;
    00098       case VEH_SHIP:  this->u.ship.visual_effect = VE_DEFAULT; break;
    00099       default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
    00100     }
    00101     /* Set cargo aging period to the default value. */
    00102     this->info.cargo_age_period = CARGO_AGING_TICKS;
    00103     return;
    00104   }
    00105
    00106   /* Copy the original engine info for this slot */
    00107   this->info = _orig_engine_info[_engine_offsets[type] + base];
    00108
    00109   /* Copy the original engine data for this slot */
    00110   switch (type) {
    00111     default: NOT_REACHED();
    00112
    00113     case VEH_TRAIN:
    00114       this->u.rail = _orig_rail_vehicle_info[base];
    00115       this->original_image_index = this->u.rail.image_index;
    00116       this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
    00117
    00118       /* Set the default model life of original wagons to "infinite" */
    00119       if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
    00120
    00121       break;
    00122
    00123     case VEH_ROAD:
    00124       this->u.road = _orig_road_vehicle_info[base];
    00125       this->original_image_index = this->u.road.image_index;
    00126       this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
    00127       break;
    00128
    00129     case VEH_SHIP:
    00130       this->u.ship = _orig_ship_vehicle_info[base];
    00131       this->original_image_index = this->u.ship.image_index;
    00132       this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
    00133       break;
    00134
    00135     case VEH_AIRCRAFT:
    00136       this->u.air = _orig_aircraft_vehicle_info[base];
    00137       this->original_image_index = this->u.air.image_index;
    00138       this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
    00139       break;
    00140   }
    00141 }
    00142
    00143 Engine::~Engine()
    00144 {
    00145   UnloadWagonOverrides(this);
    00146   free(this->name);
    00147 }
    00148
    00153 bool Engine::IsEnabled() const
    00154 {
    00155   return this->info.string_id != STR_NEWGRF_INVALID_ENGINE && HasBit(this->info.climates, _settings_game.game_creation.landscape);
    00156 }
    00157
    00163 uint32 Engine::GetGRFID() const
    00164 {
    00165   const GRFFile *file = this->GetGRF();
    00166   return file == NULL ? 0 : file->grfid;
    00167 }
    00168
    00174 bool Engine::CanCarryCargo() const
    00175 {
    00176   /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
    00177    * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
    00178    * for livery selection etc.
    00179    * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
    00180    */
    00181   switch (this->type) {
    00182     case VEH_TRAIN:
    00183       if (this->u.rail.capacity == 0) return false;
    00184       break;
    00185
    00186     case VEH_ROAD:
    00187       if (this->u.road.capacity == 0) return false;
    00188       break;
    00189
    00190     case VEH_SHIP:
    00191     case VEH_AIRCRAFT:
    00192       break;
    00193
    00194     default: NOT_REACHED();
    00195   }
    00196   return this->GetDefaultCargoType() != CT_INVALID;
    00197 }
    00198
    00199
    00207 uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
    00208 {
    00209   assert(v == NULL || this->index == v->engine_type);
    00210   if (mail_capacity != NULL) *mail_capacity = 0;
    00211
    00212   if (!this->CanCarryCargo()) return 0;
    00213
    00214   bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
    00215   CargoID default_cargo = this->GetDefaultCargoType();
    00216   CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
    00217
    00218   if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
    00219     *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
    00220   }
    00221
    00222   /* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
    00223   if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
    00224       (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
    00225     uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
    00226     if (callback != CALLBACK_FAILED) return callback;
    00227   }
    00228
    00229   /* Get capacity according to property resp. CB */
    00230   uint capacity;
    00231   uint extra_mail_cap = 0;
    00232   switch (this->type) {
    00233     case VEH_TRAIN:
    00234       capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY,        this->u.rail.capacity, v);
    00235
    00236       /* In purchase list add the capacity of the second head. Always use the plain property for this. */
    00237       if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
    00238       break;
    00239
    00240     case VEH_ROAD:
    00241       capacity = GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY,      this->u.road.capacity, v);
    00242       break;
    00243
    00244     case VEH_SHIP:
    00245       capacity = GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY,         this->u.ship.capacity, v);
    00246       break;
    00247
    00248     case VEH_AIRCRAFT:
    00249       capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity, v);
    00250       if (!IsCargoInClass(cargo_type, CC_PASSENGERS)) {
    00251         extra_mail_cap = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
    00252       }
    00253       if (!new_multipliers && cargo_type == CT_MAIL) return capacity + extra_mail_cap;
    00254       default_cargo = CT_PASSENGERS; // Always use 'passengers' wrt. cargo multipliers
    00255       break;
    00256
    00257     default: NOT_REACHED();
    00258   }
    00259
    00260   if (!new_multipliers) {
    00261     /* Use the passenger multiplier for mail as well */
    00262     capacity += extra_mail_cap;
    00263     extra_mail_cap = 0;
    00264   }
    00265
    00266   /* Apply multipliers depending on cargo- and vehicletype. */
    00267   if (new_multipliers || (this->type != VEH_SHIP && default_cargo != cargo_type)) {
    00268     uint16 default_multiplier = new_multipliers ? 0x100 : CargoSpec::Get(default_cargo)->multiplier;
    00269     uint16 cargo_multiplier = CargoSpec::Get(cargo_type)->multiplier;
    00270     capacity *= cargo_multiplier;
    00271     if (extra_mail_cap > 0) {
    00272       uint mail_multiplier = CargoSpec::Get(CT_MAIL)->multiplier;
    00273       capacity += (default_multiplier * extra_mail_cap * cargo_multiplier + mail_multiplier / 2) / mail_multiplier;
    00274     }
    00275     capacity = (capacity + default_multiplier / 2) / default_multiplier;
    00276   }
    00277
    00278   return capacity;
    00279 }
    00280
    00285 Money Engine::GetRunningCost() const
    00286 {
    00287   Price base_price;
    00288   uint cost_factor;
    00289   switch (this->type) {
    00290     case VEH_ROAD:
    00291       base_price = this->u.road.running_cost_class;
    00292       if (base_price == INVALID_PRICE) return 0;
    00293       cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
    00294       break;
    00295
    00296     case VEH_TRAIN:
    00297       base_price = this->u.rail.running_cost_class;
    00298       if (base_price == INVALID_PRICE) return 0;
    00299       cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
    00300       break;
    00301
    00302     case VEH_SHIP:
    00303       base_price = PR_RUNNING_SHIP;
    00304       cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
    00305       break;
    00306
    00307     case VEH_AIRCRAFT:
    00308       base_price = PR_RUNNING_AIRCRAFT;
    00309       cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
    00310       break;
    00311
    00312     default: NOT_REACHED();
    00313   }
    00314
    00315   return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
    00316 }
    00317
    00322 Money Engine::GetCost() const
    00323 {
    00324   Price base_price;
    00325   uint cost_factor;
    00326   switch (this->type) {
    00327     case VEH_ROAD:
    00328       base_price = PR_BUILD_VEHICLE_ROAD;
    00329       cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
    00330       break;
    00331
    00332     case VEH_TRAIN:
    00333       if (this->u.rail.railveh_type == RAILVEH_WAGON) {
    00334         base_price = PR_BUILD_VEHICLE_WAGON;
    00335         cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
    00336       } else {
    00337         base_price = PR_BUILD_VEHICLE_TRAIN;
    00338         cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
    00339       }
    00340       break;
    00341
    00342     case VEH_SHIP:
    00343       base_price = PR_BUILD_VEHICLE_SHIP;
    00344       cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
    00345       break;
    00346
    00347     case VEH_AIRCRAFT:
    00348       base_price = PR_BUILD_VEHICLE_AIRCRAFT;
    00349       cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
    00350       break;
    00351
    00352     default: NOT_REACHED();
    00353   }
    00354
    00355   return GetPrice(base_price, cost_factor, this->GetGRF(), -8);
    00356 }
    00357
    00362 uint Engine::GetDisplayMaxSpeed() const
    00363 {
    00364   switch (this->type) {
    00365     case VEH_TRAIN:
    00366       return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
    00367
    00368     case VEH_ROAD: {
    00369       uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
    00370       return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
    00371     }
    00372
    00373     case VEH_SHIP:
    00374       return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
    00375
    00376     case VEH_AIRCRAFT: {
    00377       uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
    00378       if (max_speed != 0) {
    00379         return (max_speed * 128) / 10;
    00380       }
    00381       return this->u.air.max_speed;
    00382     }
    00383
    00384     default: NOT_REACHED();
    00385   }
    00386 }
    00387
    00394 uint Engine::GetPower() const
    00395 {
    00396   /* Only trains and road vehicles have 'power'. */
    00397   switch (this->type) {
    00398     case VEH_TRAIN:
    00399       return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
    00400     case VEH_ROAD:
    00401       return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
    00402
    00403     default: NOT_REACHED();
    00404   }
    00405 }
    00406
    00412 uint Engine::GetDisplayWeight() const
    00413 {
    00414   /* Only trains and road vehicles have 'weight'. */
    00415   switch (this->type) {
    00416     case VEH_TRAIN:
    00417       return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
    00418     case VEH_ROAD:
    00419       return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
    00420
    00421     default: NOT_REACHED();
    00422   }
    00423 }
    00424
    00430 uint Engine::GetDisplayMaxTractiveEffort() const
    00431 {
    00432   /* Only trains and road vehicles have 'tractive effort'. */
    00433   switch (this->type) {
    00434     case VEH_TRAIN:
    00435       return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
    00436     case VEH_ROAD:
    00437       return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
    00438
    00439     default: NOT_REACHED();
    00440   }
    00441 }
    00442
    00447 Date Engine::GetLifeLengthInDays() const
    00448 {
    00449   /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
    00450   return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
    00451 }
    00452
    00457 uint16 Engine::GetRange() const
    00458 {
    00459   switch (this->type) {
    00460     case VEH_AIRCRAFT:
    00461       return GetEngineProperty(this->index, PROP_AIRCRAFT_RANGE, this->u.air.max_range);
    00462
    00463     default: NOT_REACHED();
    00464   }
    00465 }
    00466
    00470 void EngineOverrideManager::ResetToDefaultMapping()
    00471 {
    00472   this->Clear();
    00473   for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
    00474     for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
    00475       EngineIDMapping *eid = this->Append();
    00476       eid->type            = type;
    00477       eid->grfid           = INVALID_GRFID;
    00478       eid->internal_id     = internal_id;
    00479       eid->substitute_id   = internal_id;
    00480     }
    00481   }
    00482 }
    00483
    00493 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
    00494 {
    00495   const EngineIDMapping *end = this->End();
    00496   EngineID index = 0;
    00497   for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
    00498     if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
    00499       return index;
    00500     }
    00501   }
    00502   return INVALID_ENGINE;
    00503 }
    00504
    00510 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
    00511 {
    00512   const Vehicle *v;
    00513   FOR_ALL_VEHICLES(v) {
    00514     if (IsCompanyBuildableVehicleType(v)) return false;
    00515   }
    00516
    00517   /* Reset the engines, they will get new EngineIDs */
    00518   _engine_mngr.ResetToDefaultMapping();
    00519   ReloadNewGRFData();
    00520
    00521   return true;
    00522 }
    00523
    00527 void SetupEngines()
    00528 {
    00529   DeleteWindowByClass(WC_ENGINE_PREVIEW);
    00530   _engine_pool.CleanPool();
    00531
    00532   assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
    00533   const EngineIDMapping *end = _engine_mngr.End();
    00534   uint index = 0;
    00535   for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
    00536     /* Assert is safe; there won't be more than 256 original vehicles
    00537      * in any case, and we just cleaned the pool. */
    00538     assert(Engine::CanAllocateItem());
    00539     const Engine *e = new Engine(eid->type, eid->internal_id);
    00540     assert(e->index == index);
    00541   }
    00542
    00543   _introduced_railtypes = 0;
    00544 }
    00545
    00549 static void CheckRailIntroduction()
    00550 {
    00551   /* All railtypes have been introduced. */
    00552   if (_introduced_railtypes == UINT16_MAX || Company::GetPoolSize() == 0) return;
    00553
    00554   /* We need to find the railtypes that are known to all companies. */
    00555   RailTypes rts = (RailTypes)UINT16_MAX;
    00556
    00557   /* We are at, or past the introduction date of the rail. */
    00558   Company *c;
    00559   FOR_ALL_COMPANIES(c) {
    00560     c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
    00561     rts &= c->avail_railtypes;
    00562   }
    00563
    00564   _introduced_railtypes |= rts;
    00565 }
    00566
    00567 void ShowEnginePreviewWindow(EngineID engine);
    00568
    00574 static bool IsWagon(EngineID index)
    00575 {
    00576   const Engine *e = Engine::Get(index);
    00577   return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
    00578 }
    00579
    00584 static void CalcEngineReliability(Engine *e)
    00585 {
    00586   uint age = e->age;
    00587
    00588   /* Check for early retirement */
    00589   if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
    00590     int retire_early = e->info.retire_early;
    00591     uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
    00592     if (retire_early != 0 && age >= retire_early_max_age) {
    00593       /* Early retirement is enabled and we're past the date... */
    00594       e->company_avail = 0;
    00595       AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
    00596     }
    00597   }
    00598
    00599   if (age < e->duration_phase_1) {
    00600     uint start = e->reliability_start;
    00601     e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
    00602   } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
    00603     /* We are at the peak of this engines life. It will have max reliability.
    00604      * This is also true if the engines never expire. They will not go bad over time */
    00605     e->reliability = e->reliability_max;
    00606   } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
    00607     uint max = e->reliability_max;
    00608     e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
    00609   } else {
    00610     /* time's up for this engine.
    00611      * We will now completely retire this design */
    00612     e->company_avail = 0;
    00613     e->reliability = e->reliability_final;
    00614     /* Kick this engine out of the lists */
    00615     AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
    00616   }
    00617   SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
    00618   SetWindowClassesDirty(WC_REPLACE_VEHICLE);
    00619 }
    00620
    00622 void SetYearEngineAgingStops()
    00623 {
    00624   /* Determine last engine aging year, default to 2050 as previously. */
    00625   _year_engine_aging_stops = 2050;
    00626
    00627   const Engine *e;
    00628   FOR_ALL_ENGINES(e) {
    00629     const EngineInfo *ei = &e->info;
    00630
    00631     /* Exclude certain engines */
    00632     if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
    00633     if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
    00634
    00635     /* Base year ending date on half the model life */
    00636     YearMonthDay ymd;
    00637     ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
    00638
    00639     _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
    00640   }
    00641 }
    00642
    00648 void StartupOneEngine(Engine *e, Date aging_date)
    00649 {
    00650   const EngineInfo *ei = &e->info;
    00651
    00652   e->age = 0;
    00653   e->flags = 0;
    00654   e->company_avail = 0;
    00655
    00656   /* Don't randomise the start-date in the first two years after gamestart to ensure availability
    00657    * of engines in early starting games.
    00658    * Note: TTDP uses fixed 1922 */
    00659   uint32 r = Random();
    00660   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;
    00661   if (e->intro_date <= _date) {
    00662     e->age = (aging_date - e->intro_date) >> 5;
    00663     e->company_avail = (CompanyMask)-1;
    00664     e->flags |= ENGINE_AVAILABLE;
    00665   }
    00666
    00667   e->reliability_start = GB(r, 16, 14) + 0x7AE0;
    00668   r = Random();
    00669   e->reliability_max   = GB(r,  0, 14) + 0xBFFF;
    00670   e->reliability_final = GB(r, 16, 14) + 0x3FFF;
    00671
    00672   r = Random();
    00673   e->duration_phase_1 = GB(r, 0, 5) + 7;
    00674   e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
    00675   e->duration_phase_3 = GB(r, 9, 7) + 120;
    00676
    00677   e->reliability_spd_dec = ei->decay_speed << 2;
    00678
    00679   CalcEngineReliability(e);
    00680
    00681   /* prevent certain engines from ever appearing. */
    00682   if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
    00683     e->flags |= ENGINE_AVAILABLE;
    00684     e->company_avail = 0;
    00685   }
    00686 }
    00687
    00692 void StartupEngines()
    00693 {
    00694   Engine *e;
    00695   /* Aging of vehicles stops, so account for that when starting late */
    00696   const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
    00697
    00698   FOR_ALL_ENGINES(e) {
    00699     StartupOneEngine(e, aging_date);
    00700   }
    00701
    00702   /* Update the bitmasks for the vehicle lists */
    00703   Company *c;
    00704   FOR_ALL_COMPANIES(c) {
    00705     c->avail_railtypes = GetCompanyRailtypes(c->index);
    00706     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
    00707   }
    00708
    00709   /* Rail types that are invalid or never introduced are marked as
    00710    * being introduced upon start. That way we can easily check whether
    00711    * there is any date related introduction that is still going to
    00712    * happen somewhere in the future. */
    00713   for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
    00714     const RailtypeInfo *rti = GetRailTypeInfo(rt);
    00715     if (rti->label != 0 && IsInsideMM(rti->introduction_date, 0, MAX_DAY)) continue;
    00716
    00717     SetBit(_introduced_railtypes, rt);
    00718   }
    00719
    00720   CheckRailIntroduction();
    00721
    00722   /* Invalidate any open purchase lists */
    00723   InvalidateWindowClassesData(WC_BUILD_VEHICLE);
    00724 }
    00725
    00731 static void AcceptEnginePreview(EngineID eid, CompanyID company)
    00732 {
    00733   Engine *e = Engine::Get(eid);
    00734   Company *c = Company::Get(company);
    00735
    00736   SetBit(e->company_avail, company);
    00737   if (e->type == VEH_TRAIN) {
    00738     assert(e->u.rail.railtype < RAILTYPE_END);
    00739     c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
    00740   } else if (e->type == VEH_ROAD) {
    00741     SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
    00742   }
    00743
    00744   e->preview_company = INVALID_COMPANY;
    00745   e->preview_asked = (CompanyMask)-1;
    00746   if (company == _local_company) {
    00747     AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
    00748   }
    00749
    00750   /* Update the toolbar. */
    00751   if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
    00752   if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
    00753
    00754   /* Notify preview window, that it might want to close.
    00755    * Note: We cannot directly close the window.
    00756    *       In singleplayer this function is called from the preview window, so
    00757    *       we have to use the GUI-scope scheduling of InvalidateWindowData.
    00758    */
    00759   InvalidateWindowData(WC_ENGINE_PREVIEW, eid);
    00760 }
    00761
    00767 static CompanyID GetPreviewCompany(Engine *e)
    00768 {
    00769   CompanyID best_company = INVALID_COMPANY;
    00770
    00771   /* For trains the cargomask has no useful meaning, since you can attach other wagons */
    00772   uint32 cargomask = e->type != VEH_TRAIN ? GetUnionOfArticulatedRefitMasks(e->index, true) : (uint32)-1;
    00773
    00774   int32 best_hist = -1;
    00775   const Company *c;
    00776   FOR_ALL_COMPANIES(c) {
    00777     if (c->block_preview == 0 && !HasBit(e->preview_asked, c->index) &&
    00778         c->old_economy[0].performance_history > best_hist) {
    00779
    00780       /* Check whether the company uses similar vehicles */
    00781       Vehicle *v;
    00782       FOR_ALL_VEHICLES(v) {
    00783         if (v->owner != c->index || v->type != e->type) continue;
    00784         if (!v->GetEngine()->CanCarryCargo() || !HasBit(cargomask, v->cargo_type)) continue;
    00785
    00786         best_hist = c->old_economy[0].performance_history;
    00787         best_company = c->index;
    00788         break;
    00789       }
    00790     }
    00791   }
    00792
    00793   return best_company;
    00794 }
    00795
    00803 static bool IsVehicleTypeDisabled(VehicleType type, bool ai)
    00804 {
    00805   switch (type) {
    00806     case VEH_TRAIN:    return _settings_game.vehicle.max_trains == 0   || (ai && _settings_game.ai.ai_disable_veh_train);
    00807     case VEH_ROAD:     return _settings_game.vehicle.max_roadveh == 0  || (ai && _settings_game.ai.ai_disable_veh_roadveh);
    00808     case VEH_SHIP:     return _settings_game.vehicle.max_ships == 0    || (ai && _settings_game.ai.ai_disable_veh_ship);
    00809     case VEH_AIRCRAFT: return _settings_game.vehicle.max_aircraft == 0 || (ai && _settings_game.ai.ai_disable_veh_aircraft);
    00810
    00811     default: NOT_REACHED();
    00812   }
    00813 }
    00814
    00816 void EnginesDailyLoop()
    00817 {
    00818   CheckRailIntroduction();
    00819
    00820   if (_cur_year >= _year_engine_aging_stops) return;
    00821
    00822   Engine *e;
    00823   FOR_ALL_ENGINES(e) {
    00824     EngineID i = e->index;
    00825     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
    00826       if (e->preview_company != INVALID_COMPANY) {
    00827         if (!--e->preview_wait) {
    00828           DeleteWindowById(WC_ENGINE_PREVIEW, i);
    00829           e->preview_company = INVALID_COMPANY;
    00830         }
    00831       } else if (CountBits(e->preview_asked) < MAX_COMPANIES) {
    00832         e->preview_company = GetPreviewCompany(e);
    00833
    00834         if (e->preview_company == INVALID_COMPANY) {
    00835           e->preview_asked = (CompanyMask)-1;
    00836           continue;
    00837         }
    00838
    00839         SetBit(e->preview_asked, e->preview_company);
    00840         e->preview_wait = 20;
    00841         /* AIs are intentionally not skipped for preview even if they cannot build a certain
    00842          * vehicle type. This is done to not give poor performing human companies an "unfair"
    00843          * boost that they wouldn't have gotten against other human companies. The check on
    00844          * the line below is just to make AIs not notice that they have a preview if they
    00845          * cannot build the vehicle. */
    00846         if (!IsVehicleTypeDisabled(e->type, true)) AI::NewEvent(e->preview_company, new ScriptEventEnginePreview(i));
    00847         if (IsInteractiveCompany(e->preview_company)) ShowEnginePreviewWindow(i);
    00848       }
    00849     }
    00850   }
    00851 }
    00852
    00863 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00864 {
    00865   Engine *e = Engine::GetIfValid(p1);
    00866   if (e == NULL || e->preview_company != _current_company) return CMD_ERROR;
    00867
    00868   if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
    00869
    00870   return CommandCost();
    00871 }
    00872
    00878 static void NewVehicleAvailable(Engine *e)
    00879 {
    00880   Vehicle *v;
    00881   Company *c;
    00882   EngineID index = e->index;
    00883
    00884   /* In case the company didn't build the vehicle during the intro period,
    00885    * prevent that company from getting future intro periods for a while. */
    00886   if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
    00887     FOR_ALL_COMPANIES(c) {
    00888       uint block_preview = c->block_preview;
    00889
    00890       if (!HasBit(e->company_avail, c->index)) continue;
    00891
    00892       /* We assume the user did NOT build it.. prove me wrong ;) */
    00893       c->block_preview = 20;
    00894
    00895       FOR_ALL_VEHICLES(v) {
    00896         if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
    00897             (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
    00898           if (v->owner == c->index && v->engine_type == index) {
    00899             /* The user did prove me wrong, so restore old value */
    00900             c->block_preview = block_preview;
    00901             break;
    00902           }
    00903         }
    00904       }
    00905     }
    00906   }
    00907
    00908   e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
    00909   AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
    00910
    00911   /* Now available for all companies */
    00912   e->company_avail = (CompanyMask)-1;
    00913
    00914   /* Do not introduce new rail wagons */
    00915   if (IsWagon(index)) return;
    00916
    00917   if (e->type == VEH_TRAIN) {
    00918     /* maybe make another rail type available */
    00919     RailType railtype = e->u.rail.railtype;
    00920     assert(railtype < RAILTYPE_END);
    00921     FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
    00922   } else if (e->type == VEH_ROAD) {
    00923     /* maybe make another road type available */
    00924     FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
    00925   }
    00926
    00927   /* Only broadcast event if AIs are able to build this vehicle type. */
    00928   if (!IsVehicleTypeDisabled(e->type, true)) AI::BroadcastNewEvent(new ScriptEventEngineAvailable(index));
    00929
    00930   /* Only provide the "New Vehicle available" news paper entry, if engine can be built. */
    00931   if (!IsVehicleTypeDisabled(e->type, false)) {
    00932     SetDParam(0, GetEngineCategoryName(index));
    00933     SetDParam(1, index);
    00934     AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NT_NEW_VEHICLES, NF_VEHICLE, NR_ENGINE, index);
    00935   }
    00936
    00937   /* Update the toolbar. */
    00938   if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
    00939   if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
    00940
    00941   /* Close pending preview windows */
    00942   DeleteWindowById(WC_ENGINE_PREVIEW, index);
    00943 }
    00944
    00946 void EnginesMonthlyLoop()
    00947 {
    00948   if (_cur_year < _year_engine_aging_stops) {
    00949     Engine *e;
    00950     FOR_ALL_ENGINES(e) {
    00951       /* Age the vehicle */
    00952       if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
    00953         e->age++;
    00954         CalcEngineReliability(e);
    00955       }
    00956
    00957       /* Do not introduce invalid engines */
    00958       if (!e->IsEnabled()) continue;
    00959
    00960       if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
    00961         /* Introduce it to all companies */
    00962         NewVehicleAvailable(e);
    00963       } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
    00964         /* Introduction date has passed...
    00965          * Check if it is allowed to build this vehicle type at all
    00966          * based on the current game settings. If not, it does not
    00967          * make sense to show the preview dialog to any company. */
    00968         if (IsVehicleTypeDisabled(e->type, false)) continue;
    00969
    00970         /* Do not introduce new rail wagons */
    00971         if (IsWagon(e->index)) continue;
    00972
    00973         /* Show preview dialog to one of the companies. */
    00974         e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
    00975         e->preview_company = INVALID_COMPANY;
    00976         e->preview_asked = 0;
    00977       }
    00978     }
    00979
    00980     InvalidateWindowClassesData(WC_BUILD_VEHICLE); // rebuild the purchase list (esp. when sorted by reliability)
    00981   }
    00982 }
    00983
    00989 static bool IsUniqueEngineName(const char *name)
    00990 {
    00991   const Engine *e;
    00992
    00993   FOR_ALL_ENGINES(e) {
    00994     if (e->name != NULL && strcmp(e->name, name) == 0) return false;
    00995   }
    00996
    00997   return true;
    00998 }
    00999
    01009 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01010 {
    01011   Engine *e = Engine::GetIfValid(p1);
    01012   if (e == NULL) return CMD_ERROR;
    01013
    01014   bool reset = StrEmpty(text);
    01015
    01016   if (!reset) {
    01017     if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
    01018     if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01019   }
    01020
    01021   if (flags & DC_EXEC) {
    01022     free(e->name);
    01023
    01024     if (reset) {
    01025       e->name = NULL;
    01026     } else {
    01027       e->name = strdup(text);
    01028     }
    01029
    01030     MarkWholeScreenDirty();
    01031   }
    01032
    01033   return CommandCost();
    01034 }
    01035
    01036
    01045 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
    01046 {
    01047   const Engine *e = Engine::GetIfValid(engine);
    01048
    01049   /* check if it's an engine that is in the engine array */
    01050   if (e == NULL) return false;
    01051
    01052   /* check if it's an engine of specified type */
    01053   if (e->type != type) return false;
    01054
    01055   /* check if it's available ... */
    01056   if (company == OWNER_DEITY) {
    01057     /* ... for any company (preview does not count) */
    01058     if (!(e->flags & ENGINE_AVAILABLE) || e->company_avail == 0) return false;
    01059   } else {
    01060     /* ... for this company */
    01061     if (!HasBit(e->company_avail, company)) return false;
    01062   }
    01063
    01064   if (!e->IsEnabled()) return false;
    01065
    01066   if (type == VEH_TRAIN && company != OWNER_DEITY) {
    01067     /* Check if the rail type is available to this company */
    01068     const Company *c = Company::Get(company);
    01069     if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
    01070   }
    01071
    01072   return true;
    01073 }
    01074
    01081 bool IsEngineRefittable(EngineID engine)
    01082 {
    01083   const Engine *e = Engine::GetIfValid(engine);
    01084
    01085   /* check if it's an engine that is in the engine array */
    01086   if (e == NULL) return false;
    01087
    01088   if (!e->CanCarryCargo()) return false;
    01089
    01090   const EngineInfo *ei = &e->info;
    01091   if (ei->refit_mask == 0) return false;
    01092
    01093   /* Are there suffixes?
    01094    * Note: This does not mean the suffixes are actually available for every consist at any time. */
    01095   if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
    01096
    01097   /* Is there any cargo except the default cargo? */
    01098   CargoID default_cargo = e->GetDefaultCargoType();
    01099   return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
    01100 }