engine.cpp

Go to the documentation of this file.
00001 /* $Id: engine.cpp 22701 2011-07-30 17:45:37Z rubidium $ */
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 "group.h"
00020 #include "strings_func.h"
00021 #include "core/random_func.hpp"
00022 #include "window_func.h"
00023 #include "date_func.h"
00024 #include "autoreplace_gui.h"
00025 #include "string_func.h"
00026 #include "ai/ai.hpp"
00027 #include "core/pool_func.hpp"
00028 #include "engine_gui.h"
00029 #include "engine_func.h"
00030 #include "engine_base.h"
00031 #include "company_base.h"
00032 #include "vehicle_func.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     /* Mark engine as valid anyway */
00089     this->info.climates = 0x80;
00090     /* Set model life to maximum to make wagons available */
00091     this->info.base_life = 0xFF;
00092     /* Set road vehicle tractive effort to the default value */
00093     if (type == VEH_ROAD) this->u.road.tractive_effort = 0x4C;
00094     /* Aircraft must have CT_INVALID as default, as there is no property */
00095     if (type == VEH_AIRCRAFT) this->info.cargo_type = CT_INVALID;
00096     /* Set visual effect to the default value */
00097     switch (type) {
00098       case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
00099       case VEH_ROAD:  this->u.road.visual_effect = VE_DEFAULT; break;
00100       case VEH_SHIP:  this->u.ship.visual_effect = VE_DEFAULT; break;
00101       default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
00102     }
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;
00156 }
00157 
00163 bool Engine::CanCarryCargo() const
00164 {
00165   /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
00166    * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
00167    * for livery selection etc.
00168    * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
00169    */
00170   switch (this->type) {
00171     case VEH_TRAIN:
00172       if (this->u.rail.capacity == 0) return false;
00173       break;
00174 
00175     case VEH_ROAD:
00176       if (this->u.road.capacity == 0) return false;
00177       break;
00178 
00179     case VEH_SHIP:
00180     case VEH_AIRCRAFT:
00181       break;
00182 
00183     default: NOT_REACHED();
00184   }
00185   return this->GetDefaultCargoType() != CT_INVALID;
00186 }
00187 
00200 uint Engine::GetDisplayDefaultCapacity(uint16 *mail_capacity) const
00201 {
00202   if (mail_capacity != NULL) *mail_capacity = 0;
00203   if (!this->CanCarryCargo()) return 0;
00204   switch (type) {
00205     case VEH_TRAIN:
00206       return GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity) + (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? this->u.rail.capacity : 0);
00207 
00208     case VEH_ROAD:
00209       return GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity);
00210 
00211     case VEH_SHIP:
00212       return GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity);
00213 
00214     case VEH_AIRCRAFT: {
00215       uint capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity);
00216       CargoID cargo = this->GetDefaultCargoType();
00217       if (IsCargoInClass(cargo, CC_PASSENGERS)) {
00218         if (mail_capacity != NULL) *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity);
00219       } else {
00220         capacity += GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity);
00221       }
00222       switch (cargo) {
00223         case CT_PASSENGERS:
00224         case CT_MAIL:       return capacity;
00225         case CT_GOODS:      return capacity / 2;
00226         default:            return capacity / 4;
00227       }
00228     }
00229 
00230     default: NOT_REACHED();
00231   }
00232 }
00233 
00238 Money Engine::GetRunningCost() const
00239 {
00240   Price base_price;
00241   uint cost_factor;
00242   switch (this->type) {
00243     case VEH_ROAD:
00244       base_price = this->u.road.running_cost_class;
00245       if (base_price == INVALID_PRICE) return 0;
00246       cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
00247       break;
00248 
00249     case VEH_TRAIN:
00250       base_price = this->u.rail.running_cost_class;
00251       if (base_price == INVALID_PRICE) return 0;
00252       cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
00253       break;
00254 
00255     case VEH_SHIP:
00256       base_price = PR_RUNNING_SHIP;
00257       cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
00258       break;
00259 
00260     case VEH_AIRCRAFT:
00261       base_price = PR_RUNNING_AIRCRAFT;
00262       cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
00263       break;
00264 
00265     default: NOT_REACHED();
00266   }
00267 
00268   return GetPrice(base_price, cost_factor, this->grf_prop.grffile, -8);
00269 }
00270 
00275 Money Engine::GetCost() const
00276 {
00277   Price base_price;
00278   uint cost_factor;
00279   switch (this->type) {
00280     case VEH_ROAD:
00281       base_price = PR_BUILD_VEHICLE_ROAD;
00282       cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
00283       break;
00284 
00285     case VEH_TRAIN:
00286       if (this->u.rail.railveh_type == RAILVEH_WAGON) {
00287         base_price = PR_BUILD_VEHICLE_WAGON;
00288         cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
00289       } else {
00290         base_price = PR_BUILD_VEHICLE_TRAIN;
00291         cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
00292       }
00293       break;
00294 
00295     case VEH_SHIP:
00296       base_price = PR_BUILD_VEHICLE_SHIP;
00297       cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
00298       break;
00299 
00300     case VEH_AIRCRAFT:
00301       base_price = PR_BUILD_VEHICLE_AIRCRAFT;
00302       cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
00303       break;
00304 
00305     default: NOT_REACHED();
00306   }
00307 
00308   return GetPrice(base_price, cost_factor, this->grf_prop.grffile, -8);
00309 }
00310 
00315 uint Engine::GetDisplayMaxSpeed() const
00316 {
00317   switch (this->type) {
00318     case VEH_TRAIN:
00319       return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
00320 
00321     case VEH_ROAD: {
00322       uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
00323       return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
00324     }
00325 
00326     case VEH_SHIP:
00327       return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
00328 
00329     case VEH_AIRCRAFT: {
00330       uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
00331       if (max_speed != 0) {
00332         return (max_speed * 128) / 10;
00333       }
00334       return this->u.air.max_speed;
00335     }
00336 
00337     default: NOT_REACHED();
00338   }
00339 }
00340 
00347 uint Engine::GetPower() const
00348 {
00349   /* Only trains and road vehicles have 'power'. */
00350   switch (this->type) {
00351     case VEH_TRAIN:
00352       return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
00353     case VEH_ROAD:
00354       return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
00355 
00356     default: NOT_REACHED();
00357   }
00358 }
00359 
00365 uint Engine::GetDisplayWeight() const
00366 {
00367   /* Only trains and road vehicles have 'weight'. */
00368   switch (this->type) {
00369     case VEH_TRAIN:
00370       return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
00371     case VEH_ROAD:
00372       return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
00373 
00374     default: NOT_REACHED();
00375   }
00376 }
00377 
00383 uint Engine::GetDisplayMaxTractiveEffort() const
00384 {
00385   /* Only trains and road vehicles have 'tractive effort'. */
00386   switch (this->type) {
00387     case VEH_TRAIN:
00388       return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
00389     case VEH_ROAD:
00390       return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
00391 
00392     default: NOT_REACHED();
00393   }
00394 }
00395 
00400 Date Engine::GetLifeLengthInDays() const
00401 {
00402   /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
00403   return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
00404 }
00405 
00409 void EngineOverrideManager::ResetToDefaultMapping()
00410 {
00411   this->Clear();
00412   for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
00413     for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
00414       EngineIDMapping *eid = this->Append();
00415       eid->type            = type;
00416       eid->grfid           = INVALID_GRFID;
00417       eid->internal_id     = internal_id;
00418       eid->substitute_id   = internal_id;
00419     }
00420   }
00421 }
00422 
00432 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
00433 {
00434   const EngineIDMapping *end = this->End();
00435   EngineID index = 0;
00436   for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
00437     if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
00438       return index;
00439     }
00440   }
00441   return INVALID_ENGINE;
00442 }
00443 
00449 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
00450 {
00451   const Vehicle *v;
00452   FOR_ALL_VEHICLES(v) {
00453     if (IsCompanyBuildableVehicleType(v)) return false;
00454   }
00455 
00456   /* Reset the engines, they will get new EngineIDs */
00457   _engine_mngr.ResetToDefaultMapping();
00458   ReloadNewGRFData();
00459 
00460   return true;
00461 }
00462 
00466 void SetCachedEngineCounts()
00467 {
00468   size_t engines = Engine::GetPoolSize();
00469 
00470   /* Set up the engine count for all companies */
00471   Company *c;
00472   FOR_ALL_COMPANIES(c) {
00473     free(c->num_engines);
00474     c->num_engines = CallocT<EngineID>(engines);
00475   }
00476 
00477   /* Recalculate */
00478   Group *g;
00479   FOR_ALL_GROUPS(g) {
00480     free(g->num_engines);
00481     g->num_engines = CallocT<EngineID>(engines);
00482   }
00483 
00484   const Vehicle *v;
00485   FOR_ALL_VEHICLES(v) {
00486     if (!v->IsEngineCountable()) continue;
00487 
00488     assert(v->engine_type < engines);
00489 
00490     Company::Get(v->owner)->num_engines[v->engine_type]++;
00491 
00492     if (v->group_id == DEFAULT_GROUP) continue;
00493 
00494     g = Group::Get(v->group_id);
00495     assert(v->type == g->vehicle_type);
00496     assert(v->owner == g->owner);
00497 
00498     g->num_engines[v->engine_type]++;
00499   }
00500 }
00501 
00505 void SetupEngines()
00506 {
00507   DeleteWindowByClass(WC_ENGINE_PREVIEW);
00508   _engine_pool.CleanPool();
00509 
00510   assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
00511   const EngineIDMapping *end = _engine_mngr.End();
00512   uint index = 0;
00513   for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
00514     /* Assert is safe; there won't be more than 256 original vehicles
00515      * in any case, and we just cleaned the pool. */
00516     assert(Engine::CanAllocateItem());
00517     const Engine *e = new Engine(eid->type, eid->internal_id);
00518     assert(e->index == index);
00519   }
00520 
00521   _introduced_railtypes = 0;
00522 }
00523 
00527 static void CheckRailIntroduction()
00528 {
00529   /* All railtypes have been introduced. */
00530   if (_introduced_railtypes == UINT16_MAX || Company::GetPoolSize() == 0) return;
00531 
00532   /* We need to find the railtypes that are known to all companies. */
00533   RailTypes rts = (RailTypes)UINT16_MAX;
00534 
00535   /* We are at, or past the introduction date of the rail. */
00536   Company *c;
00537   FOR_ALL_COMPANIES(c) {
00538     c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
00539     rts &= c->avail_railtypes;
00540   }
00541 
00542   _introduced_railtypes |= rts;
00543 }
00544 
00545 void ShowEnginePreviewWindow(EngineID engine);
00546 
00547 /* Determine if an engine type is a wagon (and not a loco) */
00548 static bool IsWagon(EngineID index)
00549 {
00550   const Engine *e = Engine::Get(index);
00551   return e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON;
00552 }
00553 
00554 static void CalcEngineReliability(Engine *e)
00555 {
00556   uint age = e->age;
00557 
00558   /* Check for early retirement */
00559   if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
00560     int retire_early = e->info.retire_early;
00561     uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
00562     if (retire_early != 0 && age >= retire_early_max_age) {
00563       /* Early retirement is enabled and we're past the date... */
00564       e->company_avail = 0;
00565       AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00566     }
00567   }
00568 
00569   if (age < e->duration_phase_1) {
00570     uint start = e->reliability_start;
00571     e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
00572   } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
00573     /* We are at the peak of this engines life. It will have max reliability.
00574      * This is also true if the engines never expire. They will not go bad over time */
00575     e->reliability = e->reliability_max;
00576   } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
00577     uint max = e->reliability_max;
00578     e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
00579   } else {
00580     /* time's up for this engine.
00581      * We will now completely retire this design */
00582     e->company_avail = 0;
00583     e->reliability = e->reliability_final;
00584     /* Kick this engine out of the lists */
00585     AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00586   }
00587   SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
00588   SetWindowClassesDirty(WC_REPLACE_VEHICLE);
00589 }
00590 
00592 void SetYearEngineAgingStops()
00593 {
00594   /* Determine last engine aging year, default to 2050 as previously. */
00595   _year_engine_aging_stops = 2050;
00596 
00597   const Engine *e;
00598   FOR_ALL_ENGINES(e) {
00599     const EngineInfo *ei = &e->info;
00600 
00601     /* Exclude certain engines */
00602     if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
00603     if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
00604 
00605     /* Base year ending date on half the model life */
00606     YearMonthDay ymd;
00607     ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
00608 
00609     _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
00610   }
00611 }
00612 
00613 void StartupOneEngine(Engine *e, Date aging_date)
00614 {
00615   const EngineInfo *ei = &e->info;
00616 
00617   e->age = 0;
00618   e->flags = 0;
00619   e->company_avail = 0;
00620 
00621   /* Don't randomise the start-date in the first two years after gamestart to ensure availability
00622    * of engines in early starting games.
00623    * Note: TTDP uses fixed 1922 */
00624   uint32 r = Random();
00625   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;
00626   if (e->intro_date <= _date) {
00627     e->age = (aging_date - e->intro_date) >> 5;
00628     e->company_avail = (CompanyMask)-1;
00629     e->flags |= ENGINE_AVAILABLE;
00630   }
00631 
00632   e->reliability_start = GB(r, 16, 14) + 0x7AE0;
00633   r = Random();
00634   e->reliability_max   = GB(r,  0, 14) + 0xBFFF;
00635   e->reliability_final = GB(r, 16, 14) + 0x3FFF;
00636 
00637   r = Random();
00638   e->duration_phase_1 = GB(r, 0, 5) + 7;
00639   e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
00640   e->duration_phase_3 = GB(r, 9, 7) + 120;
00641 
00642   e->reliability_spd_dec = ei->decay_speed << 2;
00643 
00644   CalcEngineReliability(e);
00645 
00646   /* prevent certain engines from ever appearing. */
00647   if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
00648     e->flags |= ENGINE_AVAILABLE;
00649     e->company_avail = 0;
00650   }
00651 }
00652 
00653 void StartupEngines()
00654 {
00655   Engine *e;
00656   /* Aging of vehicles stops, so account for that when starting late */
00657   const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
00658 
00659   FOR_ALL_ENGINES(e) {
00660     StartupOneEngine(e, aging_date);
00661   }
00662 
00663   /* Update the bitmasks for the vehicle lists */
00664   Company *c;
00665   FOR_ALL_COMPANIES(c) {
00666     c->avail_railtypes = GetCompanyRailtypes(c->index);
00667     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
00668   }
00669 
00670   /* Rail types that are invalid or never introduced are marked as
00671    * being introduced upon start. That way we can easily check whether
00672    * there is any date related introduction that is still going to
00673    * happen somewhere in the future. */
00674   for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
00675     const RailtypeInfo *rti = GetRailTypeInfo(rt);
00676     if (rti->label != 0 && IsInsideMM(rti->introduction_date, 0, MAX_DAY)) continue;
00677 
00678     SetBit(_introduced_railtypes, rt);
00679   }
00680 
00681   CheckRailIntroduction();
00682 
00683   /* Invalidate any open purchase lists */
00684   InvalidateWindowClassesData(WC_BUILD_VEHICLE);
00685 }
00686 
00687 static void AcceptEnginePreview(EngineID eid, CompanyID company)
00688 {
00689   Engine *e = Engine::Get(eid);
00690   Company *c = Company::Get(company);
00691 
00692   SetBit(e->company_avail, company);
00693   if (e->type == VEH_TRAIN) {
00694     assert(e->u.rail.railtype < RAILTYPE_END);
00695     c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
00696   } else if (e->type == VEH_ROAD) {
00697     SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
00698   }
00699 
00700   e->preview_company_rank = 0xFF;
00701   if (company == _local_company) {
00702     AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00703   }
00704 
00705   /* Update the toolbar. */
00706   if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
00707   if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
00708 }
00709 
00715 static CompanyID GetBestCompany(uint8 pp)
00716 {
00717   CompanyID best_company;
00718   CompanyMask mask = 0;
00719 
00720   do {
00721     int32 best_hist = -1;
00722     best_company = INVALID_COMPANY;
00723 
00724     const Company *c;
00725     FOR_ALL_COMPANIES(c) {
00726       if (c->block_preview == 0 && !HasBit(mask, c->index) &&
00727           c->old_economy[0].performance_history > best_hist) {
00728         best_hist = c->old_economy[0].performance_history;
00729         best_company = c->index;
00730       }
00731     }
00732 
00733     if (best_company == INVALID_COMPANY) return INVALID_COMPANY;
00734 
00735     SetBit(mask, best_company);
00736   } while (--pp != 0);
00737 
00738   return best_company;
00739 }
00740 
00742 void EnginesDailyLoop()
00743 {
00744   CheckRailIntroduction();
00745 
00746   if (_cur_year >= _year_engine_aging_stops) return;
00747 
00748   Engine *e;
00749   FOR_ALL_ENGINES(e) {
00750     EngineID i = e->index;
00751     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
00752       if (e->flags & ENGINE_OFFER_WINDOW_OPEN) {
00753         if (e->preview_company_rank != 0xFF && !--e->preview_wait) {
00754           e->flags &= ~ENGINE_OFFER_WINDOW_OPEN;
00755           DeleteWindowById(WC_ENGINE_PREVIEW, i);
00756           e->preview_company_rank++;
00757         }
00758       } else if (e->preview_company_rank != 0xFF) {
00759         CompanyID best_company = GetBestCompany(e->preview_company_rank);
00760 
00761         if (best_company == INVALID_COMPANY) {
00762           e->preview_company_rank = 0xFF;
00763           continue;
00764         }
00765 
00766         e->flags |= ENGINE_OFFER_WINDOW_OPEN;
00767         e->preview_wait = 20;
00768         AI::NewEvent(best_company, new AIEventEnginePreview(i));
00769         if (IsInteractiveCompany(best_company)) ShowEnginePreviewWindow(i);
00770       }
00771     }
00772   }
00773 }
00774 
00785 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00786 {
00787   Engine *e = Engine::GetIfValid(p1);
00788   if (e == NULL || GetBestCompany(e->preview_company_rank) != _current_company) return CMD_ERROR;
00789 
00790   if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
00791 
00792   return CommandCost();
00793 }
00794 
00800 static void NewVehicleAvailable(Engine *e)
00801 {
00802   Vehicle *v;
00803   Company *c;
00804   EngineID index = e->index;
00805 
00806   /* In case the company didn't build the vehicle during the intro period,
00807    * prevent that company from getting future intro periods for a while. */
00808   if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
00809     FOR_ALL_COMPANIES(c) {
00810       uint block_preview = c->block_preview;
00811 
00812       if (!HasBit(e->company_avail, c->index)) continue;
00813 
00814       /* We assume the user did NOT build it.. prove me wrong ;) */
00815       c->block_preview = 20;
00816 
00817       FOR_ALL_VEHICLES(v) {
00818         if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
00819             (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
00820           if (v->owner == c->index && v->engine_type == index) {
00821             /* The user did prove me wrong, so restore old value */
00822             c->block_preview = block_preview;
00823             break;
00824           }
00825         }
00826       }
00827     }
00828   }
00829 
00830   e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
00831   AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00832 
00833   /* Now available for all companies */
00834   e->company_avail = (CompanyMask)-1;
00835 
00836   /* Do not introduce new rail wagons */
00837   if (IsWagon(index)) return;
00838 
00839   if (e->type == VEH_TRAIN) {
00840     /* maybe make another rail type available */
00841     RailType railtype = e->u.rail.railtype;
00842     assert(railtype < RAILTYPE_END);
00843     FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
00844   } else if (e->type == VEH_ROAD) {
00845     /* maybe make another road type available */
00846     FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
00847   }
00848 
00849   AI::BroadcastNewEvent(new AIEventEngineAvailable(index));
00850 
00851   SetDParam(0, GetEngineCategoryName(index));
00852   SetDParam(1, index);
00853   AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NS_NEW_VEHICLES, NR_ENGINE, index);
00854 
00855   /* Update the toolbar. */
00856   if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
00857   if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
00858 }
00859 
00860 void EnginesMonthlyLoop()
00861 {
00862   if (_cur_year < _year_engine_aging_stops) {
00863     Engine *e;
00864     FOR_ALL_ENGINES(e) {
00865       /* Age the vehicle */
00866       if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
00867         e->age++;
00868         CalcEngineReliability(e);
00869       }
00870 
00871       /* Do not introduce invalid engines */
00872       if (!e->IsEnabled()) continue;
00873 
00874       if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
00875         /* Introduce it to all companies */
00876         NewVehicleAvailable(e);
00877       } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
00878         /* Introduction date has passed.. show introducing dialog to one companies. */
00879         e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
00880 
00881         /* Do not introduce new rail wagons */
00882         if (!IsWagon(e->index)) {
00883           e->preview_company_rank = 1; // Give to the company with the highest rating.
00884         }
00885       }
00886     }
00887   }
00888 }
00889 
00890 static bool IsUniqueEngineName(const char *name)
00891 {
00892   const Engine *e;
00893 
00894   FOR_ALL_ENGINES(e) {
00895     if (e->name != NULL && strcmp(e->name, name) == 0) return false;
00896   }
00897 
00898   return true;
00899 }
00900 
00910 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00911 {
00912   Engine *e = Engine::GetIfValid(p1);
00913   if (e == NULL) return CMD_ERROR;
00914 
00915   bool reset = StrEmpty(text);
00916 
00917   if (!reset) {
00918     if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
00919     if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
00920   }
00921 
00922   if (flags & DC_EXEC) {
00923     free(e->name);
00924 
00925     if (reset) {
00926       e->name = NULL;
00927     } else {
00928       e->name = strdup(text);
00929     }
00930 
00931     MarkWholeScreenDirty();
00932   }
00933 
00934   return CommandCost();
00935 }
00936 
00937 
00946 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
00947 {
00948   const Engine *e = Engine::GetIfValid(engine);
00949 
00950   /* check if it's an engine that is in the engine array */
00951   if (e == NULL) return false;
00952 
00953   /* check if it's an engine of specified type */
00954   if (e->type != type) return false;
00955 
00956   /* check if it's available */
00957   if (!HasBit(e->company_avail, company)) return false;
00958 
00959   if (!e->IsEnabled()) return false;
00960 
00961   if (type == VEH_TRAIN) {
00962     /* Check if the rail type is available to this company */
00963     const Company *c = Company::Get(company);
00964     if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
00965   }
00966 
00967   return true;
00968 }
00969 
00976 bool IsEngineRefittable(EngineID engine)
00977 {
00978   const Engine *e = Engine::GetIfValid(engine);
00979 
00980   /* check if it's an engine that is in the engine array */
00981   if (e == NULL) return false;
00982 
00983   if (!e->CanCarryCargo()) return false;
00984 
00985   const EngineInfo *ei = &e->info;
00986   if (ei->refit_mask == 0) return false;
00987 
00988   /* Are there suffixes?
00989    * Note: This does not mean the suffixes are actually available for every consist at any time. */
00990   if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
00991 
00992   /* Is there any cargo except the default cargo? */
00993   CargoID default_cargo = e->GetDefaultCargoType();
00994   return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
00995 }