# train_cmd.cpp

Go to the documentation of this file.

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