train_cmd.cpp

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