# train_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: train_cmd.cpp 19665 2010-04-17 22:27:49Z 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 (this->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   /* Exit if the current order doesn't have a destination, but the train has orders. */
    02234   if ((v->current_order.IsType(OT_NOTHING) || v->current_order.IsType(OT_LEAVESTATION) || v->current_order.IsType(OT_LOADING)) && v->GetNumOrders() > 0) return;
    02235
    02236   Trackdir td = v->GetVehicleTrackdir();
    02237
    02238   /* On a tile with a red non-pbs signal, don't look ahead. */
    02239   if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
    02240       !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
    02241       GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
    02242
    02243   CFollowTrackRail ft(v);
    02244   if (!ft.Follow(v->tile, td)) return;
    02245
    02246   if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
    02247     /* Next tile is not reserved. */
    02248     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
    02249       if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
    02250         /* If the next tile is a PBS signal, try to make a reservation. */
    02251         TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
    02252         if (_settings_game.pf.forbid_90_deg) {
    02253           tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
    02254         }
    02255         ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
    02256       }
    02257     }
    02258   }
    02259 }
    02260
    02261 static bool CheckTrainStayInDepot(Train *v)
    02262 {
    02263   /* bail out if not all wagons are in the same depot or not in a depot at all */
    02264   for (const Train *u = v; u != NULL; u = u->Next()) {
    02265     if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
    02266   }
    02267
    02268   /* if the train got no power, then keep it in the depot */
    02269   if (v->tcache.cached_power == 0) {
    02270     v->vehstatus |= VS_STOPPED;
    02271     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
    02272     return true;
    02273   }
    02274
    02275   SigSegState seg_state;
    02276
    02277   if (v->force_proceed == 0) {
    02278     /* force proceed was not pressed */
    02279     if (++v->wait_counter < 37) {
    02280       SetWindowClassesDirty(WC_TRAINS_LIST);
    02281       return true;
    02282     }
    02283
    02284     v->wait_counter = 0;
    02285
    02286     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02287     if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
    02288       /* Full and no PBS signal in block or depot reserved, can't exit. */
    02289       SetWindowClassesDirty(WC_TRAINS_LIST);
    02290       return true;
    02291     }
    02292   } else {
    02293     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02294   }
    02295
    02296   /* We are leaving a depot, but have to go to the exact same one; re-enter */
    02297   if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
    02298     /* We need to have a reservation for this to work. */
    02299     if (HasDepotReservation(v->tile)) return true;
    02300     SetDepotReservation(v->tile, true);
    02301     VehicleEnterDepot(v);
    02302     return true;
    02303   }
    02304
    02305   /* Only leave when we can reserve a path to our destination. */
    02306   if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == 0) {
    02307     /* No path and no force proceed. */
    02308     SetWindowClassesDirty(WC_TRAINS_LIST);
    02309     MarkTrainAsStuck(v);
    02310     return true;
    02311   }
    02312
    02313   SetDepotReservation(v->tile, true);
    02314   if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
    02315
    02316   VehicleServiceInDepot(v);
    02317   SetWindowClassesDirty(WC_TRAINS_LIST);
    02318   v->PlayLeaveStationSound();
    02319
    02320   v->track = TRACK_BIT_X;
    02321   if (v->direction & 2) v->track = TRACK_BIT_Y;
    02322
    02323   v->vehstatus &= ~VS_HIDDEN;
    02324   v->cur_speed = 0;
    02325
    02326   v->UpdateDeltaXY(v->direction);
    02327   v->cur_image = v->GetImage(v->direction);
    02328   VehicleMove(v, false);
    02329   UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
    02330   v->UpdateAcceleration();
    02331   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
    02332
    02333   return false;
    02334 }
    02335
    02337 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
    02338 {
    02339   DiagDirection dir = TrackdirToExitdir(track_dir);
    02340
    02341   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    02342     /* Are we just leaving a tunnel/bridge? */
    02343     if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
    02344       TileIndex end = GetOtherTunnelBridgeEnd(tile);
    02345
    02346       if (!HasVehicleOnTunnelBridge(tile, end, v)) {
    02347         /* Free the reservation only if no other train is on the tiles. */
    02348         SetTunnelBridgeReservation(tile, false);
    02349         SetTunnelBridgeReservation(end, false);
    02350
    02351         if (_settings_client.gui.show_track_reservation) {
    02352           MarkTileDirtyByTile(tile);
    02353           MarkTileDirtyByTile(end);
    02354         }
    02355       }
    02356     }
    02357   } else if (IsRailStationTile(tile)) {
    02358     TileIndex new_tile = TileAddByDiagDir(tile, dir);
    02359     /* If the new tile is not a further tile of the same station, we
    02360      * clear the reservation for the whole platform. */
    02361     if (!IsCompatibleTrainStationTile(new_tile, tile)) {
    02362       SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
    02363     }
    02364   } else {
    02365     /* Any other tile */
    02366     UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
    02367   }
    02368 }
    02369
    02371 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
    02372 {
    02373   assert(v->IsFrontEngine());
    02374
    02375   TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
    02376   Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
    02377   bool      free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
    02378   StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
    02379
    02380   /* Don't free reservation if it's not ours. */
    02381   if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
    02382
    02383   CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
    02384   while (ft.Follow(tile, td)) {
    02385     tile = ft.m_new_tile;
    02386     TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
    02387     td = RemoveFirstTrackdir(&bits);
    02388     assert(bits == TRACKDIR_BIT_NONE);
    02389
    02390     if (!IsValidTrackdir(td)) break;
    02391
    02392     if (IsTileType(tile, MP_RAILWAY)) {
    02393       if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
    02394         /* Conventional signal along trackdir: remove reservation and stop. */
    02395         UnreserveRailTrack(tile, TrackdirToTrack(td));
    02396         break;
    02397       }
    02398       if (HasPbsSignalOnTrackdir(tile, td)) {
    02399         if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
    02400           /* Red PBS signal? Can't be our reservation, would be green then. */
    02401           break;
    02402         } else {
    02403           /* Turn the signal back to red. */
    02404           SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
    02405           MarkTileDirtyByTile(tile);
    02406         }
    02407       } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
    02408         break;
    02409       }
    02410     }
    02411
    02412     /* Don't free first station/bridge/tunnel if we are on it. */
    02413     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);
    02414
    02415     free_tile = true;
    02416   }
    02417 }
    02418
    02419 static const byte _initial_tile_subcoord[6][4][3] = {
    02420 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
    02421 {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
    02422 {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
    02423 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
    02424 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
    02425 {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
    02426 };
    02427
    02440 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool do_track_reservation, PBSTileInfo *dest)
    02441 {
    02442   switch (_settings_game.pf.pathfinder_for_trains) {
    02443     case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
    02444     case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
    02445
    02446     default: NOT_REACHED();
    02447   }
    02448 }
    02449
    02455 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
    02456 {
    02457   PBSTileInfo origin = FollowTrainReservation(v);
    02458
    02459   CFollowTrackRail ft(v);
    02460
    02461   TileIndex tile = origin.tile;
    02462   Trackdir  cur_td = origin.trackdir;
    02463   while (ft.Follow(tile, cur_td)) {
    02464     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
    02465       /* Possible signal tile. */
    02466       if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
    02467     }
    02468
    02469     if (_settings_game.pf.forbid_90_deg) {
    02470       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
    02471       if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
    02472     }
    02473
    02474     /* Station, depot or waypoint are a possible target. */
    02475     bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
    02476     if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
    02477       /* Choice found or possible target encountered.
    02478        * On finding a possible target, we need to stop and let the pathfinder handle the
    02479        * remaining path. This is because we don't know if this target is in one of our
    02480        * orders, so we might cause pathfinding to fail later on if we find a choice.
    02481        * This failure would cause a bogous call to TryReserveSafePath which might reserve
    02482        * a wrong path not leading to our next destination. */
    02483       if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
    02484
    02485       /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
    02486        * actually starts its search at the first unreserved tile. */
    02487       if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
    02488
    02489       /* Choice found, path valid but not okay. Save info about the choice tile as well. */
    02490       if (new_tracks) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
    02491       if (enterdir) *enterdir = ft.m_exitdir;
    02492       return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
    02493     }
    02494
    02495     tile = ft.m_new_tile;
    02496     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
    02497
    02498     if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
    02499       bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
    02500       if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
    02501       /* Safe position is all good, path valid and okay. */
    02502       return PBSTileInfo(tile, cur_td, true);
    02503     }
    02504
    02505     if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
    02506   }
    02507
    02508   if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
    02509     /* End of line, path valid and okay. */
    02510     return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
    02511   }
    02512
    02513   /* Sorry, can't reserve path, back out. */
    02514   tile = origin.tile;
    02515   cur_td = origin.trackdir;
    02516   TileIndex stopped = ft.m_old_tile;
    02517   Trackdir  stopped_td = ft.m_old_td;
    02518   while (tile != stopped || cur_td != stopped_td) {
    02519     if (!ft.Follow(tile, cur_td)) break;
    02520
    02521     if (_settings_game.pf.forbid_90_deg) {
    02522       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
    02523       assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
    02524     }
    02525     assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
    02526
    02527     tile = ft.m_new_tile;
    02528     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
    02529
    02530     UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
    02531   }
    02532
    02533   /* Path invalid. */
    02534   return PBSTileInfo();
    02535 }
    02536
    02547 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
    02548 {
    02549   switch (_settings_game.pf.pathfinder_for_trains) {
    02550     case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
    02551     case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
    02552
    02553     default: NOT_REACHED();
    02554   }
    02555 }
    02556
    02558 class VehicleOrderSaver
    02559 {
    02560 private:
    02561   Vehicle        *v;
    02562   Order          old_order;
    02563   TileIndex      old_dest_tile;
    02564   StationID      old_last_station_visited;
    02565   VehicleOrderID index;
    02566
    02567 public:
    02568   VehicleOrderSaver(Vehicle *_v) :
    02569     v(_v),
    02570     old_order(_v->current_order),
    02571     old_dest_tile(_v->dest_tile),
    02572     old_last_station_visited(_v->last_station_visited),
    02573     index(_v->cur_order_index)
    02574   {
    02575   }
    02576
    02577   ~VehicleOrderSaver()
    02578   {
    02579     this->v->current_order = this->old_order;
    02580     this->v->dest_tile = this->old_dest_tile;
    02581     this->v->last_station_visited = this->old_last_station_visited;
    02582   }
    02583
    02589   bool SwitchToNextOrder(bool skip_first)
    02590   {
    02591     if (this->v->GetNumOrders() == 0) return false;
    02592
    02593     if (skip_first) ++this->index;
    02594
    02595     int conditional_depth = 0;
    02596
    02597     do {
    02598       /* Wrap around. */
    02599       if (this->index >= this->v->GetNumOrders()) this->index = 0;
    02600
    02601       Order *order = this->v->GetOrder(this->index);
    02602       assert(order != NULL);
    02603
    02604       switch (order->GetType()) {
    02605         case OT_GOTO_DEPOT:
    02606           /* Skip service in depot orders when the train doesn't need service. */
    02607           if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
    02608         case OT_GOTO_STATION:
    02609         case OT_GOTO_WAYPOINT:
    02610           this->v->current_order = *order;
    02611           UpdateOrderDest(this->v, order);
    02612           return true;
    02613         case OT_CONDITIONAL: {
    02614           if (conditional_depth > this->v->GetNumOrders()) return false;
    02615           VehicleOrderID next = ProcessConditionalOrder(order, this->v);
    02616           if (next != INVALID_VEH_ORDER_ID) {
    02617             conditional_depth++;
    02618             this->index = next;
    02619             /* Don't increment next, so no break here. */
    02620             continue;
    02621           }
    02622           break;
    02623         }
    02624         default:
    02625           break;
    02626       }
    02627       /* Don't increment inside the while because otherwise conditional
    02628        * orders can lead to an infinite loop. */
    02629       ++this->index;
    02630     } while (this->index != this->v->cur_order_index);
    02631
    02632     return false;
    02633   }
    02634 };
    02635
    02636 /* choose a track */
    02637 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
    02638 {
    02639   Track best_track = INVALID_TRACK;
    02640   bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
    02641   bool changed_signal = false;
    02642
    02643   assert((tracks & ~TRACK_BIT_MASK) == 0);
    02644
    02645   if (got_reservation != NULL) *got_reservation = false;
    02646
    02647   /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
    02648   TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
    02649   /* Do we have a suitable reserved track? */
    02650   if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
    02651
    02652   /* Quick return in case only one possible track is available */
    02653   if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
    02654     Track track = FindFirstTrack(tracks);
    02655     /* We need to check for signals only here, as a junction tile can't have signals. */
    02656     if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
    02657       do_track_reservation = true;
    02658       changed_signal = true;
    02659       SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
    02660     } else if (!do_track_reservation) {
    02661       return track;
    02662     }
    02663     best_track = track;
    02664   }
    02665
    02666   PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
    02667   DiagDirection dest_enterdir = enterdir;
    02668   if (do_track_reservation) {
    02669     /* Check if the train needs service here, so it has a chance to always find a depot.
    02670      * Also check if the current order is a service order so we don't reserve a path to
    02671      * the destination but instead to the next one if service isn't needed. */
    02672     CheckIfTrainNeedsService(v);
    02673     if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
    02674
    02675     res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
    02676     if (res_dest.tile == INVALID_TILE) {
    02677       /* Reservation failed? */
    02678       if (mark_stuck) MarkTrainAsStuck(v);
    02679       if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
    02680       return FindFirstTrack(tracks);
    02681     }
    02682   }
    02683
    02684   /* Save the current train order. The destructor will restore the old order on function exit. */
    02685   VehicleOrderSaver orders(v);
    02686
    02687   /* If the current tile is the destination of the current order and
    02688    * a reservation was requested, advance to the next order.
    02689    * Don't advance on a depot order as depots are always safe end points
    02690    * for a path and no look-ahead is necessary. This also avoids a
    02691    * problem with depot orders not part of the order list when the
    02692    * order list itself is empty. */
    02693   if (v->current_order.IsType(OT_LEAVESTATION)) {
    02694     orders.SwitchToNextOrder(false);
    02695   } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
    02696       v->current_order.IsType(OT_GOTO_STATION) ?
    02697       IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
    02698       v->tile == v->dest_tile))) {
    02699     orders.SwitchToNextOrder(true);
    02700   }
    02701
    02702   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
    02703     /* Pathfinders are able to tell that route was only 'guessed'. */
    02704     bool      path_not_found = false;
    02705     TileIndex new_tile = res_dest.tile;
    02706
    02707     Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, &path_not_found, do_track_reservation, &res_dest);
    02708     if (new_tile == tile) best_track = next_track;
    02709
    02710     /* handle "path not found" state */
    02711     if (path_not_found) {
    02712       /* PF didn't find the route */
    02713       if (!HasBit(v->flags, VRF_NO_PATH_TO_DESTINATION)) {
    02714         /* it is first time the problem occurred, set the "path not found" flag */
    02715         SetBit(v->flags, VRF_NO_PATH_TO_DESTINATION);
    02716         /* and notify user about the event */
    02717         AI::NewEvent(v->owner, new AIEventVehicleLost(v->index));
    02718         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
    02719           SetDParam(0, v->index);
    02720           AddVehicleNewsItem(
    02721             STR_NEWS_TRAIN_IS_LOST,
    02722             NS_ADVICE,
    02723             v->index
    02724           );
    02725         }
    02726       }
    02727     } else {
    02728       /* route found, is the train marked with "path not found" flag? */
    02729       if (HasBit(v->flags, VRF_NO_PATH_TO_DESTINATION)) {
    02730         /* clear the flag as the PF's problem was solved */
    02731         ClrBit(v->flags, VRF_NO_PATH_TO_DESTINATION);
    02732         /* can we also delete the "News" item somehow? */
    02733       }
    02734     }
    02735   }
    02736
    02737   /* No track reservation requested -> finished. */
    02738   if (!do_track_reservation) return best_track;
    02739
    02740   /* A path was found, but could not be reserved. */
    02741   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
    02742     if (mark_stuck) MarkTrainAsStuck(v);
    02743     FreeTrainTrackReservation(v);
    02744     return best_track;
    02745   }
    02746
    02747   /* No possible reservation target found, we are probably lost. */
    02748   if (res_dest.tile == INVALID_TILE) {
    02749     /* Try to find any safe destination. */
    02750     PBSTileInfo origin = FollowTrainReservation(v);
    02751     if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
    02752       TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
    02753       best_track = FindFirstTrack(res);
    02754       TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
    02755       if (got_reservation != NULL) *got_reservation = true;
    02756       if (changed_signal) MarkTileDirtyByTile(tile);
    02757     } else {
    02758       FreeTrainTrackReservation(v);
    02759       if (mark_stuck) MarkTrainAsStuck(v);
    02760     }
    02761     return best_track;
    02762   }
    02763
    02764   if (got_reservation != NULL) *got_reservation = true;
    02765
    02766   /* Reservation target found and free, check if it is safe. */
    02767   while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
    02768     /* Extend reservation until we have found a safe position. */
    02769     DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
    02770     TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
    02771     TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
    02772     if (_settings_game.pf.forbid_90_deg) {
    02773       reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
    02774     }
    02775
    02776     /* Get next order with destination. */
    02777     if (orders.SwitchToNextOrder(true)) {
    02778       PBSTileInfo cur_dest;
    02779       DoTrainPathfind(v, next_tile, exitdir, reachable, NULL, true, &cur_dest);
    02780       if (cur_dest.tile != INVALID_TILE) {
    02781         res_dest = cur_dest;
    02782         if (res_dest.okay) continue;
    02783         /* Path found, but could not be reserved. */
    02784         FreeTrainTrackReservation(v);
    02785         if (mark_stuck) MarkTrainAsStuck(v);
    02786         if (got_reservation != NULL) *got_reservation = false;
    02787         changed_signal = false;
    02788         break;
    02789       }
    02790     }
    02791     /* No order or no safe position found, try any position. */
    02792     if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
    02793       FreeTrainTrackReservation(v);
    02794       if (mark_stuck) MarkTrainAsStuck(v);
    02795       if (got_reservation != NULL) *got_reservation = false;
    02796       changed_signal = false;
    02797     }
    02798     break;
    02799   }
    02800
    02801   TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
    02802
    02803   if (changed_signal) MarkTileDirtyByTile(tile);
    02804
    02805   return best_track;
    02806 }
    02807
    02816 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
    02817 {
    02818   assert(v->IsFrontEngine());
    02819
    02820   /* We have to handle depots specially as the track follower won't look
    02821    * at the depot tile itself but starts from the next tile. If we are still
    02822    * inside the depot, a depot reservation can never be ours. */
    02823   if (v->track == TRACK_BIT_DEPOT) {
    02824     if (HasDepotReservation(v->tile)) {
    02825       if (mark_as_stuck) MarkTrainAsStuck(v);
    02826       return false;
    02827     } else {
    02828       /* Depot not reserved, but the next tile might be. */
    02829       TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
    02830       if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
    02831     }
    02832   }
    02833
    02834   Vehicle *other_train = NULL;
    02835   PBSTileInfo origin = FollowTrainReservation(v, &other_train);
    02836   /* The path we are driving on is alread blocked by some other train.
    02837    * This can only happen in certain situations when mixing path and
    02838    * block signals or when changing tracks and/or signals.
    02839    * Exit here as doing any further reservations will probably just
    02840    * make matters worse. */
    02841   if (other_train != NULL && other_train->index != v->index) {
    02842     if (mark_as_stuck) MarkTrainAsStuck(v);
    02843     return false;
    02844   }
    02845   /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
    02846   if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
    02847     /* Can't be stuck then. */
    02848     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    02849     ClrBit(v->flags, VRF_TRAIN_STUCK);
    02850     return true;
    02851   }
    02852
    02853   /* If we are in a depot, tentativly reserve the depot. */
    02854   if (v->track == TRACK_BIT_DEPOT) {
    02855     SetDepotReservation(v->tile, true);
    02856     if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
    02857   }
    02858
    02859   DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
    02860   TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
    02861   TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
    02862
    02863   if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
    02864
    02865   bool res_made = false;
    02866   ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
    02867
    02868   if (!res_made) {
    02869     /* Free the depot reservation as well. */
    02870     if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
    02871     return false;
    02872   }
    02873
    02874   if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
    02875     v->wait_counter = 0;
    02876     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    02877   }
    02878   ClrBit(v->flags, VRF_TRAIN_STUCK);
    02879   return true;
    02880 }
    02881
    02882
    02883 static bool CheckReverseTrain(const Train *v)
    02884 {
    02885   if (_settings_game.difficulty.line_reverse_mode != 0 ||
    02886       v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
    02887       !(v->direction & 1)) {
    02888     return false;
    02889   }
    02890
    02891   assert(v->track != TRACK_BIT_NONE);
    02892
    02893   switch (_settings_game.pf.pathfinder_for_trains) {
    02894     case VPF_NPF: return NPFTrainCheckReverse(v);
    02895     case VPF_YAPF: return YapfTrainCheckReverse(v);
    02896
    02897     default: NOT_REACHED();
    02898   }
    02899 }
    02900
    02901 TileIndex Train::GetOrderStationLocation(StationID station)
    02902 {
    02903   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
    02904
    02905   const Station *st = Station::Get(station);
    02906   if (!(st->facilities & FACIL_TRAIN)) {
    02907     /* The destination station has no trainstation tiles. */
    02908     this->IncrementOrderIndex();
    02909     return 0;
    02910   }
    02911
    02912   return st->xy;
    02913 }
    02914
    02915 void Train::MarkDirty()
    02916 {
    02917   Vehicle *v = this;
    02918   do {
    02919     v->UpdateViewport(false, false);
    02920   } while ((v = v->Next()) != NULL);
    02921
    02922   /* need to update acceleration and cached values since the goods on the train changed. */
    02923   this->CargoChanged();
    02924   this->UpdateAcceleration();
    02925 }
    02926
    02936 int Train::UpdateSpeed()
    02937 {
    02938   uint accel;
    02939
    02940   switch (_settings_game.vehicle.train_acceleration_model) {
    02941     default: NOT_REACHED();
    02942     case AM_ORIGINAL:
    02943       accel = this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2);
    02944       break;
    02945     case AM_REALISTIC:
    02946       this->max_speed = this->GetCurrentMaxSpeed();
    02947       accel = this->GetAcceleration();
    02948       break;
    02949   }
    02950
    02951   uint spd = this->subspeed + accel;
    02952   this->subspeed = (byte)spd;
    02953   {
    02954     int tempmax = this->max_speed;
    02955     if (this->cur_speed > this->max_speed)
    02956       tempmax = this->cur_speed - (this->cur_speed / 10) - 1;
    02957     this->cur_speed = spd = Clamp(this->cur_speed + ((int)spd >> 8), 0, tempmax);
    02958   }
    02959
    02960   /* Scale speed by 3/4. Previously this was only done when the train was
    02961    * facing diagonally and would apply to however many moves the train made
    02962    * regardless the of direction actually moved in. Now it is always scaled,
    02963    * 256 spd is used to go straight and 192 is used to go diagonally
    02964    * (3/4 of 256). This results in the same effect, but without the error the
    02965    * previous method caused.
    02966    *
    02967    * The scaling is done in this direction and not by multiplying the amount
    02968    * to be subtracted by 4/3 so that the leftover speed can be saved in a
    02969    * byte in this->progress.
    02970    */
    02971   int scaled_spd = spd * 3 >> 2;
    02972
    02973   scaled_spd += this->progress;
    02974   this->progress = 0; // set later in TrainLocoHandler or TrainController
    02975   return scaled_spd;
    02976 }
    02977
    02978 static void TrainEnterStation(Train *v, StationID station)
    02979 {
    02980   v->last_station_visited = station;
    02981
    02982   /* check if a train ever visited this station before */
    02983   Station *st = Station::Get(station);
    02984   if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
    02985     st->had_vehicle_of_type |= HVOT_TRAIN;
    02986     SetDParam(0, st->index);
    02987     AddVehicleNewsItem(
    02988       STR_NEWS_FIRST_TRAIN_ARRIVAL,
    02989       v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
    02990       v->index,
    02991       st->index
    02992     );
    02993     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
    02994   }
    02995
    02996   v->BeginLoading();
    02997
    02998   StationAnimationTrigger(st, v->tile, STAT_ANIM_TRAIN_ARRIVES);
    02999 }
    03000
    03001 static byte AfterSetTrainPos(Train *v, bool new_tile)
    03002 {
    03003   byte old_z = v->z_pos;
    03004   v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
    03005
    03006   if (new_tile) {
    03007     ClrBit(v->flags, VRF_GOINGUP);
    03008     ClrBit(v->flags, VRF_GOINGDOWN);
    03009
    03010     if (v->track == TRACK_BIT_X || v->track == TRACK_BIT_Y) {
    03011       /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped.
    03012        * To check whether the current tile is sloped, and in which
    03013        * direction it is sloped, we get the 'z' at the center of
    03014        * the tile (middle_z) and the edge of the tile (old_z),
    03015        * which we then can compare. */
    03016       static const int HALF_TILE_SIZE = TILE_SIZE / 2;
    03017       static const int INV_TILE_SIZE_MASK = ~(TILE_SIZE - 1);
    03018
    03019       byte middle_z = GetSlopeZ((v->x_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE, (v->y_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE);
    03020
    03021       if (middle_z != v->z_pos) {
    03022         SetBit(v->flags, (middle_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN);
    03023       }
    03024     }
    03025   }
    03026
    03027   VehicleMove(v, true);
    03028   return old_z;
    03029 }
    03030
    03031 /* Check if the vehicle is compatible with the specified tile */
    03032 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
    03033 {
    03034   return
    03035     IsTileOwner(tile, v->owner) && (
    03036       !v->IsFrontEngine() ||
    03037       HasBit(v->compatible_railtypes, GetRailType(tile))
    03038     );
    03039 }
    03040
    03041 struct RailtypeSlowdownParams {
    03042   byte small_turn, large_turn;
    03043   byte z_up; // fraction to remove when moving up
    03044   byte z_down; // fraction to remove when moving down
    03045 };
    03046
    03047 static const RailtypeSlowdownParams _railtype_slowdown[] = {
    03048   /* normal accel */
    03049   {256 / 4, 256 / 2, 256 / 4, 2},
    03050   {256 / 4, 256 / 2, 256 / 4, 2},
    03051   {256 / 4, 256 / 2, 256 / 4, 2},
    03052   {0,       256 / 2, 256 / 4, 2},
    03053 };
    03054
    03056 static inline void AffectSpeedByZChange(Train *v, byte old_z)
    03057 {
    03058   if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
    03059
    03060   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
    03061
    03062   if (old_z < v->z_pos) {
    03063     v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
    03064   } else {
    03065     uint16 spd = v->cur_speed + rsp->z_down;
    03066     if (spd <= v->max_speed) v->cur_speed = spd;
    03067   }
    03068 }
    03069
    03070 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
    03071 {
    03072   if (IsTileType(tile, MP_RAILWAY) &&
    03073       GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
    03074     TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
    03075     Trackdir trackdir = FindFirstTrackdir(tracks);
    03076     if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
    03077       /* A PBS block with a non-PBS signal facing us? */
    03078       if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
    03079     }
    03080   }
    03081   return false;
    03082 }
    03083
    03087 void Train::ReserveTrackUnderConsist() const
    03088 {
    03089   for (const Train *u = this; u != NULL; u = u->Next()) {
    03090     switch (u->track) {
    03091       case TRACK_BIT_WORMHOLE:
    03092         TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
    03093         break;
    03094       case TRACK_BIT_DEPOT:
    03095         break;
    03096       default:
    03097         TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
    03098         break;
    03099     }
    03100   }
    03101 }
    03102
    03103 uint Train::Crash(bool flooded)
    03104 {
    03105   uint pass = 0;
    03106   if (this->IsFrontEngine()) {
    03107     pass += 4; // driver
    03108
    03109     /* Remove the reserved path in front of the train if it is not stuck.
    03110      * Also clear all reserved tracks the train is currently on. */
    03111     if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
    03112     for (const Train *v = this; v != NULL; v = v->Next()) {
    03113       ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
    03114       if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
    03115         /* ClearPathReservation will not free the wormhole exit
    03116          * if the train has just entered the wormhole. */
    03117         SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
    03118       }
    03119     }
    03120
    03121     /* we may need to update crossing we were approaching,
    03122     * but must be updated after the train has been marked crashed */
    03123     TileIndex crossing = TrainApproachingCrossingTile(this);
    03124     if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
    03125
    03126     /* Remove the loading indicators (if any) */
    03127     HideFillingPercent(&this->fill_percent_te_id);
    03128   }
    03129
    03130   pass += Vehicle::Crash(flooded);
    03131
    03132   this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
    03133   return pass;
    03134 }
    03135
    03142 static uint TrainCrashed(Train *v)
    03143 {
    03144   uint num = 0;
    03145
    03146   /* do not crash train twice */
    03147   if (!(v->vehstatus & VS_CRASHED)) {
    03148     num = v->Crash();
    03149     AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
    03150   }
    03151
    03152   /* Try to re-reserve track under already crashed train too.
    03153    * SetVehicleCrashed() clears the reservation! */
    03154   v->ReserveTrackUnderConsist();
    03155
    03156   return num;
    03157 }
    03158
    03159 struct TrainCollideChecker {
    03160   Train *v;
    03161   uint num;
    03162 };
    03163
    03164 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
    03165 {
    03166   TrainCollideChecker *tcc = (TrainCollideChecker*)data;
    03167
    03168   /* not a train or in depot */
    03169   if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
    03170
    03171   /* do not crash into trains of another company. */
    03172   if (v->owner != tcc->v->owner) return NULL;
    03173
    03174   /* get first vehicle now to make most usual checks faster */
    03175   Train *coll = Train::From(v)->First();
    03176
    03177   /* can't collide with own wagons */
    03178   if (coll == tcc->v) return NULL;
    03179
    03180   int x_diff = v->x_pos - tcc->v->x_pos;
    03181   int y_diff = v->y_pos - tcc->v->y_pos;
    03182
    03183   /* Do fast calculation to check whether trains are not in close vicinity
    03184    * and quickly reject trains distant enough for any collision.
    03185    * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
    03186    * Differences are then ORed and then we check for any higher bits */
    03187   uint hash = (y_diff + 7) | (x_diff + 7);
    03188   if (hash & ~15) return NULL;
    03189
    03190   /* Slower check using multiplication */
    03191   if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
    03192
    03193   /* Happens when there is a train under bridge next to bridge head */
    03194   if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
    03195
    03196   /* crash both trains */
    03197   tcc->num += TrainCrashed(tcc->v);
    03198   tcc->num += TrainCrashed(coll);
    03199
    03200   return NULL; // continue searching
    03201 }
    03202
    03209 static bool CheckTrainCollision(Train *v)
    03210 {
    03211   /* can't collide in depot */
    03212   if (v->track == TRACK_BIT_DEPOT) return false;
    03213
    03214   assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
    03215
    03216   TrainCollideChecker tcc;
    03217   tcc.v = v;
    03218   tcc.num = 0;
    03219
    03220   /* find colliding vehicles */
    03221   if (v->track == TRACK_BIT_WORMHOLE) {
    03222     FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
    03223     FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
    03224   } else {
    03225     FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
    03226   }
    03227
    03228   /* any dead -> no crash */
    03229   if (tcc.num == 0) return false;
    03230
    03231   SetDParam(0, tcc.num);
    03232   AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH,
    03233     NS_ACCIDENT,
    03234     v->index
    03235   );
    03236
    03237   ModifyStationRatingAround(v->tile, v->owner, -160, 30);
    03238   SndPlayVehicleFx(SND_13_BIG_CRASH, v);
    03239   return true;
    03240 }
    03241
    03242 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
    03243 {
    03244   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
    03245
    03246   Train *t = Train::From(v);
    03247   DiagDirection exitdir = *(DiagDirection *)data;
    03248
    03249   /* not front engine of a train, inside wormhole or depot, crashed */
    03250   if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
    03251
    03252   if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
    03253
    03254   return t;
    03255 }
    03256
    03257 static void TrainController(Train *v, Vehicle *nomove)
    03258 {
    03259   Train *first = v->First();
    03260   Train *prev;
    03261   bool direction_changed = false; // has direction of any part changed?
    03262
    03263   /* For every vehicle after and including the given vehicle */
    03264   for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
    03265     DiagDirection enterdir = DIAGDIR_BEGIN;
    03266     bool update_signals_crossing = false; // will we update signals or crossing state?
    03267
    03268     GetNewVehiclePosResult gp = GetNewVehiclePos(v);
    03269     if (v->track != TRACK_BIT_WORMHOLE) {
    03270       /* Not inside tunnel */
    03271       if (gp.old_tile == gp.new_tile) {
    03272         /* Staying in the old tile */
    03273         if (v->track == TRACK_BIT_DEPOT) {
    03274           /* Inside depot */
    03275           gp.x = v->x_pos;
    03276           gp.y = v->y_pos;
    03277         } else {
    03278           /* Not inside depot */
    03279
    03280           /* Reverse when we are at the end of the track already, do not move to the new position */
    03281           if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v)) return;
    03282
    03283           uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    03284           if (HasBit(r, VETS_CANNOT_ENTER)) {
    03285             goto invalid_rail;
    03286           }
    03287           if (HasBit(r, VETS_ENTERED_STATION)) {
    03288             /* The new position is the end of the platform */
    03289             TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
    03290           }
    03291         }
    03292       } else {
    03293         /* A new tile is about to be entered. */
    03294
    03295         /* Determine what direction we're entering the new tile from */
    03296         enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
    03297         assert(IsValidDiagDirection(enterdir));
    03298
    03299         /* Get the status of the tracks in the new tile and mask
    03300          * away the bits that aren't reachable. */
    03301         TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
    03302         TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
    03303
    03304         TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
    03305         TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
    03306
    03307         TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
    03308         if (_settings_game.pf.forbid_90_deg && prev == NULL) {
    03309           /* We allow wagons to make 90 deg turns, because forbid_90_deg
    03310            * can be switched on halfway a turn */
    03311           bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
    03312         }
    03313
    03314         if (bits == TRACK_BIT_NONE) goto invalid_rail;
    03315
    03316         /* Check if the new tile contrains tracks that are compatible
    03317          * with the current train, if not, bail out. */
    03318         if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
    03319
    03320         TrackBits chosen_track;
    03321         if (prev == NULL) {
    03322           /* Currently the locomotive is active. Determine which one of the
    03323            * available tracks to choose */
    03324           chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
    03325           assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
    03326
    03327           if (v->force_proceed != 0 && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
    03328             /* For each signal we find decrease the counter by one.
    03329              * We start at two, so the first signal we pass decreases
    03330              * this to one, then if we reach the next signal it is
    03331              * decreased to zero and we won't pass that new signal. */
    03332             Trackdir dir = FindFirstTrackdir(trackdirbits);
    03333             if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
    03334                 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
    03335               /* However, we do not want to be stopped by PBS signals
    03336                * entered via the back. */
    03337               v->force_proceed--;
    03338               SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03339             }
    03340           }
    03341
    03342           /* Check if it's a red signal and that force proceed is not clicked. */
    03343           if ((red_signals & chosen_track) && v->force_proceed == 0) {
    03344             /* In front of a red signal */
    03345             Trackdir i = FindFirstTrackdir(trackdirbits);
    03346
    03347             /* Don't handle stuck trains here. */
    03348             if (HasBit(v->flags, VRF_TRAIN_STUCK)) return;
    03349
    03350             if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
    03351               v->cur_speed = 0;
    03352               v->subspeed = 0;
    03353               v->progress = 255 - 100;
    03354               if (_settings_game.pf.wait_oneway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return;
    03355             } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
    03356               v->cur_speed = 0;
    03357               v->subspeed = 0;
    03358               v->progress = 255 - 10;
    03359               if (_settings_game.pf.wait_twoway_signal == 255 || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
    03360                 DiagDirection exitdir = TrackdirToExitdir(i);
    03361                 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
    03362
    03363                 exitdir = ReverseDiagDir(exitdir);
    03364
    03365                 /* check if a train is waiting on the other side */
    03366                 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return;
    03367               }
    03368             }
    03369
    03370             /* If we would reverse but are currently in a PBS block and
    03371              * reversing of stuck trains is disabled, don't reverse.
    03372              * This does not apply if the reason for reversing is a one-way
    03373              * signal blocking us, because a train would then be stuck forever. */
    03374             if (_settings_game.pf.wait_for_pbs_path == 255 && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
    03375                 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
    03376               v->wait_counter = 0;
    03377               return;
    03378             }
    03379             goto reverse_train_direction;
    03380           } else {
    03381             TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
    03382           }
    03383         } else {
    03384           /* The wagon is active, simply follow the prev vehicle. */
    03385           if (prev->tile == gp.new_tile) {
    03386             /* Choose the same track as prev */
    03387             if (prev->track == TRACK_BIT_WORMHOLE) {
    03388               /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
    03389                * However, just choose the track into the wormhole. */
    03390               assert(IsTunnel(prev->tile));
    03391               chosen_track = bits;
    03392             } else {
    03393               chosen_track = prev->track;
    03394             }
    03395           } else {
    03396             /* Choose the track that leads to the tile where prev is.
    03397              * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
    03398              * I.e. when the tile between them has only space for a single vehicle like
    03399              *  1) horizontal/vertical track tiles and
    03400              *  2) some orientations of tunnelentries, where the vehicle is already inside the wormhole at 8/16 from the tileedge.
    03401              *     Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnelentry.
    03402              */
    03403             static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
    03404               {TRACK_BIT_X,     TRACK_BIT_LOWER, TRACK_BIT_NONE,  TRACK_BIT_LEFT },
    03405               {TRACK_BIT_UPPER, TRACK_BIT_Y,     TRACK_BIT_LEFT,  TRACK_BIT_NONE },
    03406               {TRACK_BIT_NONE,  TRACK_BIT_RIGHT, TRACK_BIT_X,     TRACK_BIT_UPPER},
    03407               {TRACK_BIT_RIGHT, TRACK_BIT_NONE,  TRACK_BIT_LOWER, TRACK_BIT_Y    }
    03408             };
    03409             DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
    03410             assert(IsValidDiagDirection(exitdir));
    03411             chosen_track = _connecting_track[enterdir][exitdir];
    03412           }
    03413           chosen_track &= bits;
    03414         }
    03415
    03416         /* Make sure chosen track is a valid track */
    03417         assert(
    03418             chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
    03419             chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
    03420             chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
    03421
    03422         /* Update XY to reflect the entrance to the new tile, and select the direction to use */
    03423         const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
    03424         gp.x = (gp.x & ~0xF) | b[0];
    03425         gp.y = (gp.y & ~0xF) | b[1];
    03426         Direction chosen_dir = (Direction)b[2];
    03427
    03428         /* Call the landscape function and tell it that the vehicle entered the tile */
    03429         uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
    03430         if (HasBit(r, VETS_CANNOT_ENTER)) {
    03431           goto invalid_rail;
    03432         }
    03433
    03434         if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
    03435           Track track = FindFirstTrack(chosen_track);
    03436           Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
    03437           if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
    03438             SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
    03439             MarkTileDirtyByTile(gp.new_tile);
    03440           }
    03441
    03442           /* Clear any track reservation when the last vehicle leaves the tile */
    03443           if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
    03444
    03445           v->tile = gp.new_tile;
    03446
    03447           if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
    03448             v->First()->PowerChanged();
    03449             v->First()->UpdateAcceleration();
    03450           }
    03451
    03452           v->track = chosen_track;
    03453           assert(v->track);
    03454         }
    03455
    03456         /* We need to update signal status, but after the vehicle position hash
    03457          * has been updated by AfterSetTrainPos() */
    03458         update_signals_crossing = true;
    03459
    03460         if (chosen_dir != v->direction) {
    03461           if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
    03462             const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
    03463             DirDiff diff = DirDifference(v->direction, chosen_dir);
    03464             v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
    03465           }
    03466           direction_changed = true;
    03467           v->direction = chosen_dir;
    03468         }
    03469
    03470         if (v->IsFrontEngine()) {
    03471           v->wait_counter = 0;
    03472
    03473           /* If we are approching a crossing that is reserved, play the sound now. */
    03474           TileIndex crossing = TrainApproachingCrossingTile(v);
    03475           if (crossing != INVALID_TILE && HasCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
    03476
    03477           /* Always try to extend the reservation when entering a tile. */
    03478           CheckNextTrainTile(v);
    03479         }
    03480
    03481         if (HasBit(r, VETS_ENTERED_STATION)) {
    03482           /* The new position is the location where we want to stop */
    03483           TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
    03484         }
    03485       }
    03486     } else {
    03487       /* In a tunnel or on a bridge
    03488        * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
    03489        * - for bridges, only the middle part - without the bridge heads */
    03490       if (!(v->vehstatus & VS_HIDDEN)) {
    03491         v->cur_speed =
    03492           min(v->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
    03493       }
    03494
    03495       if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
    03496         /* Perform look-ahead on tunnel exit. */
    03497         if (v->IsFrontEngine()) {
    03498           TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
    03499           CheckNextTrainTile(v);
    03500         }
    03501       } else {
    03502         v->x_pos = gp.x;
    03503         v->y_pos = gp.y;
    03504         VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
    03505         continue;
    03506       }
    03507     }
    03508
    03509     /* update image of train, as well as delta XY */
    03510     v->UpdateDeltaXY(v->direction);
    03511
    03512     v->x_pos = gp.x;
    03513     v->y_pos = gp.y;
    03514
    03515     /* update the Z position of the vehicle */
    03516     byte old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile));
    03517
    03518     if (prev == NULL) {
    03519       /* This is the first vehicle in the train */
    03520       AffectSpeedByZChange(v, old_z);
    03521     }
    03522
    03523     if (update_signals_crossing) {
    03524       if (v->IsFrontEngine()) {
    03525         if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
    03526           /* We are entering a block with PBS signals right now, but
    03527            * not through a PBS signal. This means we don't have a
    03528            * reservation right now. As a conventional signal will only
    03529            * ever be green if no other train is in the block, getting
    03530            * a path should always be possible. If the player built
    03531            * such a strange network that it is not possible, the train
    03532            * will be marked as stuck and the player has to deal with
    03533            * the problem. */
    03534           if ((!HasReservedTracks(gp.new_tile, v->track) &&
    03535               !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
    03536               !TryPathReserve(v)) {
    03537             MarkTrainAsStuck(v);
    03538           }
    03539         }
    03540       }
    03541
    03542       /* Signals can only change when the first
    03543        * (above) or the last vehicle moves. */
    03544       if (v->Next() == NULL) {
    03545         TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
    03546         if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
    03547       }
    03548     }
    03549
    03550     /* Do not check on every tick to save some computing time. */
    03551     if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
    03552   }
    03553
    03554   if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
    03555
    03556   return;
    03557
    03558 invalid_rail:
    03559   /* We've reached end of line?? */
    03560   if (prev != NULL) error("Disconnecting train");
    03561
    03562 reverse_train_direction:
    03563   v->wait_counter = 0;
    03564   v->cur_speed = 0;
    03565   v->subspeed = 0;
    03566   ReverseTrainDirection(v);
    03567 }
    03568
    03574 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
    03575 {
    03576   TrackBits *trackbits = (TrackBits *)data;
    03577
    03578   if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
    03579     if (Train::From(v)->track == TRACK_BIT_WORMHOLE) {
    03580       /* Vehicle is inside a wormhole, v->track contains no useful value then. */
    03581       *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
    03582     } else {
    03583       *trackbits |= Train::From(v)->track;
    03584     }
    03585   }
    03586
    03587   return NULL;
    03588 }
    03589
    03597 static void DeleteLastWagon(Train *v)
    03598 {
    03599   Train *first = v->First();
    03600
    03601   /* Go to the last wagon and delete the link pointing there
    03602    * *u is then the one-before-last wagon, and *v the last
    03603    * one which will physicially be removed */
    03604   Train *u = v;
    03605   for (; v->Next() != NULL; v = v->Next()) u = v;
    03606   u->SetNext(NULL);
    03607
    03608   if (first != v) {
    03609     /* Recalculate cached train properties */
    03610     first->ConsistChanged(false);
    03611     /* Update the depot window if the first vehicle is in depot -
    03612      * if v == first, then it is updated in PreDestructor() */
    03613     if (first->track == TRACK_BIT_DEPOT) {
    03614       SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
    03615     }
    03616   }
    03617
    03618   /* 'v' shouldn't be accessed after it has been deleted */
    03619   TrackBits trackbits = v->track;
    03620   TileIndex tile = v->tile;
    03621   Owner owner = v->owner;
    03622
    03623   delete v;
    03624   v = NULL; // make sure nobody will try to read 'v' anymore
    03625
    03626   if (trackbits == TRACK_BIT_WORMHOLE) {
    03627     /* Vehicle is inside a wormhole, v->track contains no useful value then. */
    03628     trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
    03629   }
    03630
    03631   Track track = TrackBitsToTrack(trackbits);
    03632   if (HasReservedTracks(tile, trackbits)) {
    03633     UnreserveRailTrack(tile, track);
    03634
    03635     /* If there are still crashed vehicles on the tile, give the track reservation to them */
    03636     TrackBits remaining_trackbits = TRACK_BIT_NONE;
    03637     FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
    03638
    03639     /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
    03640     assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
    03641     for (Track t = TRACK_BEGIN; t < TRACK_END; t++) {
    03642       if (HasBit(remaining_trackbits, t)) {
    03643         TryReserveRailTrack(tile, t);
    03644       }
    03645     }
    03646   }
    03647
    03648   /* check if the wagon was on a road/rail-crossing */
    03649   if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
    03650
    03651   /* Update signals */
    03652   if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
    03653     UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
    03654   } else {
    03655     SetSignalsOnBothDir(tile, track, owner);
    03656   }
    03657 }
    03658
    03659 static void ChangeTrainDirRandomly(Train *v)
    03660 {
    03661   static const DirDiff delta[] = {
    03662     DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
    03663   };
    03664
    03665   do {
    03666     /* We don't need to twist around vehicles if they're not visible */
    03667     if (!(v->vehstatus & VS_HIDDEN)) {
    03668       v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
    03669       v->UpdateDeltaXY(v->direction);
    03670       v->cur_image = v->GetImage(v->direction);
    03671       /* Refrain from updating the z position of the vehicle when on
    03672        * a bridge, because AfterSetTrainPos will put the vehicle under
    03673        * the bridge in that case */
    03674       if (v->track != TRACK_BIT_WORMHOLE) AfterSetTrainPos(v, false);
    03675     }
    03676   } while ((v = v->Next()) != NULL);
    03677 }
    03678
    03679 static bool HandleCrashedTrain(Train *v)
    03680 {
    03681   int state = ++v->crash_anim_pos;
    03682
    03683   if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
    03684     CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
    03685   }
    03686
    03687   uint32 r;
    03688   if (state <= 200 && Chance16R(1, 7, r)) {
    03689     int index = (r * 10 >> 16);
    03690
    03691     Vehicle *u = v;
    03692     do {
    03693       if (--index < 0) {
    03694         r = Random();
    03695
    03696         CreateEffectVehicleRel(u,
    03697           GB(r,  8, 3) + 2,
    03698           GB(r, 16, 3) + 2,
    03699           GB(r,  0, 3) + 5,
    03700           EV_EXPLOSION_SMALL);
    03701         break;
    03702       }
    03703     } while ((u = u->Next()) != NULL);
    03704   }
    03705
    03706   if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
    03707
    03708   if (state >= 4440 && !(v->tick_counter & 0x1F)) {
    03709     bool ret = v->Next() != NULL;
    03710     DeleteLastWagon(v);
    03711     return ret;
    03712   }
    03713
    03714   return true;
    03715 }
    03716
    03717 static void HandleBrokenTrain(Train *v)
    03718 {
    03719   if (v->breakdown_ctr != 1) {
    03720     v->breakdown_ctr = 1;
    03721     v->cur_speed = 0;
    03722
    03723     if (v->breakdowns_since_last_service != 255)
    03724       v->breakdowns_since_last_service++;
    03725
    03726     v->MarkDirty();
    03727     SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03728     SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
    03729
    03730     if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
    03731       SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
    03732         SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
    03733     }
    03734
    03735     if (!(v->vehstatus & VS_HIDDEN)) {
    03736       EffectVehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
    03737       if (u != NULL) u->animation_state = v->breakdown_delay * 2;
    03738     }
    03739   }
    03740
    03741   if (!(v->tick_counter & 3)) {
    03742     if (!--v->breakdown_delay) {
    03743       v->breakdown_ctr = 0;
    03744       v->MarkDirty();
    03745       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
    03746     }
    03747   }
    03748 }
    03749
    03751 static const uint16 _breakdown_speeds[16] = {
    03752   225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
    03753 };
    03754
    03755
    03763 static bool TrainApproachingLineEnd(Train *v, bool signal)
    03764 {
    03765   /* Calc position within the current tile */
    03766   uint x = v->x_pos & 0xF;
    03767   uint y = v->y_pos & 0xF;
    03768
    03769   /* for diagonal directions, 'x' will be 0..15 -
    03770    * for other directions, it will be 1, 3, 5, ..., 15 */
    03771   switch (v->direction) {
    03772     case DIR_N : x = ~x + ~y + 25; break;
    03773     case DIR_NW: x = y;            // FALLTHROUGH
    03774     case DIR_NE: x = ~x + 16;      break;
    03775     case DIR_E : x = ~x + y + 9;   break;
    03776     case DIR_SE: x = y;            break;
    03777     case DIR_S : x = x + y - 7;    break;
    03778     case DIR_W : x = ~y + x + 9;   break;
    03779     default: break;
    03780   }
    03781
    03782   /* do not reverse when approaching red signal */
    03783   if (!signal && x + (v->tcache.cached_veh_length + 1) / 2 >= TILE_SIZE) {
    03784     /* we are too near the tile end, reverse now */
    03785     v->cur_speed = 0;
    03786     ReverseTrainDirection(v);
    03787     return false;
    03788   }
    03789
    03790   /* slow down */
    03791   v->vehstatus |= VS_TRAIN_SLOWING;
    03792   uint16 break_speed = _breakdown_speeds[x & 0xF];
    03793   if (break_speed < v->cur_speed) v->cur_speed = break_speed;
    03794
    03795   return true;
    03796 }
    03797
    03798
    03804 static bool TrainCanLeaveTile(const Train *v)
    03805 {
    03806   /* Exit if inside a tunnel/bridge or a depot */
    03807   if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
    03808
    03809   TileIndex tile = v->tile;
    03810
    03811   /* entering a tunnel/bridge? */
    03812   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    03813     DiagDirection dir = GetTunnelBridgeDirection(tile);
    03814     if (DiagDirToDir(dir) == v->direction) return false;
    03815   }
    03816
    03817   /* entering a depot? */
    03818   if (IsRailDepotTile(tile)) {
    03819     DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
    03820     if (DiagDirToDir(dir) == v->direction) return false;
    03821   }
    03822
    03823   return true;
    03824 }
    03825
    03826
    03834 static TileIndex TrainApproachingCrossingTile(const Train *v)
    03835 {
    03836   assert(v->IsFrontEngine());
    03837   assert(!(v->vehstatus & VS_CRASHED));
    03838
    03839   if (!TrainCanLeaveTile(v)) return INVALID_TILE;
    03840
    03841   DiagDirection dir = TrainExitDir(v->direction, v->track);
    03842   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
    03843
    03844   /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
    03845   if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
    03846       !CheckCompatibleRail(v, tile)) {
    03847     return INVALID_TILE;
    03848   }
    03849
    03850   return tile;
    03851 }
    03852
    03853
    03860 static bool TrainCheckIfLineEnds(Train *v)
    03861 {
    03862   /* First, handle broken down train */
    03863
    03864   int t = v->breakdown_ctr;
    03865   if (t > 1) {
    03866     v->vehstatus |= VS_TRAIN_SLOWING;
    03867
    03868     uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
    03869     if (break_speed < v->cur_speed) v->cur_speed = break_speed;
    03870   } else {
    03871     v->vehstatus &= ~VS_TRAIN_SLOWING;
    03872   }
    03873
    03874   if (!TrainCanLeaveTile(v)) return true;
    03875
    03876   /* Determine the non-diagonal direction in which we will exit this tile */
    03877   DiagDirection dir = TrainExitDir(v->direction, v->track);
    03878   /* Calculate next tile */
    03879   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
    03880
    03881   /* Determine the track status on the next tile */
    03882   TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
    03883   TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
    03884
    03885   TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
    03886   TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
    03887
    03888   /* We are sure the train is not entering a depot, it is detected above */
    03889
    03890   /* mask unreachable track bits if we are forbidden to do 90deg turns */
    03891   TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
    03892   if (_settings_game.pf.forbid_90_deg) {
    03893     bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
    03894   }
    03895
    03896   /* no suitable trackbits at all || unusable rail (wrong type or owner) */
    03897   if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
    03898     return TrainApproachingLineEnd(v, false);
    03899   }
    03900
    03901   /* approaching red signal */
    03902   if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true);
    03903
    03904   /* approaching a rail/road crossing? then make it red */
    03905   if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
    03906
    03907   return true;
    03908 }
    03909
    03910
    03911 static bool TrainLocoHandler(Train *v, bool mode)
    03912 {
    03913   /* train has crashed? */
    03914   if (v->vehstatus & VS_CRASHED) {
    03915     return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
    03916   }
    03917
    03918   if (v->force_proceed != 0) {
    03919     ClrBit(v->flags, VRF_TRAIN_STUCK);
    03920     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03921   }
    03922
    03923   /* train is broken down? */
    03924   if (v->breakdown_ctr != 0) {
    03925     if (v->breakdown_ctr <= 2) {
    03926       HandleBrokenTrain(v);
    03927       return true;
    03928     }
    03929     if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
    03930   }
    03931
    03932   if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
    03933     ReverseTrainDirection(v);
    03934   }
    03935
    03936   /* exit if train is stopped */
    03937   if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
    03938
    03939   bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
    03940   if (ProcessOrders(v) && CheckReverseTrain(v)) {
    03941     v->wait_counter = 0;
    03942     v->cur_speed = 0;
    03943     v->subspeed = 0;
    03944     ReverseTrainDirection(v);
    03945     return true;
    03946   }
    03947
    03948   v->HandleLoading(mode);
    03949
    03950   if (v->current_order.IsType(OT_LOADING)) return true;
    03951
    03952   if (CheckTrainStayInDepot(v)) return true;
    03953
    03954   if (!mode) HandleLocomotiveSmokeCloud(v);
    03955
    03956   /* We had no order but have an order now, do look ahead. */
    03957   if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
    03958     CheckNextTrainTile(v);
    03959   }
    03960
    03961   /* Handle stuck trains. */
    03962   if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
    03963     ++v->wait_counter;
    03964
    03965     /* Should we try reversing this tick if still stuck? */
    03966     bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.wait_for_pbs_path < 255;
    03967
    03968     if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == 0) return true;
    03969     if (!TryPathReserve(v)) {
    03970       /* Still stuck. */
    03971       if (turn_around) ReverseTrainDirection(v);
    03972
    03973       if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
    03974         /* Show message to player. */
    03975         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
    03976           SetDParam(0, v->index);
    03977           AddVehicleNewsItem(
    03978             STR_NEWS_TRAIN_IS_STUCK,
    03979             NS_ADVICE,
    03980             v->index
    03981           );
    03982         }
    03983         v->wait_counter = 0;
    03984       }
    03985       /* Exit if force proceed not pressed, else reset stuck flag anyway. */
    03986       if (v->force_proceed == 0) return true;
    03987       ClrBit(v->flags, VRF_TRAIN_STUCK);
    03988       v->wait_counter = 0;
    03989       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03990     }
    03991   }
    03992
    03993   if (v->current_order.IsType(OT_LEAVESTATION)) {
    03994     v->current_order.Free();
    03995     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    03996     return true;
    03997   }
    03998
    03999   int j = v->UpdateSpeed();
    04000
    04001   /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
    04002   if (v->cur_speed == 0 && v->tcache.last_speed == 0 && (v->vehstatus & VS_STOPPED)) {
    04003     /* If we manually stopped, we're not force-proceeding anymore. */
    04004     v->force_proceed = 0;
    04005     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04006   }
    04007
    04008   int adv_spd = (v->direction & 1) ? 192 : 256;
    04009   if (j < adv_spd) {
    04010     /* if the vehicle has speed 0, update the last_speed field. */
    04011     if (v->cur_speed == 0) SetLastSpeed(v, v->cur_speed);
    04012   } else {
    04013     TrainCheckIfLineEnds(v);
    04014     /* Loop until the train has finished moving. */
    04015     for (;;) {
    04016       j -= adv_spd;
    04017       TrainController(v, NULL);
    04018       /* Don't continue to move if the train crashed. */
    04019       if (CheckTrainCollision(v)) break;
    04020       /* 192 spd used for going straight, 256 for going diagonally. */
    04021       adv_spd = (v->direction & 1) ? 192 : 256;
    04022
    04023       /* No more moving this tick */
    04024       if (j < adv_spd || v->cur_speed == 0) break;
    04025
    04026       OrderType order_type = v->current_order.GetType();
    04027       /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
    04028       if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
    04029             (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
    04030             IsTileType(v->tile, MP_STATION) &&
    04031             v->current_order.GetDestination() == GetStationIndex(v->tile)) {
    04032         ProcessOrders(v);
    04033       }
    04034     }
    04035     SetLastSpeed(v, v->cur_speed);
    04036   }
    04037
    04038   for (Train *u = v; u != NULL; u = u->Next()) {
    04039     if ((u->vehstatus & VS_HIDDEN) != 0) continue;
    04040
    04041     u->UpdateViewport(false, false);
    04042   }
    04043
    04044   if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
    04045
    04046   return true;
    04047 }
    04048
    04049
    04050
    04051 Money Train::GetRunningCost() const
    04052 {
    04053   Money cost = 0;
    04054   const Train *v = this;
    04055
    04056   do {
    04057     const Engine *e = Engine::Get(v->engine_type);
    04058     if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
    04059
    04060     uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
    04061     if (cost_factor == 0) continue;
    04062
    04063     /* Halve running cost for multiheaded parts */
    04064     if (v->IsMultiheaded()) cost_factor /= 2;
    04065
    04066     cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->grffile);
    04067   } while ((v = v->GetNextVehicle()) != NULL);
    04068
    04069   return cost;
    04070 }
    04071
    04072
    04073 bool Train::Tick()
    04074 {
    04075   this->tick_counter++;
    04076
    04077   if (this->IsFrontEngine()) {
    04078     if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
    04079
    04080     this->current_order_time++;
    04081
    04082     if (!TrainLocoHandler(this, false)) return false;
    04083
    04084     return TrainLocoHandler(this, true);
    04085   } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
    04086     /* Delete flooded standalone wagon chain */
    04087     if (++this->crash_anim_pos >= 4400) {
    04088       delete this;
    04089       return false;
    04090     }
    04091   }
    04092
    04093   return true;
    04094 }
    04095
    04096 static void CheckIfTrainNeedsService(Train *v)
    04097 {
    04098   if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
    04099   if (v->IsInDepot()) {
    04100     VehicleServiceInDepot(v);
    04101     return;
    04102   }
    04103
    04104   uint max_penalty;
    04105   switch (_settings_game.pf.pathfinder_for_trains) {
    04106     case VPF_NPF:  max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty;  break;
    04107     case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
    04108     default: NOT_REACHED();
    04109   }
    04110
    04111   FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
    04112   /* Only go to the depot if it is not too far out of our way. */
    04113   if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
    04114     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
    04115       /* If we were already heading for a depot but it has
    04116        * suddenly moved farther away, we continue our normal
    04117        * schedule? */
    04118       v->current_order.MakeDummy();
    04119       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04120     }
    04121     return;
    04122   }
    04123
    04124   DepotID depot = GetDepotIndex(tfdd.tile);
    04125
    04126   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
    04127       v->current_order.GetDestination() != depot &&
    04128       !Chance16(3, 16)) {
    04129     return;
    04130   }
    04131
    04132   v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
    04133   v->dest_tile = tfdd.tile;
    04134   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
    04135 }
    04136
    04137 void Train::OnNewDay()
    04138 {
    04139   if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
    04140
    04141   if (this->IsFrontEngine()) {
    04142     CheckVehicleBreakdown(this);
    04143     AgeVehicle(this);
    04144
    04145     CheckIfTrainNeedsService(this);
    04146
    04147     CheckOrders(this);
    04148
    04149     /* update destination */
    04150     if (this->current_order.IsType(OT_GOTO_STATION)) {
    04151       TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
    04152       if (tile != INVALID_TILE) this->dest_tile = tile;
    04153     }
    04154
    04155     if (this->running_ticks != 0) {
    04156       /* running costs */
    04157       CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR  * DAY_TICKS));
    04158
    04159       this->profit_this_year -= cost.GetCost();
    04160       this->running_ticks = 0;
    04161
    04162       SubtractMoneyFromCompanyFract(this->owner, cost);
    04163
    04164       SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
    04165       SetWindowClassesDirty(WC_TRAINS_LIST);
    04166     }
    04167   } else if (this->IsEngine()) {
    04168     /* Also age engines that aren't front engines */
    04169     AgeVehicle(this);
    04170   }
    04171 }
    04172
    04173 Trackdir Train::GetVehicleTrackdir() const
    04174 {
    04175   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
    04176
    04177   if (this->track == TRACK_BIT_DEPOT) {
    04178     /* We'll assume the train is facing outwards */
    04179     return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
    04180   }
    04181
    04182   if (this->track == TRACK_BIT_WORMHOLE) {
    04183     /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
    04184     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
    04185   }
    04186
    04187   return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
    04188 }