# train_cmd.cpp

Go to the documentation of this file.

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