train_cmd.cpp

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