# train_cmd.cpp

Go to the documentation of this file.

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