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

Generated on Sat Dec 26 20:06:07 2009 for OpenTTD by  doxygen 1.5.6