# train_cmd.cpp

Go to the documentation of this file.

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