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