train_cmd.cpp

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

Generated on Wed Dec 30 20:40:08 2009 for OpenTTD by  doxygen 1.5.6