train_cmd.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 "gui.h"
00014 #include "articulated_vehicles.h"
00015 #include "command_func.h"
00016 #include "pathfinder/npf/npf_func.h"
00017 #include "pathfinder/yapf/yapf.hpp"
00018 #include "news_func.h"
00019 #include "company_func.h"
00020 #include "vehicle_gui.h"
00021 #include "newgrf_sound.h"
00022 #include "newgrf_text.h"
00023 #include "group.h"
00024 #include "strings_func.h"
00025 #include "viewport_func.h"
00026 #include "window_func.h"
00027 #include "vehicle_func.h"
00028 #include "sound_func.h"
00029 #include "ai/ai.hpp"
00030 #include "newgrf_station.h"
00031 #include "effectvehicle_func.h"
00032 #include "gamelog.h"
00033 #include "network/network.h"
00034 #include "spritecache.h"
00035 #include "core/random_func.hpp"
00036 #include "company_base.h"
00037 #include "newgrf.h"
00038 #include "order_backup.h"
00039 #include "cargodest_func.h"
00040 
00041 #include "table/strings.h"
00042 #include "table/train_cmd.h"
00043 
00044 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
00045 static bool TrainCheckIfLineEnds(Train *v);
00046 static void TrainController(Train *v, Vehicle *nomove);
00047 static TileIndex TrainApproachingCrossingTile(const Train *v);
00048 static void CheckIfTrainNeedsService(Train *v);
00049 static void CheckNextTrainTile(Train *v);
00050 
00051 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4,  8};
00052 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
00053 
00054 
00062 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
00063 {
00064   static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
00065 
00066   DiagDirection diagdir = DirToDiagDir(direction);
00067 
00068   /* Determine the diagonal direction in which we will exit this tile */
00069   if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
00070     diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
00071   }
00072 
00073   return diagdir;
00074 }
00075 
00076 
00082 byte FreightWagonMult(CargoID cargo)
00083 {
00084   if (!CargoSpec::Get(cargo)->is_freight) return 1;
00085   return _settings_game.vehicle.freight_trains;
00086 }
00087 
00093 static void RailVehicleLengthChanged(const Train *u)
00094 {
00095   /* show a warning once for each engine in whole game and once for each GRF after each game load */
00096   const Engine *engine = Engine::Get(u->engine_type);
00097   uint32 grfid = engine->grf_prop.grffile->grfid;
00098   GRFConfig *grfconfig = GetGRFConfig(grfid);
00099   if (GamelogGRFBugReverse(grfid, engine->grf_prop.local_id) || !HasBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH)) {
00100     ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, GBUG_VEH_LENGTH, true);
00101   }
00102 }
00103 
00105 void CheckTrainsLengths()
00106 {
00107   const Train *v;
00108   bool first = true;
00109 
00110   FOR_ALL_TRAINS(v) {
00111     if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
00112       for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
00113         if (u->track != TRACK_BIT_DEPOT) {
00114           if ((w->track != TRACK_BIT_DEPOT &&
00115               max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->gcache.cached_veh_length) ||
00116               (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
00117             SetDParam(0, v->index);
00118             SetDParam(1, v->owner);
00119             ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
00120 
00121             if (!_networking && first) {
00122               first = false;
00123               DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
00124             }
00125             /* Break so we warn only once for each train. */
00126             break;
00127           }
00128         }
00129       }
00130     }
00131   }
00132 }
00133 
00138 void Train::RailtypeChanged()
00139 {
00140   for (Train *u = this; u != NULL; u = u->Next()) {
00141     /* The wagon-is-powered-state should not change, so the weight does not change. */
00142     u->UpdateVisualEffect(false);
00143   }
00144   this->PowerChanged();
00145   if (this->IsFrontEngine()) this->UpdateAcceleration();
00146 }
00147 
00154 void Train::ConsistChanged(bool same_length)
00155 {
00156   uint16 max_speed = UINT16_MAX;
00157 
00158   assert(this->IsFrontEngine() || this->IsFreeWagon());
00159 
00160   const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
00161   EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
00162   this->gcache.cached_total_length = 0;
00163   this->compatible_railtypes = RAILTYPES_NONE;
00164 
00165   bool train_can_tilt = true;
00166 
00167   for (Train *u = this; u != NULL; u = u->Next()) {
00168     const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
00169 
00170     /* Check the this->first cache. */
00171     assert(u->First() == this);
00172 
00173     /* update the 'first engine' */
00174     u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
00175     u->railtype = rvi_u->railtype;
00176 
00177     if (u->IsEngine()) first_engine = u->engine_type;
00178 
00179     /* Set user defined data to its default value */
00180     u->tcache.user_def_data = rvi_u->user_def_data;
00181     this->InvalidateNewGRFCache();
00182     u->InvalidateNewGRFCache();
00183   }
00184 
00185   for (Train *u = this; u != NULL; u = u->Next()) {
00186     /* Update user defined data (must be done before other properties) */
00187     u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
00188     this->InvalidateNewGRFCache();
00189     u->InvalidateNewGRFCache();
00190   }
00191 
00192   uint32 cargo_mask = 0;
00193 
00194   for (Train *u = this; u != NULL; u = u->Next()) {
00195     const Engine *e_u = Engine::Get(u->engine_type);
00196     const RailVehicleInfo *rvi_u = &e_u->u.rail;
00197 
00198     if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
00199 
00200     /* Cache wagon override sprite group. NULL is returned if there is none */
00201     u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
00202 
00203     /* Reset colour map */
00204     u->colourmap = PAL_NONE;
00205 
00206     /* Update powered-wagon-status and visual effect */
00207     u->UpdateVisualEffect(true);
00208 
00209     if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
00210         UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
00211       /* wagon is powered */
00212       SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
00213     } else {
00214       ClrBit(u->flags, VRF_POWEREDWAGON);
00215     }
00216 
00217     if (!u->IsArticulatedPart()) {
00218       /* Do not count powered wagons for the compatible railtypes, as wagons always
00219          have railtype normal */
00220       if (rvi_u->power > 0) {
00221         this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
00222       }
00223 
00224       /* Some electric engines can be allowed to run on normal rail. It happens to all
00225        * existing electric engines when elrails are disabled and then re-enabled */
00226       if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
00227         u->railtype = RAILTYPE_RAIL;
00228         u->compatible_railtypes |= RAILTYPES_RAIL;
00229       }
00230 
00231       /* max speed is the minimum of the speed limits of all vehicles in the consist */
00232       if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
00233         uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
00234         if (speed != 0) max_speed = min(speed, max_speed);
00235       }
00236     }
00237 
00238     /* Store carried cargo. */
00239     u->cargo_cap = GetVehicleCapacity(u);
00240     if (u->cargo_type != INVALID_CARGO && u->cargo_cap > 0) SetBit(cargo_mask, u->cargo_type);
00241 
00242     /* check the vehicle length (callback) */
00243     uint16 veh_len = CALLBACK_FAILED;
00244     if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
00245       veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
00246     }
00247     if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
00248     veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
00249 
00250     /* verify length hasn't changed */
00251     if (same_length && veh_len != u->gcache.cached_veh_length) RailVehicleLengthChanged(u);
00252 
00253     /* update vehicle length? */
00254     if (!same_length) u->gcache.cached_veh_length = veh_len;
00255 
00256     this->gcache.cached_total_length += u->gcache.cached_veh_length;
00257     this->InvalidateNewGRFCache();
00258     u->InvalidateNewGRFCache();
00259   }
00260 
00261   /* store consist weight/max speed in cache */
00262   this->vcache.cached_cargo_mask = cargo_mask;
00263   this->vcache.cached_max_speed = max_speed;
00264   this->tcache.cached_tilt = train_can_tilt;
00265   this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
00266 
00267   /* recalculate cached weights and power too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) */
00268   this->CargoChanged();
00269 
00270   if (this->IsFrontEngine()) {
00271     this->UpdateAcceleration();
00272     SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00273     InvalidateWindowData(WC_VEHICLE_REFIT, this->index);
00274   }
00275 }
00276 
00287 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
00288 {
00289   const Station *st = Station::Get(station_id);
00290   *station_ahead  = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
00291   *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
00292 
00293   /* Default to the middle of the station for stations stops that are not in
00294    * the order list like intermediate stations when non-stop is disabled */
00295   OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
00296   if (v->gcache.cached_total_length >= *station_length) {
00297     /* The train is longer than the station, make it stop at the far end of the platform */
00298     osl = OSL_PLATFORM_FAR_END;
00299   } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
00300     osl = v->current_order.GetStopLocation();
00301   }
00302 
00303   /* The stop location of the FRONT! of the train */
00304   int stop;
00305   switch (osl) {
00306     default: NOT_REACHED();
00307 
00308     case OSL_PLATFORM_NEAR_END:
00309       stop = v->gcache.cached_total_length;
00310       break;
00311 
00312     case OSL_PLATFORM_MIDDLE:
00313       stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
00314       break;
00315 
00316     case OSL_PLATFORM_FAR_END:
00317       stop = *station_length;
00318       break;
00319   }
00320 
00321   /* Subtract half the front vehicle length of the train so we get the real
00322    * stop location of the train.
00323    * Actually, the center of all vehicles is half a normal vehicle's length
00324    * from the front of the vehicle, so even in case the vehicle is 1/8th
00325    * long, the center is still at 1/2 of VEHICLE_LENGTH. Basically FS#3569. */
00326   return stop - VEHICLE_LENGTH / 2;
00327 }
00328 
00329 
00334 int Train::GetCurveSpeedLimit() const
00335 {
00336   assert(this->First() == this);
00337 
00338   static const int absolute_max_speed = UINT16_MAX;
00339   int max_speed = absolute_max_speed;
00340 
00341   if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
00342 
00343   int curvecount[2] = {0, 0};
00344 
00345   /* first find the curve speed limit */
00346   int numcurve = 0;
00347   int sum = 0;
00348   int pos = 0;
00349   int lastpos = -1;
00350   for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
00351     Direction this_dir = u->direction;
00352     Direction next_dir = u->Next()->direction;
00353 
00354     DirDiff dirdiff = DirDifference(this_dir, next_dir);
00355     if (dirdiff == DIRDIFF_SAME) continue;
00356 
00357     if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
00358     if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
00359     if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
00360       if (lastpos != -1) {
00361         numcurve++;
00362         sum += pos - lastpos;
00363         if (pos - lastpos == 1) {
00364           max_speed = 88;
00365         }
00366       }
00367       lastpos = pos;
00368     }
00369 
00370     /* if we have a 90 degree turn, fix the speed limit to 60 */
00371     if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
00372       max_speed = 61;
00373     }
00374   }
00375 
00376   if (numcurve > 0 && max_speed > 88) {
00377     if (curvecount[0] == 1 && curvecount[1] == 1) {
00378       max_speed = absolute_max_speed;
00379     } else {
00380       sum /= numcurve;
00381       max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
00382     }
00383   }
00384 
00385   if (max_speed != absolute_max_speed) {
00386     /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
00387     const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
00388     max_speed += (max_speed / 2) * rti->curve_speed;
00389 
00390     if (this->tcache.cached_tilt) {
00391       /* Apply max_speed bonus of 20% for a tilting train */
00392       max_speed += max_speed / 5;
00393     }
00394   }
00395 
00396   return max_speed;
00397 }
00398 
00403 int Train::GetCurrentMaxSpeed() const
00404 {
00405   int max_speed = this->tcache.cached_max_curve_speed;
00406   assert(max_speed == this->GetCurveSpeedLimit());
00407 
00408   if (IsRailStationTile(this->tile)) {
00409     StationID sid = GetStationIndex(this->tile);
00410     if (this->current_order.ShouldStopAtStation(this, sid)) {
00411       int station_ahead;
00412       int station_length;
00413       int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
00414 
00415       /* The distance to go is whatever is still ahead of the train minus the
00416        * distance from the train's stop location to the end of the platform */
00417       int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
00418 
00419       if (distance_to_go > 0) {
00420         int st_max_speed = 120;
00421 
00422         int delta_v = this->cur_speed / (distance_to_go + 1);
00423         if (max_speed > (this->cur_speed - delta_v)) {
00424           st_max_speed = this->cur_speed - (delta_v / 10);
00425         }
00426 
00427         st_max_speed = max(st_max_speed, 25 * distance_to_go);
00428         max_speed = min(max_speed, st_max_speed);
00429       }
00430     }
00431   }
00432 
00433   for (const Train *u = this; u != NULL; u = u->Next()) {
00434     if (u->track == TRACK_BIT_DEPOT) {
00435       max_speed = min(max_speed, 61);
00436       break;
00437     }
00438   }
00439 
00440   return min(max_speed, this->gcache.cached_max_track_speed);
00441 }
00442 
00443 void Train::UpdateAcceleration()
00444 {
00445   assert(this->IsFrontEngine());
00446 
00447   uint power = this->gcache.cached_power;
00448   uint weight = this->gcache.cached_weight;
00449   assert(weight != 0);
00450   this->acceleration = Clamp(power / weight * 4, 1, 255);
00451 }
00452 
00458 int Train::GetDisplayImageWidth(Point *offset) const
00459 {
00460   int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
00461   int vehicle_pitch = 0;
00462 
00463   const Engine *e = Engine::Get(this->engine_type);
00464   if (e->grf_prop.grffile != NULL && is_custom_sprite(e->u.rail.image_index)) {
00465     reference_width = e->grf_prop.grffile->traininfo_vehicle_width;
00466     vehicle_pitch = e->grf_prop.grffile->traininfo_vehicle_pitch;
00467   }
00468 
00469   if (offset != NULL) {
00470     offset->x = reference_width / 2;
00471     offset->y = vehicle_pitch;
00472   }
00473   return this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
00474 }
00475 
00476 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
00477 {
00478   return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
00479 }
00480 
00481 SpriteID Train::GetImage(Direction direction) const
00482 {
00483   uint8 spritenum = this->spritenum;
00484   SpriteID sprite;
00485 
00486   if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
00487 
00488   if (is_custom_sprite(spritenum)) {
00489     sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)));
00490     if (sprite != 0) return sprite;
00491 
00492     spritenum = Engine::Get(this->engine_type)->original_image_index;
00493   }
00494 
00495   sprite = GetDefaultTrainSprite(spritenum, direction);
00496 
00497   if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
00498 
00499   return sprite;
00500 }
00501 
00502 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y)
00503 {
00504   const Engine *e = Engine::Get(engine);
00505   Direction dir = rear_head ? DIR_E : DIR_W;
00506   uint8 spritenum = e->u.rail.image_index;
00507 
00508   if (is_custom_sprite(spritenum)) {
00509     SpriteID sprite = GetCustomVehicleIcon(engine, dir);
00510     if (sprite != 0) {
00511       if (e->grf_prop.grffile != NULL) {
00512         y += e->grf_prop.grffile->traininfo_vehicle_pitch;
00513       }
00514       return sprite;
00515     }
00516 
00517     spritenum = Engine::Get(engine)->original_image_index;
00518   }
00519 
00520   if (rear_head) spritenum++;
00521 
00522   return GetDefaultTrainSprite(spritenum, DIR_W);
00523 }
00524 
00525 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal)
00526 {
00527   if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00528     int yf = y;
00529     int yr = y;
00530 
00531     SpriteID spritef = GetRailIcon(engine, false, yf);
00532     SpriteID spriter = GetRailIcon(engine, true, yr);
00533     const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
00534     const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
00535 
00536     preferred_x = Clamp(preferred_x, left - real_spritef->x_offs + 14, right - real_spriter->width - real_spriter->x_offs - 15);
00537 
00538     DrawSprite(spritef, pal, preferred_x - 14, yf);
00539     DrawSprite(spriter, pal, preferred_x + 15, yr);
00540   } else {
00541     SpriteID sprite = GetRailIcon(engine, false, y);
00542     const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00543     preferred_x = Clamp(preferred_x, left - real_sprite->x_offs, right - real_sprite->width - real_sprite->x_offs);
00544     DrawSprite(sprite, pal, preferred_x, y);
00545   }
00546 }
00547 
00556 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
00557 {
00558   const RailVehicleInfo *rvi = &e->u.rail;
00559 
00560   /* Check that the wagon can drive on the track in question */
00561   if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00562 
00563   if (flags & DC_EXEC) {
00564     Train *v = new Train();
00565     *ret = v;
00566     v->spritenum = rvi->image_index;
00567 
00568     v->engine_type = e->index;
00569     v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
00570 
00571     DiagDirection dir = GetRailDepotDirection(tile);
00572 
00573     v->direction = DiagDirToDir(dir);
00574     v->tile = tile;
00575 
00576     int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
00577     int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
00578 
00579     v->x_pos = x;
00580     v->y_pos = y;
00581     v->z_pos = GetSlopeZ(x, y);
00582     v->owner = _current_company;
00583     v->track = TRACK_BIT_DEPOT;
00584     v->vehstatus = VS_HIDDEN | VS_DEFPAL;
00585 
00586     v->SetWagon();
00587 
00588     v->SetFreeWagon();
00589     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00590 
00591     v->cargo_type = e->GetDefaultCargoType();
00592     v->cargo_cap = rvi->capacity;
00593 
00594     v->railtype = rvi->railtype;
00595 
00596     v->build_year = _cur_year;
00597     v->cur_image = SPR_IMG_QUERY;
00598     v->random_bits = VehicleRandomBits();
00599 
00600     v->group_id = DEFAULT_GROUP;
00601 
00602     AddArticulatedParts(v);
00603 
00604     _new_vehicle_id = v->index;
00605 
00606     VehicleMove(v, false);
00607     v->First()->ConsistChanged(false);
00608     UpdateTrainGroupID(v->First());
00609 
00610     CheckConsistencyOfArticulatedVehicle(v);
00611 
00612     /* Try to connect the vehicle to one of free chains of wagons. */
00613     Train *w;
00614     FOR_ALL_TRAINS(w) {
00615       if (w->tile == tile &&              
00616           w->IsFreeWagon() &&             
00617           w->engine_type == e->index &&   
00618           w->First() != v &&              
00619           !(w->vehstatus & VS_CRASHED)) { 
00620         DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
00621         break;
00622       }
00623     }
00624   }
00625 
00626   return CommandCost();
00627 }
00628 
00630 static void NormalizeTrainVehInDepot(const Train *u)
00631 {
00632   const Train *v;
00633   FOR_ALL_TRAINS(v) {
00634     if (v->IsFreeWagon() && v->tile == u->tile &&
00635         v->track == TRACK_BIT_DEPOT) {
00636       if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
00637           CMD_MOVE_RAIL_VEHICLE).Failed())
00638         break;
00639     }
00640   }
00641 }
00642 
00643 static void AddRearEngineToMultiheadedTrain(Train *v)
00644 {
00645   Train *u = new Train();
00646   v->value >>= 1;
00647   u->value = v->value;
00648   u->direction = v->direction;
00649   u->owner = v->owner;
00650   u->tile = v->tile;
00651   u->x_pos = v->x_pos;
00652   u->y_pos = v->y_pos;
00653   u->z_pos = v->z_pos;
00654   u->track = TRACK_BIT_DEPOT;
00655   u->vehstatus = v->vehstatus & ~VS_STOPPED;
00656   u->spritenum = v->spritenum + 1;
00657   u->cargo_type = v->cargo_type;
00658   u->cargo_subtype = v->cargo_subtype;
00659   u->cargo_cap = v->cargo_cap;
00660   u->railtype = v->railtype;
00661   u->engine_type = v->engine_type;
00662   u->build_year = v->build_year;
00663   u->cur_image = SPR_IMG_QUERY;
00664   u->random_bits = VehicleRandomBits();
00665   v->SetMultiheaded();
00666   u->SetMultiheaded();
00667   v->SetNext(u);
00668   VehicleMove(u, false);
00669 
00670   /* Now we need to link the front and rear engines together */
00671   v->other_multiheaded_part = u;
00672   u->other_multiheaded_part = v;
00673 }
00674 
00684 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00685 {
00686   const RailVehicleInfo *rvi = &e->u.rail;
00687 
00688   if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
00689 
00690   /* Check if depot and new engine uses the same kind of tracks *
00691    * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
00692   if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00693 
00694   if (flags & DC_EXEC) {
00695     DiagDirection dir = GetRailDepotDirection(tile);
00696     int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
00697     int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
00698 
00699     Train *v = new Train();
00700     *ret = v;
00701     v->direction = DiagDirToDir(dir);
00702     v->tile = tile;
00703     v->owner = _current_company;
00704     v->x_pos = x;
00705     v->y_pos = y;
00706     v->z_pos = GetSlopeZ(x, y);
00707     v->track = TRACK_BIT_DEPOT;
00708     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00709     v->spritenum = rvi->image_index;
00710     v->cargo_type = e->GetDefaultCargoType();
00711     v->cargo_cap = rvi->capacity;
00712     v->last_station_visited = INVALID_STATION;
00713 
00714     v->engine_type = e->index;
00715     v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
00716 
00717     v->reliability = e->reliability;
00718     v->reliability_spd_dec = e->reliability_spd_dec;
00719     v->max_age = e->GetLifeLengthInDays();
00720 
00721     v->railtype = rvi->railtype;
00722     _new_vehicle_id = v->index;
00723 
00724     v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_trains;
00725     v->date_of_last_service = _date;
00726     v->build_year = _cur_year;
00727     v->cur_image = SPR_IMG_QUERY;
00728     v->random_bits = VehicleRandomBits();
00729 
00730     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00731 
00732     v->group_id = DEFAULT_GROUP;
00733 
00734     v->SetFrontEngine();
00735     v->SetEngine();
00736 
00737     VehicleMove(v, false);
00738 
00739     if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
00740       AddRearEngineToMultiheadedTrain(v);
00741     } else {
00742       AddArticulatedParts(v);
00743     }
00744 
00745     v->ConsistChanged(false);
00746     UpdateTrainGroupID(v);
00747 
00748     if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
00749       NormalizeTrainVehInDepot(v);
00750     }
00751 
00752     CheckConsistencyOfArticulatedVehicle(v);
00753   }
00754 
00755   return CommandCost();
00756 }
00757 
00758 
00759 bool Train::IsInDepot() const
00760 {
00761   /* Is the front engine stationary in the depot? */
00762   if (!IsRailDepotTile(this->tile) || this->cur_speed != 0) return false;
00763 
00764   /* Check whether the rest is also already trying to enter the depot. */
00765   for (const Train *v = this; v != NULL; v = v->Next()) {
00766     if (v->track != TRACK_BIT_DEPOT || v->tile != this->tile) return false;
00767   }
00768 
00769   return true;
00770 }
00771 
00772 bool Train::IsStoppedInDepot() const
00773 {
00774   /* Are we stopped? Of course wagons don't really care... */
00775   if (this->IsFrontEngine() && !(this->vehstatus & VS_STOPPED)) return false;
00776   return this->IsInDepot();
00777 }
00778 
00779 static Train *FindGoodVehiclePos(const Train *src)
00780 {
00781   EngineID eng = src->engine_type;
00782   TileIndex tile = src->tile;
00783 
00784   Train *dst;
00785   FOR_ALL_TRAINS(dst) {
00786     if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
00787       /* check so all vehicles in the line have the same engine. */
00788       Train *t = dst;
00789       while (t->engine_type == eng) {
00790         t = t->Next();
00791         if (t == NULL) return dst;
00792       }
00793     }
00794   }
00795 
00796   return NULL;
00797 }
00798 
00800 typedef SmallVector<Train *, 16> TrainList;
00801 
00807 static void MakeTrainBackup(TrainList &list, Train *t)
00808 {
00809   for (; t != NULL; t = t->Next()) *list.Append() = t;
00810 }
00811 
00816 static void RestoreTrainBackup(TrainList &list)
00817 {
00818   /* No train, nothing to do. */
00819   if (list.Length() == 0) return;
00820 
00821   Train *prev = NULL;
00822   /* Iterate over the list and rebuild it. */
00823   for (Train **iter = list.Begin(); iter != list.End(); iter++) {
00824     Train *t = *iter;
00825     if (prev != NULL) {
00826       prev->SetNext(t);
00827     } else if (t->Previous() != NULL) {
00828       /* Make sure the head of the train is always the first in the chain. */
00829       t->Previous()->SetNext(NULL);
00830     }
00831     prev = t;
00832   }
00833 }
00834 
00840 static void RemoveFromConsist(Train *part, bool chain = false)
00841 {
00842   Train *tail = chain ? part->Last() : part->GetLastEnginePart();
00843 
00844   /* Unlink at the front, but make it point to the next
00845    * vehicle after the to be remove part. */
00846   if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
00847 
00848   /* Unlink at the back */
00849   tail->SetNext(NULL);
00850 }
00851 
00857 static void InsertInConsist(Train *dst, Train *chain)
00858 {
00859   /* We do not want to add something in the middle of an articulated part. */
00860   assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
00861 
00862   chain->Last()->SetNext(dst->Next());
00863   dst->SetNext(chain);
00864 }
00865 
00871 static void NormaliseDualHeads(Train *t)
00872 {
00873   for (; t != NULL; t = t->GetNextVehicle()) {
00874     if (!t->IsMultiheaded() || !t->IsEngine()) continue;
00875 
00876     /* Make sure that there are no free cars before next engine */
00877     Train *u;
00878     for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
00879 
00880     if (u == t->other_multiheaded_part) continue;
00881 
00882     /* Remove the part from the 'wrong' train */
00883     RemoveFromConsist(t->other_multiheaded_part);
00884     /* And add it to the 'right' train */
00885     InsertInConsist(u, t->other_multiheaded_part);
00886   }
00887 }
00888 
00893 static void NormaliseSubtypes(Train *chain)
00894 {
00895   /* Nothing to do */
00896   if (chain == NULL) return;
00897 
00898   /* We must be the first in the chain. */
00899   assert(chain->Previous() == NULL);
00900 
00901   /* Set the appropriate bits for the first in the chain. */
00902   if (chain->IsWagon()) {
00903     chain->SetFreeWagon();
00904   } else {
00905     assert(chain->IsEngine());
00906     chain->SetFrontEngine();
00907   }
00908 
00909   /* Now clear the bits for the rest of the chain */
00910   for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
00911     t->ClearFreeWagon();
00912     t->ClearFrontEngine();
00913   }
00914 }
00915 
00925 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
00926 {
00927   /* Just add 'new' engines and subtract the original ones.
00928    * If that's less than or equal to 0 we can be sure we did
00929    * not add any engines (read: trains) along the way. */
00930   if ((src          != NULL && src->IsEngine()          ? 1 : 0) +
00931       (dst          != NULL && dst->IsEngine()          ? 1 : 0) -
00932       (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
00933       (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
00934     return CommandCost();
00935   }
00936 
00937   /* Get a free unit number and check whether it's within the bounds.
00938    * There will always be a maximum of one new train. */
00939   if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
00940 
00941   return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00942 }
00943 
00949 static CommandCost CheckTrainAttachment(Train *t)
00950 {
00951   /* No multi-part train, no need to check. */
00952   if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
00953 
00954   /* The maximum length for a train. For each part we decrease this by one
00955    * and if the result is negative the train is simply too long. */
00956   int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
00957 
00958   Train *head = t;
00959   Train *prev = t;
00960 
00961   /* Break the prev -> t link so it always holds within the loop. */
00962   t = t->Next();
00963   prev->SetNext(NULL);
00964 
00965   /* Make sure the cache is cleared. */
00966   head->InvalidateNewGRFCache();
00967 
00968   while (t != NULL) {
00969     allowed_len -= t->gcache.cached_veh_length;
00970 
00971     Train *next = t->Next();
00972 
00973     /* Unlink the to-be-added piece; it is already unlinked from the previous
00974      * part due to the fact that the prev -> t link is broken. */
00975     t->SetNext(NULL);
00976 
00977     /* Don't check callback for articulated or rear dual headed parts */
00978     if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
00979       /* Back up and clear the first_engine data to avoid using wagon override group */
00980       EngineID first_engine = t->gcache.first_engine;
00981       t->gcache.first_engine = INVALID_ENGINE;
00982 
00983       /* We don't want the cache to interfere. head's cache is cleared before
00984        * the loop and after each callback does not need to be cleared here. */
00985       t->InvalidateNewGRFCache();
00986 
00987       uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
00988 
00989       /* Restore original first_engine data */
00990       t->gcache.first_engine = first_engine;
00991 
00992       /* We do not want to remember any cached variables from the test run */
00993       t->InvalidateNewGRFCache();
00994       head->InvalidateNewGRFCache();
00995 
00996       if (callback != CALLBACK_FAILED) {
00997         /* A failing callback means everything is okay */
00998         StringID error = STR_NULL;
00999 
01000         if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01001         if (callback  < 0xFD) error = GetGRFStringID(GetEngineGRFID(head->engine_type), 0xD000 + callback);
01002 
01003         if (error != STR_NULL) return_cmd_error(error);
01004       }
01005     }
01006 
01007     /* And link it to the new part. */
01008     prev->SetNext(t);
01009     prev = t;
01010     t = next;
01011   }
01012 
01013   if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
01014   return CommandCost();
01015 }
01016 
01027 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
01028 {
01029   /* Check whether we may actually construct the trains. */
01030   CommandCost ret = CheckTrainAttachment(src);
01031   if (ret.Failed()) return ret;
01032   ret = CheckTrainAttachment(dst);
01033   if (ret.Failed()) return ret;
01034 
01035   /* Check whether we need to build a new train. */
01036   return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
01037 }
01038 
01047 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
01048 {
01049   /* First determine the front of the two resulting trains */
01050   if (*src_head == *dst_head) {
01051     /* If we aren't moving part(s) to a new train, we are just moving the
01052      * front back and there is not destination head. */
01053     *dst_head = NULL;
01054   } else if (*dst_head == NULL) {
01055     /* If we are moving to a new train the head of the move train would become
01056      * the head of the new vehicle. */
01057     *dst_head = src;
01058   }
01059 
01060   if (src == *src_head) {
01061     /* If we are moving the front of a train then we are, in effect, creating
01062      * a new head for the train. Point to that. Unless we are moving the whole
01063      * train in which case there is not 'source' train anymore.
01064      * In case we are a multiheaded part we want the complete thing to come
01065      * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
01066      * that is followed by a rear multihead we do not want to include that. */
01067     *src_head = move_chain ? NULL :
01068         (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
01069   }
01070 
01071   /* Now it's just simply removing the part that we are going to move from the
01072    * source train and *if* the destination is a not a new train add the chain
01073    * at the destination location. */
01074   RemoveFromConsist(src, move_chain);
01075   if (*dst_head != src) InsertInConsist(dst, src);
01076 
01077   /* Now normalise the dual heads, that is move the dual heads around in such
01078    * a way that the head and rear of a dual head are in the same train */
01079   NormaliseDualHeads(*src_head);
01080   NormaliseDualHeads(*dst_head);
01081 }
01082 
01088 static void NormaliseTrainHead(Train *head)
01089 {
01090   /* Not much to do! */
01091   if (head == NULL) return;
01092 
01093   /* Tell the 'world' the train changed. */
01094   head->ConsistChanged(false);
01095   UpdateTrainGroupID(head);
01096 
01097   /* Not a front engine, i.e. a free wagon chain. No need to do more. */
01098   if (!head->IsFrontEngine()) return;
01099 
01100   PrefillRouteLinks(head);
01101 
01102   /* Update the refit button and window */
01103   InvalidateWindowData(WC_VEHICLE_REFIT, head->index);
01104   SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, VVW_WIDGET_REFIT_VEH);
01105 
01106   /* If we don't have a unit number yet, set one. */
01107   if (head->unitnumber != 0) return;
01108   head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
01109 }
01110 
01123 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01124 {
01125   VehicleID s = GB(p1, 0, 20);
01126   VehicleID d = GB(p2, 0, 20);
01127   bool move_chain = HasBit(p1, 20);
01128 
01129   Train *src = Train::GetIfValid(s);
01130   if (src == NULL) return CMD_ERROR;
01131 
01132   CommandCost ret = CheckOwnership(src->owner);
01133   if (ret.Failed()) return ret;
01134 
01135   /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
01136   if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
01137 
01138   /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
01139   Train *dst;
01140   if (d == INVALID_VEHICLE) {
01141     dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
01142   } else {
01143     dst = Train::GetIfValid(d);
01144     if (dst == NULL) return CMD_ERROR;
01145 
01146     CommandCost ret = CheckOwnership(dst->owner);
01147     if (ret.Failed()) return ret;
01148 
01149     /* Do not allow appending to crashed vehicles, too */
01150     if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
01151   }
01152 
01153   /* if an articulated part is being handled, deal with its parent vehicle */
01154   src = src->GetFirstEnginePart();
01155   if (dst != NULL) {
01156     dst = dst->GetFirstEnginePart();
01157   }
01158 
01159   /* don't move the same vehicle.. */
01160   if (src == dst) return CommandCost();
01161 
01162   /* locate the head of the two chains */
01163   Train *src_head = src->First();
01164   Train *dst_head;
01165   if (dst != NULL) {
01166     dst_head = dst->First();
01167     if (dst_head->tile != src_head->tile) return CMD_ERROR;
01168     /* Now deal with articulated part of destination wagon */
01169     dst = dst->GetLastEnginePart();
01170   } else {
01171     dst_head = NULL;
01172   }
01173 
01174   if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01175 
01176   /* When moving all wagons, we can't have the same src_head and dst_head */
01177   if (move_chain && src_head == dst_head) return CommandCost();
01178 
01179   /* When moving a multiheaded part to be place after itself, bail out. */
01180   if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
01181 
01182   /* Check if all vehicles in the source train are stopped inside a depot. */
01183   if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01184 
01185   /* Check if all vehicles in the destination train are stopped inside a depot. */
01186   if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01187 
01188   /* First make a backup of the order of the trains. That way we can do
01189    * whatever we want with the order and later on easily revert. */
01190   TrainList original_src;
01191   TrainList original_dst;
01192 
01193   MakeTrainBackup(original_src, src_head);
01194   MakeTrainBackup(original_dst, dst_head);
01195 
01196   /* Also make backup of the original heads as ArrangeTrains can change them.
01197    * For the destination head we do not care if it is the same as the source
01198    * head because in that case it's just a copy. */
01199   Train *original_src_head = src_head;
01200   Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
01201 
01202   /* (Re)arrange the trains in the wanted arrangement. */
01203   ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
01204 
01205   if ((flags & DC_AUTOREPLACE) == 0) {
01206     /* If the autoreplace flag is set we do not need to test for the validity
01207      * because we are going to revert the train to its original state. As we
01208      * assume the original state was correct autoreplace can skip this. */
01209     CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
01210     if (ret.Failed()) {
01211       /* Restore the train we had. */
01212       RestoreTrainBackup(original_src);
01213       RestoreTrainBackup(original_dst);
01214       return ret;
01215     }
01216   }
01217 
01218   /* do it? */
01219   if (flags & DC_EXEC) {
01220     /* First normalise the sub types of the chains. */
01221     NormaliseSubtypes(src_head);
01222     NormaliseSubtypes(dst_head);
01223 
01224     /* There are 14 different cases:
01225      *  1) front engine gets moved to a new train, it stays a front engine.
01226      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01227      *     b) the 'next' part is an engine that becomes a front engine.
01228      *     c) there is no 'next' part, nothing else happens
01229      *  2) front engine gets moved to another train, it is not a front engine anymore
01230      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01231      *     b) the 'next' part is an engine that becomes a front engine.
01232      *     c) there is no 'next' part, nothing else happens
01233      *  3) front engine gets moved to later in the current train, it is not a front engine anymore.
01234      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01235      *     b) the 'next' part is an engine that becomes a front engine.
01236      *  4) free wagon gets moved
01237      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01238      *     b) the 'next' part is an engine that becomes a front engine.
01239      *     c) there is no 'next' part, nothing else happens
01240      *  5) non front engine gets moved and becomes a new train, nothing else happens
01241      *  6) non front engine gets moved within a train / to another train, nothing hapens
01242      *  7) wagon gets moved, nothing happens
01243      */
01244     if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
01245       /* Cases #2 and #3: the front engine gets trashed. */
01246       DeleteWindowById(WC_VEHICLE_VIEW, src->index);
01247       DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
01248       DeleteWindowById(WC_VEHICLE_REFIT, src->index);
01249       DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
01250       DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
01251 
01252       /* We are going to be moved to a different train, and
01253        * we were the front engine of the original train. */
01254       if (dst_head != NULL && dst_head != src && (src_head == NULL || !src_head->IsFrontEngine())) {
01255         DecreaseGroupNumVehicle(src->group_id);
01256       }
01257 
01258       /* The front engine is going to be moved later in the
01259        * current train, and it will not be a train anymore. */
01260       if (dst_head == NULL && !src_head->IsFrontEngine()) {
01261         DecreaseGroupNumVehicle(src->group_id);
01262       }
01263 
01264       /* Delete orders, group stuff and the unit number as we're not the
01265        * front of any vehicle anymore. */
01266       DeleteVehicleOrders(src);
01267       RemoveVehicleFromGroup(src);
01268       src->unitnumber = 0;
01269     }
01270 
01271     /* We were a front engine and we are becoming one for a different train.
01272      * Increase the group counter accordingly. */
01273     if (original_src_head == src && dst_head == src) {
01274       IncreaseGroupNumVehicle(src->group_id);
01275     }
01276 
01277     /* We weren't a front engine but are becoming one. So
01278      * we should be put in the default group. */
01279     if (original_src_head != src && dst_head == src) {
01280       SetTrainGroupID(src, DEFAULT_GROUP);
01281     }
01282 
01283     /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
01284     NormaliseTrainHead(src_head);
01285     NormaliseTrainHead(dst_head);
01286 
01287     /* Pre-fill route links after adding a vehicle. */
01288     if (dst_head != NULL && dst_head->IsFrontEngine()) PrefillRouteLinks(dst_head);
01289 
01290     /* We are undoubtedly changing something in the depot and train list. */
01291     InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01292     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01293   } else {
01294     /* We don't want to execute what we're just tried. */
01295     RestoreTrainBackup(original_src);
01296     RestoreTrainBackup(original_dst);
01297   }
01298 
01299   return CommandCost();
01300 }
01301 
01313 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
01314 {
01315   /* Check if we deleted a vehicle window */
01316   Window *w = NULL;
01317 
01318   /* Sell a chain of vehicles or not? */
01319   bool sell_chain = HasBit(data, 0);
01320 
01321   Train *v = Train::From(t)->GetFirstEnginePart();
01322   Train *first = v->First();
01323 
01324   if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01325 
01326   /* First make a backup of the order of the train. That way we can do
01327    * whatever we want with the order and later on easily revert. */
01328   TrainList original;
01329   MakeTrainBackup(original, first);
01330 
01331   /* We need to keep track of the new head and the head of what we're going to sell. */
01332   Train *new_head = first;
01333   Train *sell_head = NULL;
01334 
01335   /* Split the train in the wanted way. */
01336   ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
01337 
01338   /* We don't need to validate the second train; it's going to be sold. */
01339   CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
01340   if (ret.Failed()) {
01341     /* Restore the train we had. */
01342     RestoreTrainBackup(original);
01343     return ret;
01344   }
01345 
01346   CommandCost cost(EXPENSES_NEW_VEHICLES);
01347   for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
01348 
01349   if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
01350     return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01351   }
01352 
01353   /* do it? */
01354   if (flags & DC_EXEC) {
01355     /* First normalise the sub types of the chain. */
01356     NormaliseSubtypes(new_head);
01357 
01358     if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
01359       /* We are selling the front engine. In this case we want to
01360        * 'give' the order, unit number and such to the new head. */
01361       new_head->orders.list = first->orders.list;
01362       new_head->AddToShared(first);
01363       DeleteVehicleOrders(first);
01364 
01365       /* Copy other important data from the front engine */
01366       new_head->CopyVehicleConfigAndStatistics(first);
01367       IncreaseGroupNumVehicle(new_head->group_id);
01368 
01369       /* If we deleted a window then open a new one for the 'new' train */
01370       if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_head);
01371     } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
01372       OrderBackup::Backup(v, user);
01373     }
01374 
01375     /* We need to update the information about the train. */
01376     NormaliseTrainHead(new_head);
01377 
01378     /* We are undoubtedly changing something in the depot and train list. */
01379     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01380     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01381 
01382     /* Actually delete the sold 'goods' */
01383     delete sell_head;
01384   } else {
01385     /* We don't want to execute what we're just tried. */
01386     RestoreTrainBackup(original);
01387   }
01388 
01389   return cost;
01390 }
01391 
01392 void Train::UpdateDeltaXY(Direction direction)
01393 {
01394 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
01395   static const uint32 _delta_xy_table[8] = {
01396     MKIT(3, 3, -1, -1),
01397     MKIT(3, 7, -1, -3),
01398     MKIT(3, 3, -1, -1),
01399     MKIT(7, 3, -3, -1),
01400     MKIT(3, 3, -1, -1),
01401     MKIT(3, 7, -1, -3),
01402     MKIT(3, 3, -1, -1),
01403     MKIT(7, 3, -3, -1),
01404   };
01405 #undef MKIT
01406 
01407   uint32 x = _delta_xy_table[direction];
01408   this->x_offs        = GB(x,  0, 8);
01409   this->y_offs        = GB(x,  8, 8);
01410   this->x_extent      = GB(x, 16, 8);
01411   this->y_extent      = GB(x, 24, 8);
01412   this->z_extent      = 6;
01413 }
01414 
01416 static void MarkTrainAsStuck(Train *v)
01417 {
01418   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
01419     /* It is the first time the problem occurred, set the "train stuck" flag. */
01420     SetBit(v->flags, VRF_TRAIN_STUCK);
01421 
01422     v->wait_counter = 0;
01423 
01424     /* Stop train */
01425     v->cur_speed = 0;
01426     v->subspeed = 0;
01427     v->SetLastSpeed();
01428 
01429     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
01430   }
01431 }
01432 
01433 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
01434 {
01435   uint16 flag1 = *swap_flag1;
01436   uint16 flag2 = *swap_flag2;
01437 
01438   /* Clear the flags */
01439   ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
01440   ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01441   ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
01442   ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01443 
01444   /* Reverse the rail-flags (if needed) */
01445   if (HasBit(flag1, GVF_GOINGUP_BIT)) {
01446     SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01447   } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
01448     SetBit(*swap_flag2, GVF_GOINGUP_BIT);
01449   }
01450   if (HasBit(flag2, GVF_GOINGUP_BIT)) {
01451     SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01452   } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
01453     SetBit(*swap_flag1, GVF_GOINGUP_BIT);
01454   }
01455 }
01456 
01461 static void UpdateStatusAfterSwap(Train *v)
01462 {
01463   /* Reverse the direction. */
01464   if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
01465 
01466   /* Call the proper EnterTile function unless we are in a wormhole. */
01467   if (v->track != TRACK_BIT_WORMHOLE) {
01468     VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
01469   } else {
01470     /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
01471      * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
01472      * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
01473      * when we shouldn't have. Check if this is the case. */
01474     TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
01475     if (IsTileType(vt, MP_TUNNELBRIDGE)) {
01476       VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
01477       if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
01478         /* We have just left the wormhole, possibly set the
01479          * "goingdown" bit. UpdateInclination() can be used
01480          * because we are at the border of the tile. */
01481         v->UpdateInclination(true, true);
01482         return;
01483       }
01484     }
01485   }
01486 
01487   v->UpdateViewport(true, true);
01488 }
01489 
01490 static void ReverseTrainSwapVeh(Train *v, int l, int r)
01491 {
01492   Train *a, *b;
01493 
01494   /* locate vehicles to swap */
01495   for (a = v; l != 0; l--) a = a->Next();
01496   for (b = v; r != 0; r--) b = b->Next();
01497 
01498   if (a != b) {
01499     /* swap the hidden bits */
01500     {
01501       uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
01502       b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
01503       a->vehstatus = tmp;
01504     }
01505 
01506     Swap(a->track, b->track);
01507     Swap(a->direction, b->direction);
01508     Swap(a->x_pos, b->x_pos);
01509     Swap(a->y_pos, b->y_pos);
01510     Swap(a->tile,  b->tile);
01511     Swap(a->z_pos, b->z_pos);
01512 
01513     SwapTrainFlags(&a->gv_flags, &b->gv_flags);
01514 
01515     UpdateStatusAfterSwap(a);
01516     UpdateStatusAfterSwap(b);
01517   } else {
01518     /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
01519      * This is a little bit redundant way, a->gv_flags will
01520      * be (re)set twice, but it reduces code duplication */
01521     SwapTrainFlags(&a->gv_flags, &a->gv_flags);
01522     UpdateStatusAfterSwap(a);
01523   }
01524 
01525   /* Update power of the train in case tiles were different rail type. */
01526   v->RailtypeChanged();
01527 }
01528 
01529 
01535 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
01536 {
01537   return (v->type == VEH_TRAIN) ? v : NULL;
01538 }
01539 
01540 
01547 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
01548 {
01549   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
01550 
01551   Train *t = Train::From(v);
01552   if (!t->IsFrontEngine()) return NULL;
01553 
01554   TileIndex tile = *(TileIndex *)data;
01555 
01556   if (TrainApproachingCrossingTile(t) != tile) return NULL;
01557 
01558   return t;
01559 }
01560 
01561 
01568 static bool TrainApproachingCrossing(TileIndex tile)
01569 {
01570   assert(IsLevelCrossingTile(tile));
01571 
01572   DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
01573   TileIndex tile_from = tile + TileOffsByDiagDir(dir);
01574 
01575   if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
01576 
01577   dir = ReverseDiagDir(dir);
01578   tile_from = tile + TileOffsByDiagDir(dir);
01579 
01580   return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
01581 }
01582 
01583 
01590 void UpdateLevelCrossing(TileIndex tile, bool sound)
01591 {
01592   assert(IsLevelCrossingTile(tile));
01593 
01594   /* train on crossing || train approaching crossing || reserved */
01595   bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
01596 
01597   if (new_state != IsCrossingBarred(tile)) {
01598     if (new_state && sound) {
01599       SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01600     }
01601     SetCrossingBarred(tile, new_state);
01602     MarkTileDirtyByTile(tile);
01603   }
01604 }
01605 
01606 
01612 static inline void MaybeBarCrossingWithSound(TileIndex tile)
01613 {
01614   if (!IsCrossingBarred(tile)) {
01615     BarCrossing(tile);
01616     SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01617     MarkTileDirtyByTile(tile);
01618   }
01619 }
01620 
01621 
01627 static void AdvanceWagonsBeforeSwap(Train *v)
01628 {
01629   Train *base = v;
01630   Train *first = base; // first vehicle to move
01631   Train *last = v->Last(); // last vehicle to move
01632   uint length = CountVehiclesInChain(v);
01633 
01634   while (length > 2) {
01635     last = last->Previous();
01636     first = first->Next();
01637 
01638     int differential = base->gcache.cached_veh_length - last->gcache.cached_veh_length;
01639 
01640     /* do not update images now
01641      * negative differential will be handled in AdvanceWagonsAfterSwap() */
01642     for (int i = 0; i < differential; i++) TrainController(first, last->Next());
01643 
01644     base = first; // == base->Next()
01645     length -= 2;
01646   }
01647 }
01648 
01649 
01655 static void AdvanceWagonsAfterSwap(Train *v)
01656 {
01657   /* first of all, fix the situation when the train was entering a depot */
01658   Train *dep = v; // last vehicle in front of just left depot
01659   while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
01660     dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
01661   }
01662 
01663   Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
01664 
01665   if (leave != NULL) {
01666     /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
01667     int d = TicksToLeaveDepot(dep);
01668 
01669     if (d <= 0) {
01670       leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
01671       leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
01672       for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
01673     }
01674   } else {
01675     dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
01676   }
01677 
01678   Train *base = v;
01679   Train *first = base; // first vehicle to move
01680   Train *last = v->Last(); // last vehicle to move
01681   uint length = CountVehiclesInChain(v);
01682 
01683   /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
01684    * they have already correct spacing, so we have to make sure they are moved how they should */
01685   bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
01686 
01687   while (length > 2) {
01688     /* we reached vehicle (originally) in front of a depot, stop now
01689      * (we would move wagons that are already moved with new wagon length). */
01690     if (base == dep) break;
01691 
01692     /* the last wagon was that one leaving a depot, so do not move it anymore */
01693     if (last == dep) nomove = true;
01694 
01695     last = last->Previous();
01696     first = first->Next();
01697 
01698     int differential = last->gcache.cached_veh_length - base->gcache.cached_veh_length;
01699 
01700     /* do not update images now */
01701     for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
01702 
01703     base = first; // == base->Next()
01704     length -= 2;
01705   }
01706 }
01707 
01708 
01709 static void ReverseTrainDirection(Train *v)
01710 {
01711   if (IsRailDepotTile(v->tile)) {
01712     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01713   }
01714 
01715   /* Clear path reservation in front if train is not stuck. */
01716   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
01717 
01718   /* Check if we were approaching a rail/road-crossing */
01719   TileIndex crossing = TrainApproachingCrossingTile(v);
01720 
01721   /* count number of vehicles */
01722   int r = CountVehiclesInChain(v) - 1;  // number of vehicles - 1
01723 
01724   AdvanceWagonsBeforeSwap(v);
01725 
01726   /* swap start<>end, start+1<>end-1, ... */
01727   int l = 0;
01728   do {
01729     ReverseTrainSwapVeh(v, l++, r--);
01730   } while (l <= r);
01731 
01732   AdvanceWagonsAfterSwap(v);
01733 
01734   if (IsRailDepotTile(v->tile)) {
01735     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01736   }
01737 
01738   ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
01739 
01740   ClrBit(v->flags, VRF_REVERSING);
01741 
01742   /* recalculate cached data */
01743   v->ConsistChanged(true);
01744 
01745   /* update all images */
01746   for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
01747 
01748   /* update crossing we were approaching */
01749   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
01750 
01751   /* maybe we are approaching crossing now, after reversal */
01752   crossing = TrainApproachingCrossingTile(v);
01753   if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
01754 
01755   /* If we are inside a depot after reversing, don't bother with path reserving. */
01756   if (v->track == TRACK_BIT_DEPOT) {
01757     /* Can't be stuck here as inside a depot is always a safe tile. */
01758     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
01759     ClrBit(v->flags, VRF_TRAIN_STUCK);
01760     return;
01761   }
01762 
01763   /* TrainExitDir does not always produce the desired dir for depots and
01764    * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
01765   DiagDirection dir = TrainExitDir(v->direction, v->track);
01766   if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
01767 
01768   if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
01769     /* If we are currently on a tile with conventional signals, we can't treat the
01770      * current tile as a safe tile or we would enter a PBS block without a reservation. */
01771     bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
01772       HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
01773       !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
01774 
01775     if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01776     if (TryPathReserve(v, false, first_tile_okay)) {
01777       /* Do a look-ahead now in case our current tile was already a safe tile. */
01778       CheckNextTrainTile(v);
01779     } else if (v->current_order.GetType() != OT_LOADING) {
01780       /* Do not wait for a way out when we're still loading */
01781       MarkTrainAsStuck(v);
01782     }
01783   } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
01784     /* A train not inside a PBS block can't be stuck. */
01785     ClrBit(v->flags, VRF_TRAIN_STUCK);
01786     v->wait_counter = 0;
01787   }
01788 }
01789 
01799 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01800 {
01801   Train *v = Train::GetIfValid(p1);
01802   if (v == NULL) return CMD_ERROR;
01803 
01804   CommandCost ret = CheckOwnership(v->owner);
01805   if (ret.Failed()) return ret;
01806 
01807   if (p2 != 0) {
01808     /* turn a single unit around */
01809 
01810     if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
01811       return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
01812     }
01813     if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
01814 
01815     Train *front = v->First();
01816     /* make sure the vehicle is stopped in the depot */
01817     if (!front->IsStoppedInDepot()) {
01818       return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01819     }
01820 
01821     if (flags & DC_EXEC) {
01822       ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
01823 
01824       front->ConsistChanged(false);
01825       SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
01826       SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
01827       SetWindowDirty(WC_VEHICLE_VIEW, front->index);
01828       SetWindowClassesDirty(WC_TRAINS_LIST);
01829     }
01830   } else {
01831     /* turn the whole train around */
01832     if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
01833 
01834     if (flags & DC_EXEC) {
01835       /* Properly leave the station if we are loading and won't be loading anymore */
01836       if (v->current_order.IsType(OT_LOADING)) {
01837         const Vehicle *last = v;
01838         while (last->Next() != NULL) last = last->Next();
01839 
01840         /* not a station || different station --> leave the station */
01841         if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
01842           v->LeaveStation();
01843         }
01844       }
01845 
01846       /* We cancel any 'skip signal at dangers' here */
01847       v->force_proceed = TFP_NONE;
01848       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01849 
01850       if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
01851         ToggleBit(v->flags, VRF_REVERSING);
01852       } else {
01853         v->cur_speed = 0;
01854         v->SetLastSpeed();
01855         HideFillingPercent(&v->fill_percent_te_id);
01856         ReverseTrainDirection(v);
01857       }
01858     }
01859   }
01860   return CommandCost();
01861 }
01862 
01872 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01873 {
01874   Train *t = Train::GetIfValid(p1);
01875   if (t == NULL) return CMD_ERROR;
01876 
01877   CommandCost ret = CheckOwnership(t->owner);
01878   if (ret.Failed()) return ret;
01879 
01880 
01881   if (flags & DC_EXEC) {
01882     /* If we are forced to proceed, cancel that order.
01883      * If we are marked stuck we would want to force the train
01884      * to proceed to the next signal. In the other cases we
01885      * would like to pass the signal at danger and run till the
01886      * next signal we encounter. */
01887     t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsInDepot() ? TFP_STUCK : TFP_SIGNAL;
01888     SetWindowDirty(WC_VEHICLE_VIEW, t->index);
01889   }
01890 
01891   return CommandCost();
01892 }
01893 
01898 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
01899 {
01900   assert(!(v->vehstatus & VS_CRASHED));
01901 
01902   if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
01903 
01904   PBSTileInfo origin = FollowTrainReservation(v);
01905   if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
01906 
01907   switch (_settings_game.pf.pathfinder_for_trains) {
01908     case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
01909     case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
01910 
01911     default: NOT_REACHED();
01912   }
01913 }
01914 
01915 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
01916 {
01917   FindDepotData tfdd = FindClosestTrainDepot(this, 0);
01918   if (tfdd.best_length == UINT_MAX) return false;
01919 
01920   if (location    != NULL) *location    = tfdd.tile;
01921   if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
01922   if (reverse     != NULL) *reverse     = tfdd.reverse;
01923 
01924   return true;
01925 }
01926 
01927 void Train::PlayLeaveStationSound() const
01928 {
01929   static const SoundFx sfx[] = {
01930     SND_04_TRAIN,
01931     SND_0A_TRAIN_HORN,
01932     SND_0A_TRAIN_HORN,
01933     SND_47_MAGLEV_2,
01934     SND_41_MAGLEV
01935   };
01936 
01937   if (PlayVehicleSound(this, VSE_START)) return;
01938 
01939   EngineID engtype = this->engine_type;
01940   SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
01941 }
01942 
01944 static void CheckNextTrainTile(Train *v)
01945 {
01946   /* Don't do any look-ahead if path_backoff_interval is 255. */
01947   if (_settings_game.pf.path_backoff_interval == 255) return;
01948 
01949   /* Exit if we are inside a depot. */
01950   if (v->track == TRACK_BIT_DEPOT) return;
01951 
01952   switch (v->current_order.GetType()) {
01953     /* Exit if we reached our destination depot. */
01954     case OT_GOTO_DEPOT:
01955       if (v->tile == v->dest_tile) return;
01956       break;
01957 
01958     case OT_GOTO_WAYPOINT:
01959       /* If we reached our waypoint, make sure we see that. */
01960       if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
01961       break;
01962 
01963     case OT_NOTHING:
01964     case OT_LEAVESTATION:
01965     case OT_LOADING:
01966       /* Exit if the current order doesn't have a destination, but the train has orders. */
01967       if (v->GetNumOrders() > 0) return;
01968       break;
01969 
01970     default:
01971       break;
01972   }
01973   /* Exit if we are on a station tile and are going to stop. */
01974   if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
01975 
01976   Trackdir td = v->GetVehicleTrackdir();
01977 
01978   /* On a tile with a red non-pbs signal, don't look ahead. */
01979   if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
01980       !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
01981       GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
01982 
01983   CFollowTrackRail ft(v);
01984   if (!ft.Follow(v->tile, td)) return;
01985 
01986   if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
01987     /* Next tile is not reserved. */
01988     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
01989       if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
01990         /* If the next tile is a PBS signal, try to make a reservation. */
01991         TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
01992         if (_settings_game.pf.forbid_90_deg) {
01993           tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
01994         }
01995         ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
01996       }
01997     }
01998   }
01999 }
02000 
02001 static bool CheckTrainStayInDepot(Train *v)
02002 {
02003   /* bail out if not all wagons are in the same depot or not in a depot at all */
02004   for (const Train *u = v; u != NULL; u = u->Next()) {
02005     if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
02006   }
02007 
02008   /* if the train got no power, then keep it in the depot */
02009   if (v->gcache.cached_power == 0) {
02010     v->vehstatus |= VS_STOPPED;
02011     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
02012     return true;
02013   }
02014 
02015   SigSegState seg_state;
02016 
02017   if (v->force_proceed == TFP_NONE) {
02018     /* force proceed was not pressed */
02019     if (++v->wait_counter < 37) {
02020       SetWindowClassesDirty(WC_TRAINS_LIST);
02021       return true;
02022     }
02023 
02024     v->wait_counter = 0;
02025 
02026     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02027     if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
02028       /* Full and no PBS signal in block or depot reserved, can't exit. */
02029       SetWindowClassesDirty(WC_TRAINS_LIST);
02030       return true;
02031     }
02032   } else {
02033     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02034   }
02035 
02036   /* We are leaving a depot, but have to go to the exact same one; re-enter */
02037   if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
02038     /* We need to have a reservation for this to work. */
02039     if (HasDepotReservation(v->tile)) return true;
02040     SetDepotReservation(v->tile, true);
02041     VehicleEnterDepot(v);
02042     return true;
02043   }
02044 
02045   /* Only leave when we can reserve a path to our destination. */
02046   if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
02047     /* No path and no force proceed. */
02048     SetWindowClassesDirty(WC_TRAINS_LIST);
02049     MarkTrainAsStuck(v);
02050     return true;
02051   }
02052 
02053   SetDepotReservation(v->tile, true);
02054   if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02055 
02056   VehicleServiceInDepot(v);
02057   SetWindowClassesDirty(WC_TRAINS_LIST);
02058   v->PlayLeaveStationSound();
02059 
02060   v->track = TRACK_BIT_X;
02061   if (v->direction & 2) v->track = TRACK_BIT_Y;
02062 
02063   v->vehstatus &= ~VS_HIDDEN;
02064   v->cur_speed = 0;
02065 
02066   v->UpdateDeltaXY(v->direction);
02067   v->cur_image = v->GetImage(v->direction);
02068   VehicleMove(v, false);
02069   UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02070   v->UpdateAcceleration();
02071   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
02072 
02073   return false;
02074 }
02075 
02077 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
02078 {
02079   DiagDirection dir = TrackdirToExitdir(track_dir);
02080 
02081   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
02082     /* Are we just leaving a tunnel/bridge? */
02083     if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
02084       TileIndex end = GetOtherTunnelBridgeEnd(tile);
02085 
02086       if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
02087         /* Free the reservation only if no other train is on the tiles. */
02088         SetTunnelBridgeReservation(tile, false);
02089         SetTunnelBridgeReservation(end, false);
02090 
02091         if (_settings_client.gui.show_track_reservation) {
02092           MarkTileDirtyByTile(tile);
02093           MarkTileDirtyByTile(end);
02094         }
02095       }
02096     }
02097   } else if (IsRailStationTile(tile)) {
02098     TileIndex new_tile = TileAddByDiagDir(tile, dir);
02099     /* If the new tile is not a further tile of the same station, we
02100      * clear the reservation for the whole platform. */
02101     if (!IsCompatibleTrainStationTile(new_tile, tile)) {
02102       SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
02103     }
02104   } else {
02105     /* Any other tile */
02106     UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
02107   }
02108 }
02109 
02111 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
02112 {
02113   assert(v->IsFrontEngine());
02114 
02115   TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
02116   Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
02117   bool      free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
02118   StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
02119 
02120   /* Don't free reservation if it's not ours. */
02121   if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
02122 
02123   CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
02124   while (ft.Follow(tile, td)) {
02125     tile = ft.m_new_tile;
02126     TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
02127     td = RemoveFirstTrackdir(&bits);
02128     assert(bits == TRACKDIR_BIT_NONE);
02129 
02130     if (!IsValidTrackdir(td)) break;
02131 
02132     if (IsTileType(tile, MP_RAILWAY)) {
02133       if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
02134         /* Conventional signal along trackdir: remove reservation and stop. */
02135         UnreserveRailTrack(tile, TrackdirToTrack(td));
02136         break;
02137       }
02138       if (HasPbsSignalOnTrackdir(tile, td)) {
02139         if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
02140           /* Red PBS signal? Can't be our reservation, would be green then. */
02141           break;
02142         } else {
02143           /* Turn the signal back to red. */
02144           SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
02145           MarkTileDirtyByTile(tile);
02146         }
02147       } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
02148         break;
02149       }
02150     }
02151 
02152     /* Don't free first station/bridge/tunnel if we are on it. */
02153     if (free_tile || (!(ft.m_is_station && GetStationIndex(ft.m_new_tile) == station_id) && !ft.m_is_tunnel && !ft.m_is_bridge)) ClearPathReservation(v, tile, td);
02154 
02155     free_tile = true;
02156   }
02157 }
02158 
02159 static const byte _initial_tile_subcoord[6][4][3] = {
02160 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
02161 {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
02162 {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
02163 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
02164 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
02165 {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
02166 };
02167 
02180 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
02181 {
02182   switch (_settings_game.pf.pathfinder_for_trains) {
02183     case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02184     case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02185 
02186     default: NOT_REACHED();
02187   }
02188 }
02189 
02195 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
02196 {
02197   PBSTileInfo origin = FollowTrainReservation(v);
02198 
02199   CFollowTrackRail ft(v);
02200 
02201   TileIndex tile = origin.tile;
02202   Trackdir  cur_td = origin.trackdir;
02203   while (ft.Follow(tile, cur_td)) {
02204     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02205       /* Possible signal tile. */
02206       if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
02207     }
02208 
02209     if (_settings_game.pf.forbid_90_deg) {
02210       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02211       if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
02212     }
02213 
02214     /* Station, depot or waypoint are a possible target. */
02215     bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
02216     if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
02217       /* Choice found or possible target encountered.
02218        * On finding a possible target, we need to stop and let the pathfinder handle the
02219        * remaining path. This is because we don't know if this target is in one of our
02220        * orders, so we might cause pathfinding to fail later on if we find a choice.
02221        * This failure would cause a bogous call to TryReserveSafePath which might reserve
02222        * a wrong path not leading to our next destination. */
02223       if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
02224 
02225       /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
02226        * actually starts its search at the first unreserved tile. */
02227       if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
02228 
02229       /* Choice found, path valid but not okay. Save info about the choice tile as well. */
02230       if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02231       if (enterdir != NULL) *enterdir = ft.m_exitdir;
02232       return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
02233     }
02234 
02235     tile = ft.m_new_tile;
02236     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02237 
02238     if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
02239       bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
02240       if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
02241       /* Safe position is all good, path valid and okay. */
02242       return PBSTileInfo(tile, cur_td, true);
02243     }
02244 
02245     if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
02246   }
02247 
02248   if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
02249     /* End of line, path valid and okay. */
02250     return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
02251   }
02252 
02253   /* Sorry, can't reserve path, back out. */
02254   tile = origin.tile;
02255   cur_td = origin.trackdir;
02256   TileIndex stopped = ft.m_old_tile;
02257   Trackdir  stopped_td = ft.m_old_td;
02258   while (tile != stopped || cur_td != stopped_td) {
02259     if (!ft.Follow(tile, cur_td)) break;
02260 
02261     if (_settings_game.pf.forbid_90_deg) {
02262       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02263       assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
02264     }
02265     assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
02266 
02267     tile = ft.m_new_tile;
02268     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02269 
02270     UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
02271   }
02272 
02273   /* Path invalid. */
02274   return PBSTileInfo();
02275 }
02276 
02287 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
02288 {
02289   switch (_settings_game.pf.pathfinder_for_trains) {
02290     case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02291     case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02292 
02293     default: NOT_REACHED();
02294   }
02295 }
02296 
02298 class VehicleOrderSaver
02299 {
02300 private:
02301   Train          *v;
02302   Order          old_order;
02303   TileIndex      old_dest_tile;
02304   StationID      old_last_station_visited;
02305   VehicleOrderID index;
02306   bool           suppress_implicit_orders;
02307 
02308 public:
02309   VehicleOrderSaver(Train *_v) :
02310     v(_v),
02311     old_order(_v->current_order),
02312     old_dest_tile(_v->dest_tile),
02313     old_last_station_visited(_v->last_station_visited),
02314     index(_v->cur_real_order_index),
02315     suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
02316   {
02317   }
02318 
02319   ~VehicleOrderSaver()
02320   {
02321     this->v->current_order = this->old_order;
02322     this->v->dest_tile = this->old_dest_tile;
02323     this->v->last_station_visited = this->old_last_station_visited;
02324     SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
02325   }
02326 
02332   bool SwitchToNextOrder(bool skip_first)
02333   {
02334     if (this->v->GetNumOrders() == 0) return false;
02335 
02336     if (skip_first) ++this->index;
02337 
02338     int conditional_depth = 0;
02339 
02340     do {
02341       /* Wrap around. */
02342       if (this->index >= this->v->GetNumOrders()) this->index = 0;
02343 
02344       Order *order = this->v->GetOrder(this->index);
02345       assert(order != NULL);
02346 
02347       switch (order->GetType()) {
02348         case OT_GOTO_DEPOT:
02349           /* Skip service in depot orders when the train doesn't need service. */
02350           if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
02351         case OT_GOTO_STATION:
02352         case OT_GOTO_WAYPOINT:
02353           this->v->current_order = *order;
02354           UpdateOrderDest(this->v, order);
02355           return true;
02356         case OT_CONDITIONAL: {
02357           if (conditional_depth > this->v->GetNumOrders()) return false;
02358           VehicleOrderID next = ProcessConditionalOrder(order, this->v);
02359           if (next != INVALID_VEH_ORDER_ID) {
02360             conditional_depth++;
02361             this->index = next;
02362             /* Don't increment next, so no break here. */
02363             continue;
02364           }
02365           break;
02366         }
02367         default:
02368           break;
02369       }
02370       /* Don't increment inside the while because otherwise conditional
02371        * orders can lead to an infinite loop. */
02372       ++this->index;
02373     } while (this->index != this->v->cur_real_order_index);
02374 
02375     return false;
02376   }
02377 };
02378 
02379 /* choose a track */
02380 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
02381 {
02382   Track best_track = INVALID_TRACK;
02383   bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
02384   bool changed_signal = false;
02385 
02386   assert((tracks & ~TRACK_BIT_MASK) == 0);
02387 
02388   if (got_reservation != NULL) *got_reservation = false;
02389 
02390   /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
02391   TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
02392   /* Do we have a suitable reserved track? */
02393   if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
02394 
02395   /* Quick return in case only one possible track is available */
02396   if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
02397     Track track = FindFirstTrack(tracks);
02398     /* We need to check for signals only here, as a junction tile can't have signals. */
02399     if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
02400       do_track_reservation = true;
02401       changed_signal = true;
02402       SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
02403     } else if (!do_track_reservation) {
02404       return track;
02405     }
02406     best_track = track;
02407   }
02408 
02409   PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
02410   DiagDirection dest_enterdir = enterdir;
02411   if (do_track_reservation) {
02412     /* Check if the train needs service here, so it has a chance to always find a depot.
02413      * Also check if the current order is a service order so we don't reserve a path to
02414      * the destination but instead to the next one if service isn't needed. */
02415     CheckIfTrainNeedsService(v);
02416     if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
02417 
02418     res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
02419     if (res_dest.tile == INVALID_TILE) {
02420       /* Reservation failed? */
02421       if (mark_stuck) MarkTrainAsStuck(v);
02422       if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
02423       return FindFirstTrack(tracks);
02424     }
02425   }
02426 
02427   /* Save the current train order. The destructor will restore the old order on function exit. */
02428   VehicleOrderSaver orders(v);
02429 
02430   /* If the current tile is the destination of the current order and
02431    * a reservation was requested, advance to the next order.
02432    * Don't advance on a depot order as depots are always safe end points
02433    * for a path and no look-ahead is necessary. This also avoids a
02434    * problem with depot orders not part of the order list when the
02435    * order list itself is empty. */
02436   if (v->current_order.IsType(OT_LEAVESTATION)) {
02437     orders.SwitchToNextOrder(false);
02438   } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
02439       v->current_order.IsType(OT_GOTO_STATION) ?
02440       IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
02441       v->tile == v->dest_tile))) {
02442     orders.SwitchToNextOrder(true);
02443   }
02444 
02445   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02446     /* Pathfinders are able to tell that route was only 'guessed'. */
02447     bool      path_found = true;
02448     TileIndex new_tile = res_dest.tile;
02449 
02450     Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
02451     if (new_tile == tile) best_track = next_track;
02452     v->HandlePathfindingResult(path_found);
02453   }
02454 
02455   /* No track reservation requested -> finished. */
02456   if (!do_track_reservation) return best_track;
02457 
02458   /* A path was found, but could not be reserved. */
02459   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02460     if (mark_stuck) MarkTrainAsStuck(v);
02461     FreeTrainTrackReservation(v);
02462     return best_track;
02463   }
02464 
02465   /* No possible reservation target found, we are probably lost. */
02466   if (res_dest.tile == INVALID_TILE) {
02467     /* Try to find any safe destination. */
02468     PBSTileInfo origin = FollowTrainReservation(v);
02469     if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
02470       TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
02471       best_track = FindFirstTrack(res);
02472       TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02473       if (got_reservation != NULL) *got_reservation = true;
02474       if (changed_signal) MarkTileDirtyByTile(tile);
02475     } else {
02476       FreeTrainTrackReservation(v);
02477       if (mark_stuck) MarkTrainAsStuck(v);
02478     }
02479     return best_track;
02480   }
02481 
02482   if (got_reservation != NULL) *got_reservation = true;
02483 
02484   /* Reservation target found and free, check if it is safe. */
02485   while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
02486     /* Extend reservation until we have found a safe position. */
02487     DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
02488     TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
02489     TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
02490     if (_settings_game.pf.forbid_90_deg) {
02491       reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
02492     }
02493 
02494     /* Get next order with destination. */
02495     if (orders.SwitchToNextOrder(true)) {
02496       PBSTileInfo cur_dest;
02497       bool path_found;
02498       DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
02499       if (cur_dest.tile != INVALID_TILE) {
02500         res_dest = cur_dest;
02501         if (res_dest.okay) continue;
02502         /* Path found, but could not be reserved. */
02503         FreeTrainTrackReservation(v);
02504         if (mark_stuck) MarkTrainAsStuck(v);
02505         if (got_reservation != NULL) *got_reservation = false;
02506         changed_signal = false;
02507         break;
02508       }
02509     }
02510     /* No order or no safe position found, try any position. */
02511     if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
02512       FreeTrainTrackReservation(v);
02513       if (mark_stuck) MarkTrainAsStuck(v);
02514       if (got_reservation != NULL) *got_reservation = false;
02515       changed_signal = false;
02516     }
02517     break;
02518   }
02519 
02520   TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02521 
02522   if (changed_signal) MarkTileDirtyByTile(tile);
02523 
02524   return best_track;
02525 }
02526 
02535 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
02536 {
02537   assert(v->IsFrontEngine());
02538 
02539   /* We have to handle depots specially as the track follower won't look
02540    * at the depot tile itself but starts from the next tile. If we are still
02541    * inside the depot, a depot reservation can never be ours. */
02542   if (v->track == TRACK_BIT_DEPOT) {
02543     if (HasDepotReservation(v->tile)) {
02544       if (mark_as_stuck) MarkTrainAsStuck(v);
02545       return false;
02546     } else {
02547       /* Depot not reserved, but the next tile might be. */
02548       TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
02549       if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
02550     }
02551   }
02552 
02553   Vehicle *other_train = NULL;
02554   PBSTileInfo origin = FollowTrainReservation(v, &other_train);
02555   /* The path we are driving on is already blocked by some other train.
02556    * This can only happen in certain situations when mixing path and
02557    * block signals or when changing tracks and/or signals.
02558    * Exit here as doing any further reservations will probably just
02559    * make matters worse. */
02560   if (other_train != NULL && other_train->index != v->index) {
02561     if (mark_as_stuck) MarkTrainAsStuck(v);
02562     return false;
02563   }
02564   /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
02565   if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
02566     /* Can't be stuck then. */
02567     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
02568     ClrBit(v->flags, VRF_TRAIN_STUCK);
02569     return true;
02570   }
02571 
02572   /* If we are in a depot, tentatively reserve the depot. */
02573   if (v->track == TRACK_BIT_DEPOT) {
02574     SetDepotReservation(v->tile, true);
02575     if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02576   }
02577 
02578   DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
02579   TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
02580   TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
02581 
02582   if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
02583 
02584   bool res_made = false;
02585   ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
02586 
02587   if (!res_made) {
02588     /* Free the depot reservation as well. */
02589     if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
02590     return false;
02591   }
02592 
02593   if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
02594     v->wait_counter = 0;
02595     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
02596   }
02597   ClrBit(v->flags, VRF_TRAIN_STUCK);
02598   return true;
02599 }
02600 
02601 
02602 static bool CheckReverseTrain(const Train *v)
02603 {
02604   if (_settings_game.difficulty.line_reverse_mode != 0 ||
02605       v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
02606       !(v->direction & 1)) {
02607     return false;
02608   }
02609 
02610   assert(v->track != TRACK_BIT_NONE);
02611 
02612   switch (_settings_game.pf.pathfinder_for_trains) {
02613     case VPF_NPF: return NPFTrainCheckReverse(v);
02614     case VPF_YAPF: return YapfTrainCheckReverse(v);
02615 
02616     default: NOT_REACHED();
02617   }
02618 }
02619 
02620 TileIndex Train::GetOrderStationLocation(StationID station)
02621 {
02622   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
02623 
02624   const Station *st = Station::Get(station);
02625   if (!(st->facilities & FACIL_TRAIN)) {
02626     /* The destination station has no trainstation tiles. */
02627     this->IncrementRealOrderIndex();
02628     return 0;
02629   }
02630 
02631   return st->xy;
02632 }
02633 
02634 void Train::MarkDirty()
02635 {
02636   Train *v = this;
02637   do {
02638     v->UpdateViewport(false, false);
02639   } while ((v = v->Next()) != NULL);
02640 
02641   /* need to update acceleration and cached values since the goods on the train changed. */
02642   this->CargoChanged();
02643   this->UpdateAcceleration();
02644 }
02645 
02653 int Train::UpdateSpeed()
02654 {
02655   switch (_settings_game.vehicle.train_acceleration_model) {
02656     default: NOT_REACHED();
02657     case AM_ORIGINAL:
02658       return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->gcache.cached_max_track_speed);
02659 
02660     case AM_REALISTIC:
02661       return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
02662   }
02663 }
02664 
02670 static void TrainEnterStation(Train *v, StationID station)
02671 {
02672   /* check if a train ever visited this station before */
02673   Station *st = Station::Get(station);
02674   if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
02675     st->had_vehicle_of_type |= HVOT_TRAIN;
02676     SetDParam(0, st->index);
02677     AddVehicleNewsItem(
02678       STR_NEWS_FIRST_TRAIN_ARRIVAL,
02679       v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
02680       v->index,
02681       st->index
02682     );
02683     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
02684   }
02685 
02686   v->force_proceed = TFP_NONE;
02687   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
02688 
02689   v->BeginLoading(station);
02690 
02691   TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
02692 }
02693 
02694 /* Check if the vehicle is compatible with the specified tile */
02695 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
02696 {
02697   return IsTileOwner(tile, v->owner) &&
02698       (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
02699 }
02700 
02701 struct RailtypeSlowdownParams {
02702   byte small_turn, large_turn;
02703   byte z_up; // fraction to remove when moving up
02704   byte z_down; // fraction to remove when moving down
02705 };
02706 
02707 static const RailtypeSlowdownParams _railtype_slowdown[] = {
02708   /* normal accel */
02709   {256 / 4, 256 / 2, 256 / 4, 2}, 
02710   {256 / 4, 256 / 2, 256 / 4, 2}, 
02711   {256 / 4, 256 / 2, 256 / 4, 2}, 
02712   {0,       256 / 2, 256 / 4, 2}, 
02713 };
02714 
02716 static inline void AffectSpeedByZChange(Train *v, byte old_z)
02717 {
02718   if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
02719 
02720   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
02721 
02722   if (old_z < v->z_pos) {
02723     v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
02724   } else {
02725     uint16 spd = v->cur_speed + rsp->z_down;
02726     if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
02727   }
02728 }
02729 
02730 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
02731 {
02732   if (IsTileType(tile, MP_RAILWAY) &&
02733       GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
02734     TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
02735     Trackdir trackdir = FindFirstTrackdir(tracks);
02736     if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
02737       /* A PBS block with a non-PBS signal facing us? */
02738       if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
02739     }
02740   }
02741   return false;
02742 }
02743 
02747 void Train::ReserveTrackUnderConsist() const
02748 {
02749   for (const Train *u = this; u != NULL; u = u->Next()) {
02750     switch (u->track) {
02751       case TRACK_BIT_WORMHOLE:
02752         TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
02753         break;
02754       case TRACK_BIT_DEPOT:
02755         break;
02756       default:
02757         TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
02758         break;
02759     }
02760   }
02761 }
02762 
02763 uint Train::Crash(bool flooded)
02764 {
02765   uint pass = 0;
02766   if (this->IsFrontEngine()) {
02767     pass += 2; // driver
02768 
02769     /* Remove the reserved path in front of the train if it is not stuck.
02770      * Also clear all reserved tracks the train is currently on. */
02771     if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
02772     for (const Train *v = this; v != NULL; v = v->Next()) {
02773       ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
02774       if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
02775         /* ClearPathReservation will not free the wormhole exit
02776          * if the train has just entered the wormhole. */
02777         SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
02778       }
02779     }
02780 
02781     /* we may need to update crossing we were approaching,
02782      * but must be updated after the train has been marked crashed */
02783     TileIndex crossing = TrainApproachingCrossingTile(this);
02784     if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
02785 
02786     /* Remove the loading indicators (if any) */
02787     HideFillingPercent(&this->fill_percent_te_id);
02788   }
02789 
02790   pass += this->GroundVehicleBase::Crash(flooded);
02791 
02792   this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
02793   return pass;
02794 }
02795 
02802 static uint TrainCrashed(Train *v)
02803 {
02804   uint num = 0;
02805 
02806   /* do not crash train twice */
02807   if (!(v->vehstatus & VS_CRASHED)) {
02808     num = v->Crash();
02809     AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
02810   }
02811 
02812   /* Try to re-reserve track under already crashed train too.
02813    * Crash() clears the reservation! */
02814   v->ReserveTrackUnderConsist();
02815 
02816   return num;
02817 }
02818 
02819 struct TrainCollideChecker {
02820   Train *v; 
02821   uint num; 
02822 };
02823 
02824 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
02825 {
02826   TrainCollideChecker *tcc = (TrainCollideChecker*)data;
02827 
02828   /* not a train or in depot */
02829   if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
02830 
02831   /* do not crash into trains of another company. */
02832   if (v->owner != tcc->v->owner) return NULL;
02833 
02834   /* get first vehicle now to make most usual checks faster */
02835   Train *coll = Train::From(v)->First();
02836 
02837   /* can't collide with own wagons */
02838   if (coll == tcc->v) return NULL;
02839 
02840   int x_diff = v->x_pos - tcc->v->x_pos;
02841   int y_diff = v->y_pos - tcc->v->y_pos;
02842 
02843   /* Do fast calculation to check whether trains are not in close vicinity
02844    * and quickly reject trains distant enough for any collision.
02845    * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
02846    * Differences are then ORed and then we check for any higher bits */
02847   uint hash = (y_diff + 7) | (x_diff + 7);
02848   if (hash & ~15) return NULL;
02849 
02850   /* Slower check using multiplication */
02851   if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
02852 
02853   /* Happens when there is a train under bridge next to bridge head */
02854   if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
02855 
02856   /* crash both trains */
02857   tcc->num += TrainCrashed(tcc->v);
02858   tcc->num += TrainCrashed(coll);
02859 
02860   return NULL; // continue searching
02861 }
02862 
02869 static bool CheckTrainCollision(Train *v)
02870 {
02871   /* can't collide in depot */
02872   if (v->track == TRACK_BIT_DEPOT) return false;
02873 
02874   assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
02875 
02876   TrainCollideChecker tcc;
02877   tcc.v = v;
02878   tcc.num = 0;
02879 
02880   /* find colliding vehicles */
02881   if (v->track == TRACK_BIT_WORMHOLE) {
02882     FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
02883     FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
02884   } else {
02885     FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
02886   }
02887 
02888   /* any dead -> no crash */
02889   if (tcc.num == 0) return false;
02890 
02891   SetDParam(0, tcc.num);
02892   AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH,
02893     NS_ACCIDENT,
02894     v->index
02895   );
02896 
02897   ModifyStationRatingAround(v->tile, v->owner, -160, 30);
02898   SndPlayVehicleFx(SND_13_BIG_CRASH, v);
02899   return true;
02900 }
02901 
02902 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
02903 {
02904   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
02905 
02906   Train *t = Train::From(v);
02907   DiagDirection exitdir = *(DiagDirection *)data;
02908 
02909   /* not front engine of a train, inside wormhole or depot, crashed */
02910   if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
02911 
02912   if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
02913 
02914   return t;
02915 }
02916 
02917 static void TrainController(Train *v, Vehicle *nomove)
02918 {
02919   Train *first = v->First();
02920   Train *prev;
02921   bool direction_changed = false; // has direction of any part changed?
02922 
02923   /* For every vehicle after and including the given vehicle */
02924   for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
02925     DiagDirection enterdir = DIAGDIR_BEGIN;
02926     bool update_signals_crossing = false; // will we update signals or crossing state?
02927 
02928     GetNewVehiclePosResult gp = GetNewVehiclePos(v);
02929     if (v->track != TRACK_BIT_WORMHOLE) {
02930       /* Not inside tunnel */
02931       if (gp.old_tile == gp.new_tile) {
02932         /* Staying in the old tile */
02933         if (v->track == TRACK_BIT_DEPOT) {
02934           /* Inside depot */
02935           gp.x = v->x_pos;
02936           gp.y = v->y_pos;
02937         } else {
02938           /* Not inside depot */
02939 
02940           /* Reverse when we are at the end of the track already, do not move to the new position */
02941           if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v)) return;
02942 
02943           uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
02944           if (HasBit(r, VETS_CANNOT_ENTER)) {
02945             goto invalid_rail;
02946           }
02947           if (HasBit(r, VETS_ENTERED_STATION)) {
02948             /* The new position is the end of the platform */
02949             TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
02950           }
02951         }
02952       } else {
02953         /* A new tile is about to be entered. */
02954 
02955         /* Determine what direction we're entering the new tile from */
02956         enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
02957         assert(IsValidDiagDirection(enterdir));
02958 
02959         /* Get the status of the tracks in the new tile and mask
02960          * away the bits that aren't reachable. */
02961         TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
02962         TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
02963 
02964         TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
02965         TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
02966 
02967         TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
02968         if (_settings_game.pf.forbid_90_deg && prev == NULL) {
02969           /* We allow wagons to make 90 deg turns, because forbid_90_deg
02970            * can be switched on halfway a turn */
02971           bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
02972         }
02973 
02974         if (bits == TRACK_BIT_NONE) goto invalid_rail;
02975 
02976         /* Check if the new tile constrains tracks that are compatible
02977          * with the current train, if not, bail out. */
02978         if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
02979 
02980         TrackBits chosen_track;
02981         if (prev == NULL) {
02982           /* Currently the locomotive is active. Determine which one of the
02983            * available tracks to choose */
02984           chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
02985           assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
02986 
02987           if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
02988             /* For each signal we find decrease the counter by one.
02989              * We start at two, so the first signal we pass decreases
02990              * this to one, then if we reach the next signal it is
02991              * decreased to zero and we won't pass that new signal. */
02992             Trackdir dir = FindFirstTrackdir(trackdirbits);
02993             if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
02994                 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
02995               /* However, we do not want to be stopped by PBS signals
02996                * entered via the back. */
02997               v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
02998               SetWindowDirty(WC_VEHICLE_VIEW, v->index);
02999             }
03000           }
03001 
03002           /* Check if it's a red signal and that force proceed is not clicked. */
03003           if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
03004             /* In front of a red signal */
03005             Trackdir i = FindFirstTrackdir(trackdirbits);
03006 
03007             /* Don't handle stuck trains here. */
03008             if (HasBit(v->flags, VRF_TRAIN_STUCK)) return;
03009 
03010             if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
03011               v->cur_speed = 0;
03012               v->subspeed = 0;
03013               v->progress = 255 - 100;
03014               if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return;
03015             } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
03016               v->cur_speed = 0;
03017               v->subspeed = 0;
03018               v->progress = 255 - 10;
03019               if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
03020                 DiagDirection exitdir = TrackdirToExitdir(i);
03021                 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
03022 
03023                 exitdir = ReverseDiagDir(exitdir);
03024 
03025                 /* check if a train is waiting on the other side */
03026                 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return;
03027               }
03028             }
03029 
03030             /* If we would reverse but are currently in a PBS block and
03031              * reversing of stuck trains is disabled, don't reverse.
03032              * This does not apply if the reason for reversing is a one-way
03033              * signal blocking us, because a train would then be stuck forever. */
03034             if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
03035                 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
03036               v->wait_counter = 0;
03037               return;
03038             }
03039             goto reverse_train_direction;
03040           } else {
03041             TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
03042           }
03043         } else {
03044           /* The wagon is active, simply follow the prev vehicle. */
03045           if (prev->tile == gp.new_tile) {
03046             /* Choose the same track as prev */
03047             if (prev->track == TRACK_BIT_WORMHOLE) {
03048               /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
03049                * However, just choose the track into the wormhole. */
03050               assert(IsTunnel(prev->tile));
03051               chosen_track = bits;
03052             } else {
03053               chosen_track = prev->track;
03054             }
03055           } else {
03056             /* Choose the track that leads to the tile where prev is.
03057              * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
03058              * I.e. when the tile between them has only space for a single vehicle like
03059              *  1) horizontal/vertical track tiles and
03060              *  2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
03061              *     Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
03062              */
03063             static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
03064               {TRACK_BIT_X,     TRACK_BIT_LOWER, TRACK_BIT_NONE,  TRACK_BIT_LEFT },
03065               {TRACK_BIT_UPPER, TRACK_BIT_Y,     TRACK_BIT_LEFT,  TRACK_BIT_NONE },
03066               {TRACK_BIT_NONE,  TRACK_BIT_RIGHT, TRACK_BIT_X,     TRACK_BIT_UPPER},
03067               {TRACK_BIT_RIGHT, TRACK_BIT_NONE,  TRACK_BIT_LOWER, TRACK_BIT_Y    }
03068             };
03069             DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
03070             assert(IsValidDiagDirection(exitdir));
03071             chosen_track = _connecting_track[enterdir][exitdir];
03072           }
03073           chosen_track &= bits;
03074         }
03075 
03076         /* Make sure chosen track is a valid track */
03077         assert(
03078             chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
03079             chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
03080             chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
03081 
03082         /* Update XY to reflect the entrance to the new tile, and select the direction to use */
03083         const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
03084         gp.x = (gp.x & ~0xF) | b[0];
03085         gp.y = (gp.y & ~0xF) | b[1];
03086         Direction chosen_dir = (Direction)b[2];
03087 
03088         /* Call the landscape function and tell it that the vehicle entered the tile */
03089         uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03090         if (HasBit(r, VETS_CANNOT_ENTER)) {
03091           goto invalid_rail;
03092         }
03093 
03094         if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
03095           Track track = FindFirstTrack(chosen_track);
03096           Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
03097           if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
03098             SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
03099             MarkTileDirtyByTile(gp.new_tile);
03100           }
03101 
03102           /* Clear any track reservation when the last vehicle leaves the tile */
03103           if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
03104 
03105           v->tile = gp.new_tile;
03106 
03107           if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
03108             v->First()->RailtypeChanged();
03109           }
03110 
03111           v->track = chosen_track;
03112           assert(v->track);
03113         }
03114 
03115         /* We need to update signal status, but after the vehicle position hash
03116          * has been updated by UpdateInclination() */
03117         update_signals_crossing = true;
03118 
03119         if (chosen_dir != v->direction) {
03120           if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
03121             const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
03122             DirDiff diff = DirDifference(v->direction, chosen_dir);
03123             v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
03124           }
03125           direction_changed = true;
03126           v->direction = chosen_dir;
03127         }
03128 
03129         if (v->IsFrontEngine()) {
03130           v->wait_counter = 0;
03131 
03132           /* If we are approaching a crossing that is reserved, play the sound now. */
03133           TileIndex crossing = TrainApproachingCrossingTile(v);
03134           if (crossing != INVALID_TILE && HasCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
03135 
03136           /* Always try to extend the reservation when entering a tile. */
03137           CheckNextTrainTile(v);
03138         }
03139 
03140         if (HasBit(r, VETS_ENTERED_STATION)) {
03141           /* The new position is the location where we want to stop */
03142           TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03143         }
03144       }
03145     } else {
03146       /* In a tunnel or on a bridge
03147        * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
03148        * - for bridges, only the middle part - without the bridge heads */
03149       if (!(v->vehstatus & VS_HIDDEN)) {
03150         Train *first = v->First();
03151         first->cur_speed = min(first->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
03152       }
03153 
03154       if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
03155         /* Perform look-ahead on tunnel exit. */
03156         if (v->IsFrontEngine()) {
03157           TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
03158           CheckNextTrainTile(v);
03159         }
03160         /* Prevent v->UpdateInclination() being called with wrong parameters.
03161          * This could happen if the train was reversed inside the tunnel/bridge. */
03162         if (gp.old_tile == gp.new_tile) {
03163           gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
03164         }
03165       } else {
03166         v->x_pos = gp.x;
03167         v->y_pos = gp.y;
03168         VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
03169         continue;
03170       }
03171     }
03172 
03173     /* update image of train, as well as delta XY */
03174     v->UpdateDeltaXY(v->direction);
03175 
03176     v->x_pos = gp.x;
03177     v->y_pos = gp.y;
03178 
03179     /* update the Z position of the vehicle */
03180     byte old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
03181 
03182     if (prev == NULL) {
03183       /* This is the first vehicle in the train */
03184       AffectSpeedByZChange(v, old_z);
03185     }
03186 
03187     if (update_signals_crossing) {
03188       if (v->IsFrontEngine()) {
03189         if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
03190           /* We are entering a block with PBS signals right now, but
03191            * not through a PBS signal. This means we don't have a
03192            * reservation right now. As a conventional signal will only
03193            * ever be green if no other train is in the block, getting
03194            * a path should always be possible. If the player built
03195            * such a strange network that it is not possible, the train
03196            * will be marked as stuck and the player has to deal with
03197            * the problem. */
03198           if ((!HasReservedTracks(gp.new_tile, v->track) &&
03199               !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
03200               !TryPathReserve(v)) {
03201             MarkTrainAsStuck(v);
03202           }
03203         }
03204       }
03205 
03206       /* Signals can only change when the first
03207        * (above) or the last vehicle moves. */
03208       if (v->Next() == NULL) {
03209         TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
03210         if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
03211       }
03212     }
03213 
03214     /* Do not check on every tick to save some computing time. */
03215     if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
03216   }
03217 
03218   if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
03219 
03220   return;
03221 
03222 invalid_rail:
03223   /* We've reached end of line?? */
03224   if (prev != NULL) error("Disconnecting train");
03225 
03226 reverse_train_direction:
03227   v->wait_counter = 0;
03228   v->cur_speed = 0;
03229   v->subspeed = 0;
03230   ReverseTrainDirection(v);
03231 }
03232 
03239 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
03240 {
03241   TrackBits *trackbits = (TrackBits *)data;
03242 
03243   if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
03244     TrackBits train_tbits = Train::From(v)->track;
03245     if (train_tbits == TRACK_BIT_WORMHOLE) {
03246       /* Vehicle is inside a wormhole, v->track contains no useful value then. */
03247       *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
03248     } else if (train_tbits != TRACK_BIT_DEPOT) {
03249       *trackbits |= train_tbits;
03250     }
03251   }
03252 
03253   return NULL;
03254 }
03255 
03263 static void DeleteLastWagon(Train *v)
03264 {
03265   Train *first = v->First();
03266 
03267   /* Go to the last wagon and delete the link pointing there
03268    * *u is then the one-before-last wagon, and *v the last
03269    * one which will physically be removed */
03270   Train *u = v;
03271   for (; v->Next() != NULL; v = v->Next()) u = v;
03272   u->SetNext(NULL);
03273 
03274   if (first != v) {
03275     /* Recalculate cached train properties */
03276     first->ConsistChanged(false);
03277     /* Update the depot window if the first vehicle is in depot -
03278      * if v == first, then it is updated in PreDestructor() */
03279     if (first->track == TRACK_BIT_DEPOT) {
03280       SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
03281     }
03282   }
03283 
03284   /* 'v' shouldn't be accessed after it has been deleted */
03285   TrackBits trackbits = v->track;
03286   TileIndex tile = v->tile;
03287   Owner owner = v->owner;
03288 
03289   delete v;
03290   v = NULL; // make sure nobody will try to read 'v' anymore
03291 
03292   if (trackbits == TRACK_BIT_WORMHOLE) {
03293     /* Vehicle is inside a wormhole, v->track contains no useful value then. */
03294     trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
03295   }
03296 
03297   Track track = TrackBitsToTrack(trackbits);
03298   if (HasReservedTracks(tile, trackbits)) {
03299     UnreserveRailTrack(tile, track);
03300 
03301     /* If there are still crashed vehicles on the tile, give the track reservation to them */
03302     TrackBits remaining_trackbits = TRACK_BIT_NONE;
03303     FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
03304 
03305     /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
03306     assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
03307     Track t;
03308     FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
03309   }
03310 
03311   /* check if the wagon was on a road/rail-crossing */
03312   if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
03313 
03314   /* Update signals */
03315   if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
03316     UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
03317   } else {
03318     SetSignalsOnBothDir(tile, track, owner);
03319   }
03320 }
03321 
03326 static void ChangeTrainDirRandomly(Train *v)
03327 {
03328   static const DirDiff delta[] = {
03329     DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
03330   };
03331 
03332   do {
03333     /* We don't need to twist around vehicles if they're not visible */
03334     if (!(v->vehstatus & VS_HIDDEN)) {
03335       v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
03336       v->UpdateDeltaXY(v->direction);
03337       v->cur_image = v->GetImage(v->direction);
03338       /* Refrain from updating the z position of the vehicle when on
03339        * a bridge, because UpdateInclination() will put the vehicle under
03340        * the bridge in that case */
03341       if (v->track != TRACK_BIT_WORMHOLE) v->UpdateInclination(false, false);
03342     }
03343   } while ((v = v->Next()) != NULL);
03344 }
03345 
03351 static bool HandleCrashedTrain(Train *v)
03352 {
03353   int state = ++v->crash_anim_pos;
03354 
03355   if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
03356     CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
03357   }
03358 
03359   uint32 r;
03360   if (state <= 200 && Chance16R(1, 7, r)) {
03361     int index = (r * 10 >> 16);
03362 
03363     Vehicle *u = v;
03364     do {
03365       if (--index < 0) {
03366         r = Random();
03367 
03368         CreateEffectVehicleRel(u,
03369           GB(r,  8, 3) + 2,
03370           GB(r, 16, 3) + 2,
03371           GB(r,  0, 3) + 5,
03372           EV_EXPLOSION_SMALL);
03373         break;
03374       }
03375     } while ((u = u->Next()) != NULL);
03376   }
03377 
03378   if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
03379 
03380   if (state >= 4440 && !(v->tick_counter & 0x1F)) {
03381     bool ret = v->Next() != NULL;
03382     DeleteLastWagon(v);
03383     return ret;
03384   }
03385 
03386   return true;
03387 }
03388 
03390 static const uint16 _breakdown_speeds[16] = {
03391   225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
03392 };
03393 
03394 
03402 static bool TrainApproachingLineEnd(Train *v, bool signal)
03403 {
03404   /* Calc position within the current tile */
03405   uint x = v->x_pos & 0xF;
03406   uint y = v->y_pos & 0xF;
03407 
03408   /* for diagonal directions, 'x' will be 0..15 -
03409    * for other directions, it will be 1, 3, 5, ..., 15 */
03410   switch (v->direction) {
03411     case DIR_N : x = ~x + ~y + 25; break;
03412     case DIR_NW: x = y;            // FALL THROUGH
03413     case DIR_NE: x = ~x + 16;      break;
03414     case DIR_E : x = ~x + y + 9;   break;
03415     case DIR_SE: x = y;            break;
03416     case DIR_S : x = x + y - 7;    break;
03417     case DIR_W : x = ~y + x + 9;   break;
03418     default: break;
03419   }
03420 
03421   /* Do not reverse when approaching red signal. Make sure the vehicle's front
03422    * does not cross the tile boundary when we do reverse, but as the vehicle's
03423    * location is based on their center, use half a vehicle's length as offset.
03424    * Actually, the center of all vehicles is half a normal vehicle's length
03425    * from the front of the vehicle, so even in case the vehicle is 1/8th
03426    * long, the center is still at 1/2 of VEHICLE_LENGTH. Basically FS#3569. */
03427   if (!signal && x + VEHICLE_LENGTH / 2 >= TILE_SIZE) {
03428     /* we are too near the tile end, reverse now */
03429     v->cur_speed = 0;
03430     ReverseTrainDirection(v);
03431     return false;
03432   }
03433 
03434   /* slow down */
03435   v->vehstatus |= VS_TRAIN_SLOWING;
03436   uint16 break_speed = _breakdown_speeds[x & 0xF];
03437   if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03438 
03439   return true;
03440 }
03441 
03442 
03448 static bool TrainCanLeaveTile(const Train *v)
03449 {
03450   /* Exit if inside a tunnel/bridge or a depot */
03451   if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
03452 
03453   TileIndex tile = v->tile;
03454 
03455   /* entering a tunnel/bridge? */
03456   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
03457     DiagDirection dir = GetTunnelBridgeDirection(tile);
03458     if (DiagDirToDir(dir) == v->direction) return false;
03459   }
03460 
03461   /* entering a depot? */
03462   if (IsRailDepotTile(tile)) {
03463     DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
03464     if (DiagDirToDir(dir) == v->direction) return false;
03465   }
03466 
03467   return true;
03468 }
03469 
03470 
03478 static TileIndex TrainApproachingCrossingTile(const Train *v)
03479 {
03480   assert(v->IsFrontEngine());
03481   assert(!(v->vehstatus & VS_CRASHED));
03482 
03483   if (!TrainCanLeaveTile(v)) return INVALID_TILE;
03484 
03485   DiagDirection dir = TrainExitDir(v->direction, v->track);
03486   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03487 
03488   /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
03489   if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
03490       !CheckCompatibleRail(v, tile)) {
03491     return INVALID_TILE;
03492   }
03493 
03494   return tile;
03495 }
03496 
03497 
03504 static bool TrainCheckIfLineEnds(Train *v)
03505 {
03506   /* First, handle broken down train */
03507 
03508   int t = v->breakdown_ctr;
03509   if (t > 1) {
03510     v->vehstatus |= VS_TRAIN_SLOWING;
03511 
03512     uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
03513     if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03514   } else {
03515     v->vehstatus &= ~VS_TRAIN_SLOWING;
03516   }
03517 
03518   if (!TrainCanLeaveTile(v)) return true;
03519 
03520   /* Determine the non-diagonal direction in which we will exit this tile */
03521   DiagDirection dir = TrainExitDir(v->direction, v->track);
03522   /* Calculate next tile */
03523   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03524 
03525   /* Determine the track status on the next tile */
03526   TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
03527   TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
03528 
03529   TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03530   TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
03531 
03532   /* We are sure the train is not entering a depot, it is detected above */
03533 
03534   /* mask unreachable track bits if we are forbidden to do 90deg turns */
03535   TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03536   if (_settings_game.pf.forbid_90_deg) {
03537     bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03538   }
03539 
03540   /* no suitable trackbits at all || unusable rail (wrong type or owner) */
03541   if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
03542     return TrainApproachingLineEnd(v, false);
03543   }
03544 
03545   /* approaching red signal */
03546   if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true);
03547 
03548   /* approaching a rail/road crossing? then make it red */
03549   if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
03550 
03551   return true;
03552 }
03553 
03554 
03555 static bool TrainLocoHandler(Train *v, bool mode)
03556 {
03557   /* train has crashed? */
03558   if (v->vehstatus & VS_CRASHED) {
03559     return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
03560   }
03561 
03562   if (v->force_proceed != TFP_NONE) {
03563     ClrBit(v->flags, VRF_TRAIN_STUCK);
03564     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03565   }
03566 
03567   /* train is broken down? */
03568   if (v->HandleBreakdown()) return true;
03569 
03570   if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
03571     ReverseTrainDirection(v);
03572   }
03573 
03574   /* exit if train is stopped */
03575   if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
03576 
03577   bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
03578   if (ProcessOrders(v) && CheckReverseTrain(v)) {
03579     v->wait_counter = 0;
03580     v->cur_speed = 0;
03581     v->subspeed = 0;
03582     ClrBit(v->flags, VRF_LEAVING_STATION);
03583     ReverseTrainDirection(v);
03584     return true;
03585   } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
03586     /* Try to reserve a path when leaving the station as we
03587      * might not be marked as wanting a reservation, e.g.
03588      * when an overlength train gets turned around in a station. */
03589     DiagDirection dir = TrainExitDir(v->direction, v->track);
03590     if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
03591 
03592     if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
03593       TryPathReserve(v, true, true);
03594     }
03595     ClrBit(v->flags, VRF_LEAVING_STATION);
03596   }
03597 
03598   v->HandleLoading(mode);
03599 
03600   if (v->current_order.IsType(OT_LOADING)) return true;
03601 
03602   if (CheckTrainStayInDepot(v)) return true;
03603 
03604   if (!mode) v->ShowVisualEffect();
03605 
03606   /* We had no order but have an order now, do look ahead. */
03607   if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
03608     CheckNextTrainTile(v);
03609   }
03610 
03611   /* Handle stuck trains. */
03612   if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
03613     ++v->wait_counter;
03614 
03615     /* Should we try reversing this tick if still stuck? */
03616     bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
03617 
03618     if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
03619     if (!TryPathReserve(v)) {
03620       /* Still stuck. */
03621       if (turn_around) ReverseTrainDirection(v);
03622 
03623       if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
03624         /* Show message to player. */
03625         if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
03626           SetDParam(0, v->index);
03627           AddVehicleNewsItem(
03628             STR_NEWS_TRAIN_IS_STUCK,
03629             NS_ADVICE,
03630             v->index
03631           );
03632         }
03633         v->wait_counter = 0;
03634       }
03635       /* Exit if force proceed not pressed, else reset stuck flag anyway. */
03636       if (v->force_proceed == TFP_NONE) return true;
03637       ClrBit(v->flags, VRF_TRAIN_STUCK);
03638       v->wait_counter = 0;
03639       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03640     }
03641   }
03642 
03643   if (v->current_order.IsType(OT_LEAVESTATION)) {
03644     v->current_order.Free();
03645     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03646     return true;
03647   }
03648 
03649   int j = v->UpdateSpeed();
03650 
03651   /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
03652   if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
03653     /* If we manually stopped, we're not force-proceeding anymore. */
03654     v->force_proceed = TFP_NONE;
03655     SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03656   }
03657 
03658   int adv_spd = v->GetAdvanceDistance();
03659   if (j < adv_spd) {
03660     /* if the vehicle has speed 0, update the last_speed field. */
03661     if (v->cur_speed == 0) v->SetLastSpeed();
03662   } else {
03663     TrainCheckIfLineEnds(v);
03664     /* Loop until the train has finished moving. */
03665     for (;;) {
03666       j -= adv_spd;
03667       TrainController(v, NULL);
03668       /* Don't continue to move if the train crashed. */
03669       if (CheckTrainCollision(v)) break;
03670       /* Determine distance to next map position */
03671       adv_spd = v->GetAdvanceDistance();
03672 
03673       /* No more moving this tick */
03674       if (j < adv_spd || v->cur_speed == 0) break;
03675 
03676       OrderType order_type = v->current_order.GetType();
03677       /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
03678       if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
03679             (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
03680             IsTileType(v->tile, MP_STATION) &&
03681             v->current_order.GetDestination() == GetStationIndex(v->tile)) {
03682         ProcessOrders(v);
03683       }
03684     }
03685     v->SetLastSpeed();
03686   }
03687 
03688   for (Train *u = v; u != NULL; u = u->Next()) {
03689     if ((u->vehstatus & VS_HIDDEN) != 0) continue;
03690 
03691     u->UpdateViewport(false, false);
03692   }
03693 
03694   if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
03695 
03696   return true;
03697 }
03698 
03699 
03700 
03701 Money Train::GetRunningCost() const
03702 {
03703   Money cost = 0;
03704   const Train *v = this;
03705 
03706   do {
03707     const Engine *e = Engine::Get(v->engine_type);
03708     if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
03709 
03710     uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
03711     if (cost_factor == 0) continue;
03712 
03713     /* Halve running cost for multiheaded parts */
03714     if (v->IsMultiheaded()) cost_factor /= 2;
03715 
03716     cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->grf_prop.grffile);
03717   } while ((v = v->GetNextVehicle()) != NULL);
03718 
03719   return cost;
03720 }
03721 
03722 
03723 bool Train::Tick()
03724 {
03725   this->tick_counter++;
03726 
03727   if (this->IsFrontEngine()) {
03728     if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
03729 
03730     this->current_order_time++;
03731 
03732     if (!TrainLocoHandler(this, false)) return false;
03733 
03734     return TrainLocoHandler(this, true);
03735   } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
03736     /* Delete flooded standalone wagon chain */
03737     if (++this->crash_anim_pos >= 4400) {
03738       delete this;
03739       return false;
03740     }
03741   }
03742 
03743   return true;
03744 }
03745 
03746 static void CheckIfTrainNeedsService(Train *v)
03747 {
03748   if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
03749   if (v->IsInDepot()) {
03750     VehicleServiceInDepot(v);
03751     return;
03752   }
03753 
03754   uint max_penalty;
03755   switch (_settings_game.pf.pathfinder_for_trains) {
03756     case VPF_NPF:  max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty;  break;
03757     case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
03758     default: NOT_REACHED();
03759   }
03760 
03761   FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
03762   /* Only go to the depot if it is not too far out of our way. */
03763   if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
03764     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
03765       /* If we were already heading for a depot but it has
03766        * suddenly moved farther away, we continue our normal
03767        * schedule? */
03768       v->current_order.MakeDummy();
03769       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03770     }
03771     return;
03772   }
03773 
03774   DepotID depot = GetDepotIndex(tfdd.tile);
03775 
03776   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
03777       v->current_order.GetDestination() != depot &&
03778       !Chance16(3, 16)) {
03779     return;
03780   }
03781 
03782   SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
03783   v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
03784   v->dest_tile = tfdd.tile;
03785   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03786 }
03787 
03788 void Train::OnNewDay()
03789 {
03790   if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
03791 
03792   if (this->IsFrontEngine()) {
03793     CheckVehicleBreakdown(this);
03794     AgeVehicle(this);
03795 
03796     CheckIfTrainNeedsService(this);
03797 
03798     CheckOrders(this);
03799 
03800     /* update destination */
03801     if (this->current_order.IsType(OT_GOTO_STATION)) {
03802       TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
03803       if (tile != INVALID_TILE) this->dest_tile = tile;
03804     }
03805 
03806     if (this->running_ticks != 0) {
03807       /* running costs */
03808       CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR  * DAY_TICKS));
03809 
03810       this->profit_this_year -= cost.GetCost();
03811       this->running_ticks = 0;
03812 
03813       SubtractMoneyFromCompanyFract(this->owner, cost);
03814 
03815       SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
03816       SetWindowClassesDirty(WC_TRAINS_LIST);
03817     }
03818   } else if (this->IsEngine()) {
03819     /* Also age engines that aren't front engines */
03820     AgeVehicle(this);
03821   }
03822 }
03823 
03824 Trackdir Train::GetVehicleTrackdir() const
03825 {
03826   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
03827 
03828   if (this->track == TRACK_BIT_DEPOT) {
03829     /* We'll assume the train is facing outwards */
03830     return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
03831   }
03832 
03833   if (this->track == TRACK_BIT_WORMHOLE) {
03834     /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
03835     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
03836   }
03837 
03838   return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
03839 }

Generated on Fri Jun 3 05:19:00 2011 for OpenTTD by  doxygen 1.6.1