# train_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: train_cmd.cpp 20585 2010-08-20 18:28:46Z 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 "gui.h"
    00014 #include "articulated_vehicles.h"
    00015 #include "command_func.h"
    00016 #include "pathfinder/npf/npf_func.h"
    00017 #include "pathfinder/yapf/yapf.hpp"
    00018 #include "news_func.h"
    00019 #include "company_func.h"
    00020 #include "vehicle_gui.h"
    00021 #include "newgrf_engine.h"
    00022 #include "newgrf_sound.h"
    00023 #include "newgrf_text.h"
    00024 #include "group.h"
    00025 #include "table/sprites.h"
    00026 #include "strings_func.h"
    00027 #include "functions.h"
    00028 #include "window_func.h"
    00029 #include "vehicle_func.h"
    00030 #include "sound_func.h"
    00031 #include "autoreplace_gui.h"
    00032 #include "ai/ai.hpp"
    00033 #include "newgrf_station.h"
    00034 #include "effectvehicle_func.h"
    00035 #include "effectvehicle_base.h"
    00036 #include "gamelog.h"
    00037 #include "network/network.h"
    00038 #include "spritecache.h"
    00039 #include "core/random_func.hpp"
    00040 #include "company_base.h"
    00041 #include "engine_base.h"
    00042 #include "engine_func.h"
    00043 #include "newgrf.h"
    00044
    00045 #include "table/strings.h"
    00046 #include "table/train_cmd.h"
    00047
    00048 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
    00049 static bool TrainCheckIfLineEnds(Train *v);
    00050 static void TrainController(Train *v, Vehicle *nomove);
    00051 static TileIndex TrainApproachingCrossingTile(const Train *v);
    00052 static void CheckIfTrainNeedsService(Train *v);
    00053 static void CheckNextTrainTile(Train *v);
    00054
    00055 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4,  8};
    00056 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
    00057
    00058
    00066 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
    00067 {
    00068   static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
    00069
    00070   DiagDirection diagdir = DirToDiagDir(direction);
    00071
    00072   /* Determine the diagonal direction in which we will exit this tile */
    00073   if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
    00074     diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
    00075   }
    00076
    00077   return diagdir;
    00078 }
    00079
    00080
    00085 byte FreightWagonMult(CargoID cargo)
    00086 {
    00087   if (!CargoSpec::Get(cargo)->is_freight) return 1;
    00088   return _settings_game.vehicle.freight_trains;
    00089 }
    00090
    00091
    00095 void Train::PowerChanged()
    00096 {
    00097   assert(this->First() == this);
    00098
    00099   uint32 total_power = 0;
    00100   uint32 max_te = 0;
    00101   uint32 number_of_parts = 0;
    00102   uint16 max_rail_speed = this->tcache.cached_max_speed;
    00103
    00104   for (const Train *u = this; u != NULL; u = u->Next()) {
    00105     uint32 current_power = u->GetPower();
    00106     total_power += current_power;
    00107
    00108     /* Only powered parts add tractive effort */
    00109     if (current_power > 0) max_te += u->GetWeight() * u->GetTractiveEffort();
    00110     total_power += u->GetPoweredPartPower(this);
    00111     number_of_parts++;
    00112
    00113     /* Get minimum max speed for rail */
    00114     uint16 rail_speed = GetRailTypeInfo(GetRailType(u->tile))->max_speed;
    00115     if (rail_speed > 0) max_rail_speed = min(max_rail_speed, rail_speed);
    00116   }
    00117
    00118   this->tcache.cached_axle_resistance = 60 * number_of_parts;
    00119   this->tcache.cached_air_drag = 20 + 3 * number_of_parts;
    00120
    00121   max_te *= 10000; // Tractive effort in (tonnes * 1000 * 10 =) N
    00122   max_te /= 256;   // Tractive effort is a [0-255] coefficient
    00123   if (this->tcache.cached_power != total_power || this->tcache.cached_max_te != max_te) {
    00124     /* Stop the vehicle if it has no power */
    00125     if (total_power == 0) this->vehstatus |= VS_STOPPED;
    00126
    00127     this->tcache.cached_power = total_power;
    00128     this->tcache.cached_max_te = max_te;
    00129     SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
    00130     SetWindowWidgetDirty(WC_VEHICLE_VIEW, this->index, VVW_WIDGET_START_STOP_VEH);
    00131   }
    00132
    00133   this->tcache.cached_max_rail_speed = max_rail_speed;
    00134 }
    00135
    00136
    00141 void Train::CargoChanged()
    00142 {
    00143   assert(this->First() == this);
    00144   uint32 weight = 0;
    00145
    00146   for (Train *u = this; u != NULL; u = u->Next()) {
    00147     uint32 current_weight = u->GetWeight();
    00148     weight += current_weight;
    00149     u->tcache.cached_slope_resistance = current_weight * u->GetSlopeSteepness();
    00150   }
    00151
    00152   /* store consist weight in cache */
    00153   this->tcache.cached_weight = weight;
    00154
    00155   /* Now update train power (tractive effort is dependent on weight) */
    00156   this->PowerChanged();
    00157 }
    00158
    00159
    00164 static void RailVehicleLengthChanged(const Train *u)
    00165 {
    00166   /* show a warning once for each engine in whole game and once for each GRF after each game load */
    00167   const Engine *engine = Engine::Get(u->engine_type);
    00168   uint32 grfid = engine->grffile->grfid;
    00169   GRFConfig *grfconfig = GetGRFConfig(grfid);
    00170   if (GamelogGRFBugReverse(grfid, engine->internal_id) || !HasBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH)) {
    00171     ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, GBUG_VEH_LENGTH, true);
    00172   }
    00173 }
    00174
    00176 void CheckTrainsLengths()
    00177 {
    00178   const Train *v;
    00179
    00180   FOR_ALL_TRAINS(v) {
    00181     if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
    00182       for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
    00183         if (u->track != TRACK_BIT_DEPOT) {
    00184           if ((w->track != TRACK_BIT_DEPOT &&
    00185               max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->tcache.cached_veh_length) ||
    00186               (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
    00187             SetDParam(0, v->index);
    00188             SetDParam(1, v->owner);
    00189             ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, 0, 0, true);
    00190
    00191             if (!_networking) DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
    00192           }
    00193         }
    00194       }
    00195     }
    00196   }
    00197 }
    00198
    00203 void Train::RailtypeChanged()
    00204 {
    00205   for (Train *u = this; u != NULL; u = u->Next()) {
    00206     /* The wagon-is-powered-state should not change, so the weight does not change. */
    00207     u->UpdateVisualEffect(false);
    00208   }
    00209   this->PowerChanged();
    00210   if (this->IsFrontEngine()) this->UpdateAcceleration();
    00211 }
    00212
    00217 void Train::UpdateVisualEffect(bool allow_power_change)
    00218 {
    00219   byte powered_before = this->tcache.cached_vis_effect & 0x80;
    00220
    00221   const Engine *e = Engine::Get(this->engine_type);
    00222   if (e->u.rail.visual_effect != 0) {
    00223     this->tcache.cached_vis_effect = e->u.rail.visual_effect;
    00224   } else {
    00225     if (this->IsWagon() || this->IsArticulatedPart()) {
    00226       /* Wagons and articulated parts have no effect by default */
    00227       this->tcache.cached_vis_effect = 0x40;
    00228     } else if (e->u.rail.engclass == 0) {
    00229       /* Steam is offset by -4 units */
    00230       this->tcache.cached_vis_effect = 4;
    00231     } else {
    00232       /* Diesel fumes and sparks come from the centre */
    00233       this->tcache.cached_vis_effect = 8;
    00234     }
    00235   }
    00236
    00237   /* Check powered wagon / visual effect callback */
    00238   if (HasBit(e->info.callback_mask, CBM_TRAIN_WAGON_POWER)) {
    00239     uint16 callback = GetVehicleCallback(CBID_TRAIN_WAGON_POWER, 0, 0, this->engine_type, this);
    00240
    00241     if (callback != CALLBACK_FAILED) this->tcache.cached_vis_effect = GB(callback, 0, 8);
    00242   }
    00243
    00244   if (!allow_power_change && powered_before != (this->tcache.cached_vis_effect & 0x80)) {
    00245     this->tcache.cached_vis_effect ^= 0x80;
    00246     ShowNewGrfVehicleError(this->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_POWERED_WAGON, GBUG_VEH_POWERED_WAGON, false);
    00247   }
    00248 }
    00249
    00256 void Train::ConsistChanged(bool same_length)
    00257 {
    00258   uint16 max_speed = UINT16_MAX;
    00259
    00260   assert(this->IsFrontEngine() || this->IsFreeWagon());
    00261
    00262   const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
    00263   EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
    00264   this->tcache.cached_total_length = 0;
    00265   this->compatible_railtypes = RAILTYPES_NONE;
    00266
    00267   bool train_can_tilt = true;
    00268
    00269   for (Train *u = this; u != NULL; u = u->Next()) {
    00270     const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
    00271
    00272     /* Check the this->first cache. */
    00273     assert(u->First() == this);
    00274
    00275     /* update the 'first engine' */
    00276     u->tcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
    00277     u->railtype = rvi_u->railtype;
    00278
    00279     if (u->IsEngine()) first_engine = u->engine_type;
    00280
    00281     /* Set user defined data to its default value */
    00282     u->tcache.user_def_data = rvi_u->user_def_data;
    00283     this->InvalidateNewGRFCache();
    00284     u->InvalidateNewGRFCache();
    00285   }
    00286
    00287   for (Train *u = this; u != NULL; u = u->Next()) {
    00288     /* Update user defined data (must be done before other properties) */
    00289     u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
    00290     this->InvalidateNewGRFCache();
    00291     u->InvalidateNewGRFCache();
    00292   }
    00293
    00294   for (Train *u = this; u != NULL; u = u->Next()) {
    00295     const Engine *e_u = Engine::Get(u->engine_type);
    00296     const RailVehicleInfo *rvi_u = &e_u->u.rail;
    00297
    00298     if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
    00299
    00300     /* Cache wagon override sprite group. NULL is returned if there is none */
    00301     u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->tcache.first_engine);
    00302
    00303     /* Reset colour map */
    00304     u->colourmap = PAL_NONE;
    00305
    00306     /* Update powered-wagon-status and visual effect */
    00307     u->UpdateVisualEffect(true);
    00308
    00309     if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
    00310       UsesWagonOverride(u) && !HasBit(u->tcache.cached_vis_effect, 7)) {
    00311       /* wagon is powered */
    00312       SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
    00313     } else {
    00314       ClrBit(u->flags, VRF_POWEREDWAGON);
    00315     }
    00316
    00317     if (!u->IsArticulatedPart()) {
    00318       /* Do not count powered wagons for the compatible railtypes, as wagons always
    00319          have railtype normal */
    00320       if (rvi_u->power > 0) {
    00321         this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
    00322       }
    00323
    00324       /* Some electric engines can be allowed to run on normal rail. It happens to all
    00325        * existing electric engines when elrails are disabled and then re-enabled */
    00326       if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
    00327         u->railtype = RAILTYPE_RAIL;
    00328         u->compatible_railtypes |= RAILTYPES_RAIL;
    00329       }
    00330
    00331       /* max speed is the minimum of the speed limits of all vehicles in the consist */
    00332       if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
    00333         uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
    00334         if (speed != 0) max_speed = min(speed, max_speed);
    00335       }
    00336     }
    00337
    00338     u->cargo_cap = GetVehicleCapacity(u);
    00339
    00340     /* check the vehicle length (callback) */
    00341     uint16 veh_len = CALLBACK_FAILED;
    00342     if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
    00343       veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
    00344     }
    00345     if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
    00346     veh_len = 8 - Clamp(veh_len, 0, 7);
    00347
    00348     /* verify length hasn't changed */
    00349     if (same_length && veh_len != u->tcache.cached_veh_length) RailVehicleLengthChanged(u);
    00350
    00351     /* update vehicle length? */
    00352     if (!same_length) u->tcache.cached_veh_length = veh_len;
    00353
    00354     this->tcache.cached_total_length += u->tcache.cached_veh_length;
    00355     this->InvalidateNewGRFCache();
    00356     u->InvalidateNewGRFCache();
    00357   }
    00358
    00359   /* store consist weight/max speed in cache */
    00360   this->tcache.cached_max_speed = max_speed;
    00361   this->tcache.cached_tilt = train_can_tilt;
    00362   this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
    00363
    00364   /* 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) */
    00365   this->CargoChanged();
    00366
    00367   if (this->IsFrontEngine()) {
    00368     this->UpdateAcceleration();
    00369     SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
    00370   }
    00371 }
    00372
    00383 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
    00384 {
    00385   const Station *st = Station::Get(station_id);
    00386   *station_ahead  = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
    00387   *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
    00388
    00389   /* Default to the middle of the station for stations stops that are not in
    00390    * the order list like intermediate stations when non-stop is disabled */
    00391   OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
    00392   if (v->tcache.cached_total_length >= *station_length) {
    00393     /* The train is longer than the station, make it stop at the far end of the platform */
    00394     osl = OSL_PLATFORM_FAR_END;
    00395   } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
    00396     osl = v->current_order.GetStopLocation();
    00397   }
    00398
    00399   /* The stop location of the FRONT! of the train */
    00400   int stop;
    00401   switch (osl) {
    00402     default: NOT_REACHED();
    00403
    00404     case OSL_PLATFORM_NEAR_END:
    00405       stop = v->tcache.cached_total_length;
    00406       break;
    00407
    00408     case OSL_PLATFORM_MIDDLE:
    00409       stop = *station_length - (*station_length - v->tcache.cached_total_length) / 2;
    00410       break;
    00411
    00412     case OSL_PLATFORM_FAR_END:
    00413       stop = *station_length;
    00414       break;
    00415   }
    00416
    00417   /* Substract half the front vehicle length of the train so we get the real
    00418    * stop location of the train. */
    00419   return stop - (v->tcache.cached_veh_length + 1) / 2;
    00420 }
    00421
    00422
    00427 int Train::GetCurveSpeedLimit() const
    00428 {
    00429   assert(this->First() == this);
    00430
    00431   static const int absolute_max_speed = UINT16_MAX;
    00432   int max_speed = absolute_max_speed;
    00433
    00434   if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
    00435
    00436   int curvecount[2] = {0, 0};
    00437
    00438   /* first find the curve speed limit */
    00439   int numcurve = 0;
    00440   int sum = 0;
    00441   int pos = 0;
    00442   int lastpos = -1;
    00443   for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
    00444     Direction this_dir = u->direction;
    00445     Direction next_dir = u->Next()->direction;
    00446
    00447     DirDiff dirdiff = DirDifference(this_dir, next_dir);
    00448     if (dirdiff == DIRDIFF_SAME) continue;
    00449
    00450     if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
    00451     if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
    00452     if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
    00453       if (lastpos != -1) {
    00454         numcurve++;
    00455         sum += pos - lastpos;
    00456         if (pos - lastpos == 1) {
    00457           max_speed = 88;
    00458         }
    00459       }
    00460       lastpos = pos;
    00461     }
    00462
    00463     /* if we have a 90 degree turn, fix the speed limit to 60 */
    00464     if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
    00465       max_speed = 61;
    00466     }
    00467   }
    00468
    00469   if (numcurve > 0 && max_speed > 88) {
    00470     if (curvecount[0] == 1 && curvecount[1] == 1) {
    00471       max_speed = absolute_max_speed;
    00472     } else {
    00473       sum /= numcurve;
    00474       max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
    00475     }
    00476   }
    00477
    00478   if (max_speed != absolute_max_speed) {
    00479     /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
    00480     const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
    00481     max_speed += (max_speed / 2) * rti->curve_speed;
    00482
    00483     if (this->tcache.cached_tilt) {
    00484       /* Apply max_speed bonus of 20% for a tilting train */
    00485       max_speed += max_speed / 5;
    00486     }
    00487   }
    00488
    00489   return max_speed;
    00490 }
    00491
    00496 int Train::GetCurrentMaxSpeed() const
    00497 {
    00498   int max_speed = this->tcache.cached_max_curve_speed;
    00499   assert(max_speed == this->GetCurveSpeedLimit());
    00500
    00501   if (IsRailStationTile(this->tile)) {
    00502     StationID sid = GetStationIndex(this->tile);
    00503     if (this->current_order.ShouldStopAtStation(this, sid)) {
    00504       int station_ahead;
    00505       int station_length;
    00506       int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
    00507
    00508       /* The distance to go is whatever is still ahead of the train minus the
    00509        * distance from the train's stop location to the end of the platform */
    00510       int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
    00511
    00512       if (distance_to_go > 0) {
    00513         int st_max_speed = 120;
    00514
    00515         int delta_v = this->cur_speed / (distance_to_go + 1);
    00516         if (max_speed > (this->cur_speed - delta_v)) {
    00517           st_max_speed = this->cur_speed - (delta_v / 10);
    00518         }
    00519
    00520         st_max_speed = max(st_max_speed, 25 * distance_to_go);
    00521         max_speed = min(max_speed, st_max_speed);
    00522       }
    00523     }
    00524   }
    00525
    00526   for (const Train *u = this; u != NULL; u = u->Next()) {
    00527     if (u->track == TRACK_BIT_DEPOT) {
    00528       max_speed = min(max_speed, 61);
    00529       break;
    00530     }
    00531   }
    00532
    00533   return min(max_speed, this->tcache.cached_max_rail_speed);
    00534 }
    00535
    00541 int Train::GetAcceleration() const
    00542 {
    00543   int32 speed = this->GetCurrentSpeed();
    00544
    00545   /* Weight is stored in tonnes */
    00546   int32 mass = this->tcache.cached_weight;
    00547
    00548   /* Power is stored in HP, we need it in watts. */
    00549   int32 power = this->tcache.cached_power * 746;
    00550
    00551   int32 resistance = 0;
    00552
    00553   bool maglev = this->GetAccelerationType() == 2;
    00554
    00555   const int area = 120;
    00556   if (!maglev) {
    00557     resistance = (13 * mass) / 10;
    00558     resistance += this->tcache.cached_axle_resistance;
    00559     resistance += (this->GetRollingFriction() * mass * speed) / 1000;
    00560     resistance += (area * this->tcache.cached_air_drag * speed * speed) / 10000;
    00561   } else {
    00562     resistance += (area * this->tcache.cached_air_drag * speed * speed) / 20000;
    00563   }
    00564
    00565   resistance += this->GetSlopeResistance();
    00566   resistance *= 4; //[N]
    00567
    00568   /* This value allows to know if the vehicle is accelerating or braking. */
    00569   AccelStatus mode = this->GetAccelerationStatus();
    00570
    00571   const int max_te = this->tcache.cached_max_te; // [N]
    00572   int force;
    00573   if (speed > 0) {
    00574     if (!maglev) {
    00575       force = power / speed; //[N]
    00576       force *= 22;
    00577       force /= 10;
    00578       if (mode == AS_ACCEL && force > max_te) force = max_te;
    00579     } else {
    00580       force = power / 25;
    00581     }
    00582   } else {
    00583     /* "kickoff" acceleration */
    00584     force = (mode == AS_ACCEL && !maglev) ? min(max_te, power) : power;
    00585     force = max(force, (mass * 8) + resistance);
    00586   }
    00587
    00588   if (mode == AS_ACCEL) {
    00589     return (force - resistance) / (mass * 2);
    00590   } else {
    00591     return min(-force - resistance, -10000) / mass;
    00592   }
    00593 }
    00594
    00595 void Train::UpdateAcceleration()
    00596 {
    00597   assert(this->IsFrontEngine());
    00598
    00599   this->max_speed = this->tcache.cached_max_rail_speed;
    00600
    00601   uint power = this->tcache.cached_power;
    00602   uint weight = this->tcache.cached_weight;
    00603   assert(weight != 0);
    00604   this->acceleration = Clamp(power / weight * 4, 1, 255);
    00605 }
    00606
    00612 int Train::GetDisplayImageWidth(Point *offset) const
    00613 {
    00614   int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
    00615   int vehicle_pitch = 0;
    00616
    00617   const Engine *e = Engine::Get(this->engine_type);
    00618   if (e->grffile != NULL && is_custom_sprite(e->u.rail.image_index)) {
    00619     reference_width = e->grffile->traininfo_vehicle_width;
    00620     vehicle_pitch = e->grffile->traininfo_vehicle_pitch;
    00621   }
    00622
    00623   if (offset != NULL) {
    00624     offset->x = reference_width / 2;
    00625     offset->y = vehicle_pitch;
    00626   }
    00627   return this->tcache.cached_veh_length * reference_width / 8;
    00628 }
    00629
    00630 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
    00631 {
    00632   return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
    00633 }
    00634
    00635 SpriteID Train::GetImage(Direction direction) const
    00636 {
    00637   uint8 spritenum = this->spritenum;
    00638   SpriteID sprite;
    00639
    00640   if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
    00641
    00642   if (is_custom_sprite(spritenum)) {
    00643     sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)));
    00644     if (sprite != 0) return sprite;
    00645
    00646     spritenum = Engine::Get(this->engine_type)->original_image_index;
    00647   }
    00648
    00649   sprite = GetDefaultTrainSprite(spritenum, direction);
    00650
    00651   if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
    00652
    00653   return sprite;
    00654 }
    00655
    00656 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y)
    00657 {
    00658   const Engine *e = Engine::Get(engine);
    00659   Direction dir = rear_head ? DIR_E : DIR_W;
    00660   uint8 spritenum = e->u.rail.image_index;
    00661
    00662   if (is_custom_sprite(spritenum)) {
    00663     SpriteID sprite = GetCustomVehicleIcon(engine, dir);
    00664     if (sprite != 0) {
    00665       if (e->grffile != NULL) {
    00666         y += e->grffile->traininfo_vehicle_pitch;
    00667       }
    00668       return sprite;
    00669     }
    00670
    00671     spritenum = Engine::Get(engine)->original_image_index;
    00672   }
    00673
    00674   if (rear_head) spritenum++;
    00675
    00676   return GetDefaultTrainSprite(spritenum, DIR_W);
    00677 }
    00678
    00679 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal)
    00680 {
    00681   if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
    00682     int yf = y;
    00683     int yr = y;
    00684
    00685     SpriteID spritef = GetRailIcon(engine, false, yf);
    00686     SpriteID spriter = GetRailIcon(engine, true, yr);
    00687     const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
    00688     const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
    00689
    00690     preferred_x = Clamp(preferred_x, left - real_spritef->x_offs + 14, right - real_spriter->width - real_spriter->x_offs - 15);
    00691
    00692     DrawSprite(spritef, pal, preferred_x - 14, yf);
    00693     DrawSprite(spriter, pal, preferred_x + 15, yr);
    00694   } else {
    00695     SpriteID sprite = GetRailIcon(engine, false, y);
    00696     const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
    00697     preferred_x = Clamp(preferred_x, left - real_sprite->x_offs, right - real_sprite->width - real_sprite->x_offs);
    00698     DrawSprite(sprite, pal, preferred_x, y);
    00699   }
    00700 }
    00701
    00702 static CommandCost CmdBuildRailWagon(EngineID engine, TileIndex tile, DoCommandFlag flags)
    00703 {
    00704   const Engine *e = Engine::Get(engine);
    00705   const RailVehicleInfo *rvi = &e->u.rail;
    00706   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
    00707
    00708   /* Engines without valid cargo should not be available */
    00709   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
    00710
    00711   if (flags & DC_QUERY_COST) return value;
    00712
    00713   /* Check that the wagon can drive on the track in question */
    00714   if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
    00715
    00716   uint num_vehicles = 1 + CountArticulatedParts(engine, false);
    00717
    00718   /* Allow for the wagon and the articulated parts */
    00719   if (!Vehicle::CanAllocateItem(num_vehicles)) {
    00720     return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    00721   }
    00722
    00723   if (flags & DC_EXEC) {
    00724     Train *v = new Train();
    00725     v->spritenum = rvi->image_index;
    00726
    00727     v->engine_type = engine;
    00728     v->tcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
    00729
    00730     DiagDirection dir = GetRailDepotDirection(tile);
    00731
    00732     v->direction = DiagDirToDir(dir);
    00733     v->tile = tile;
    00734
    00735     int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
    00736     int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
    00737
    00738     v->x_pos = x;
    00739     v->y_pos = y;
    00740     v->z_pos = GetSlopeZ(x, y);
    00741     v->owner = _current_company;
    00742     v->track = TRACK_BIT_DEPOT;
    00743     v->vehstatus = VS_HIDDEN | VS_DEFPAL;
    00744
    00745     v->SetWagon();
    00746
    00747     v->SetFreeWagon();
    00748     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    00749
    00750     v->cargo_type = e->GetDefaultCargoType();
    00751     v->cargo_cap = rvi->capacity;
    00752     v->value = value.GetCost();
    00753
    00754     v->railtype = rvi->railtype;
    00755
    00756     v->build_year = _cur_year;
    00757     v->cur_image = SPR_IMG_QUERY;
    00758     v->random_bits = VehicleRandomBits();
    00759
    00760     v->group_id = DEFAULT_GROUP;
    00761
    00762     AddArticulatedParts(v);
    00763
    00764     _new_vehicle_id = v->index;
    00765
    00766     VehicleMove(v, false);
    00767     v->First()->ConsistChanged(false);
    00768     UpdateTrainGroupID(v->First());
    00769
    00770     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    00771     if (IsLocalCompany()) {
    00772       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
    00773     }
    00774     Company::Get(_current_company)->num_engines[engine]++;
    00775
    00776     CheckConsistencyOfArticulatedVehicle(v);
    00777
    00778     /* Try to connect the vehicle to one of free chains of wagons. */
    00779     Train *w;
    00780     FOR_ALL_TRAINS(w) {
    00781       if (w->tile == tile &&
    00782           w->IsFreeWagon() &&
    00783           w->engine_type == engine &&
    00784           w->First() != v &&
    00785           !(w->vehstatus & VS_CRASHED)) {
    00786         DoCommand(0, v->index | (w->Last()->index << 16), 1, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
    00787         break;
    00788       }
    00789     }
    00790   }
    00791
    00792   return value;
    00793 }
    00794
    00796 static void NormalizeTrainVehInDepot(const Train *u)
    00797 {
    00798   const Train *v;
    00799   FOR_ALL_TRAINS(v) {
    00800     if (v->IsFreeWagon() && v->tile == u->tile &&
    00801         v->track == TRACK_BIT_DEPOT) {
    00802       if (DoCommand(0, v->index | (u->index << 16), 1, DC_EXEC,
    00803           CMD_MOVE_RAIL_VEHICLE).Failed())
    00804         break;
    00805     }
    00806   }
    00807 }
    00808
    00809 static void AddRearEngineToMultiheadedTrain(Train *v)
    00810 {
    00811   Train *u = new Train();
    00812   v->value >>= 1;
    00813   u->value = v->value;
    00814   u->direction = v->direction;
    00815   u->owner = v->owner;
    00816   u->tile = v->tile;
    00817   u->x_pos = v->x_pos;
    00818   u->y_pos = v->y_pos;
    00819   u->z_pos = v->z_pos;
    00820   u->track = TRACK_BIT_DEPOT;
    00821   u->vehstatus = v->vehstatus & ~VS_STOPPED;
    00822   u->spritenum = v->spritenum + 1;
    00823   u->cargo_type = v->cargo_type;
    00824   u->cargo_subtype = v->cargo_subtype;
    00825   u->cargo_cap = v->cargo_cap;
    00826   u->railtype = v->railtype;
    00827   u->engine_type = v->engine_type;
    00828   u->build_year = v->build_year;
    00829   u->cur_image = SPR_IMG_QUERY;
    00830   u->random_bits = VehicleRandomBits();
    00831   v->SetMultiheaded();
    00832   u->SetMultiheaded();
    00833   v->SetNext(u);
    00834   VehicleMove(u, false);
    00835
    00836   /* Now we need to link the front and rear engines together */
    00837   v->other_multiheaded_part = u;
    00838   u->other_multiheaded_part = v;
    00839 }
    00840
    00849 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00850 {
    00851   EngineID eid = GB(p1, 0, 16);
    00852   /* Check if the engine-type is valid (for the company) */
    00853   if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE);
    00854
    00855   const Engine *e = Engine::Get(eid);
    00856   const RailVehicleInfo *rvi = &e->u.rail;
    00857   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
    00858
    00859   /* Engines with CT_INVALID should not be available */
    00860   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
    00861
    00862   if (flags & DC_QUERY_COST) return value;
    00863
    00864   /* Check if the train is actually being built in a depot belonging
    00865    * to the company. Doesn't matter if only the cost is queried */
    00866   if (!IsRailDepotTile(tile)) return CMD_ERROR;
    00867   if (!IsTileOwner(tile, _current_company)) return CMD_ERROR;
    00868
    00869   if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(eid, tile, flags);
    00870
    00871   uint num_vehicles =
    00872     (rvi->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) +
    00873     CountArticulatedParts(eid, false);
    00874
    00875   /* Check if depot and new engine uses the same kind of tracks *
    00876    * We need to see if the engine got power on the tile to avoid eletric engines in non-electric depots */
    00877   if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
    00878
    00879   /* Allow for the dual-heads and the articulated parts */
    00880   if (!Vehicle::CanAllocateItem(num_vehicles)) {
    00881     return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    00882   }
    00883
    00884   UnitID unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_TRAIN);
    00885   if (unit_num > _settings_game.vehicle.max_trains) {
    00886     return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    00887   }
    00888
    00889   if (flags & DC_EXEC) {
    00890     DiagDirection dir = GetRailDepotDirection(tile);
    00891     int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
    00892     int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
    00893
    00894     Train *v = new Train();
    00895     v->unitnumber = unit_num;
    00896     v->direction = DiagDirToDir(dir);
    00897     v->tile = tile;
    00898     v->owner = _current_company;
    00899     v->x_pos = x;
    00900     v->y_pos = y;
    00901     v->z_pos = GetSlopeZ(x, y);
    00902     v->track = TRACK_BIT_DEPOT;
    00903     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
    00904     v->spritenum = rvi->image_index;
    00905     v->cargo_type = e->GetDefaultCargoType();
    00906     v->cargo_cap = rvi->capacity;
    00907     v->max_speed = rvi->max_speed;
    00908     v->value = value.GetCost();
    00909     v->last_station_visited = INVALID_STATION;
    00910
    00911     v->engine_type = eid;
    00912     v->tcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
    00913
    00914     v->reliability = e->reliability;
    00915     v->reliability_spd_dec = e->reliability_spd_dec;
    00916     v->max_age = e->GetLifeLengthInDays();
    00917
    00918     v->railtype = rvi->railtype;
    00919     _new_vehicle_id = v->index;
    00920
    00921     v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_trains;
    00922     v->date_of_last_service = _date;
    00923     v->build_year = _cur_year;
    00924     v->cur_image = SPR_IMG_QUERY;
    00925     v->random_bits = VehicleRandomBits();
    00926
    00927     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
    00928
    00929     v->group_id = DEFAULT_GROUP;
    00930
    00931     v->SetFrontEngine();
    00932     v->SetEngine();
    00933
    00934     VehicleMove(v, false);
    00935
    00936     if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
    00937       AddRearEngineToMultiheadedTrain(v);
    00938     } else {
    00939       AddArticulatedParts(v);
    00940     }
    00941
    00942     v->ConsistChanged(false);
    00943     UpdateTrainGroupID(v);
    00944
    00945     if (!HasBit(p2, 1) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
    00946       NormalizeTrainVehInDepot(v);
    00947     }
    00948
    00949     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    00950     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    00951     SetWindowDirty(WC_COMPANY, v->owner);
    00952     if (IsLocalCompany()) {
    00953       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
    00954     }
    00955
    00956     Company::Get(_current_company)->num_engines[eid]++;
    00957
    00958     CheckConsistencyOfArticulatedVehicle(v);
    00959   }
    00960
    00961   return value;
    00962 }
    00963
    00964
    00965 bool Train::IsInDepot() const
    00966 {
    00967   /* Is the front engine stationary in the depot? */
    00968   if (!IsRailDepotTile(this->tile) || this->cur_speed != 0) return false;
    00969
    00970   /* Check whether the rest is also already trying to enter the depot. */
    00971   for (const Train *v = this; v != NULL; v = v->Next()) {
    00972     if (v->track != TRACK_BIT_DEPOT || v->tile != this->tile) return false;
    00973   }
    00974
    00975   return true;
    00976 }
    00977
    00978 bool Train::IsStoppedInDepot() const
    00979 {
    00980   /* Are we stopped? Ofcourse wagons don't really care... */
    00981   if (this->IsFrontEngine() && !(this->vehstatus & VS_STOPPED)) return false;
    00982   return this->IsInDepot();
    00983 }
    00984
    00985 static Train *FindGoodVehiclePos(const Train *src)
    00986 {
    00987   EngineID eng = src->engine_type;
    00988   TileIndex tile = src->tile;
    00989
    00990   Train *dst;
    00991   FOR_ALL_TRAINS(dst) {
    00992     if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
    00993       /* check so all vehicles in the line have the same engine. */
    00994       Train *t = dst;
    00995       while (t->engine_type == eng) {
    00996         t = t->Next();
    00997         if (t == NULL) return dst;
    00998       }
    00999     }
    01000   }
    01001
    01002   return NULL;
    01003 }
    01004
    01006 typedef SmallVector<Train *, 16> TrainList;
    01007
    01013 static void MakeTrainBackup(TrainList &list, Train *t)
    01014 {
    01015   for (; t != NULL; t = t->Next()) *list.Append() = t;
    01016 }
    01017
    01022 static void RestoreTrainBackup(TrainList &list)
    01023 {
    01024   /* No train, nothing to do. */
    01025   if (list.Length() == 0) return;
    01026
    01027   Train *prev = NULL;
    01028   /* Iterate over the list and rebuild it. */
    01029   for (Train **iter = list.Begin(); iter != list.End(); iter++) {
    01030     Train *t = *iter;
    01031     if (prev != NULL) {
    01032       prev->SetNext(t);
    01033     } else if (t->Previous() != NULL) {
    01034       /* Make sure the head of the train is always the first in the chain. */
    01035       t->Previous()->SetNext(NULL);
    01036     }
    01037     prev = t;
    01038   }
    01039 }
    01040
    01046 static void RemoveFromConsist(Train *part, bool chain = false)
    01047 {
    01048   Train *tail = chain ? part->Last() : part->GetLastEnginePart();
    01049
    01050   /* Unlink at the front, but make it point to the next
    01051    * vehicle after the to be remove part. */
    01052   if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
    01053
    01054   /* Unlink at the back */
    01055   tail->SetNext(NULL);
    01056 }
    01057
    01063 static void InsertInConsist(Train *dst, Train *chain)
    01064 {
    01065   /* We do not want to add something in the middle of an articulated part. */
    01066   assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
    01067
    01068   chain->Last()->SetNext(dst->Next());
    01069   dst->SetNext(chain);
    01070 }
    01071
    01077 static void NormaliseDualHeads(Train *t)
    01078 {
    01079   for (; t != NULL; t = t->GetNextVehicle()) {
    01080     if (!t->IsMultiheaded() || !t->IsEngine()) continue;
    01081
    01082     /* Make sure that there are no free cars before next engine */
    01083     Train *u;
    01084     for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
    01085
    01086     if (u == t->other_multiheaded_part) continue;
    01087
    01088     /* Remove the part from the 'wrong' train */
    01089     RemoveFromConsist(t->other_multiheaded_part);
    01090     /* And add it to the 'right' train */
    01091     InsertInConsist(u, t->other_multiheaded_part);
    01092   }
    01093 }
    01094
    01099 static void NormaliseSubtypes(Train *chain)
    01100 {
    01101   /* Nothing to do */
    01102   if (chain == NULL) return;
    01103
    01104   /* We must be the first in the chain. */
    01105   assert(chain->Previous() == NULL);
    01106
    01107   /* Set the appropirate bits for the first in the chain. */
    01108   if (chain->IsWagon()) {
    01109     chain->SetFreeWagon();
    01110   } else {
    01111     assert(chain->IsEngine());
    01112     chain->SetFrontEngine();
    01113   }
    01114
    01115   /* Now clear the bits for the rest of the chain */
    01116   for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
    01117     t->ClearFreeWagon();
    01118     t->ClearFrontEngine();
    01119   }
    01120 }
    01121
    01131 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
    01132 {
    01133   /* Just add 'new' engines and substract the original ones.
    01134    * If that's less than or equal to 0 we can be sure we did
    01135    * not add any engines (read: trains) along the way. */
    01136   if ((src          != NULL && src->IsEngine()          ? 1 : 0) +
    01137       (dst          != NULL && dst->IsEngine()          ? 1 : 0) -
    01138       (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
    01139       (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
    01140     return CommandCost();
    01141   }
    01142
    01143   /* Get a free unit number and check whether it's within the bounds.
    01144    * There will always be a maximum of one new train. */
    01145   if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
    01146
    01147   return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
    01148 }
    01149
    01155 static CommandCost CheckTrainAttachment(Train *t)
    01156 {
    01157   /* No multi-part train, no need to check. */
    01158   if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
    01159
    01160   /* The maximum length for a train. For each part we decrease this by one
    01161    * and if the result is negative the train is simply too long. */
    01162   int allowed_len = _settings_game.vehicle.mammoth_trains ? 100 : 10;
    01163
    01164   Train *head = t;
    01165   Train *prev = t;
    01166
    01167   /* Break the prev -> t link so it always holds within the loop. */
    01168   t = t->Next();
    01169   allowed_len--;
    01170   prev->SetNext(NULL);
    01171
    01172   /* Make sure the cache is cleared. */
    01173   head->InvalidateNewGRFCache();
    01174
    01175   while (t != NULL) {
    01176     Train *next = t->Next();
    01177
    01178     /* Unlink the to-be-added piece; it is already unlinked from the previous
    01179      * part due to the fact that the prev -> t link is broken. */
    01180     t->SetNext(NULL);
    01181
    01182     /* Don't check callback for articulated or rear dual headed parts */
    01183     if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
    01184       allowed_len--; // We do not count articulated parts and rear heads either.
    01185
    01186       /* Back up and clear the first_engine data to avoid using wagon override group */
    01187       EngineID first_engine = t->tcache.first_engine;
    01188       t->tcache.first_engine = INVALID_ENGINE;
    01189
    01190       /* We don't want the cache to interfere. head's cache is cleared before
    01191        * the loop and after each callback does not need to be cleared here. */
    01192       t->InvalidateNewGRFCache();
    01193
    01194       uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
    01195
    01196       /* Restore original first_engine data */
    01197       t->tcache.first_engine = first_engine;
    01198
    01199       /* We do not want to remember any cached variables from the test run */
    01200       t->InvalidateNewGRFCache();
    01201       head->InvalidateNewGRFCache();
    01202
    01203       if (callback != CALLBACK_FAILED) {
    01204         /* A failing callback means everything is okay */
    01205         StringID error = STR_NULL;
    01206
    01207         if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
    01208         if (callback  < 0xFD) error = GetGRFStringID(GetEngineGRFID(head->engine_type), 0xD000 + callback);
    01209
    01210         if (error != STR_NULL) return_cmd_error(error);
    01211       }
    01212     }
    01213
    01214     /* And link it to the new part. */
    01215     prev->SetNext(t);
    01216     prev = t;
    01217     t = next;
    01218   }
    01219
    01220   if (allowed_len <= 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
    01221   return CommandCost();
    01222 }
    01223
    01234 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
    01235 {
    01236   /* Check whether we may actually construct the trains. */
    01237   CommandCost ret = CheckTrainAttachment(src);
    01238   if (ret.Failed()) return ret;
    01239   ret = CheckTrainAttachment(dst);
    01240   if (ret.Failed()) return ret;
    01241
    01242   /* Check whether we need to build a new train. */
    01243   return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
    01244 }
    01245
    01254 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
    01255 {
    01256   /* First determine the front of the two resulting trains */
    01257   if (*src_head == *dst_head) {
    01258     /* If we aren't moving part(s) to a new train, we are just moving the
    01259      * front back and there is not destination head. */
    01260     *dst_head = NULL;
    01261   } else if (*dst_head == NULL) {
    01262     /* If we are moving to a new train the head of the move train would become
    01263      * the head of the new vehicle. */
    01264     *dst_head = src;
    01265   }
    01266
    01267   if (src == *src_head) {
    01268     /* If we are moving the front of a train then we are, in effect, creating
    01269      * a new head for the train. Point to that. Unless we are moving the whole
    01270      * train in which case there is not 'source' train anymore.
    01271      * In case we are a multiheaded part we want the complete thing to come
    01272      * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
    01273      * that is followed by a rear multihead we do not want to include that. */
    01274     *src_head = move_chain ? NULL :
    01275         (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
    01276   }
    01277
    01278   /* Now it's just simply removing the part that we are going to move from the
    01279    * source train and *if* the destination is a not a new train add the chain
    01280    * at the destination location. */
    01281   RemoveFromConsist(src, move_chain);
    01282   if (*dst_head != src) InsertInConsist(dst, src);
    01283
    01284   /* Now normalise the dual heads, that is move the dual heads around in such
    01285    * a way that the head and rear of a dual head are in the same train */
    01286   NormaliseDualHeads(*src_head);
    01287   NormaliseDualHeads(*dst_head);
    01288 }
    01289
    01295 static void NormaliseTrainHead(Train *head)
    01296 {
    01297   /* Not much to do! */
    01298   if (head == NULL) return;
    01299
    01300   /* Tell the 'world' the train changed. */
    01301   head->ConsistChanged(false);
    01302   UpdateTrainGroupID(head);
    01303
    01304   /* Not a front engine, i.e. a free wagon chain. No need to do more. */
    01305   if (!head->IsFrontEngine()) return;
    01306
    01307   /* Update the refit button and window */
    01308   SetWindowDirty(WC_VEHICLE_REFIT, head->index);
    01309   SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, VVW_WIDGET_REFIT_VEH);
    01310
    01311   /* If we don't have a unit number yet, set one. */
    01312   if (head->unitnumber != 0) return;
    01313   head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
    01314 }
    01315
    01327 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01328 {
    01329   VehicleID s = GB(p1, 0, 16);
    01330   VehicleID d = GB(p1, 16, 16);
    01331   bool move_chain = HasBit(p2, 0);
    01332
    01333   Train *src = Train::GetIfValid(s);
    01334   if (src == NULL || !CheckOwnership(src->owner)) return CMD_ERROR;
    01335
    01336   /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
    01337   if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
    01338
    01339   /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
    01340   Train *dst;
    01341   if (d == INVALID_VEHICLE) {
    01342     dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
    01343   } else {
    01344     dst = Train::GetIfValid(d);
    01345     if (dst == NULL || !CheckOwnership(dst->owner)) return CMD_ERROR;
    01346
    01347     /* Do not allow appending to crashed vehicles, too */
    01348     if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
    01349   }
    01350
    01351   /* if an articulated part is being handled, deal with its parent vehicle */
    01352   src = src->GetFirstEnginePart();
    01353   if (dst != NULL) {
    01354     dst = dst->GetFirstEnginePart();
    01355   }
    01356
    01357   /* don't move the same vehicle.. */
    01358   if (src == dst) return CommandCost();
    01359
    01360   /* locate the head of the two chains */
    01361   Train *src_head = src->First();
    01362   Train *dst_head;
    01363   if (dst != NULL) {
    01364     dst_head = dst->First();
    01365     if (dst_head->tile != src_head->tile) return CMD_ERROR;
    01366     /* Now deal with articulated part of destination wagon */
    01367     dst = dst->GetLastEnginePart();
    01368   } else {
    01369     dst_head = NULL;
    01370   }
    01371
    01372   if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
    01373
    01374   /* When moving all wagons, we can't have the same src_head and dst_head */
    01375   if (move_chain && src_head == dst_head) return CommandCost();
    01376
    01377   /* When moving a multiheaded part to be place after itself, bail out. */
    01378   if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
    01379
    01380   /* Check if all vehicles in the source train are stopped inside a depot. */
    01381   if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
    01382
    01383   /* Check if all vehicles in the destination train are stopped inside a depot. */
    01384   if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
    01385
    01386   /* First make a backup of the order of the trains. That way we can do
    01387    * whatever we want with the order and later on easily revert. */
    01388   TrainList original_src;
    01389   TrainList original_dst;
    01390
    01391   MakeTrainBackup(original_src, src_head);
    01392   MakeTrainBackup(original_dst, dst_head);
    01393
    01394   /* Also make backup of the original heads as ArrangeTrains can change them.
    01395    * For the destination head we do not care if it is the same as the source
    01396    * head because in that case it's just a copy. */
    01397   Train *original_src_head = src_head;
    01398   Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
    01399
    01400   /* (Re)arrange the trains in the wanted arrangement. */
    01401   ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
    01402
    01403   if ((flags & DC_AUTOREPLACE) == 0) {
    01404     /* If the autoreplace flag is set we do not need to test for the validity
    01405      * because we are going to revert the train to its original state. As we
    01406      * assume the original state was correct autoreplace can skip this. */
    01407     CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
    01408     if (ret.Failed()) {
    01409       /* Restore the train we had. */
    01410       RestoreTrainBackup(original_src);
    01411       RestoreTrainBackup(original_dst);
    01412       return ret;
    01413     }
    01414   }
    01415
    01416   /* do it? */
    01417   if (flags & DC_EXEC) {
    01418     /* First normalise the sub types of the chains. */
    01419     NormaliseSubtypes(src_head);
    01420     NormaliseSubtypes(dst_head);
    01421
    01422     /* There are 14 different cases:
    01423      *  1) front engine gets moved to a new train, it stays a front engine.
    01424      *     a) the 'next' part is a wagon, that becomes a free wagon chain.
    01425      *     b) the 'next' part is an engine, that becomes a front engine.
    01426      *     c) there is no 'next' part, nothing else happens
    01427      *  2) front engine gets moved to another train, it is not a front engine anymore
    01428      *     a) the 'next' part is a wagon, that becomes a free wagon chain.
    01429      *     b) the 'next' part is an engine, that becomes a front engine.
    01430      *     c) there is no 'next' part, nothing else happens
    01431      *  3) front engine gets moved to later in the current train, it is not an engine anymore.
    01432      *     a) the 'next' part is a wagon, that becomes a free wagon chain.
    01433      *     b) the 'next' part is an engine, that becomes a front engine.
    01434      *  4) free wagon gets moved
    01435      *     a) the 'next' part is a wagon, that becomes a free wagon chain.
    01436      *     b) the 'next' part is an engine, that becomes a front engine.
    01437      *     c) there is no 'next' part, nothing else happens
    01438      *  5) non front engine gets moved and becomes a new train, nothing else happens
    01439      *  6) non front engine gets moved within a train / to another train, nothing hapens
    01440      *  7) wagon gets moved, nothing happens
    01441      */
    01442     if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
    01443       /* Cases #2 and #3: the front engine gets trashed. */
    01444       DeleteWindowById(WC_VEHICLE_VIEW, src->index);
    01445       DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
    01446       DeleteWindowById(WC_VEHICLE_REFIT, src->index);
    01447       DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
    01448       DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
    01449
    01450       /* We are going to be move to another train. So we
    01451        * are no part of this group anymore. In case we
    01452        * are not moving group... well, then we do not need
    01453        * to move.
    01454        * Or we are moving to later in the train and our
    01455        * new head isn't a front engine anymore.
    01456        */
    01457       if (dst_head != NULL ? dst_head != src : !src_head->IsFrontEngine()) {
    01458         DecreaseGroupNumVehicle(src->group_id);
    01459       }
    01460
    01461       /* Delete orders, group stuff and the unit number as we're not the
    01462        * front of any vehicle anymore. */
    01463       DeleteVehicleOrders(src);
    01464       RemoveVehicleFromGroup(src);
    01465       src->unitnumber = 0;
    01466     }
    01467
    01468     /* We weren't a front engine but are becoming one. So
    01469      * we should be put in the default group. */
    01470     if (original_src_head != src && dst_head == src) {
    01471       SetTrainGroupID(src, DEFAULT_GROUP);
    01472     }
    01473
    01474     /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
    01475     NormaliseTrainHead(src_head);
    01476     NormaliseTrainHead(dst_head);
    01477
    01478     /* We are undoubtedly changing something in the depot and train list. */
    01479     InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
    01480     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    01481   } else {
    01482     /* We don't want to execute what we're just tried. */
    01483     RestoreTrainBackup(original_src);
    01484     RestoreTrainBackup(original_dst);
    01485   }
    01486
    01487   return CommandCost();
    01488 }
    01489
    01501 CommandCost CmdSellRailWagon(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01502 {
    01503   /* Check if we deleted a vehicle window */
    01504   Window *w = NULL;
    01505
    01506   Train *v = Train::GetIfValid(p1);
    01507   if (v == NULL || !CheckOwnership(v->owner)) return CMD_ERROR;
    01508
    01509   /* Sell a chain of vehicles or not? */
    01510   bool sell_chain = HasBit(p2, 0);
    01511
    01512   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_CAN_T_SELL_DESTROYED_VEHICLE);
    01513
    01514   v = v->GetFirstEnginePart();
    01515   Train *first = v->First();
    01516
    01517   /* make sure the vehicle is stopped in the depot */
    01518   if (!first->IsStoppedInDepot()) {
    01519     return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
    01520   }
    01521
    01522   if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
    01523
    01524   /* First make a backup of the order of the train. That way we can do
    01525    * whatever we want with the order and later on easily revert. */
    01526   TrainList original;
    01527   MakeTrainBackup(original, first);
    01528
    01529   /* We need to keep track of the new head and the head of what we're going to sell. */
    01530   Train *new_head = first;
    01531   Train *sell_head = NULL;
    01532
    01533   /* Split the train in the wanted way. */
    01534   ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
    01535
    01536   /* We don't need to validate the second train; it's going to be sold. */
    01537   CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
    01538   if (ret.Failed()) {
    01539     /* Restore the train we had. */
    01540     RestoreTrainBackup(original);
    01541     return ret;
    01542   }
    01543
    01544   CommandCost cost(EXPENSES_NEW_VEHICLES);
    01545   for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
    01546
    01547   /* do it? */
    01548   if (flags & DC_EXEC) {
    01549     /* First normalise the sub types of the chain. */
    01550     NormaliseSubtypes(new_head);
    01551
    01552     if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
    01553       /* We are selling the front engine. In this case we want to
    01554        * 'give' the order, unitnumber and such to the new head. */
    01555       new_head->orders.list = first->orders.list;
    01556       new_head->AddToShared(first);
    01557       DeleteVehicleOrders(first);
    01558
    01559       /* Copy other important data from the front engine */
    01560       new_head->CopyVehicleConfigAndStatistics(first);
    01561       IncreaseGroupNumVehicle(new_head->group_id);
    01562
    01563       /* If we deleted a window then open a new one for the 'new' train */
    01564       if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_head);
    01565     }
    01566
    01567     /* We need to update the information about the train. */
    01568     NormaliseTrainHead(new_head);
    01569
    01570     /* We are undoubtedly changing something in the depot and train list. */
    01571     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    01572     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    01573
    01574     /* Actually delete the sold 'goods' */
    01575     delete sell_head;
    01576   } else {
    01577     /* We don't want to execute what we're just tried. */
    01578     RestoreTrainBackup(original);
    01579   }
    01580
    01581   return cost;
    01582 }
    01583
    01584 void Train::UpdateDeltaXY(Direction direction)
    01585 {
    01586 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
    01587   static const uint32 _delta_xy_table[8] = {
    01588     MKIT(3, 3, -1, -1),
    01589     MKIT(3, 7, -1, -3),
    01590     MKIT(3, 3, -1, -1),
    01591     MKIT(7, 3, -3, -1),
    01592     MKIT(3, 3, -1, -1),
    01593     MKIT(3, 7, -1, -3),
    01594     MKIT(3, 3, -1, -1),
    01595     MKIT(7, 3, -3, -1),
    01596   };
    01597 #undef MKIT
    01598
    01599   uint32 x = _delta_xy_table[direction];
    01600   this->x_offs        = GB(x,  0, 8);
    01601   this->y_offs        = GB(x,  8, 8);
    01602   this->x_extent      = GB(x, 16, 8);
    01603   this->y_extent      = GB(x, 24, 8);
    01604   this->z_extent      = 6;
    01605 }
    01606
    01607 static inline void SetLastSpeed(Train *v, int spd)
    01608 {
    01609   int old = v->tcache.last_speed;
    01610   if (spd != old) {
    01611     v->tcache.last_speed = spd;
    01612     if (_settings_client.gui.vehicle_speed || (old == 0) != (spd == 0)) {
    01613       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01614     }
    01615   }
    01616 }
    01617
    01619 static void MarkTrainAsStuck(Train *v)
    01620 {
    01621   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
    01622     /* It is the first time the problem occured, set the "train stuck" flag. */
    01623     SetBit(v->flags, VRF_TRAIN_STUCK);
    01624
    01625     v->wait_counter = 0;
    01626
    01627     /* Stop train */
    01628     v->cur_speed = 0;
    01629     v->subspeed = 0;
    01630     SetLastSpeed(v, 0);
    01631
    01632     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01633   }
    01634 }
    01635
    01636 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
    01637 {
    01638   uint16 flag1 = *swap_flag1;
    01639   uint16 flag2 = *swap_flag2;
    01640
    01641   /* Clear the flags */
    01642   ClrBit(*swap_flag1, VRF_GOINGUP);
    01643   ClrBit(*swap_flag1, VRF_GOINGDOWN);
    01644   ClrBit(*swap_flag2, VRF_GOINGUP);
    01645   ClrBit(*swap_flag2, VRF_GOINGDOWN);
    01646
    01647   /* Reverse the rail-flags (if needed) */
    01648   if (HasBit(flag1, VRF_GOINGUP)) {
    01649     SetBit(*swap_flag2, VRF_GOINGDOWN);
    01650   } else if (HasBit(flag1, VRF_GOINGDOWN)) {
    01651     SetBit(*swap_flag2, VRF_GOINGUP);
    01652   }
    01653   if (HasBit(flag2, VRF_GOINGUP)) {
    01654     SetBit(*swap_flag1, VRF_GOINGDOWN);
    01655   } else if (HasBit(flag2, VRF_GOINGDOWN)) {
    01656     SetBit(*swap_flag1, VRF_GOINGUP);
    01657   }
    01658 }
    01659
    01660 static void ReverseTrainSwapVeh(Train *v, int l, int r)
    01661 {
    01662   Train *a, *b;
    01663
    01664   /* locate vehicles to swap */
    01665   for (a = v; l != 0; l--) a = a->Next();
    01666   for (b = v; r != 0; r--) b = b->Next();
    01667
    01668   if (a != b) {
    01669     /* swap the hidden bits */
    01670     {
    01671       uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus&VS_HIDDEN);
    01672       b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus&VS_HIDDEN);
    01673       a->vehstatus = tmp;
    01674     }
    01675
    01676     Swap(a->track, b->track);
    01677     Swap(a->direction,    b->direction);
    01678
    01679     /* toggle direction */
    01680     if (a->track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
    01681     if (b->track != TRACK_BIT_DEPOT) b->direction = ReverseDir(b->direction);
    01682
    01683     Swap(a->x_pos, b->x_pos);
    01684     Swap(a->y_pos, b->y_pos);
    01685     Swap(a->tile,  b->tile);
    01686     Swap(a->z_pos, b->z_pos);
    01687
    01688     SwapTrainFlags(&a->flags, &b->flags);
    01689
    01690     /* update other vars */
    01691     a->UpdateViewport(true, true);
    01692     b->UpdateViewport(true, true);
    01693
    01694     /* call the proper EnterTile function unless we are in a wormhole */
    01695     if (a->track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
    01696     if (b->track != TRACK_BIT_WORMHOLE) VehicleEnterTile(b, b->tile, b->x_pos, b->y_pos);
    01697   } else {
    01698     if (a->track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
    01699     a->UpdateViewport(true, true);
    01700
    01701     if (a->track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
    01702   }
    01703
    01704   /* Update train's power incase tiles were different rail type */
    01705   v->RailtypeChanged();
    01706 }
    01707
    01708
    01714 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
    01715 {
    01716   return (v->type == VEH_TRAIN) ? v : NULL;
    01717 }
    01718
    01719
    01726 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
    01727 {
    01728   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
    01729
    01730   Train *t = Train::From(v);
    01731   if (!t->IsFrontEngine()) return NULL;
    01732
    01733   TileIndex tile = *(TileIndex *)data;
    01734
    01735   if (TrainApproachingCrossingTile(t) != tile) return NULL;
    01736
    01737   return t;
    01738 }
    01739
    01740
    01747 static bool TrainApproachingCrossing(TileIndex tile)
    01748 {
    01749   assert(IsLevelCrossingTile(tile));
    01750
    01751   DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
    01752   TileIndex tile_from = tile + TileOffsByDiagDir(dir);
    01753
    01754   if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
    01755
    01756   dir = ReverseDiagDir(dir);
    01757   tile_from = tile + TileOffsByDiagDir(dir);
    01758
    01759   return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
    01760 }
    01761
    01762
    01769 void UpdateLevelCrossing(TileIndex tile, bool sound)
    01770 {
    01771   assert(IsLevelCrossingTile(tile));
    01772
    01773   /* train on crossing || train approaching crossing || reserved */
    01774   bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
    01775
    01776   if (new_state != IsCrossingBarred(tile)) {
    01777     if (new_state && sound) {
    01778       SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
    01779     }
    01780     SetCrossingBarred(tile, new_state);
    01781     MarkTileDirtyByTile(tile);
    01782   }
    01783 }
    01784
    01785
    01791 static inline void MaybeBarCrossingWithSound(TileIndex tile)
    01792 {
    01793   if (!IsCrossingBarred(tile)) {
    01794     BarCrossing(tile);
    01795     SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
    01796     MarkTileDirtyByTile(tile);
    01797   }
    01798 }
    01799
    01800
    01806 static void AdvanceWagonsBeforeSwap(Train *v)
    01807 {
    01808   Train *base = v;
    01809   Train *first = base; // first vehicle to move
    01810   Train *last = v->Last(); // last vehicle to move
    01811   uint length = CountVehiclesInChain(v);
    01812
    01813   while (length > 2) {
    01814     last = last->Previous();
    01815     first = first->Next();
    01816
    01817     int differential = base->tcache.cached_veh_length - last->tcache.cached_veh_length;
    01818
    01819     /* do not update images now
    01820      * negative differential will be handled in AdvanceWagonsAfterSwap() */
    01821     for (int i = 0; i < differential; i++) TrainController(first, last->Next());
    01822
    01823     base = first; // == base->Next()
    01824     length -= 2;
    01825   }
    01826 }
    01827
    01828
    01834 static void AdvanceWagonsAfterSwap(Train *v)
    01835 {
    01836   /* first of all, fix the situation when the train was entering a depot */
    01837   Train *dep = v; // last vehicle in front of just left depot
    01838   while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
    01839     dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
    01840   }
    01841
    01842   Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
    01843
    01844   if (leave != NULL) {
    01845     /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
    01846     int d = TicksToLeaveDepot(dep);
    01847
    01848     if (d <= 0) {
    01849       leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
    01850       leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
    01851       for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
    01852     }
    01853   } else {
    01854     dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
    01855   }
    01856
    01857   Train *base = v;
    01858   Train *first = base; // first vehicle to move
    01859   Train *last = v->Last(); // last vehicle to move
    01860   uint length = CountVehiclesInChain(v);
    01861
    01862   /* we have to make sure all wagons that leave a depot because of train reversing are moved coorectly
    01863    * they have already correct spacing, so we have to make sure they are moved how they should */
    01864   bool nomove = (dep == NULL); // if there is no vehicle leaving a depot, limit the number of wagons moved immediatelly
    01865
    01866   while (length > 2) {
    01867     /* we reached vehicle (originally) in front of a depot, stop now
    01868      * (we would move wagons that are alredy moved with new wagon length) */
    01869     if (base == dep) break;
    01870
    01871     /* the last wagon was that one leaving a depot, so do not move it anymore */
    01872     if (last == dep) nomove = true;
    01873
    01874     last = last->Previous();
    01875     first = first->Next();
    01876
    01877     int differential = last->tcache.cached_veh_length - base->tcache.cached_veh_length;
    01878
    01879     /* do not update images now */
    01880     for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
    01881
    01882     base = first; // == base->Next()
    01883     length -= 2;
    01884   }
    01885 }
    01886
    01887
    01888 static void ReverseTrainDirection(Train *v)
    01889 {
    01890   if (IsRailDepotTile(v->tile)) {
    01891     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    01892   }
    01893
    01894   /* Clear path reservation in front if train is not stuck. */
    01895   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
    01896
    01897   /* Check if we were approaching a rail/road-crossing */
    01898   TileIndex crossing = TrainApproachingCrossingTile(v);
    01899
    01900   /* count number of vehicles */
    01901   int r = CountVehiclesInChain(v) - 1;  // number of vehicles - 1
    01902
    01903   AdvanceWagonsBeforeSwap(v);
    01904
    01905   /* swap start<>end, start+1<>end-1, ... */
    01906   int l = 0;
    01907   do {
    01908     ReverseTrainSwapVeh(v, l++, r--);
    01909   } while (l <= r);
    01910
    01911   AdvanceWagonsAfterSwap(v);
    01912
    01913   if (IsRailDepotTile(v->tile)) {
    01914     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    01915   }
    01916
    01917   ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
    01918
    01919   ClrBit(v->flags, VRF_REVERSING);
    01920
    01921   /* recalculate cached data */
    01922   v->ConsistChanged(true);
    01923
    01924   /* update all images */
    01925   for (Vehicle *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
    01926
    01927   /* update crossing we were approaching */
    01928   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
    01929
    01930   /* maybe we are approaching crossing now, after reversal */
    01931   crossing = TrainApproachingCrossingTile(v);
    01932   if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
    01933
    01934   /* If we are inside a depot after reversing, don't bother with path reserving. */
    01935   if (v->track == TRACK_BIT_DEPOT) {
    01936     /* Can't be stuck here as inside a depot is always a safe tile. */
    01937     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    01938     ClrBit(v->flags, VRF_TRAIN_STUCK);
    01939     return;
    01940   }
    01941
    01942   /* TrainExitDir does not always produce the desired dir for depots and
    01943    * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
    01944   DiagDirection dir = TrainExitDir(v->direction, v->track);
    01945   if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
    01946
    01947   if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
    01948     /* If we are currently on a tile with conventional signals, we can't treat the
    01949      * current tile as a safe tile or we would enter a PBS block without a reservation. */
    01950     bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
    01951       HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
    01952       !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
    01953
    01954     if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
    01955     if (TryPathReserve(v, false, first_tile_okay)) {
    01956       /* Do a look-ahead now in case our current tile was already a safe tile. */
    01957       CheckNextTrainTile(v);
    01958     } else if (v->current_order.GetType() != OT_LOADING) {
    01959       /* Do not wait for a way out when we're still loading */
    01960       MarkTrainAsStuck(v);
    01961     }
    01962   } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
    01963     /* A train not inside a PBS block can't be stuck. */
    01964     ClrBit(v->flags, VRF_TRAIN_STUCK);
    01965     v->wait_counter = 0;
    01966   }
    01967 }
    01968
    01977 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01978 {
    01979   Train *v = Train::GetIfValid(p1);
    01980   if (v == NULL || !CheckOwnership(v->owner)) return CMD_ERROR;
    01981
    01982   if (p2 != 0) {
    01983     /* turn a single unit around */
    01984
    01985     if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
    01986       return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
    01987     }
    01988
    01989     Train *front = v->First();
    01990     /* make sure the vehicle is stopped in the depot */
    01991     if (!front->IsStoppedInDepot()) {
    01992       return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
    01993     }
    01994
    01995     if (flags & DC_EXEC) {
    01996       ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
    01997       SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    01998       SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
    01999       /* We cancel any 'skip signal at dangers' here */
    02000       v->force_proceed = 0;
    02001       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    02002     }
    02003   } else {
    02004     /* turn the whole train around */
    02005     if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
    02006
    02007     if (flags & DC_EXEC) {
    02008       /* Properly leave the station if we are loading and won't be loading anymore */
    02009       if (v->current_order.IsType(OT_LOADING)) {
    02010         const Vehicle *last = v;
    02011         while (last->Next() != NULL) last = last->Next();
    02012
    02013         /* not a station || different station --> leave the station */
    02014         if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
    02015           v->LeaveStation();
    02016         }
    02017       }
    02018
    02019       /* We cancel any 'skip signal at dangers' here */
    02020       v->force_proceed = 0;
    02021       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    02022
    02023       if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
    02024         ToggleBit(v->flags, VRF_REVERSING);
    02025       } else {
    02026         v->cur_speed = 0;
    02027         SetLastSpeed(v, 0);
    02028         HideFillingPercent(&v->fill_percent_te_id);
    02029         ReverseTrainDirection(v);
    02030       }
    02031     }
    02032   }
    02033   return CommandCost();
    02034 }
    02035
    02044 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02045 {
    02046   Train *t = Train::GetIfValid(p1);
    02047   if (t == NULL || !CheckOwnership(t->owner)) return CMD_ERROR;
    02048
    02049   if (flags & DC_EXEC) {
    02050     /* If we are forced to proceed, cancel that order.
    02051      * If we are marked stuck we would want to force the train
    02052      * to proceed to the next signal. In the other cases we
    02053      * would like to pass the signal at danger and run till the
    02054      * next signal we encounter. */
    02055     t->force_proceed = t->force_proceed == 2 ? 0 : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsInDepot() ? 1 : 2;
    02056     SetWindowDirty(WC_VEHICLE_VIEW, t->index);
    02057   }
    02058
    02059   return CommandCost();
    02060 }
    02061
    02073 CommandCost CmdRefitRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02074 {
    02075   CargoID new_cid = GB(p2, 0, 8);
    02076   byte new_subtype = GB(p2, 8, 8);
    02077   bool only_this = HasBit(p2, 16);
    02078
    02079   Train *v = Train::GetIfValid(p1);
    02080   if (v == NULL || !CheckOwnership(v->owner)) return CMD_ERROR;
    02081
    02082   if (!v->IsStoppedInDepot()) return_cmd_error(STR_TRAIN_MUST_BE_STOPPED);
    02083   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_CAN_T_REFIT_DESTROYED_VEHICLE);
    02084
    02085   /* Check cargo */
    02086   if (new_cid >= NUM_CARGO) return CMD_ERROR;
    02087
    02088   CommandCost cost = RefitVehicle(v, only_this, new_cid, new_subtype, flags);
    02089
    02090   /* Update the train's cached variables */
    02091   if (flags & DC_EXEC) {
    02092     Train *front = v->First();
    02093     front->ConsistChanged(false);
    02094     SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
    02095     SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
    02096     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
    02097   } else {
    02098     v->InvalidateNewGRFCacheOfChain(); // always invalidate; querycost might have filled it
    02099   }
    02100
    02101   return cost;
    02102 }
    02103
    02106 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
    02107 {
    02108   assert(!(v->vehstatus & VS_CRASHED));
    02109
    02110   if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
    02111
    02112   PBSTileInfo origin = FollowTrainReservation(v);
    02113   if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
    02114
    02115   switch (_settings_game.pf.pathfinder_for_trains) {
    02116     case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
    02117     case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
    02118
    02119     default: NOT_REACHED();
    02120   }
    02121 }
    02122
    02123 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
    02124 {
    02125   FindDepotData tfdd = FindClosestTrainDepot(this, 0);
    02126   if (tfdd.best_length == UINT_MAX) return false;
    02127
    02128   if (location    != NULL) *location    = tfdd.tile;
    02129   if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
    02130   if (reverse     != NULL) *reverse     = tfdd.reverse;
    02131
    02132   return true;
    02133 }
    02134
    02145 CommandCost CmdSendTrainToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02146 {
    02147   if (p2 & DEPOT_MASS_SEND) {
    02148     /* Mass goto depot requested */
    02149     if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
    02150     return SendAllVehiclesToDepot(VEH_TRAIN, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
    02151   }
    02152
    02153   Train *v = Train::GetIfValid(p1);
    02154   if (v == NULL) return CMD_ERROR;
    02155
    02156   return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
    02157 }
    02158
    02159 static const int8 _vehicle_smoke_pos[8] = {
    02160   1, 1, 1, 0, -1, -1, -1, 0
    02161 };
    02162
    02163 static void HandleLocomotiveSmokeCloud(const Train *v)
    02164 {
    02165   bool sound = false;
    02166
    02167   if ((v->vehstatus & VS_TRAIN_SLOWING) || v->cur_speed < 2) {
    02168     return;
    02169   }
    02170
    02171   const Train *u = v;
    02172
    02173   do {
    02174     const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
    02175     int effect_offset = GB(v->tcache.cached_vis_effect, 0, 4) - 8;
    02176     byte effect_type = GB(v->tcache.cached_vis_effect, 4, 2);
    02177     bool disable_effect = HasBit(v->tcache.cached_vis_effect, 6);
    02178
    02179     /* no smoke? */
    02180     if ((rvi->railveh_type == RAILVEH_WAGON && effect_type == 0) ||
    02181         disable_effect ||
    02182         v->vehstatus & VS_HIDDEN) {
    02183       continue;
    02184     }
    02185
    02186     /* No smoke in depots or tunnels */
    02187     if (IsRailDepotTile(v->tile) || IsTunnelTile(v->tile)) continue;
    02188
    02189     /* No sparks for electric vehicles on nonelectrified tracks */
    02190     if (!HasPowerOnRail(v->railtype, GetTileRailType(v->tile))) continue;
    02191
    02192     if (effect_type == 0) {
    02193       /* Use default effect type for engine class. */
    02194       effect_type = rvi->engclass;
    02195     } else {
    02196       effect_type--;
    02197     }
    02198
    02199     int x = _vehicle_smoke_pos[v->direction] * effect_offset;
    02200     int y = _vehicle_smoke_pos[(v->direction + 2) % 8] * effect_offset;
    02201
    02202     if (HasBit(v->flags, VRF_REVERSE_DIRECTION)) {
    02203       x = -x;
    02204       y = -y;
    02205     }
    02206
    02207     switch (effect_type) {
    02208       case 0:
    02209         /* steam smoke. */
    02210         if (GB(v->tick_counter, 0, 4) == 0) {
    02211           CreateEffectVehicleRel(v, x, y, 10, EV_STEAM_SMOKE);
    02212           sound = true;
    02213         }
    02214         break;
    02215
    02216       case 1:
    02217         /* diesel smoke */
    02218         if (u->cur_speed <= 40 && Chance16(15, 128)) {
    02219           CreateEffectVehicleRel(v, 0, 0, 10, EV_DIESEL_SMOKE);
    02220           sound = true;
    02221         }
    02222         break;
    02223
    02224       case 2:
    02225         /* blue spark */
    02226         if (GB(v->tick_counter, 0, 2) == 0 && Chance16(1, 45)) {
    02227           CreateEffectVehicleRel(v, 0, 0, 10, EV_ELECTRIC_SPARK);
    02228           sound = true;
    02229         }
    02230         break;
    02231
    02232       default:
    02233         break;
    02234     }
    02235   } while ((v = v->Next()) != NULL);
    02236
    02237   if (sound) PlayVehicleSound(u, VSE_TRAIN_EFFECT);
    02238 }
    02239
    02240 void Train::PlayLeaveStationSound() const
    02241 {
    02242   static const SoundFx sfx[] = {
    02243     SND_04_TRAIN,
    02244     SND_0A_TRAIN_HORN,
    02245     SND_0A_TRAIN_HORN,
    02246     SND_47_MAGLEV_2,
    02247     SND_41_MAGLEV
    02248   };
    02249
    02250   if (PlayVehicleSound(this, VSE_START)) return;
    02251
    02252   EngineID engtype = this->engine_type;
    02253   SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
    02254 }
    02255
    02257 static void CheckNextTrainTile(Train *v)
    02258 {
    02259   /* Don't do any look-ahead if path_backoff_interval is 255. */
    02260   if (_settings_game.pf.path_backoff_interval == 255) return;
    02261
    02262   /* Exit if we reached our destination depot or are inside a depot. */
    02263   if ((v->tile == v->dest_tile && v->current_order.IsType(OT_GOTO_DEPOT)) || v->track == TRACK_BIT_DEPOT) return;
    02264   /* Exit if we are on a station tile and are going to stop. */
    02265   if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
    02266   /* If we reached our waypoint, make sure we see that. */
    02267   if (v->current_order.IsType(OT_GOTO_WAYPOINT) && IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
    02268   /* Exit if the current order doesn't have a destination, but the train has orders. */
    02269   if ((v->current_order.IsType(OT_NOTHING) || v->current_order.IsType(OT_LEAVESTATION) || v->current_order.IsType(OT_LOADING)) && v->GetNumOrders() > 0) return;
    02270
    02271   Trackdir td = v->GetVehicleTrackdir();
    02272
    02273   /* On a tile with a red non-pbs signal, don't look ahead. */
    02274   if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
    02275       !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
    02276       GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
    02277
    02278   CFollowTrackRail ft(v);
    02279   if (!ft.Follow(v->tile, td)) return;
    02280
    02281   if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
    02282     /* Next tile is not reserved. */
    02283     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
    02284       if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
    02285         /* If the next tile is a PBS signal, try to make a reservation. */
    02286         TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
    02287         if (_settings_game.pf.forbid_90_deg) {
    02288           tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
    02289         }
    02290         ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
    02291       }
    02292     }
    02293   }
    02294 }
    02295
    02296 static bool CheckTrainStayInDepot(Train *v)
    02297 {
    02298   /* bail out if not all wagons are in the same depot or not in a depot at all */
    02299   for (const Train *u = v; u != NULL; u = u->Next()) {
    02300     if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
    02301   }
    02302
    02303   /* if the train got no power, then keep it in the depot */
    02304   if (v->tcache.cached_power == 0) {
    02305     v->vehstatus |= VS_STOPPED;
    02306     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    02307     return true;
    02308   }
    02309
    02310   SigSegState seg_state;
    02311
    02312   if (v->force_proceed == 0) {
    02313     /* force proceed was not pressed */
    02314     if (++v->wait_counter < 37) {
    02315       SetWindowClassesDirty(WC_TRAINS_LIST);
    02316       return true;
    02317     }
    02318
    02319     v->wait_counter = 0;
    02320
    02321     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02322     if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
    02323       /* Full and no PBS signal in block or depot reserved, can't exit. */
    02324       SetWindowClassesDirty(WC_TRAINS_LIST);
    02325       return true;
    02326     }
    02327   } else {
    02328     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02329   }
    02330
    02331   /* We are leaving a depot, but have to go to the exact same one; re-enter */
    02332   if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
    02333     /* We need to have a reservation for this to work. */
    02334     if (HasDepotReservation(v->tile)) return true;
    02335     SetDepotReservation(v->tile, true);
    02336     VehicleEnterDepot(v);
    02337     return true;
    02338   }
    02339
    02340   /* Only leave when we can reserve a path to our destination. */
    02341   if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == 0) {
    02342     /* No path and no force proceed. */
    02343     SetWindowClassesDirty(WC_TRAINS_LIST);
    02344     MarkTrainAsStuck(v);
    02345     return true;
    02346   }
    02347
    02348   SetDepotReservation(v->tile, true);
    02349   if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
    02350
    02351   VehicleServiceInDepot(v);
    02352   SetWindowClassesDirty(WC_TRAINS_LIST);
    02353   v->PlayLeaveStationSound();
    02354
    02355   v->track = TRACK_BIT_X;
    02356   if (v->direction & 2) v->track = TRACK_BIT_Y;
    02357
    02358   v->vehstatus &= ~VS_HIDDEN;
    02359   v->cur_speed = 0;
    02360
    02361   v->UpdateDeltaXY(v->direction);
    02362   v->cur_image = v->GetImage(v->direction);
    02363   VehicleMove(v, false);
    02364   UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02365   v->UpdateAcceleration();
    02366   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    02367
    02368   return false;
    02369 }
    02370
    02372 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
    02373 {
    02374   DiagDirection dir = TrackdirToExitdir(track_dir);
    02375
    02376   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    02377     /* Are we just leaving a tunnel/bridge? */
    02378     if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
    02379       TileIndex end = GetOtherTunnelBridgeEnd(tile);
    02380
    02381       if (!HasVehicleOnTunnelBridge(tile, end, v)) {
    02382         /* Free the reservation only if no other train is on the tiles. */
    02383         SetTunnelBridgeReservation(tile, false);
    02384         SetTunnelBridgeReservation(end, false);
    02385
    02386         if (_settings_client.gui.show_track_reservation) {
    02387           MarkTileDirtyByTile(tile);
    02388           MarkTileDirtyByTile(end);
    02389         }
    02390       }
    02391     }
    02392   } else if (IsRailStationTile(tile)) {
    02393     TileIndex new_tile = TileAddByDiagDir(tile, dir);
    02394     /* If the new tile is not a further tile of the same station, we
    02395      * clear the reservation for the whole platform. */
    02396     if (!IsCompatibleTrainStationTile(new_tile, tile)) {
    02397       SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
    02398     }
    02399   } else {
    02400     /* Any other tile */
    02401     UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
    02402   }
    02403 }
    02404
    02406 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
    02407 {
    02408   assert(v->IsFrontEngine());
    02409
    02410   TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
    02411   Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
    02412   bool      free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
    02413   StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
    02414
    02415   /* Don't free reservation if it's not ours. */
    02416   if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
    02417
    02418   CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
    02419   while (ft.Follow(tile, td)) {
    02420     tile = ft.m_new_tile;
    02421     TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
    02422     td = RemoveFirstTrackdir(&bits);
    02423     assert(bits == TRACKDIR_BIT_NONE);
    02424
    02425     if (!IsValidTrackdir(td)) break;
    02426
    02427     if (IsTileType(tile, MP_RAILWAY)) {
    02428       if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
    02429         /* Conventional signal along trackdir: remove reservation and stop. */
    02430         UnreserveRailTrack(tile, TrackdirToTrack(td));
    02431         break;
    02432       }
    02433       if (HasPbsSignalOnTrackdir(tile, td)) {
    02434         if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
    02435           /* Red PBS signal? Can't be our reservation, would be green then. */
    02436           break;
    02437         } else {
    02438           /* Turn the signal back to red. */
    02439           SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
    02440           MarkTileDirtyByTile(tile);
    02441         }
    02442       } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
    02443         break;
    02444       }
    02445     }
    02446
    02447     /* Don't free first station/bridge/tunnel if we are on it. */
    02448     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);
    02449
    02450     free_tile = true;
    02451   }
    02452 }
    02453
    02454 static const byte _initial_tile_subcoord[6][4][3] = {
    02455 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
    02456 {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
    02457 {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
    02458 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
    02459 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
    02460 {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
    02461 };
    02462
    02475 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool do_track_reservation, PBSTileInfo *dest)
    02476 {
    02477   switch (_settings_game.pf.pathfinder_for_trains) {
    02478     case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
    02479     case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
    02480
    02481     default: NOT_REACHED();
    02482   }
    02483 }
    02484
    02490 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
    02491 {
    02492   PBSTileInfo origin = FollowTrainReservation(v);
    02493
    02494   CFollowTrackRail ft(v);
    02495
    02496   TileIndex tile = origin.tile;
    02497   Trackdir  cur_td = origin.trackdir;
    02498   while (ft.Follow(tile, cur_td)) {
    02499     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
    02500       /* Possible signal tile. */
    02501       if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
    02502     }
    02503
    02504     if (_settings_game.pf.forbid_90_deg) {
    02505       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
    02506       if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
    02507     }
    02508
    02509     /* Station, depot or waypoint are a possible target. */
    02510     bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
    02511     if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
    02512       /* Choice found or possible target encountered.
    02513        * On finding a possible target, we need to stop and let the pathfinder handle the
    02514        * remaining path. This is because we don't know if this target is in one of our
    02515        * orders, so we might cause pathfinding to fail later on if we find a choice.
    02516        * This failure would cause a bogous call to TryReserveSafePath which might reserve
    02517        * a wrong path not leading to our next destination. */
    02518       if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
    02519
    02520       /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
    02521        * actually starts its search at the first unreserved tile. */
    02522       if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
    02523
    02524       /* Choice found, path valid but not okay. Save info about the choice tile as well. */
    02525       if (new_tracks) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
    02526       if (enterdir) *enterdir = ft.m_exitdir;
    02527       return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
    02528     }
    02529
    02530     tile = ft.m_new_tile;
    02531     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
    02532
    02533     if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
    02534       bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
    02535       if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
    02536       /* Safe position is all good, path valid and okay. */
    02537       return PBSTileInfo(tile, cur_td, true);
    02538     }
    02539
    02540     if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
    02541   }
    02542
    02543   if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
    02544     /* End of line, path valid and okay. */
    02545     return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
    02546   }
    02547
    02548   /* Sorry, can't reserve path, back out. */
    02549   tile = origin.tile;
    02550   cur_td = origin.trackdir;
    02551   TileIndex stopped = ft.m_old_tile;
    02552   Trackdir  stopped_td = ft.m_old_td;
    02553   while (tile != stopped || cur_td != stopped_td) {
    02554     if (!ft.Follow(tile, cur_td)) break;
    02555
    02556     if (_settings_game.pf.forbid_90_deg) {
    02557       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
    02558       assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
    02559     }
    02560     assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
    02561
    02562     tile = ft.m_new_tile;
    02563     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
    02564
    02565     UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
    02566   }
    02567
    02568   /* Path invalid. */
    02569   return PBSTileInfo();
    02570 }
    02571
    02582 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
    02583 {
    02584   switch (_settings_game.pf.pathfinder_for_trains) {
    02585     case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
    02586     case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
    02587
    02588     default: NOT_REACHED();
    02589   }
    02590 }
    02591
    02593 class VehicleOrderSaver
    02594 {
    02595 private:
    02596   Vehicle        *v;
    02597   Order          old_order;
    02598   TileIndex      old_dest_tile;
    02599   StationID      old_last_station_visited;
    02600   VehicleOrderID index;
    02601
    02602 public:
    02603   VehicleOrderSaver(Vehicle *_v) :
    02604     v(_v),
    02605     old_order(_v->current_order),
    02606     old_dest_tile(_v->dest_tile),
    02607     old_last_station_visited(_v->last_station_visited),
    02608     index(_v->cur_order_index)
    02609   {
    02610   }
    02611
    02612   ~VehicleOrderSaver()
    02613   {
    02614     this->v->current_order = this->old_order;
    02615     this->v->dest_tile = this->old_dest_tile;
    02616     this->v->last_station_visited = this->old_last_station_visited;
    02617   }
    02618
    02624   bool SwitchToNextOrder(bool skip_first)
    02625   {
    02626     if (this->v->GetNumOrders() == 0) return false;
    02627
    02628     if (skip_first) ++this->index;
    02629
    02630     int conditional_depth = 0;
    02631
    02632     do {
    02633       /* Wrap around. */
    02634       if (this->index >= this->v->GetNumOrders()) this->index = 0;
    02635
    02636       Order *order = this->v->GetOrder(this->index);
    02637       assert(order != NULL);
    02638
    02639       switch (order->GetType()) {
    02640         case OT_GOTO_DEPOT:
    02641           /* Skip service in depot orders when the train doesn't need service. */
    02642           if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
    02643         case OT_GOTO_STATION:
    02644         case OT_GOTO_WAYPOINT:
    02645           this->v->current_order = *order;
    02646           UpdateOrderDest(this->v, order);
    02647           return true;
    02648         case OT_CONDITIONAL: {
    02649           if (conditional_depth > this->v->GetNumOrders()) return false;
    02650           VehicleOrderID next = ProcessConditionalOrder(order, this->v);
    02651           if (next != INVALID_VEH_ORDER_ID) {
    02652             conditional_depth++;
    02653             this->index = next;
    02654             /* Don't increment next, so no break here. */
    02655             continue;
    02656           }
    02657           break;
    02658         }
    02659         default:
    02660           break;
    02661       }
    02662       /* Don't increment inside the while because otherwise conditional
    02663        * orders can lead to an infinite loop. */
    02664       ++this->index;
    02665     } while (this->index != this->v->cur_order_index);
    02666
    02667     return false;
    02668   }
    02669 };
    02670
    02671 /* choose a track */
    02672 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
    02673 {
    02674   Track best_track = INVALID_TRACK;
    02675   bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
    02676   bool changed_signal = false;
    02677
    02678   assert((tracks & ~TRACK_BIT_MASK) == 0);
    02679
    02680   if (got_reservation != NULL) *got_reservation = false;
    02681
    02682   /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
    02683   TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
    02684   /* Do we have a suitable reserved track? */
    02685   if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
    02686
    02687   /* Quick return in case only one possible track is available */
    02688   if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
    02689     Track track = FindFirstTrack(tracks);
    02690     /* We need to check for signals only here, as a junction tile can't have signals. */
    02691     if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
    02692       do_track_reservation = true;
    02693       changed_signal = true;
    02694       SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
    02695     } else if (!do_track_reservation) {
    02696       return track;
    02697     }
    02698     best_track = track;
    02699   }
    02700
    02701   PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
    02702   DiagDirection dest_enterdir = enterdir;
    02703   if (do_track_reservation) {
    02704     /* Check if the train needs service here, so it has a chance to always find a depot.
    02705      * Also check if the current order is a service order so we don't reserve a path to
    02706      * the destination but instead to the next one if service isn't needed. */
    02707     CheckIfTrainNeedsService(v);
    02708     if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
    02709
    02710     res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
    02711     if (res_dest.tile == INVALID_TILE) {
    02712       /* Reservation failed? */
    02713       if (mark_stuck) MarkTrainAsStuck(v);
    02714       if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
    02715       return FindFirstTrack(tracks);
    02716     }
    02717   }
    02718
    02719   /* Save the current train order. The destructor will restore the old order on function exit. */
    02720   VehicleOrderSaver orders(v);
    02721
    02722   /* If the current tile is the destination of the current order and
    02723    * a reservation was requested, advance to the next order.
    02724    * Don't advance on a depot order as depots are always safe end points
    02725    * for a path and no look-ahead is necessary. This also avoids a
    02726    * problem with depot orders not part of the order list when the
    02727    * order list itself is empty. */
    02728   if (v->current_order.IsType(OT_LEAVESTATION)) {
    02729     orders.SwitchToNextOrder(false);
    02730   } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
    02731       v->current_order.IsType(OT_GOTO_STATION) ?
    02732       IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
    02733       v->tile == v->dest_tile))) {
    02734     orders.SwitchToNextOrder(true);
    02735   }
    02736
    02737   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
    02738     /* Pathfinders are able to tell that route was only 'guessed'. */
    02739     bool      path_not_found = false;
    02740     TileIndex new_tile = res_dest.tile;
    02741
    02742     Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, &path_not_found, do_track_reservation, &res_dest);
    02743     if (new_tile == tile) best_track = next_track;
    02744
    02745     /* handle "path not found" state */
    02746     if (path_not_found) {
    02747       /* PF didn't find the route */
    02748       if (!HasBit(v->flags, VRF_NO_PATH_TO_DESTINATION)) {
    02749         /* it is first time the problem occurred, set the "path not found" flag */
    02750         SetBit(v->flags, VRF_NO_PATH_TO_DESTINATION);
    02751         /* and notify user about the event */
    02752         AI::NewEvent(v->owner, new AIEventVehicleLost(v->index));
    02753         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
    02754           SetDParam(0, v->index);
    02755           AddVehicleNewsItem(
    02756             STR_NEWS_TRAIN_IS_LOST,
    02757             NS_ADVICE,
    02758             v->index
    02759           );
    02760         }
    02761       }
    02762     } else {
    02763       /* route found, is the train marked with "path not found" flag? */
    02764       if (HasBit(v->flags, VRF_NO_PATH_TO_DESTINATION)) {
    02765         /* clear the flag as the PF's problem was solved */
    02766         ClrBit(v->flags, VRF_NO_PATH_TO_DESTINATION);
    02767         /* can we also delete the "News" item somehow? */
    02768       }
    02769     }
    02770   }
    02771
    02772   /* No track reservation requested -> finished. */
    02773   if (!do_track_reservation) return best_track;
    02774
    02775   /* A path was found, but could not be reserved. */
    02776   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
    02777     if (mark_stuck) MarkTrainAsStuck(v);
    02778     FreeTrainTrackReservation(v);
    02779     return best_track;
    02780   }
    02781
    02782   /* No possible reservation target found, we are probably lost. */
    02783   if (res_dest.tile == INVALID_TILE) {
    02784     /* Try to find any safe destination. */
    02785     PBSTileInfo origin = FollowTrainReservation(v);
    02786     if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
    02787       TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
    02788       best_track = FindFirstTrack(res);
    02789       TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
    02790       if (got_reservation != NULL) *got_reservation = true;
    02791       if (changed_signal) MarkTileDirtyByTile(tile);
    02792     } else {
    02793       FreeTrainTrackReservation(v);
    02794       if (mark_stuck) MarkTrainAsStuck(v);
    02795     }
    02796     return best_track;
    02797   }
    02798
    02799   if (got_reservation != NULL) *got_reservation = true;
    02800
    02801   /* Reservation target found and free, check if it is safe. */
    02802   while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
    02803     /* Extend reservation until we have found a safe position. */
    02804     DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
    02805     TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
    02806     TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
    02807     if (_settings_game.pf.forbid_90_deg) {
    02808       reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
    02809     }
    02810
    02811     /* Get next order with destination. */
    02812     if (orders.SwitchToNextOrder(true)) {
    02813       PBSTileInfo cur_dest;
    02814       DoTrainPathfind(v, next_tile, exitdir, reachable, NULL, true, &cur_dest);
    02815       if (cur_dest.tile != INVALID_TILE) {
    02816         res_dest = cur_dest;
    02817         if (res_dest.okay) continue;
    02818         /* Path found, but could not be reserved. */
    02819         FreeTrainTrackReservation(v);
    02820         if (mark_stuck) MarkTrainAsStuck(v);
    02821         if (got_reservation != NULL) *got_reservation = false;
    02822         changed_signal = false;
    02823         break;
    02824       }
    02825     }
    02826     /* No order or no safe position found, try any position. */
    02827     if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
    02828       FreeTrainTrackReservation(v);
    02829       if (mark_stuck) MarkTrainAsStuck(v);
    02830       if (got_reservation != NULL) *got_reservation = false;
    02831       changed_signal = false;
    02832     }
    02833     break;
    02834   }
    02835
    02836   TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
    02837
    02838   if (changed_signal) MarkTileDirtyByTile(tile);
    02839
    02840   return best_track;
    02841 }
    02842
    02851 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
    02852 {
    02853   assert(v->IsFrontEngine());
    02854
    02855   /* We have to handle depots specially as the track follower won't look
    02856    * at the depot tile itself but starts from the next tile. If we are still
    02857    * inside the depot, a depot reservation can never be ours. */
    02858   if (v->track == TRACK_BIT_DEPOT) {
    02859     if (HasDepotReservation(v->tile)) {
    02860       if (mark_as_stuck) MarkTrainAsStuck(v);
    02861       return false;
    02862     } else {
    02863       /* Depot not reserved, but the next tile might be. */
    02864       TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
    02865       if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
    02866     }
    02867   }
    02868
    02869   Vehicle *other_train = NULL;
    02870   PBSTileInfo origin = FollowTrainReservation(v, &other_train);
    02871   /* The path we are driving on is alread blocked by some other train.
    02872    * This can only happen in certain situations when mixing path and
    02873    * block signals or when changing tracks and/or signals.
    02874    * Exit here as doing any further reservations will probably just
    02875    * make matters worse. */
    02876   if (other_train != NULL && other_train->index != v->index) {
    02877     if (mark_as_stuck) MarkTrainAsStuck(v);
    02878     return false;
    02879   }
    02880   /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
    02881   if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
    02882     /* Can't be stuck then. */
    02883     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    02884     ClrBit(v->flags, VRF_TRAIN_STUCK);
    02885     return true;
    02886   }
    02887
    02888   /* If we are in a depot, tentativly reserve the depot. */
    02889   if (v->track == TRACK_BIT_DEPOT) {
    02890     SetDepotReservation(v->tile, true);
    02891     if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
    02892   }
    02893
    02894   DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
    02895   TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
    02896   TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
    02897
    02898   if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
    02899
    02900   bool res_made = false;
    02901   ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
    02902
    02903   if (!res_made) {
    02904     /* Free the depot reservation as well. */
    02905     if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
    02906     return false;
    02907   }
    02908
    02909   if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
    02910     v->wait_counter = 0;
    02911     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    02912   }
    02913   ClrBit(v->flags, VRF_TRAIN_STUCK);
    02914   return true;
    02915 }
    02916
    02917
    02918 static bool CheckReverseTrain(const Train *v)
    02919 {
    02920   if (_settings_game.difficulty.line_reverse_mode != 0 ||
    02921       v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
    02922       !(v->direction & 1)) {
    02923     return false;
    02924   }
    02925
    02926   assert(v->track != TRACK_BIT_NONE);
    02927
    02928   switch (_settings_game.pf.pathfinder_for_trains) {
    02929     case VPF_NPF: return NPFTrainCheckReverse(v);
    02930     case VPF_YAPF: return YapfTrainCheckReverse(v);
    02931
    02932     default: NOT_REACHED();
    02933   }
    02934 }
    02935
    02936 TileIndex Train::GetOrderStationLocation(StationID station)
    02937 {
    02938   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
    02939
    02940   const Station *st = Station::Get(station);
    02941   if (!(st->facilities & FACIL_TRAIN)) {
    02942     /* The destination station has no trainstation tiles. */
    02943     this->IncrementOrderIndex();
    02944     return 0;
    02945   }
    02946
    02947   return st->xy;
    02948 }
    02949
    02950 void Train::MarkDirty()
    02951 {
    02952   Vehicle *v = this;
    02953   do {
    02954     v->UpdateViewport(false, false);
    02955   } while ((v = v->Next()) != NULL);
    02956
    02957   /* need to update acceleration and cached values since the goods on the train changed. */
    02958   this->CargoChanged();
    02959   this->UpdateAcceleration();
    02960 }
    02961
    02971 int Train::UpdateSpeed()
    02972 {
    02973   uint accel;
    02974
    02975   switch (_settings_game.vehicle.train_acceleration_model) {
    02976     default: NOT_REACHED();
    02977     case AM_ORIGINAL:
    02978       accel = this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2);
    02979       break;
    02980     case AM_REALISTIC:
    02981       this->max_speed = this->GetCurrentMaxSpeed();
    02982       accel = this->GetAcceleration();
    02983       break;
    02984   }
    02985
    02986   uint spd = this->subspeed + accel;
    02987   this->subspeed = (byte)spd;
    02988   {
    02989     int tempmax = this->max_speed;
    02990     if (this->cur_speed > this->max_speed)
    02991       tempmax = this->cur_speed - (this->cur_speed / 10) - 1;
    02992     this->cur_speed = spd = Clamp(this->cur_speed + ((int)spd >> 8), 0, tempmax);
    02993   }
    02994
    02995   /* Scale speed by 3/4. Previously this was only done when the train was
    02996    * facing diagonally and would apply to however many moves the train made
    02997    * regardless the of direction actually moved in. Now it is always scaled,
    02998    * 256 spd is used to go straight and 192 is used to go diagonally
    02999    * (3/4 of 256). This results in the same effect, but without the error the
    03000    * previous method caused.
    03001    *
    03002    * The scaling is done in this direction and not by multiplying the amount
    03003    * to be subtracted by 4/3 so that the leftover speed can be saved in a
    03004    * byte in this->progress.
    03005    */
    03006   int scaled_spd = spd * 3 >> 2;
    03007
    03008   scaled_spd += this->progress;
    03009   this->progress = 0; // set later in TrainLocoHandler or TrainController
    03010   return scaled_spd;
    03011 }
    03012
    03013 static void TrainEnterStation(Train *v, StationID station)
    03014 {
    03015   v->last_station_visited = station;
    03016
    03017   /* check if a train ever visited this station before */
    03018   Station *st = Station::Get(station);
    03019   if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
    03020     st->had_vehicle_of_type |= HVOT_TRAIN;
    03021     SetDParam(0, st->index);
    03022     AddVehicleNewsItem(
    03023       STR_NEWS_FIRST_TRAIN_ARRIVAL,
    03024       v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
    03025       v->index,
    03026       st->index
    03027     );
    03028     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
    03029   }
    03030
    03031   v->force_proceed = 0;
    03032   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03033
    03034   v->BeginLoading();
    03035
    03036   StationAnimationTrigger(st, v->tile, STAT_ANIM_TRAIN_ARRIVES);
    03037 }
    03038
    03039 static byte AfterSetTrainPos(Train *v, bool new_tile)
    03040 {
    03041   byte old_z = v->z_pos;
    03042   v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
    03043
    03044   if (new_tile) {
    03045     ClrBit(v->flags, VRF_GOINGUP);
    03046     ClrBit(v->flags, VRF_GOINGDOWN);
    03047
    03048     if (v->track == TRACK_BIT_X || v->track == TRACK_BIT_Y) {
    03049       /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped.
    03050        * To check whether the current tile is sloped, and in which
    03051        * direction it is sloped, we get the 'z' at the center of
    03052        * the tile (middle_z) and the edge of the tile (old_z),
    03053        * which we then can compare. */
    03054       static const int HALF_TILE_SIZE = TILE_SIZE / 2;
    03055       static const int INV_TILE_SIZE_MASK = ~(TILE_SIZE - 1);
    03056
    03057       byte middle_z = GetSlopeZ((v->x_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE, (v->y_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE);
    03058
    03059       if (middle_z != v->z_pos) {
    03060         SetBit(v->flags, (middle_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN);
    03061       }
    03062     }
    03063   }
    03064
    03065   VehicleMove(v, true);
    03066   return old_z;
    03067 }
    03068
    03069 /* Check if the vehicle is compatible with the specified tile */
    03070 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
    03071 {
    03072   return
    03073     IsTileOwner(tile, v->owner) && (
    03074       !v->IsFrontEngine() ||
    03075       HasBit(v->compatible_railtypes, GetRailType(tile))
    03076     );
    03077 }
    03078
    03079 struct RailtypeSlowdownParams {
    03080   byte small_turn, large_turn;
    03081   byte z_up; // fraction to remove when moving up
    03082   byte z_down; // fraction to remove when moving down
    03083 };
    03084
    03085 static const RailtypeSlowdownParams _railtype_slowdown[] = {
    03086   /* normal accel */
    03087   {256 / 4, 256 / 2, 256 / 4, 2},
    03088   {256 / 4, 256 / 2, 256 / 4, 2},
    03089   {256 / 4, 256 / 2, 256 / 4, 2},
    03090   {0,       256 / 2, 256 / 4, 2},
    03091 };
    03092
    03094 static inline void AffectSpeedByZChange(Train *v, byte old_z)
    03095 {
    03096   if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
    03097
    03098   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
    03099
    03100   if (old_z < v->z_pos) {
    03101     v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
    03102   } else {
    03103     uint16 spd = v->cur_speed + rsp->z_down;
    03104     if (spd <= v->max_speed) v->cur_speed = spd;
    03105   }
    03106 }
    03107
    03108 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
    03109 {
    03110   if (IsTileType(tile, MP_RAILWAY) &&
    03111       GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
    03112     TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
    03113     Trackdir trackdir = FindFirstTrackdir(tracks);
    03114     if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
    03115       /* A PBS block with a non-PBS signal facing us? */
    03116       if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
    03117     }
    03118   }
    03119   return false;
    03120 }
    03121
    03125 void Train::ReserveTrackUnderConsist() const
    03126 {
    03127   for (const Train *u = this; u != NULL; u = u->Next()) {
    03128     switch (u->track) {
    03129       case TRACK_BIT_WORMHOLE:
    03130         TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
    03131         break;
    03132       case TRACK_BIT_DEPOT:
    03133         break;
    03134       default:
    03135         TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
    03136         break;
    03137     }
    03138   }
    03139 }
    03140
    03141 uint Train::Crash(bool flooded)
    03142 {
    03143   uint pass = 0;
    03144   if (this->IsFrontEngine()) {
    03145     pass += 4; // driver
    03146
    03147     /* Remove the reserved path in front of the train if it is not stuck.
    03148      * Also clear all reserved tracks the train is currently on. */
    03149     if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
    03150     for (const Train *v = this; v != NULL; v = v->Next()) {
    03151       ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
    03152       if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
    03153         /* ClearPathReservation will not free the wormhole exit
    03154          * if the train has just entered the wormhole. */
    03155         SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
    03156       }
    03157     }
    03158
    03159     /* we may need to update crossing we were approaching,
    03160     * but must be updated after the train has been marked crashed */
    03161     TileIndex crossing = TrainApproachingCrossingTile(this);
    03162     if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
    03163
    03164     /* Remove the loading indicators (if any) */
    03165     HideFillingPercent(&this->fill_percent_te_id);
    03166   }
    03167
    03168   pass += Vehicle::Crash(flooded);
    03169
    03170   this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
    03171   return pass;
    03172 }
    03173
    03180 static uint TrainCrashed(Train *v)
    03181 {
    03182   uint num = 0;
    03183
    03184   /* do not crash train twice */
    03185   if (!(v->vehstatus & VS_CRASHED)) {
    03186     num = v->Crash();
    03187     AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
    03188   }
    03189
    03190   /* Try to re-reserve track under already crashed train too.
    03191    * SetVehicleCrashed() clears the reservation! */
    03192   v->ReserveTrackUnderConsist();
    03193
    03194   return num;
    03195 }
    03196
    03197 struct TrainCollideChecker {
    03198   Train *v;
    03199   uint num;
    03200 };
    03201
    03202 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
    03203 {
    03204   TrainCollideChecker *tcc = (TrainCollideChecker*)data;
    03205
    03206   /* not a train or in depot */
    03207   if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
    03208
    03209   /* do not crash into trains of another company. */
    03210   if (v->owner != tcc->v->owner) return NULL;
    03211
    03212   /* get first vehicle now to make most usual checks faster */
    03213   Train *coll = Train::From(v)->First();
    03214
    03215   /* can't collide with own wagons */
    03216   if (coll == tcc->v) return NULL;
    03217
    03218   int x_diff = v->x_pos - tcc->v->x_pos;
    03219   int y_diff = v->y_pos - tcc->v->y_pos;
    03220
    03221   /* Do fast calculation to check whether trains are not in close vicinity
    03222    * and quickly reject trains distant enough for any collision.
    03223    * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
    03224    * Differences are then ORed and then we check for any higher bits */
    03225   uint hash = (y_diff + 7) | (x_diff + 7);
    03226   if (hash & ~15) return NULL;
    03227
    03228   /* Slower check using multiplication */
    03229   if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
    03230
    03231   /* Happens when there is a train under bridge next to bridge head */
    03232   if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
    03233
    03234   /* crash both trains */
    03235   tcc->num += TrainCrashed(tcc->v);
    03236   tcc->num += TrainCrashed(coll);
    03237
    03238   return NULL; // continue searching
    03239 }
    03240
    03247 static bool CheckTrainCollision(Train *v)
    03248 {
    03249   /* can't collide in depot */
    03250   if (v->track == TRACK_BIT_DEPOT) return false;
    03251
    03252   assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
    03253
    03254   TrainCollideChecker tcc;
    03255   tcc.v = v;
    03256   tcc.num = 0;
    03257
    03258   /* find colliding vehicles */
    03259   if (v->track == TRACK_BIT_WORMHOLE) {
    03260     FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
    03261     FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
    03262   } else {
    03263     FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
    03264   }
    03265
    03266   /* any dead -> no crash */
    03267   if (tcc.num == 0) return false;
    03268
    03269   SetDParam(0, tcc.num);
    03270   AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH,
    03271     NS_ACCIDENT,
    03272     v->index
    03273   );
    03274
    03275   ModifyStationRatingAround(v->tile, v->owner, -160, 30);
    03276   SndPlayVehicleFx(SND_13_BIG_CRASH, v);
    03277   return true;
    03278 }
    03279
    03280 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
    03281 {
    03282   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
    03283
    03284   Train *t = Train::From(v);
    03285   DiagDirection exitdir = *(DiagDirection *)data;
    03286
    03287   /* not front engine of a train, inside wormhole or depot, crashed */
    03288   if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
    03289
    03290   if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
    03291
    03292   return t;
    03293 }
    03294
    03295 static void TrainController(Train *v, Vehicle *nomove)
    03296 {
    03297   Train *first = v->First();
    03298   Train *prev;
    03299   bool direction_changed = false; // has direction of any part changed?
    03300
    03301   /* For every vehicle after and including the given vehicle */
    03302   for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
    03303     DiagDirection enterdir = DIAGDIR_BEGIN;
    03304     bool update_signals_crossing = false; // will we update signals or crossing state?
    03305
    03306     GetNewVehiclePosResult gp = GetNewVehiclePos(v);
    03307     if (v->track != TRACK_BIT_WORMHOLE) {
    03308       /* Not inside tunnel */
    03309       if (gp.old_tile == gp.new_tile) {
    03310         /* Staying in the old tile */
    03311         if (v->track == TRACK_BIT_DEPOT) {
    03312           /* Inside depot */
    03313           gp.x = v->x_pos;
    03314           gp.y = v->y_pos;
    03315         } else {
    03316           /* Not inside depot */
    03317
    03318           /* Reverse when we are at the end of the track already, do not move to the new position */
    03319           if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v)) return;
    03320
    03321           uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    03322           if (HasBit(r, VETS_CANNOT_ENTER)) {
    03323             goto invalid_rail;
    03324           }
    03325           if (HasBit(r, VETS_ENTERED_STATION)) {
    03326             /* The new position is the end of the platform */
    03327             TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
    03328           }
    03329         }
    03330       } else {
    03331         /* A new tile is about to be entered. */
    03332
    03333         /* Determine what direction we're entering the new tile from */
    03334         enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
    03335         assert(IsValidDiagDirection(enterdir));
    03336
    03337         /* Get the status of the tracks in the new tile and mask
    03338          * away the bits that aren't reachable. */
    03339         TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
    03340         TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
    03341
    03342         TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
    03343         TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
    03344
    03345         TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
    03346         if (_settings_game.pf.forbid_90_deg && prev == NULL) {
    03347           /* We allow wagons to make 90 deg turns, because forbid_90_deg
    03348            * can be switched on halfway a turn */
    03349           bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
    03350         }
    03351
    03352         if (bits == TRACK_BIT_NONE) goto invalid_rail;
    03353
    03354         /* Check if the new tile contrains tracks that are compatible
    03355          * with the current train, if not, bail out. */
    03356         if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
    03357
    03358         TrackBits chosen_track;
    03359         if (prev == NULL) {
    03360           /* Currently the locomotive is active. Determine which one of the
    03361            * available tracks to choose */
    03362           chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
    03363           assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
    03364
    03365           if (v->force_proceed != 0 && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
    03366             /* For each signal we find decrease the counter by one.
    03367              * We start at two, so the first signal we pass decreases
    03368              * this to one, then if we reach the next signal it is
    03369              * decreased to zero and we won't pass that new signal. */
    03370             Trackdir dir = FindFirstTrackdir(trackdirbits);
    03371             if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
    03372                 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
    03373               /* However, we do not want to be stopped by PBS signals
    03374                * entered via the back. */
    03375               v->force_proceed--;
    03376               SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03377             }
    03378           }
    03379
    03380           /* Check if it's a red signal and that force proceed is not clicked. */
    03381           if ((red_signals & chosen_track) && v->force_proceed == 0) {
    03382             /* In front of a red signal */
    03383             Trackdir i = FindFirstTrackdir(trackdirbits);
    03384
    03385             /* Don't handle stuck trains here. */
    03386             if (HasBit(v->flags, VRF_TRAIN_STUCK)) return;
    03387
    03388             if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
    03389               v->cur_speed = 0;
    03390               v->subspeed = 0;
    03391               v->progress = 255 - 100;
    03392               if (_settings_game.pf.wait_oneway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return;
    03393             } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
    03394               v->cur_speed = 0;
    03395               v->subspeed = 0;
    03396               v->progress = 255 - 10;
    03397               if (_settings_game.pf.wait_twoway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
    03398                 DiagDirection exitdir = TrackdirToExitdir(i);
    03399                 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
    03400
    03401                 exitdir = ReverseDiagDir(exitdir);
    03402
    03403                 /* check if a train is waiting on the other side */
    03404                 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return;
    03405               }
    03406             }
    03407
    03408             /* If we would reverse but are currently in a PBS block and
    03409              * reversing of stuck trains is disabled, don't reverse.
    03410              * This does not apply if the reason for reversing is a one-way
    03411              * signal blocking us, because a train would then be stuck forever. */
    03412             if (_settings_game.pf.wait_for_pbs_path == 255 && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
    03413                 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
    03414               v->wait_counter = 0;
    03415               return;
    03416             }
    03417             goto reverse_train_direction;
    03418           } else {
    03419             TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
    03420           }
    03421         } else {
    03422           /* The wagon is active, simply follow the prev vehicle. */
    03423           if (prev->tile == gp.new_tile) {
    03424             /* Choose the same track as prev */
    03425             if (prev->track == TRACK_BIT_WORMHOLE) {
    03426               /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
    03427                * However, just choose the track into the wormhole. */
    03428               assert(IsTunnel(prev->tile));
    03429               chosen_track = bits;
    03430             } else {
    03431               chosen_track = prev->track;
    03432             }
    03433           } else {
    03434             /* Choose the track that leads to the tile where prev is.
    03435              * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
    03436              * I.e. when the tile between them has only space for a single vehicle like
    03437              *  1) horizontal/vertical track tiles and
    03438              *  2) some orientations of tunnelentries, where the vehicle is already inside the wormhole at 8/16 from the tileedge.
    03439              *     Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnelentry.
    03440              */
    03441             static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
    03442               {TRACK_BIT_X,     TRACK_BIT_LOWER, TRACK_BIT_NONE,  TRACK_BIT_LEFT },
    03443               {TRACK_BIT_UPPER, TRACK_BIT_Y,     TRACK_BIT_LEFT,  TRACK_BIT_NONE },
    03444               {TRACK_BIT_NONE,  TRACK_BIT_RIGHT, TRACK_BIT_X,     TRACK_BIT_UPPER},
    03445               {TRACK_BIT_RIGHT, TRACK_BIT_NONE,  TRACK_BIT_LOWER, TRACK_BIT_Y    }
    03446             };
    03447             DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
    03448             assert(IsValidDiagDirection(exitdir));
    03449             chosen_track = _connecting_track[enterdir][exitdir];
    03450           }
    03451           chosen_track &= bits;
    03452         }
    03453
    03454         /* Make sure chosen track is a valid track */
    03455         assert(
    03456             chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
    03457             chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
    03458             chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
    03459
    03460         /* Update XY to reflect the entrance to the new tile, and select the direction to use */
    03461         const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
    03462         gp.x = (gp.x & ~0xF) | b[0];
    03463         gp.y = (gp.y & ~0xF) | b[1];
    03464         Direction chosen_dir = (Direction)b[2];
    03465
    03466         /* Call the landscape function and tell it that the vehicle entered the tile */
    03467         uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    03468         if (HasBit(r, VETS_CANNOT_ENTER)) {
    03469           goto invalid_rail;
    03470         }
    03471
    03472         if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
    03473           Track track = FindFirstTrack(chosen_track);
    03474           Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
    03475           if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
    03476             SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
    03477             MarkTileDirtyByTile(gp.new_tile);
    03478           }
    03479
    03480           /* Clear any track reservation when the last vehicle leaves the tile */
    03481           if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
    03482
    03483           v->tile = gp.new_tile;
    03484
    03485           if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
    03486             v->First()->RailtypeChanged();
    03487           }
    03488
    03489           v->track = chosen_track;
    03490           assert(v->track);
    03491         }
    03492
    03493         /* We need to update signal status, but after the vehicle position hash
    03494          * has been updated by AfterSetTrainPos() */
    03495         update_signals_crossing = true;
    03496
    03497         if (chosen_dir != v->direction) {
    03498           if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
    03499             const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
    03500             DirDiff diff = DirDifference(v->direction, chosen_dir);
    03501             v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
    03502           }
    03503           direction_changed = true;
    03504           v->direction = chosen_dir;
    03505         }
    03506
    03507         if (v->IsFrontEngine()) {
    03508           v->wait_counter = 0;
    03509
    03510           /* If we are approching a crossing that is reserved, play the sound now. */
    03511           TileIndex crossing = TrainApproachingCrossingTile(v);
    03512           if (crossing != INVALID_TILE && HasCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
    03513
    03514           /* Always try to extend the reservation when entering a tile. */
    03515           CheckNextTrainTile(v);
    03516         }
    03517
    03518         if (HasBit(r, VETS_ENTERED_STATION)) {
    03519           /* The new position is the location where we want to stop */
    03520           TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
    03521         }
    03522       }
    03523     } else {
    03524       /* In a tunnel or on a bridge
    03525        * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
    03526        * - for bridges, only the middle part - without the bridge heads */
    03527       if (!(v->vehstatus & VS_HIDDEN)) {
    03528         v->cur_speed =
    03529           min(v->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
    03530       }
    03531
    03532       if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
    03533         /* Perform look-ahead on tunnel exit. */
    03534         if (v->IsFrontEngine()) {
    03535           TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
    03536           CheckNextTrainTile(v);
    03537         }
    03538       } else {
    03539         v->x_pos = gp.x;
    03540         v->y_pos = gp.y;
    03541         VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
    03542         continue;
    03543       }
    03544     }
    03545
    03546     /* update image of train, as well as delta XY */
    03547     v->UpdateDeltaXY(v->direction);
    03548
    03549     v->x_pos = gp.x;
    03550     v->y_pos = gp.y;
    03551
    03552     /* update the Z position of the vehicle */
    03553     byte old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile));
    03554
    03555     if (prev == NULL) {
    03556       /* This is the first vehicle in the train */
    03557       AffectSpeedByZChange(v, old_z);
    03558     }
    03559
    03560     if (update_signals_crossing) {
    03561       if (v->IsFrontEngine()) {
    03562         if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
    03563           /* We are entering a block with PBS signals right now, but
    03564            * not through a PBS signal. This means we don't have a
    03565            * reservation right now. As a conventional signal will only
    03566            * ever be green if no other train is in the block, getting
    03567            * a path should always be possible. If the player built
    03568            * such a strange network that it is not possible, the train
    03569            * will be marked as stuck and the player has to deal with
    03570            * the problem. */
    03571           if ((!HasReservedTracks(gp.new_tile, v->track) &&
    03572               !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
    03573               !TryPathReserve(v)) {
    03574             MarkTrainAsStuck(v);
    03575           }
    03576         }
    03577       }
    03578
    03579       /* Signals can only change when the first
    03580        * (above) or the last vehicle moves. */
    03581       if (v->Next() == NULL) {
    03582         TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
    03583         if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
    03584       }
    03585     }
    03586
    03587     /* Do not check on every tick to save some computing time. */
    03588     if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
    03589   }
    03590
    03591   if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
    03592
    03593   return;
    03594
    03595 invalid_rail:
    03596   /* We've reached end of line?? */
    03597   if (prev != NULL) error("Disconnecting train");
    03598
    03599 reverse_train_direction:
    03600   v->wait_counter = 0;
    03601   v->cur_speed = 0;
    03602   v->subspeed = 0;
    03603   ReverseTrainDirection(v);
    03604 }
    03605
    03611 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
    03612 {
    03613   TrackBits *trackbits = (TrackBits *)data;
    03614
    03615   if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
    03616     if (Train::From(v)->track == TRACK_BIT_WORMHOLE) {
    03617       /* Vehicle is inside a wormhole, v->track contains no useful value then. */
    03618       *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
    03619     } else {
    03620       *trackbits |= Train::From(v)->track;
    03621     }
    03622   }
    03623
    03624   return NULL;
    03625 }
    03626
    03634 static void DeleteLastWagon(Train *v)
    03635 {
    03636   Train *first = v->First();
    03637
    03638   /* Go to the last wagon and delete the link pointing there
    03639    * *u is then the one-before-last wagon, and *v the last
    03640    * one which will physicially be removed */
    03641   Train *u = v;
    03642   for (; v->Next() != NULL; v = v->Next()) u = v;
    03643   u->SetNext(NULL);
    03644
    03645   if (first != v) {
    03646     /* Recalculate cached train properties */
    03647     first->ConsistChanged(false);
    03648     /* Update the depot window if the first vehicle is in depot -
    03649      * if v == first, then it is updated in PreDestructor() */
    03650     if (first->track == TRACK_BIT_DEPOT) {
    03651       SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
    03652     }
    03653   }
    03654
    03655   /* 'v' shouldn't be accessed after it has been deleted */
    03656   TrackBits trackbits = v->track;
    03657   TileIndex tile = v->tile;
    03658   Owner owner = v->owner;
    03659
    03660   delete v;
    03661   v = NULL; // make sure nobody will try to read 'v' anymore
    03662
    03663   if (trackbits == TRACK_BIT_WORMHOLE) {
    03664     /* Vehicle is inside a wormhole, v->track contains no useful value then. */
    03665     trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
    03666   }
    03667
    03668   Track track = TrackBitsToTrack(trackbits);
    03669   if (HasReservedTracks(tile, trackbits)) {
    03670     UnreserveRailTrack(tile, track);
    03671
    03672     /* If there are still crashed vehicles on the tile, give the track reservation to them */
    03673     TrackBits remaining_trackbits = TRACK_BIT_NONE;
    03674     FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
    03675
    03676     /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
    03677     assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
    03678     for (Track t = TRACK_BEGIN; t < TRACK_END; t++) {
    03679       if (HasBit(remaining_trackbits, t)) {
    03680         TryReserveRailTrack(tile, t);
    03681       }
    03682     }
    03683   }
    03684
    03685   /* check if the wagon was on a road/rail-crossing */
    03686   if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
    03687
    03688   /* Update signals */
    03689   if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
    03690     UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
    03691   } else {
    03692     SetSignalsOnBothDir(tile, track, owner);
    03693   }
    03694 }
    03695
    03696 static void ChangeTrainDirRandomly(Train *v)
    03697 {
    03698   static const DirDiff delta[] = {
    03699     DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
    03700   };
    03701
    03702   do {
    03703     /* We don't need to twist around vehicles if they're not visible */
    03704     if (!(v->vehstatus & VS_HIDDEN)) {
    03705       v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
    03706       v->UpdateDeltaXY(v->direction);
    03707       v->cur_image = v->GetImage(v->direction);
    03708       /* Refrain from updating the z position of the vehicle when on
    03709        * a bridge, because AfterSetTrainPos will put the vehicle under
    03710        * the bridge in that case */
    03711       if (v->track != TRACK_BIT_WORMHOLE) AfterSetTrainPos(v, false);
    03712     }
    03713   } while ((v = v->Next()) != NULL);
    03714 }
    03715
    03716 static bool HandleCrashedTrain(Train *v)
    03717 {
    03718   int state = ++v->crash_anim_pos;
    03719
    03720   if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
    03721     CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
    03722   }
    03723
    03724   uint32 r;
    03725   if (state <= 200 && Chance16R(1, 7, r)) {
    03726     int index = (r * 10 >> 16);
    03727
    03728     Vehicle *u = v;
    03729     do {
    03730       if (--index < 0) {
    03731         r = Random();
    03732
    03733         CreateEffectVehicleRel(u,
    03734           GB(r,  8, 3) + 2,
    03735           GB(r, 16, 3) + 2,
    03736           GB(r,  0, 3) + 5,
    03737           EV_EXPLOSION_SMALL);
    03738         break;
    03739       }
    03740     } while ((u = u->Next()) != NULL);
    03741   }
    03742
    03743   if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
    03744
    03745   if (state >= 4440 && !(v->tick_counter & 0x1F)) {
    03746     bool ret = v->Next() != NULL;
    03747     DeleteLastWagon(v);
    03748     return ret;
    03749   }
    03750
    03751   return true;
    03752 }
    03753
    03754 static void HandleBrokenTrain(Train *v)
    03755 {
    03756   if (v->breakdown_ctr != 1) {
    03757     v->breakdown_ctr = 1;
    03758     v->cur_speed = 0;
    03759
    03760     if (v->breakdowns_since_last_service != 255)
    03761       v->breakdowns_since_last_service++;
    03762
    03763     v->MarkDirty();
    03764     SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03765     SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
    03766
    03767     if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
    03768       SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
    03769         SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
    03770     }
    03771
    03772     if (!(v->vehstatus & VS_HIDDEN)) {
    03773       EffectVehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
    03774       if (u != NULL) u->animation_state = v->breakdown_delay * 2;
    03775     }
    03776   }
    03777
    03778   if (!(v->tick_counter & 3)) {
    03779     if (!--v->breakdown_delay) {
    03780       v->breakdown_ctr = 0;
    03781       v->MarkDirty();
    03782       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03783     }
    03784   }
    03785 }
    03786
    03788 static const uint16 _breakdown_speeds[16] = {
    03789   225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
    03790 };
    03791
    03792
    03800 static bool TrainApproachingLineEnd(Train *v, bool signal)
    03801 {
    03802   /* Calc position within the current tile */
    03803   uint x = v->x_pos & 0xF;
    03804   uint y = v->y_pos & 0xF;
    03805
    03806   /* for diagonal directions, 'x' will be 0..15 -
    03807    * for other directions, it will be 1, 3, 5, ..., 15 */
    03808   switch (v->direction) {
    03809     case DIR_N : x = ~x + ~y + 25; break;
    03810     case DIR_NW: x = y;            // FALLTHROUGH
    03811     case DIR_NE: x = ~x + 16;      break;
    03812     case DIR_E : x = ~x + y + 9;   break;
    03813     case DIR_SE: x = y;            break;
    03814     case DIR_S : x = x + y - 7;    break;
    03815     case DIR_W : x = ~y + x + 9;   break;
    03816     default: break;
    03817   }
    03818
    03819   /* do not reverse when approaching red signal */
    03820   if (!signal && x + (v->tcache.cached_veh_length + 1) / 2 >= TILE_SIZE) {
    03821     /* we are too near the tile end, reverse now */
    03822     v->cur_speed = 0;
    03823     ReverseTrainDirection(v);
    03824     return false;
    03825   }
    03826
    03827   /* slow down */
    03828   v->vehstatus |= VS_TRAIN_SLOWING;
    03829   uint16 break_speed = _breakdown_speeds[x & 0xF];
    03830   if (break_speed < v->cur_speed) v->cur_speed = break_speed;
    03831
    03832   return true;
    03833 }
    03834
    03835
    03841 static bool TrainCanLeaveTile(const Train *v)
    03842 {
    03843   /* Exit if inside a tunnel/bridge or a depot */
    03844   if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
    03845
    03846   TileIndex tile = v->tile;
    03847
    03848   /* entering a tunnel/bridge? */
    03849   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    03850     DiagDirection dir = GetTunnelBridgeDirection(tile);
    03851     if (DiagDirToDir(dir) == v->direction) return false;
    03852   }
    03853
    03854   /* entering a depot? */
    03855   if (IsRailDepotTile(tile)) {
    03856     DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
    03857     if (DiagDirToDir(dir) == v->direction) return false;
    03858   }
    03859
    03860   return true;
    03861 }
    03862
    03863
    03871 static TileIndex TrainApproachingCrossingTile(const Train *v)
    03872 {
    03873   assert(v->IsFrontEngine());
    03874   assert(!(v->vehstatus & VS_CRASHED));
    03875
    03876   if (!TrainCanLeaveTile(v)) return INVALID_TILE;
    03877
    03878   DiagDirection dir = TrainExitDir(v->direction, v->track);
    03879   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
    03880
    03881   /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
    03882   if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
    03883       !CheckCompatibleRail(v, tile)) {
    03884     return INVALID_TILE;
    03885   }
    03886
    03887   return tile;
    03888 }
    03889
    03890
    03897 static bool TrainCheckIfLineEnds(Train *v)
    03898 {
    03899   /* First, handle broken down train */
    03900
    03901   int t = v->breakdown_ctr;
    03902   if (t > 1) {
    03903     v->vehstatus |= VS_TRAIN_SLOWING;
    03904
    03905     uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
    03906     if (break_speed < v->cur_speed) v->cur_speed = break_speed;
    03907   } else {
    03908     v->vehstatus &= ~VS_TRAIN_SLOWING;
    03909   }
    03910
    03911   if (!TrainCanLeaveTile(v)) return true;
    03912
    03913   /* Determine the non-diagonal direction in which we will exit this tile */
    03914   DiagDirection dir = TrainExitDir(v->direction, v->track);
    03915   /* Calculate next tile */
    03916   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
    03917
    03918   /* Determine the track status on the next tile */
    03919   TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
    03920   TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
    03921
    03922   TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
    03923   TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
    03924
    03925   /* We are sure the train is not entering a depot, it is detected above */
    03926
    03927   /* mask unreachable track bits if we are forbidden to do 90deg turns */
    03928   TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
    03929   if (_settings_game.pf.forbid_90_deg) {
    03930     bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
    03931   }
    03932
    03933   /* no suitable trackbits at all || unusable rail (wrong type or owner) */
    03934   if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
    03935     return TrainApproachingLineEnd(v, false);
    03936   }
    03937
    03938   /* approaching red signal */
    03939   if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true);
    03940
    03941   /* approaching a rail/road crossing? then make it red */
    03942   if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
    03943
    03944   return true;
    03945 }
    03946
    03947
    03948 static bool TrainLocoHandler(Train *v, bool mode)
    03949 {
    03950   /* train has crashed? */
    03951   if (v->vehstatus & VS_CRASHED) {
    03952     return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
    03953   }
    03954
    03955   if (v->force_proceed != 0) {
    03956     ClrBit(v->flags, VRF_TRAIN_STUCK);
    03957     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03958   }
    03959
    03960   /* train is broken down? */
    03961   if (v->breakdown_ctr != 0) {
    03962     if (v->breakdown_ctr <= 2) {
    03963       HandleBrokenTrain(v);
    03964       return true;
    03965     }
    03966     if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
    03967   }
    03968
    03969   if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
    03970     ReverseTrainDirection(v);
    03971   }
    03972
    03973   /* exit if train is stopped */
    03974   if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
    03975
    03976   bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
    03977   if (ProcessOrders(v) && CheckReverseTrain(v)) {
    03978     v->wait_counter = 0;
    03979     v->cur_speed = 0;
    03980     v->subspeed = 0;
    03981     ReverseTrainDirection(v);
    03982     return true;
    03983   }
    03984
    03985   v->HandleLoading(mode);
    03986
    03987   if (v->current_order.IsType(OT_LOADING)) return true;
    03988
    03989   if (CheckTrainStayInDepot(v)) return true;
    03990
    03991   if (!mode) HandleLocomotiveSmokeCloud(v);
    03992
    03993   /* We had no order but have an order now, do look ahead. */
    03994   if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
    03995     CheckNextTrainTile(v);
    03996   }
    03997
    03998   /* Handle stuck trains. */
    03999   if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
    04000     ++v->wait_counter;
    04001
    04002     /* Should we try reversing this tick if still stuck? */
    04003     bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.wait_for_pbs_path < 255;
    04004
    04005     if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == 0) return true;
    04006     if (!TryPathReserve(v)) {
    04007       /* Still stuck. */
    04008       if (turn_around) ReverseTrainDirection(v);
    04009
    04010       if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
    04011         /* Show message to player. */
    04012         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
    04013           SetDParam(0, v->index);
    04014           AddVehicleNewsItem(
    04015             STR_NEWS_TRAIN_IS_STUCK,
    04016             NS_ADVICE,
    04017             v->index
    04018           );
    04019         }
    04020         v->wait_counter = 0;
    04021       }
    04022       /* Exit if force proceed not pressed, else reset stuck flag anyway. */
    04023       if (v->force_proceed == 0) return true;
    04024       ClrBit(v->flags, VRF_TRAIN_STUCK);
    04025       v->wait_counter = 0;
    04026       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04027     }
    04028   }
    04029
    04030   if (v->current_order.IsType(OT_LEAVESTATION)) {
    04031     v->current_order.Free();
    04032     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04033     return true;
    04034   }
    04035
    04036   int j = v->UpdateSpeed();
    04037
    04038   /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
    04039   if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
    04040     /* If we manually stopped, we're not force-proceeding anymore. */
    04041     v->force_proceed = 0;
    04042     SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    04043   }
    04044
    04045   int adv_spd = (v->direction & 1) ? 192 : 256;
    04046   if (j < adv_spd) {
    04047     /* if the vehicle has speed 0, update the last_speed field. */
    04048     if (v->cur_speed == 0) SetLastSpeed(v, v->cur_speed);
    04049   } else {
    04050     TrainCheckIfLineEnds(v);
    04051     /* Loop until the train has finished moving. */
    04052     for (;;) {
    04053       j -= adv_spd;
    04054       TrainController(v, NULL);
    04055       /* Don't continue to move if the train crashed. */
    04056       if (CheckTrainCollision(v)) break;
    04057       /* 192 spd used for going straight, 256 for going diagonally. */
    04058       adv_spd = (v->direction & 1) ? 192 : 256;
    04059
    04060       /* No more moving this tick */
    04061       if (j < adv_spd || v->cur_speed == 0) break;
    04062
    04063       OrderType order_type = v->current_order.GetType();
    04064       /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
    04065       if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
    04066             (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
    04067             IsTileType(v->tile, MP_STATION) &&
    04068             v->current_order.GetDestination() == GetStationIndex(v->tile)) {
    04069         ProcessOrders(v);
    04070       }
    04071     }
    04072     SetLastSpeed(v, v->cur_speed);
    04073   }
    04074
    04075   for (Train *u = v; u != NULL; u = u->Next()) {
    04076     if ((u->vehstatus & VS_HIDDEN) != 0) continue;
    04077
    04078     u->UpdateViewport(false, false);
    04079   }
    04080
    04081   if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
    04082
    04083   return true;
    04084 }
    04085
    04086
    04087
    04088 Money Train::GetRunningCost() const
    04089 {
    04090   Money cost = 0;
    04091   const Train *v = this;
    04092
    04093   do {
    04094     const Engine *e = Engine::Get(v->engine_type);
    04095     if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
    04096
    04097     uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
    04098     if (cost_factor == 0) continue;
    04099
    04100     /* Halve running cost for multiheaded parts */
    04101     if (v->IsMultiheaded()) cost_factor /= 2;
    04102
    04103     cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->grffile);
    04104   } while ((v = v->GetNextVehicle()) != NULL);
    04105
    04106   return cost;
    04107 }
    04108
    04109
    04110 bool Train::Tick()
    04111 {
    04112   this->tick_counter++;
    04113
    04114   if (this->IsFrontEngine()) {
    04115     if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
    04116
    04117     this->current_order_time++;
    04118
    04119     if (!TrainLocoHandler(this, false)) return false;
    04120
    04121     return TrainLocoHandler(this, true);
    04122   } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
    04123     /* Delete flooded standalone wagon chain */
    04124     if (++this->crash_anim_pos >= 4400) {
    04125       delete this;
    04126       return false;
    04127     }
    04128   }
    04129
    04130   return true;
    04131 }
    04132
    04133 static void CheckIfTrainNeedsService(Train *v)
    04134 {
    04135   if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
    04136   if (v->IsInDepot()) {
    04137     VehicleServiceInDepot(v);
    04138     return;
    04139   }
    04140
    04141   uint max_penalty;
    04142   switch (_settings_game.pf.pathfinder_for_trains) {
    04143     case VPF_NPF:  max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty;  break;
    04144     case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
    04145     default: NOT_REACHED();
    04146   }
    04147
    04148   FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
    04149   /* Only go to the depot if it is not too far out of our way. */
    04150   if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
    04151     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
    04152       /* If we were already heading for a depot but it has
    04153        * suddenly moved farther away, we continue our normal
    04154        * schedule? */
    04155       v->current_order.MakeDummy();
    04156       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04157     }
    04158     return;
    04159   }
    04160
    04161   DepotID depot = GetDepotIndex(tfdd.tile);
    04162
    04163   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
    04164       v->current_order.GetDestination() != depot &&
    04165       !Chance16(3, 16)) {
    04166     return;
    04167   }
    04168
    04169   v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
    04170   v->dest_tile = tfdd.tile;
    04171   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04172 }
    04173
    04174 void Train::OnNewDay()
    04175 {
    04176   if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
    04177
    04178   if (this->IsFrontEngine()) {
    04179     CheckVehicleBreakdown(this);
    04180     AgeVehicle(this);
    04181
    04182     CheckIfTrainNeedsService(this);
    04183
    04184     CheckOrders(this);
    04185
    04186     /* update destination */
    04187     if (this->current_order.IsType(OT_GOTO_STATION)) {
    04188       TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
    04189       if (tile != INVALID_TILE) this->dest_tile = tile;
    04190     }
    04191
    04192     if (this->running_ticks != 0) {
    04193       /* running costs */
    04194       CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR  * DAY_TICKS));
    04195
    04196       this->profit_this_year -= cost.GetCost();
    04197       this->running_ticks = 0;
    04198
    04199       SubtractMoneyFromCompanyFract(this->owner, cost);
    04200
    04201       SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
    04202       SetWindowClassesDirty(WC_TRAINS_LIST);
    04203     }
    04204   } else if (this->IsEngine()) {
    04205     /* Also age engines that aren't front engines */
    04206     AgeVehicle(this);
    04207   }
    04208 }
    04209
    04210 Trackdir Train::GetVehicleTrackdir() const
    04211 {
    04212   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
    04213
    04214   if (this->track == TRACK_BIT_DEPOT) {
    04215     /* We'll assume the train is facing outwards */
    04216     return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
    04217   }
    04218
    04219   if (this->track == TRACK_BIT_WORMHOLE) {
    04220     /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
    04221     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
    04222   }
    04223
    04224   return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
    04225 }