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 "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     /* 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     /* Set visual effect to the default value */
00093     switch (type) {
00094       case VEH_TRAIN: this->u.rail.visual_effect = VE_DEFAULT; break;
00095       case VEH_ROAD:  this->u.road.visual_effect = VE_DEFAULT; break;
00096       case VEH_SHIP:  this->u.ship.visual_effect = VE_DEFAULT; break;
00097       default: break; // The aircraft, disasters and especially visual effects have no NewGRF configured visual effects
00098     }
00099     return;
00100   }
00101 
00102   /* Copy the original engine info for this slot */
00103   this->info = _orig_engine_info[_engine_offsets[type] + base];
00104 
00105   /* Copy the original engine data for this slot */
00106   switch (type) {
00107     default: NOT_REACHED();
00108 
00109     case VEH_TRAIN:
00110       this->u.rail = _orig_rail_vehicle_info[base];
00111       this->original_image_index = this->u.rail.image_index;
00112       this->info.string_id = STR_VEHICLE_NAME_TRAIN_ENGINE_RAIL_KIRBY_PAUL_TANK_STEAM + base;
00113 
00114       /* Set the default model life of original wagons to "infinite" */
00115       if (this->u.rail.railveh_type == RAILVEH_WAGON) this->info.base_life = 0xFF;
00116 
00117       break;
00118 
00119     case VEH_ROAD:
00120       this->u.road = _orig_road_vehicle_info[base];
00121       this->original_image_index = this->u.road.image_index;
00122       this->info.string_id = STR_VEHICLE_NAME_ROAD_VEHICLE_MPS_REGAL_BUS + base;
00123       break;
00124 
00125     case VEH_SHIP:
00126       this->u.ship = _orig_ship_vehicle_info[base];
00127       this->original_image_index = this->u.ship.image_index;
00128       this->info.string_id = STR_VEHICLE_NAME_SHIP_MPS_OIL_TANKER + base;
00129       break;
00130 
00131     case VEH_AIRCRAFT:
00132       this->u.air = _orig_aircraft_vehicle_info[base];
00133       this->original_image_index = this->u.air.image_index;
00134       this->info.string_id = STR_VEHICLE_NAME_AIRCRAFT_SAMPSON_U52 + base;
00135       break;
00136   }
00137 }
00138 
00139 Engine::~Engine()
00140 {
00141   UnloadWagonOverrides(this);
00142   free(this->name);
00143 }
00144 
00149 bool Engine::IsEnabled() const
00150 {
00151   return this->info.string_id != STR_NEWGRF_INVALID_ENGINE;
00152 }
00153 
00159 bool Engine::CanCarryCargo() const
00160 {
00161   /* For engines that can appear in a consist (i.e. rail vehicles and (articulated) road vehicles), a capacity
00162    * of zero is a special case, to define the vehicle to not carry anything. The default cargotype is still used
00163    * for livery selection etc.
00164    * Note: Only the property is tested. A capacity callback returning 0 does not have the same effect.
00165    */
00166   switch (this->type) {
00167     case VEH_TRAIN:
00168       if (this->u.rail.capacity == 0) return false;
00169       break;
00170 
00171     case VEH_ROAD:
00172       if (this->u.road.capacity == 0) return false;
00173       break;
00174 
00175     case VEH_SHIP:
00176     case VEH_AIRCRAFT:
00177       break;
00178 
00179     default: NOT_REACHED();
00180   }
00181   return this->GetDefaultCargoType() != CT_INVALID;
00182 }
00183 
00196 uint Engine::GetDisplayDefaultCapacity(uint16 *mail_capacity) const
00197 {
00198   if (mail_capacity != NULL) *mail_capacity = 0;
00199   if (!this->CanCarryCargo()) return 0;
00200   switch (type) {
00201     case VEH_TRAIN:
00202       return GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity) + (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? this->u.rail.capacity : 0);
00203 
00204     case VEH_ROAD:
00205       return GetEngineProperty(this->index, PROP_ROADVEH_CARGO_CAPACITY, this->u.road.capacity);
00206 
00207     case VEH_SHIP:
00208       return GetEngineProperty(this->index, PROP_SHIP_CARGO_CAPACITY, this->u.ship.capacity);
00209 
00210     case VEH_AIRCRAFT: {
00211       uint capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_PASSENGER_CAPACITY, this->u.air.passenger_capacity);
00212       CargoID cargo = this->GetDefaultCargoType();
00213       if (IsCargoInClass(cargo, CC_PASSENGERS)) {
00214         if (mail_capacity != NULL) *mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity);
00215       } else {
00216         capacity += GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity);
00217       }
00218       switch (cargo) {
00219         case CT_PASSENGERS:
00220         case CT_MAIL:       return capacity;
00221         case CT_GOODS:      return capacity / 2;
00222         default:            return capacity / 4;
00223       }
00224     }
00225 
00226     default: NOT_REACHED();
00227   }
00228 }
00229 
00234 Money Engine::GetRunningCost() const
00235 {
00236   Price base_price;
00237   uint cost_factor;
00238   switch (this->type) {
00239     case VEH_ROAD:
00240       base_price = this->u.road.running_cost_class;
00241       if (base_price == INVALID_PRICE) return 0;
00242       cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_RUNNING_COST_FACTOR, this->u.road.running_cost);
00243       break;
00244 
00245     case VEH_TRAIN:
00246       base_price = this->u.rail.running_cost_class;
00247       if (base_price == INVALID_PRICE) return 0;
00248       cost_factor = GetEngineProperty(this->index, PROP_TRAIN_RUNNING_COST_FACTOR, this->u.rail.running_cost);
00249       break;
00250 
00251     case VEH_SHIP:
00252       base_price = PR_RUNNING_SHIP;
00253       cost_factor = GetEngineProperty(this->index, PROP_SHIP_RUNNING_COST_FACTOR, this->u.ship.running_cost);
00254       break;
00255 
00256     case VEH_AIRCRAFT:
00257       base_price = PR_RUNNING_AIRCRAFT;
00258       cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_RUNNING_COST_FACTOR, this->u.air.running_cost);
00259       break;
00260 
00261     default: NOT_REACHED();
00262   }
00263 
00264   return GetPrice(base_price, cost_factor, this->grf_prop.grffile, -8);
00265 }
00266 
00271 Money Engine::GetCost() const
00272 {
00273   Price base_price;
00274   uint cost_factor;
00275   switch (this->type) {
00276     case VEH_ROAD:
00277       base_price = PR_BUILD_VEHICLE_ROAD;
00278       cost_factor = GetEngineProperty(this->index, PROP_ROADVEH_COST_FACTOR, this->u.road.cost_factor);
00279       break;
00280 
00281     case VEH_TRAIN:
00282       if (this->u.rail.railveh_type == RAILVEH_WAGON) {
00283         base_price = PR_BUILD_VEHICLE_WAGON;
00284         cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
00285       } else {
00286         base_price = PR_BUILD_VEHICLE_TRAIN;
00287         cost_factor = GetEngineProperty(this->index, PROP_TRAIN_COST_FACTOR, this->u.rail.cost_factor);
00288       }
00289       break;
00290 
00291     case VEH_SHIP:
00292       base_price = PR_BUILD_VEHICLE_SHIP;
00293       cost_factor = GetEngineProperty(this->index, PROP_SHIP_COST_FACTOR, this->u.ship.cost_factor);
00294       break;
00295 
00296     case VEH_AIRCRAFT:
00297       base_price = PR_BUILD_VEHICLE_AIRCRAFT;
00298       cost_factor = GetEngineProperty(this->index, PROP_AIRCRAFT_COST_FACTOR, this->u.air.cost_factor);
00299       break;
00300 
00301     default: NOT_REACHED();
00302   }
00303 
00304   return GetPrice(base_price, cost_factor, this->grf_prop.grffile, -8);
00305 }
00306 
00311 uint Engine::GetDisplayMaxSpeed() const
00312 {
00313   switch (this->type) {
00314     case VEH_TRAIN:
00315       return GetEngineProperty(this->index, PROP_TRAIN_SPEED, this->u.rail.max_speed);
00316 
00317     case VEH_ROAD: {
00318       uint max_speed = GetEngineProperty(this->index, PROP_ROADVEH_SPEED, 0);
00319       return (max_speed != 0) ? max_speed * 2 : this->u.road.max_speed / 2;
00320     }
00321 
00322     case VEH_SHIP:
00323       return GetEngineProperty(this->index, PROP_SHIP_SPEED, this->u.ship.max_speed) / 2;
00324 
00325     case VEH_AIRCRAFT: {
00326       uint max_speed = GetEngineProperty(this->index, PROP_AIRCRAFT_SPEED, 0);
00327       if (max_speed != 0) {
00328         return (max_speed * 128) / 10;
00329       }
00330       return this->u.air.max_speed;
00331     }
00332 
00333     default: NOT_REACHED();
00334   }
00335 }
00336 
00343 uint Engine::GetPower() const
00344 {
00345   /* Only trains and road vehicles have 'power'. */
00346   switch (this->type) {
00347     case VEH_TRAIN:
00348       return GetEngineProperty(this->index, PROP_TRAIN_POWER, this->u.rail.power);
00349     case VEH_ROAD:
00350       return GetEngineProperty(this->index, PROP_ROADVEH_POWER, this->u.road.power) * 10;
00351 
00352     default: NOT_REACHED();
00353   }
00354 }
00355 
00361 uint Engine::GetDisplayWeight() const
00362 {
00363   /* Only trains and road vehicles have 'weight'. */
00364   switch (this->type) {
00365     case VEH_TRAIN:
00366       return GetEngineProperty(this->index, PROP_TRAIN_WEIGHT, this->u.rail.weight) << (this->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 1 : 0);
00367     case VEH_ROAD:
00368       return GetEngineProperty(this->index, PROP_ROADVEH_WEIGHT, this->u.road.weight) / 4;
00369 
00370     default: NOT_REACHED();
00371   }
00372 }
00373 
00379 uint Engine::GetDisplayMaxTractiveEffort() const
00380 {
00381   /* Only trains and road vehicles have 'tractive effort'. */
00382   switch (this->type) {
00383     case VEH_TRAIN:
00384       return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_TRAIN_TRACTIVE_EFFORT, this->u.rail.tractive_effort)) / 256;
00385     case VEH_ROAD:
00386       return (10 * this->GetDisplayWeight() * GetEngineProperty(this->index, PROP_ROADVEH_TRACTIVE_EFFORT, this->u.road.tractive_effort)) / 256;
00387 
00388     default: NOT_REACHED();
00389   }
00390 }
00391 
00396 Date Engine::GetLifeLengthInDays() const
00397 {
00398   /* Assume leap years; this gives the player a bit more than the given amount of years, but never less. */
00399   return (this->info.lifelength + _settings_game.vehicle.extend_vehicle_life) * DAYS_IN_LEAP_YEAR;
00400 }
00401 
00405 void EngineOverrideManager::ResetToDefaultMapping()
00406 {
00407   this->Clear();
00408   for (VehicleType type = VEH_TRAIN; type <= VEH_AIRCRAFT; type++) {
00409     for (uint internal_id = 0; internal_id < _engine_counts[type]; internal_id++) {
00410       EngineIDMapping *eid = this->Append();
00411       eid->type            = type;
00412       eid->grfid           = INVALID_GRFID;
00413       eid->internal_id     = internal_id;
00414       eid->substitute_id   = internal_id;
00415     }
00416   }
00417 }
00418 
00428 EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
00429 {
00430   const EngineIDMapping *end = this->End();
00431   EngineID index = 0;
00432   for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) {
00433     if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) {
00434       return index;
00435     }
00436   }
00437   return INVALID_ENGINE;
00438 }
00439 
00445 bool EngineOverrideManager::ResetToCurrentNewGRFConfig()
00446 {
00447   const Vehicle *v;
00448   FOR_ALL_VEHICLES(v) {
00449     if (IsCompanyBuildableVehicleType(v)) return false;
00450   }
00451 
00452   /* Reset the engines, they will get new EngineIDs */
00453   _engine_mngr.ResetToDefaultMapping();
00454   ReloadNewGRFData();
00455 
00456   return true;
00457 }
00458 
00462 void SetCachedEngineCounts()
00463 {
00464   size_t engines = Engine::GetPoolSize();
00465 
00466   /* Set up the engine count for all companies */
00467   Company *c;
00468   FOR_ALL_COMPANIES(c) {
00469     free(c->num_engines);
00470     c->num_engines = CallocT<EngineID>(engines);
00471   }
00472 
00473   /* Recalculate */
00474   Group *g;
00475   FOR_ALL_GROUPS(g) {
00476     free(g->num_engines);
00477     g->num_engines = CallocT<EngineID>(engines);
00478   }
00479 
00480   const Vehicle *v;
00481   FOR_ALL_VEHICLES(v) {
00482     if (!v->IsEngineCountable()) continue;
00483 
00484     assert(v->engine_type < engines);
00485 
00486     Company::Get(v->owner)->num_engines[v->engine_type]++;
00487 
00488     if (v->group_id == DEFAULT_GROUP) continue;
00489 
00490     g = Group::Get(v->group_id);
00491     assert(v->type == g->vehicle_type);
00492     assert(v->owner == g->owner);
00493 
00494     g->num_engines[v->engine_type]++;
00495   }
00496 }
00497 
00501 void SetupEngines()
00502 {
00503   DeleteWindowByClass(WC_ENGINE_PREVIEW);
00504   _engine_pool.CleanPool();
00505 
00506   assert(_engine_mngr.Length() >= _engine_mngr.NUM_DEFAULT_ENGINES);
00507   const EngineIDMapping *end = _engine_mngr.End();
00508   uint index = 0;
00509   for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
00510     /* Assert is safe; there won't be more than 256 original vehicles
00511      * in any case, and we just cleaned the pool. */
00512     assert(Engine::CanAllocateItem());
00513     const Engine *e = new Engine(eid->type, eid->internal_id);
00514     assert(e->index == index);
00515   }
00516 
00517   _introduced_railtypes = 0;
00518 }
00519 
00523 static void CheckRailIntroduction()
00524 {
00525   /* All railtypes have been introduced. */
00526   if (_introduced_railtypes == UINT16_MAX || Company::GetPoolSize() == 0) return;
00527 
00528   /* We need to find the railtypes that are known to all companies. */
00529   RailTypes rts = (RailTypes)UINT16_MAX;
00530 
00531   /* We are at, or past the introduction date of the rail. */
00532   Company *c;
00533   FOR_ALL_COMPANIES(c) {
00534     c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes, _date);
00535     rts &= c->avail_railtypes;
00536   }
00537 
00538   _introduced_railtypes |= rts;
00539 }
00540 
00541 void ShowEnginePreviewWindow(EngineID engine);
00542 
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 
00558 static void CalcEngineReliability(Engine *e)
00559 {
00560   uint age = e->age;
00561 
00562   /* Check for early retirement */
00563   if (e->company_avail != 0 && !_settings_game.vehicle.never_expire_vehicles && e->info.base_life != 0xFF) {
00564     int retire_early = e->info.retire_early;
00565     uint retire_early_max_age = max(0, e->duration_phase_1 + e->duration_phase_2 - retire_early * 12);
00566     if (retire_early != 0 && age >= retire_early_max_age) {
00567       /* Early retirement is enabled and we're past the date... */
00568       e->company_avail = 0;
00569       AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00570     }
00571   }
00572 
00573   if (age < e->duration_phase_1) {
00574     uint start = e->reliability_start;
00575     e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
00576   } else if ((age -= e->duration_phase_1) < e->duration_phase_2 || _settings_game.vehicle.never_expire_vehicles || e->info.base_life == 0xFF) {
00577     /* We are at the peak of this engines life. It will have max reliability.
00578      * This is also true if the engines never expire. They will not go bad over time */
00579     e->reliability = e->reliability_max;
00580   } else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
00581     uint max = e->reliability_max;
00582     e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
00583   } else {
00584     /* time's up for this engine.
00585      * We will now completely retire this design */
00586     e->company_avail = 0;
00587     e->reliability = e->reliability_final;
00588     /* Kick this engine out of the lists */
00589     AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00590   }
00591   SetWindowClassesDirty(WC_BUILD_VEHICLE); // Update to show the new reliability
00592   SetWindowClassesDirty(WC_REPLACE_VEHICLE);
00593 }
00594 
00596 void SetYearEngineAgingStops()
00597 {
00598   /* Determine last engine aging year, default to 2050 as previously. */
00599   _year_engine_aging_stops = 2050;
00600 
00601   const Engine *e;
00602   FOR_ALL_ENGINES(e) {
00603     const EngineInfo *ei = &e->info;
00604 
00605     /* Exclude certain engines */
00606     if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) continue;
00607     if (e->type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON) continue;
00608 
00609     /* Base year ending date on half the model life */
00610     YearMonthDay ymd;
00611     ConvertDateToYMD(ei->base_intro + (ei->lifelength * DAYS_IN_LEAP_YEAR) / 2, &ymd);
00612 
00613     _year_engine_aging_stops = max(_year_engine_aging_stops, ymd.year);
00614   }
00615 }
00616 
00622 void StartupOneEngine(Engine *e, Date aging_date)
00623 {
00624   const EngineInfo *ei = &e->info;
00625 
00626   e->age = 0;
00627   e->flags = 0;
00628   e->company_avail = 0;
00629 
00630   /* Don't randomise the start-date in the first two years after gamestart to ensure availability
00631    * of engines in early starting games.
00632    * Note: TTDP uses fixed 1922 */
00633   uint32 r = Random();
00634   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;
00635   if (e->intro_date <= _date) {
00636     e->age = (aging_date - e->intro_date) >> 5;
00637     e->company_avail = (CompanyMask)-1;
00638     e->flags |= ENGINE_AVAILABLE;
00639   }
00640 
00641   e->reliability_start = GB(r, 16, 14) + 0x7AE0;
00642   r = Random();
00643   e->reliability_max   = GB(r,  0, 14) + 0xBFFF;
00644   e->reliability_final = GB(r, 16, 14) + 0x3FFF;
00645 
00646   r = Random();
00647   e->duration_phase_1 = GB(r, 0, 5) + 7;
00648   e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
00649   e->duration_phase_3 = GB(r, 9, 7) + 120;
00650 
00651   e->reliability_spd_dec = ei->decay_speed << 2;
00652 
00653   CalcEngineReliability(e);
00654 
00655   /* prevent certain engines from ever appearing. */
00656   if (!HasBit(ei->climates, _settings_game.game_creation.landscape)) {
00657     e->flags |= ENGINE_AVAILABLE;
00658     e->company_avail = 0;
00659   }
00660 }
00661 
00663 void StartupEngines()
00664 {
00665   Engine *e;
00666   /* Aging of vehicles stops, so account for that when starting late */
00667   const Date aging_date = min(_date, ConvertYMDToDate(_year_engine_aging_stops, 0, 1));
00668 
00669   FOR_ALL_ENGINES(e) {
00670     StartupOneEngine(e, aging_date);
00671   }
00672 
00673   /* Update the bitmasks for the vehicle lists */
00674   Company *c;
00675   FOR_ALL_COMPANIES(c) {
00676     c->avail_railtypes = GetCompanyRailtypes(c->index);
00677     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
00678   }
00679 
00680   /* Rail types that are invalid or never introduced are marked as
00681    * being introduced upon start. That way we can easily check whether
00682    * there is any date related introduction that is still going to
00683    * happen somewhere in the future. */
00684   for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
00685     const RailtypeInfo *rti = GetRailTypeInfo(rt);
00686     if (rti->label != 0 && IsInsideMM(rti->introduction_date, 0, MAX_DAY)) continue;
00687 
00688     SetBit(_introduced_railtypes, rt);
00689   }
00690 
00691   CheckRailIntroduction();
00692 
00693   /* Invalidate any open purchase lists */
00694   InvalidateWindowClassesData(WC_BUILD_VEHICLE);
00695 }
00696 
00702 static void AcceptEnginePreview(EngineID eid, CompanyID company)
00703 {
00704   Engine *e = Engine::Get(eid);
00705   Company *c = Company::Get(company);
00706 
00707   SetBit(e->company_avail, company);
00708   if (e->type == VEH_TRAIN) {
00709     assert(e->u.rail.railtype < RAILTYPE_END);
00710     c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
00711   } else if (e->type == VEH_ROAD) {
00712     SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
00713   }
00714 
00715   e->preview_company_rank = 0xFF;
00716   if (company == _local_company) {
00717     AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00718   }
00719 
00720   /* Update the toolbar. */
00721   if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
00722   if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
00723 }
00724 
00730 static CompanyID GetBestCompany(uint8 pp)
00731 {
00732   CompanyID best_company;
00733   CompanyMask mask = 0;
00734 
00735   do {
00736     int32 best_hist = -1;
00737     best_company = INVALID_COMPANY;
00738 
00739     const Company *c;
00740     FOR_ALL_COMPANIES(c) {
00741       if (c->block_preview == 0 && !HasBit(mask, c->index) &&
00742           c->old_economy[0].performance_history > best_hist) {
00743         best_hist = c->old_economy[0].performance_history;
00744         best_company = c->index;
00745       }
00746     }
00747 
00748     if (best_company == INVALID_COMPANY) return INVALID_COMPANY;
00749 
00750     SetBit(mask, best_company);
00751   } while (--pp != 0);
00752 
00753   return best_company;
00754 }
00755 
00757 void EnginesDailyLoop()
00758 {
00759   CheckRailIntroduction();
00760 
00761   if (_cur_year >= _year_engine_aging_stops) return;
00762 
00763   Engine *e;
00764   FOR_ALL_ENGINES(e) {
00765     EngineID i = e->index;
00766     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
00767       if (e->flags & ENGINE_OFFER_WINDOW_OPEN) {
00768         if (e->preview_company_rank != 0xFF && !--e->preview_wait) {
00769           e->flags &= ~ENGINE_OFFER_WINDOW_OPEN;
00770           DeleteWindowById(WC_ENGINE_PREVIEW, i);
00771           e->preview_company_rank++;
00772         }
00773       } else if (e->preview_company_rank != 0xFF) {
00774         CompanyID best_company = GetBestCompany(e->preview_company_rank);
00775 
00776         if (best_company == INVALID_COMPANY) {
00777           e->preview_company_rank = 0xFF;
00778           continue;
00779         }
00780 
00781         e->flags |= ENGINE_OFFER_WINDOW_OPEN;
00782         e->preview_wait = 20;
00783         AI::NewEvent(best_company, new AIEventEnginePreview(i));
00784         if (IsInteractiveCompany(best_company)) ShowEnginePreviewWindow(i);
00785       }
00786     }
00787   }
00788 }
00789 
00800 CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00801 {
00802   Engine *e = Engine::GetIfValid(p1);
00803   if (e == NULL || GetBestCompany(e->preview_company_rank) != _current_company) return CMD_ERROR;
00804 
00805   if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
00806 
00807   return CommandCost();
00808 }
00809 
00815 static void NewVehicleAvailable(Engine *e)
00816 {
00817   Vehicle *v;
00818   Company *c;
00819   EngineID index = e->index;
00820 
00821   /* In case the company didn't build the vehicle during the intro period,
00822    * prevent that company from getting future intro periods for a while. */
00823   if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) {
00824     FOR_ALL_COMPANIES(c) {
00825       uint block_preview = c->block_preview;
00826 
00827       if (!HasBit(e->company_avail, c->index)) continue;
00828 
00829       /* We assume the user did NOT build it.. prove me wrong ;) */
00830       c->block_preview = 20;
00831 
00832       FOR_ALL_VEHICLES(v) {
00833         if (v->type == VEH_TRAIN || v->type == VEH_ROAD || v->type == VEH_SHIP ||
00834             (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft())) {
00835           if (v->owner == c->index && v->engine_type == index) {
00836             /* The user did prove me wrong, so restore old value */
00837             c->block_preview = block_preview;
00838             break;
00839           }
00840         }
00841       }
00842     }
00843   }
00844 
00845   e->flags = (e->flags & ~ENGINE_EXCLUSIVE_PREVIEW) | ENGINE_AVAILABLE;
00846   AddRemoveEngineFromAutoreplaceAndBuildWindows(e->type);
00847 
00848   /* Now available for all companies */
00849   e->company_avail = (CompanyMask)-1;
00850 
00851   /* Do not introduce new rail wagons */
00852   if (IsWagon(index)) return;
00853 
00854   if (e->type == VEH_TRAIN) {
00855     /* maybe make another rail type available */
00856     RailType railtype = e->u.rail.railtype;
00857     assert(railtype < RAILTYPE_END);
00858     FOR_ALL_COMPANIES(c) c->avail_railtypes = AddDateIntroducedRailTypes(c->avail_railtypes | GetRailTypeInfo(e->u.rail.railtype)->introduces_railtypes, _date);
00859   } else if (e->type == VEH_ROAD) {
00860     /* maybe make another road type available */
00861     FOR_ALL_COMPANIES(c) SetBit(c->avail_roadtypes, HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
00862   }
00863 
00864   AI::BroadcastNewEvent(new AIEventEngineAvailable(index));
00865 
00866   SetDParam(0, GetEngineCategoryName(index));
00867   SetDParam(1, index);
00868   AddNewsItem(STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE_WITH_TYPE, NS_NEW_VEHICLES, NR_ENGINE, index);
00869 
00870   /* Update the toolbar. */
00871   if (e->type == VEH_ROAD) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_ROAD);
00872   if (e->type == VEH_SHIP) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_WATER);
00873 }
00874 
00875 void EnginesMonthlyLoop()
00876 {
00877   if (_cur_year < _year_engine_aging_stops) {
00878     Engine *e;
00879     FOR_ALL_ENGINES(e) {
00880       /* Age the vehicle */
00881       if ((e->flags & ENGINE_AVAILABLE) && e->age != MAX_DAY) {
00882         e->age++;
00883         CalcEngineReliability(e);
00884       }
00885 
00886       /* Do not introduce invalid engines */
00887       if (!e->IsEnabled()) continue;
00888 
00889       if (!(e->flags & ENGINE_AVAILABLE) && _date >= (e->intro_date + DAYS_IN_YEAR)) {
00890         /* Introduce it to all companies */
00891         NewVehicleAvailable(e);
00892       } else if (!(e->flags & (ENGINE_AVAILABLE | ENGINE_EXCLUSIVE_PREVIEW)) && _date >= e->intro_date) {
00893         /* Introduction date has passed.. show introducing dialog to one companies. */
00894         e->flags |= ENGINE_EXCLUSIVE_PREVIEW;
00895 
00896         /* Do not introduce new rail wagons */
00897         if (!IsWagon(e->index)) {
00898           e->preview_company_rank = 1; // Give to the company with the highest rating.
00899         }
00900       }
00901     }
00902   }
00903 }
00904 
00905 static bool IsUniqueEngineName(const char *name)
00906 {
00907   const Engine *e;
00908 
00909   FOR_ALL_ENGINES(e) {
00910     if (e->name != NULL && strcmp(e->name, name) == 0) return false;
00911   }
00912 
00913   return true;
00914 }
00915 
00925 CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00926 {
00927   Engine *e = Engine::GetIfValid(p1);
00928   if (e == NULL) return CMD_ERROR;
00929 
00930   bool reset = StrEmpty(text);
00931 
00932   if (!reset) {
00933     if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR;
00934     if (!IsUniqueEngineName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
00935   }
00936 
00937   if (flags & DC_EXEC) {
00938     free(e->name);
00939 
00940     if (reset) {
00941       e->name = NULL;
00942     } else {
00943       e->name = strdup(text);
00944     }
00945 
00946     MarkWholeScreenDirty();
00947   }
00948 
00949   return CommandCost();
00950 }
00951 
00952 
00961 bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
00962 {
00963   const Engine *e = Engine::GetIfValid(engine);
00964 
00965   /* check if it's an engine that is in the engine array */
00966   if (e == NULL) return false;
00967 
00968   /* check if it's an engine of specified type */
00969   if (e->type != type) return false;
00970 
00971   /* check if it's available */
00972   if (!HasBit(e->company_avail, company)) return false;
00973 
00974   if (!e->IsEnabled()) return false;
00975 
00976   if (type == VEH_TRAIN) {
00977     /* Check if the rail type is available to this company */
00978     const Company *c = Company::Get(company);
00979     if (((GetRailTypeInfo(e->u.rail.railtype))->compatible_railtypes & c->avail_railtypes) == 0) return false;
00980   }
00981 
00982   return true;
00983 }
00984 
00991 bool IsEngineRefittable(EngineID engine)
00992 {
00993   const Engine *e = Engine::GetIfValid(engine);
00994 
00995   /* check if it's an engine that is in the engine array */
00996   if (e == NULL) return false;
00997 
00998   if (!e->CanCarryCargo()) return false;
00999 
01000   const EngineInfo *ei = &e->info;
01001   if (ei->refit_mask == 0) return false;
01002 
01003   /* Are there suffixes?
01004    * Note: This does not mean the suffixes are actually available for every consist at any time. */
01005   if (HasBit(ei->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) return true;
01006 
01007   /* Is there any cargo except the default cargo? */
01008   CargoID default_cargo = e->GetDefaultCargoType();
01009   return default_cargo != CT_INVALID && ei->refit_mask != 1U << default_cargo;
01010 }

Generated on Sun May 8 07:30:11 2011 for OpenTTD by  doxygen 1.6.1