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 "error.h"
00014 #include "articulated_vehicles.h"
00015 #include "command_func.h"
00016 #include "pathfinder/npf/npf_func.h"
00017 #include "pathfinder/yapf/yapf.hpp"
00018 #include "news_func.h"
00019 #include "company_func.h"
00020 #include "vehicle_gui.h"
00021 #include "newgrf_sound.h"
00022 #include "newgrf_text.h"
00023 #include "group.h"
00024 #include "strings_func.h"
00025 #include "viewport_func.h"
00026 #include "window_func.h"
00027 #include "vehicle_func.h"
00028 #include "sound_func.h"
00029 #include "ai/ai.hpp"
00030 #include "game/game.hpp"
00031 #include "newgrf_station.h"
00032 #include "effectvehicle_func.h"
00033 #include "gamelog.h"
00034 #include "network/network.h"
00035 #include "spritecache.h"
00036 #include "core/random_func.hpp"
00037 #include "company_base.h"
00038 #include "newgrf.h"
00039 #include "order_backup.h"
00040 #include "zoom_func.h"
00041 
00042 #include "table/strings.h"
00043 #include "table/train_cmd.h"
00044 
00045 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
00046 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
00047 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
00048 static TileIndex TrainApproachingCrossingTile(const Train *v);
00049 static void CheckIfTrainNeedsService(Train *v);
00050 static void CheckNextTrainTile(Train *v);
00051 
00052 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4,  8};
00053 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
00054 
00055 
00063 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
00064 {
00065   static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
00066 
00067   DiagDirection diagdir = DirToDiagDir(direction);
00068 
00069   /* Determine the diagonal direction in which we will exit this tile */
00070   if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
00071     diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
00072   }
00073 
00074   return diagdir;
00075 }
00076 
00077 
00083 byte FreightWagonMult(CargoID cargo)
00084 {
00085   if (!CargoSpec::Get(cargo)->is_freight) return 1;
00086   return _settings_game.vehicle.freight_trains;
00087 }
00088 
00090 void CheckTrainsLengths()
00091 {
00092   const Train *v;
00093   bool first = true;
00094 
00095   FOR_ALL_TRAINS(v) {
00096     if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
00097       for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
00098         if (u->track != TRACK_BIT_DEPOT) {
00099           if ((w->track != TRACK_BIT_DEPOT &&
00100               max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
00101               (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
00102             SetDParam(0, v->index);
00103             SetDParam(1, v->owner);
00104             ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
00105 
00106             if (!_networking && first) {
00107               first = false;
00108               DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
00109             }
00110             /* Break so we warn only once for each train. */
00111             break;
00112           }
00113         }
00114       }
00115     }
00116   }
00117 }
00118 
00123 void Train::RailtypeChanged()
00124 {
00125   for (Train *u = this; u != NULL; u = u->Next()) {
00126     /* The wagon-is-powered-state should not change, so the weight does not change. */
00127     u->UpdateVisualEffect(false);
00128   }
00129   this->PowerChanged();
00130   if (this->IsFrontEngine()) this->UpdateAcceleration();
00131 }
00132 
00139 void Train::ConsistChanged(bool same_length)
00140 {
00141   uint16 max_speed = UINT16_MAX;
00142 
00143   assert(this->IsFrontEngine() || this->IsFreeWagon());
00144 
00145   const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
00146   EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
00147   this->gcache.cached_total_length = 0;
00148   this->compatible_railtypes = RAILTYPES_NONE;
00149 
00150   bool train_can_tilt = true;
00151 
00152   for (Train *u = this; u != NULL; u = u->Next()) {
00153     const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
00154 
00155     /* Check the this->first cache. */
00156     assert(u->First() == this);
00157 
00158     /* update the 'first engine' */
00159     u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
00160     u->railtype = rvi_u->railtype;
00161 
00162     if (u->IsEngine()) first_engine = u->engine_type;
00163 
00164     /* Set user defined data to its default value */
00165     u->tcache.user_def_data = rvi_u->user_def_data;
00166     this->InvalidateNewGRFCache();
00167     u->InvalidateNewGRFCache();
00168   }
00169 
00170   for (Train *u = this; u != NULL; u = u->Next()) {
00171     /* Update user defined data (must be done before other properties) */
00172     u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
00173     this->InvalidateNewGRFCache();
00174     u->InvalidateNewGRFCache();
00175   }
00176 
00177   for (Train *u = this; u != NULL; u = u->Next()) {
00178     const Engine *e_u = u->GetEngine();
00179     const RailVehicleInfo *rvi_u = &e_u->u.rail;
00180 
00181     if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
00182 
00183     /* Cache wagon override sprite group. NULL is returned if there is none */
00184     u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
00185 
00186     /* Reset colour map */
00187     u->colourmap = PAL_NONE;
00188 
00189     /* Update powered-wagon-status and visual effect */
00190     u->UpdateVisualEffect(true);
00191 
00192     if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
00193         UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
00194       /* wagon is powered */
00195       SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
00196     } else {
00197       ClrBit(u->flags, VRF_POWEREDWAGON);
00198     }
00199 
00200     if (!u->IsArticulatedPart()) {
00201       /* Do not count powered wagons for the compatible railtypes, as wagons always
00202          have railtype normal */
00203       if (rvi_u->power > 0) {
00204         this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
00205       }
00206 
00207       /* Some electric engines can be allowed to run on normal rail. It happens to all
00208        * existing electric engines when elrails are disabled and then re-enabled */
00209       if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
00210         u->railtype = RAILTYPE_RAIL;
00211         u->compatible_railtypes |= RAILTYPES_RAIL;
00212       }
00213 
00214       /* max speed is the minimum of the speed limits of all vehicles in the consist */
00215       if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
00216         uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
00217         if (speed != 0) max_speed = min(speed, max_speed);
00218       }
00219     }
00220 
00221     u->cargo_cap = e_u->DetermineCapacity(u);
00222     u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
00223 
00224     /* check the vehicle length (callback) */
00225     uint16 veh_len = CALLBACK_FAILED;
00226     if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
00227       /* Use callback 36 */
00228       veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
00229     } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
00230       /* Use callback 11 */
00231       veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
00232     }
00233     if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
00234       ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
00235     }
00236     if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
00237     veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
00238 
00239     /* verify length hasn't changed */
00240     if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
00241 
00242     /* update vehicle length? */
00243     if (!same_length) u->gcache.cached_veh_length = veh_len;
00244 
00245     this->gcache.cached_total_length += u->gcache.cached_veh_length;
00246     this->InvalidateNewGRFCache();
00247     u->InvalidateNewGRFCache();
00248   }
00249 
00250   /* store consist weight/max speed in cache */
00251   this->vcache.cached_max_speed = max_speed;
00252   this->tcache.cached_tilt = train_can_tilt;
00253   this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
00254 
00255   /* 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) */
00256   this->CargoChanged();
00257 
00258   if (this->IsFrontEngine()) {
00259     this->UpdateAcceleration();
00260     SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00261     InvalidateWindowData(WC_VEHICLE_REFIT, this->index);
00262   }
00263 }
00264 
00275 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
00276 {
00277   const Station *st = Station::Get(station_id);
00278   *station_ahead  = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
00279   *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
00280 
00281   /* Default to the middle of the station for stations stops that are not in
00282    * the order list like intermediate stations when non-stop is disabled */
00283   OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
00284   if (v->gcache.cached_total_length >= *station_length) {
00285     /* The train is longer than the station, make it stop at the far end of the platform */
00286     osl = OSL_PLATFORM_FAR_END;
00287   } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
00288     osl = v->current_order.GetStopLocation();
00289   }
00290 
00291   /* The stop location of the FRONT! of the train */
00292   int stop;
00293   switch (osl) {
00294     default: NOT_REACHED();
00295 
00296     case OSL_PLATFORM_NEAR_END:
00297       stop = v->gcache.cached_total_length;
00298       break;
00299 
00300     case OSL_PLATFORM_MIDDLE:
00301       stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
00302       break;
00303 
00304     case OSL_PLATFORM_FAR_END:
00305       stop = *station_length;
00306       break;
00307   }
00308 
00309   /* Subtract half the front vehicle length of the train so we get the real
00310    * stop location of the train. */
00311   return stop - (v->gcache.cached_veh_length + 1) / 2;
00312 }
00313 
00314 
00319 int Train::GetCurveSpeedLimit() const
00320 {
00321   assert(this->First() == this);
00322 
00323   static const int absolute_max_speed = UINT16_MAX;
00324   int max_speed = absolute_max_speed;
00325 
00326   if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
00327 
00328   int curvecount[2] = {0, 0};
00329 
00330   /* first find the curve speed limit */
00331   int numcurve = 0;
00332   int sum = 0;
00333   int pos = 0;
00334   int lastpos = -1;
00335   for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
00336     Direction this_dir = u->direction;
00337     Direction next_dir = u->Next()->direction;
00338 
00339     DirDiff dirdiff = DirDifference(this_dir, next_dir);
00340     if (dirdiff == DIRDIFF_SAME) continue;
00341 
00342     if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
00343     if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
00344     if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
00345       if (lastpos != -1) {
00346         numcurve++;
00347         sum += pos - lastpos;
00348         if (pos - lastpos == 1 && max_speed > 88) {
00349           max_speed = 88;
00350         }
00351       }
00352       lastpos = pos;
00353     }
00354 
00355     /* if we have a 90 degree turn, fix the speed limit to 60 */
00356     if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
00357       max_speed = 61;
00358     }
00359   }
00360 
00361   if (numcurve > 0 && max_speed > 88) {
00362     if (curvecount[0] == 1 && curvecount[1] == 1) {
00363       max_speed = absolute_max_speed;
00364     } else {
00365       sum /= numcurve;
00366       max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
00367     }
00368   }
00369 
00370   if (max_speed != absolute_max_speed) {
00371     /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
00372     const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
00373     max_speed += (max_speed / 2) * rti->curve_speed;
00374 
00375     if (this->tcache.cached_tilt) {
00376       /* Apply max_speed bonus of 20% for a tilting train */
00377       max_speed += max_speed / 5;
00378     }
00379   }
00380 
00381   return max_speed;
00382 }
00383 
00388 int Train::GetCurrentMaxSpeed() const
00389 {
00390   int max_speed = this->tcache.cached_max_curve_speed;
00391   assert(max_speed == this->GetCurveSpeedLimit());
00392 
00393   if (IsRailStationTile(this->tile)) {
00394     StationID sid = GetStationIndex(this->tile);
00395     if (this->current_order.ShouldStopAtStation(this, sid)) {
00396       int station_ahead;
00397       int station_length;
00398       int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
00399 
00400       /* The distance to go is whatever is still ahead of the train minus the
00401        * distance from the train's stop location to the end of the platform */
00402       int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
00403 
00404       if (distance_to_go > 0) {
00405         int st_max_speed = 120;
00406 
00407         int delta_v = this->cur_speed / (distance_to_go + 1);
00408         if (max_speed > (this->cur_speed - delta_v)) {
00409           st_max_speed = this->cur_speed - (delta_v / 10);
00410         }
00411 
00412         st_max_speed = max(st_max_speed, 25 * distance_to_go);
00413         max_speed = min(max_speed, st_max_speed);
00414       }
00415     }
00416   }
00417 
00418   for (const Train *u = this; u != NULL; u = u->Next()) {
00419     if (u->track == TRACK_BIT_DEPOT) {
00420       max_speed = min(max_speed, 61);
00421       break;
00422     }
00423   }
00424 
00425   return min(max_speed, this->gcache.cached_max_track_speed);
00426 }
00427 
00429 void Train::UpdateAcceleration()
00430 {
00431   assert(this->IsFrontEngine());
00432 
00433   uint power = this->gcache.cached_power;
00434   uint weight = this->gcache.cached_weight;
00435   assert(weight != 0);
00436   this->acceleration = Clamp(power / weight * 4, 1, 255);
00437 }
00438 
00444 int Train::GetDisplayImageWidth(Point *offset) const
00445 {
00446   int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
00447   int vehicle_pitch = 0;
00448 
00449   const Engine *e = this->GetEngine();
00450   if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
00451     reference_width = e->GetGRF()->traininfo_vehicle_width;
00452     vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
00453   }
00454 
00455   if (offset != NULL) {
00456     offset->x = reference_width / 2;
00457     offset->y = vehicle_pitch;
00458   }
00459   return this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
00460 }
00461 
00462 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
00463 {
00464   return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
00465 }
00466 
00473 SpriteID Train::GetImage(Direction direction, EngineImageType image_type) const
00474 {
00475   uint8 spritenum = this->spritenum;
00476   SpriteID sprite;
00477 
00478   if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
00479 
00480   if (is_custom_sprite(spritenum)) {
00481     sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
00482     if (sprite != 0) return sprite;
00483 
00484     spritenum = this->GetEngine()->original_image_index;
00485   }
00486 
00487   sprite = GetDefaultTrainSprite(spritenum, direction);
00488 
00489   if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
00490 
00491   return sprite;
00492 }
00493 
00494 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type)
00495 {
00496   const Engine *e = Engine::Get(engine);
00497   Direction dir = rear_head ? DIR_E : DIR_W;
00498   uint8 spritenum = e->u.rail.image_index;
00499 
00500   if (is_custom_sprite(spritenum)) {
00501     SpriteID sprite = GetCustomVehicleIcon(engine, dir, image_type);
00502     if (sprite != 0) {
00503       if (e->GetGRF() != NULL) {
00504         y += e->GetGRF()->traininfo_vehicle_pitch;
00505       }
00506       return sprite;
00507     }
00508 
00509     spritenum = Engine::Get(engine)->original_image_index;
00510   }
00511 
00512   if (rear_head) spritenum++;
00513 
00514   return GetDefaultTrainSprite(spritenum, DIR_W);
00515 }
00516 
00517 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
00518 {
00519   if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00520     int yf = y;
00521     int yr = y;
00522 
00523     SpriteID spritef = GetRailIcon(engine, false, yf, image_type);
00524     SpriteID spriter = GetRailIcon(engine, true, yr, image_type);
00525     const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
00526     const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
00527 
00528     preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_spritef->x_offs, ZOOM_LVL_GUI) + 14, right - UnScaleByZoom(real_spriter->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_spriter->x_offs, ZOOM_LVL_GUI) - 15);
00529 
00530     DrawSprite(spritef, pal, preferred_x - 14, yf);
00531     DrawSprite(spriter, pal, preferred_x + 15, yr);
00532   } else {
00533     SpriteID sprite = GetRailIcon(engine, false, y, image_type);
00534     const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00535     preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI), right - UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI));
00536     DrawSprite(sprite, pal, preferred_x, y);
00537   }
00538 }
00539 
00548 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
00549 {
00550   const RailVehicleInfo *rvi = &e->u.rail;
00551 
00552   /* Check that the wagon can drive on the track in question */
00553   if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00554 
00555   if (flags & DC_EXEC) {
00556     Train *v = new Train();
00557     *ret = v;
00558     v->spritenum = rvi->image_index;
00559 
00560     v->engine_type = e->index;
00561     v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
00562 
00563     DiagDirection dir = GetRailDepotDirection(tile);
00564 
00565     v->direction = DiagDirToDir(dir);
00566     v->tile = tile;
00567 
00568     int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
00569     int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
00570 
00571     v->x_pos = x;
00572     v->y_pos = y;
00573     v->z_pos = GetSlopePixelZ(x, y);
00574     v->owner = _current_company;
00575     v->track = TRACK_BIT_DEPOT;
00576     v->vehstatus = VS_HIDDEN | VS_DEFPAL;
00577 
00578     v->SetWagon();
00579 
00580     v->SetFreeWagon();
00581     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00582 
00583     v->cargo_type = e->GetDefaultCargoType();
00584     v->cargo_cap = rvi->capacity;
00585 
00586     v->railtype = rvi->railtype;
00587 
00588     v->build_year = _cur_year;
00589     v->cur_image = SPR_IMG_QUERY;
00590     v->random_bits = VehicleRandomBits();
00591 
00592     v->group_id = DEFAULT_GROUP;
00593 
00594     AddArticulatedParts(v);
00595 
00596     _new_vehicle_id = v->index;
00597 
00598     VehicleUpdatePosition(v);
00599     v->First()->ConsistChanged(false);
00600     UpdateTrainGroupID(v->First());
00601 
00602     CheckConsistencyOfArticulatedVehicle(v);
00603 
00604     /* Try to connect the vehicle to one of free chains of wagons. */
00605     Train *w;
00606     FOR_ALL_TRAINS(w) {
00607       if (w->tile == tile &&              
00608           w->IsFreeWagon() &&             
00609           w->engine_type == e->index &&   
00610           w->First() != v &&              
00611           !(w->vehstatus & VS_CRASHED)) { 
00612         DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
00613         break;
00614       }
00615     }
00616   }
00617 
00618   return CommandCost();
00619 }
00620 
00622 static void NormalizeTrainVehInDepot(const Train *u)
00623 {
00624   const Train *v;
00625   FOR_ALL_TRAINS(v) {
00626     if (v->IsFreeWagon() && v->tile == u->tile &&
00627         v->track == TRACK_BIT_DEPOT) {
00628       if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
00629           CMD_MOVE_RAIL_VEHICLE).Failed())
00630         break;
00631     }
00632   }
00633 }
00634 
00635 static void AddRearEngineToMultiheadedTrain(Train *v)
00636 {
00637   Train *u = new Train();
00638   v->value >>= 1;
00639   u->value = v->value;
00640   u->direction = v->direction;
00641   u->owner = v->owner;
00642   u->tile = v->tile;
00643   u->x_pos = v->x_pos;
00644   u->y_pos = v->y_pos;
00645   u->z_pos = v->z_pos;
00646   u->track = TRACK_BIT_DEPOT;
00647   u->vehstatus = v->vehstatus & ~VS_STOPPED;
00648   u->spritenum = v->spritenum + 1;
00649   u->cargo_type = v->cargo_type;
00650   u->cargo_subtype = v->cargo_subtype;
00651   u->cargo_cap = v->cargo_cap;
00652   u->railtype = v->railtype;
00653   u->engine_type = v->engine_type;
00654   u->build_year = v->build_year;
00655   u->cur_image = SPR_IMG_QUERY;
00656   u->random_bits = VehicleRandomBits();
00657   v->SetMultiheaded();
00658   u->SetMultiheaded();
00659   v->SetNext(u);
00660   VehicleUpdatePosition(u);
00661 
00662   /* Now we need to link the front and rear engines together */
00663   v->other_multiheaded_part = u;
00664   u->other_multiheaded_part = v;
00665 }
00666 
00676 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00677 {
00678   const RailVehicleInfo *rvi = &e->u.rail;
00679 
00680   if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
00681 
00682   /* Check if depot and new engine uses the same kind of tracks *
00683    * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
00684   if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00685 
00686   if (flags & DC_EXEC) {
00687     DiagDirection dir = GetRailDepotDirection(tile);
00688     int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
00689     int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
00690 
00691     Train *v = new Train();
00692     *ret = v;
00693     v->direction = DiagDirToDir(dir);
00694     v->tile = tile;
00695     v->owner = _current_company;
00696     v->x_pos = x;
00697     v->y_pos = y;
00698     v->z_pos = GetSlopePixelZ(x, y);
00699     v->track = TRACK_BIT_DEPOT;
00700     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00701     v->spritenum = rvi->image_index;
00702     v->cargo_type = e->GetDefaultCargoType();
00703     v->cargo_cap = rvi->capacity;
00704     v->last_station_visited = INVALID_STATION;
00705     v->last_loading_station = INVALID_STATION;
00706 
00707     v->engine_type = e->index;
00708     v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
00709 
00710     v->reliability = e->reliability;
00711     v->reliability_spd_dec = e->reliability_spd_dec;
00712     v->max_age = e->GetLifeLengthInDays();
00713 
00714     v->railtype = rvi->railtype;
00715     _new_vehicle_id = v->index;
00716 
00717     v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_trains;
00718     v->date_of_last_service = _date;
00719     v->build_year = _cur_year;
00720     v->cur_image = SPR_IMG_QUERY;
00721     v->random_bits = VehicleRandomBits();
00722 
00723     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00724 
00725     v->group_id = DEFAULT_GROUP;
00726 
00727     v->SetFrontEngine();
00728     v->SetEngine();
00729 
00730     VehicleUpdatePosition(v);
00731 
00732     if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
00733       AddRearEngineToMultiheadedTrain(v);
00734     } else {
00735       AddArticulatedParts(v);
00736     }
00737 
00738     v->ConsistChanged(false);
00739     UpdateTrainGroupID(v);
00740 
00741     if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
00742       NormalizeTrainVehInDepot(v);
00743     }
00744 
00745     CheckConsistencyOfArticulatedVehicle(v);
00746   }
00747 
00748   return CommandCost();
00749 }
00750 
00755 bool Train::IsInDepot() const
00756 {
00757   /* Is the front engine stationary in the depot? */
00758   if (!IsRailDepotTile(this->tile) || this->cur_speed != 0) return false;
00759 
00760   /* Check whether the rest is also already trying to enter the depot. */
00761   for (const Train *v = this; v != NULL; v = v->Next()) {
00762     if (v->track != TRACK_BIT_DEPOT || v->tile != this->tile) return false;
00763   }
00764 
00765   return true;
00766 }
00767 
00772 bool Train::IsStoppedInDepot() const
00773 {
00774   /* Are we stopped? Of course wagons don't really care... */
00775   if (this->IsFrontEngine() && !(this->vehstatus & VS_STOPPED)) return false;
00776   return this->IsInDepot();
00777 }
00778 
00779 static Train *FindGoodVehiclePos(const Train *src)
00780 {
00781   EngineID eng = src->engine_type;
00782   TileIndex tile = src->tile;
00783 
00784   Train *dst;
00785   FOR_ALL_TRAINS(dst) {
00786     if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
00787       /* check so all vehicles in the line have the same engine. */
00788       Train *t = dst;
00789       while (t->engine_type == eng) {
00790         t = t->Next();
00791         if (t == NULL) return dst;
00792       }
00793     }
00794   }
00795 
00796   return NULL;
00797 }
00798 
00800 typedef SmallVector<Train *, 16> TrainList;
00801 
00807 static void MakeTrainBackup(TrainList &list, Train *t)
00808 {
00809   for (; t != NULL; t = t->Next()) *list.Append() = t;
00810 }
00811 
00816 static void RestoreTrainBackup(TrainList &list)
00817 {
00818   /* No train, nothing to do. */
00819   if (list.Length() == 0) return;
00820 
00821   Train *prev = NULL;
00822   /* Iterate over the list and rebuild it. */
00823   for (Train **iter = list.Begin(); iter != list.End(); iter++) {
00824     Train *t = *iter;
00825     if (prev != NULL) {
00826       prev->SetNext(t);
00827     } else if (t->Previous() != NULL) {
00828       /* Make sure the head of the train is always the first in the chain. */
00829       t->Previous()->SetNext(NULL);
00830     }
00831     prev = t;
00832   }
00833 }
00834 
00840 static void RemoveFromConsist(Train *part, bool chain = false)
00841 {
00842   Train *tail = chain ? part->Last() : part->GetLastEnginePart();
00843 
00844   /* Unlink at the front, but make it point to the next
00845    * vehicle after the to be remove part. */
00846   if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
00847 
00848   /* Unlink at the back */
00849   tail->SetNext(NULL);
00850 }
00851 
00857 static void InsertInConsist(Train *dst, Train *chain)
00858 {
00859   /* We do not want to add something in the middle of an articulated part. */
00860   assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
00861 
00862   chain->Last()->SetNext(dst->Next());
00863   dst->SetNext(chain);
00864 }
00865 
00871 static void NormaliseDualHeads(Train *t)
00872 {
00873   for (; t != NULL; t = t->GetNextVehicle()) {
00874     if (!t->IsMultiheaded() || !t->IsEngine()) continue;
00875 
00876     /* Make sure that there are no free cars before next engine */
00877     Train *u;
00878     for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
00879 
00880     if (u == t->other_multiheaded_part) continue;
00881 
00882     /* Remove the part from the 'wrong' train */
00883     RemoveFromConsist(t->other_multiheaded_part);
00884     /* And add it to the 'right' train */
00885     InsertInConsist(u, t->other_multiheaded_part);
00886   }
00887 }
00888 
00893 static void NormaliseSubtypes(Train *chain)
00894 {
00895   /* Nothing to do */
00896   if (chain == NULL) return;
00897 
00898   /* We must be the first in the chain. */
00899   assert(chain->Previous() == NULL);
00900 
00901   /* Set the appropriate bits for the first in the chain. */
00902   if (chain->IsWagon()) {
00903     chain->SetFreeWagon();
00904   } else {
00905     assert(chain->IsEngine());
00906     chain->SetFrontEngine();
00907   }
00908 
00909   /* Now clear the bits for the rest of the chain */
00910   for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
00911     t->ClearFreeWagon();
00912     t->ClearFrontEngine();
00913   }
00914 }
00915 
00925 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
00926 {
00927   /* Just add 'new' engines and subtract the original ones.
00928    * If that's less than or equal to 0 we can be sure we did
00929    * not add any engines (read: trains) along the way. */
00930   if ((src          != NULL && src->IsEngine()          ? 1 : 0) +
00931       (dst          != NULL && dst->IsEngine()          ? 1 : 0) -
00932       (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
00933       (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
00934     return CommandCost();
00935   }
00936 
00937   /* Get a free unit number and check whether it's within the bounds.
00938    * There will always be a maximum of one new train. */
00939   if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
00940 
00941   return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00942 }
00943 
00949 static CommandCost CheckTrainAttachment(Train *t)
00950 {
00951   /* No multi-part train, no need to check. */
00952   if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
00953 
00954   /* The maximum length for a train. For each part we decrease this by one
00955    * and if the result is negative the train is simply too long. */
00956   int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
00957 
00958   Train *head = t;
00959   Train *prev = t;
00960 
00961   /* Break the prev -> t link so it always holds within the loop. */
00962   t = t->Next();
00963   prev->SetNext(NULL);
00964 
00965   /* Make sure the cache is cleared. */
00966   head->InvalidateNewGRFCache();
00967 
00968   while (t != NULL) {
00969     allowed_len -= t->gcache.cached_veh_length;
00970 
00971     Train *next = t->Next();
00972 
00973     /* Unlink the to-be-added piece; it is already unlinked from the previous
00974      * part due to the fact that the prev -> t link is broken. */
00975     t->SetNext(NULL);
00976 
00977     /* Don't check callback for articulated or rear dual headed parts */
00978     if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
00979       /* Back up and clear the first_engine data to avoid using wagon override group */
00980       EngineID first_engine = t->gcache.first_engine;
00981       t->gcache.first_engine = INVALID_ENGINE;
00982 
00983       /* We don't want the cache to interfere. head's cache is cleared before
00984        * the loop and after each callback does not need to be cleared here. */
00985       t->InvalidateNewGRFCache();
00986 
00987       uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
00988 
00989       /* Restore original first_engine data */
00990       t->gcache.first_engine = first_engine;
00991 
00992       /* We do not want to remember any cached variables from the test run */
00993       t->InvalidateNewGRFCache();
00994       head->InvalidateNewGRFCache();
00995 
00996       if (callback != CALLBACK_FAILED) {
00997         /* A failing callback means everything is okay */
00998         StringID error = STR_NULL;
00999 
01000         if (t->GetGRF()->grf_version < 8) {
01001           if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01002           if (callback  < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
01003           if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
01004         } else {
01005           if (callback < 0x400) {
01006             error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
01007           } else {
01008             switch (callback) {
01009               case 0x400: // allow if railtypes match (always the case for OpenTTD)
01010               case 0x401: // allow
01011                 break;
01012 
01013               default:    // unknown reason -> disallow
01014               case 0x402: // disallow attaching
01015                 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01016                 break;
01017             }
01018           }
01019         }
01020 
01021         if (error != STR_NULL) return_cmd_error(error);
01022       }
01023     }
01024 
01025     /* And link it to the new part. */
01026     prev->SetNext(t);
01027     prev = t;
01028     t = next;
01029   }
01030 
01031   if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
01032   return CommandCost();
01033 }
01034 
01045 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
01046 {
01047   /* Check whether we may actually construct the trains. */
01048   CommandCost ret = CheckTrainAttachment(src);
01049   if (ret.Failed()) return ret;
01050   ret = CheckTrainAttachment(dst);
01051   if (ret.Failed()) return ret;
01052 
01053   /* Check whether we need to build a new train. */
01054   return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
01055 }
01056 
01065 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
01066 {
01067   /* First determine the front of the two resulting trains */
01068   if (*src_head == *dst_head) {
01069     /* If we aren't moving part(s) to a new train, we are just moving the
01070      * front back and there is not destination head. */
01071     *dst_head = NULL;
01072   } else if (*dst_head == NULL) {
01073     /* If we are moving to a new train the head of the move train would become
01074      * the head of the new vehicle. */
01075     *dst_head = src;
01076   }
01077 
01078   if (src == *src_head) {
01079     /* If we are moving the front of a train then we are, in effect, creating
01080      * a new head for the train. Point to that. Unless we are moving the whole
01081      * train in which case there is not 'source' train anymore.
01082      * In case we are a multiheaded part we want the complete thing to come
01083      * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
01084      * that is followed by a rear multihead we do not want to include that. */
01085     *src_head = move_chain ? NULL :
01086         (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
01087   }
01088 
01089   /* Now it's just simply removing the part that we are going to move from the
01090    * source train and *if* the destination is a not a new train add the chain
01091    * at the destination location. */
01092   RemoveFromConsist(src, move_chain);
01093   if (*dst_head != src) InsertInConsist(dst, src);
01094 
01095   /* Now normalise the dual heads, that is move the dual heads around in such
01096    * a way that the head and rear of a dual head are in the same train */
01097   NormaliseDualHeads(*src_head);
01098   NormaliseDualHeads(*dst_head);
01099 }
01100 
01106 static void NormaliseTrainHead(Train *head)
01107 {
01108   /* Not much to do! */
01109   if (head == NULL) return;
01110 
01111   /* Tell the 'world' the train changed. */
01112   head->ConsistChanged(false);
01113   UpdateTrainGroupID(head);
01114 
01115   /* Not a front engine, i.e. a free wagon chain. No need to do more. */
01116   if (!head->IsFrontEngine()) return;
01117 
01118   /* Update the refit button and window */
01119   InvalidateWindowData(WC_VEHICLE_REFIT, head->index);
01120   SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
01121 
01122   /* If we don't have a unit number yet, set one. */
01123   if (head->unitnumber != 0) return;
01124   head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
01125 }
01126 
01139 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01140 {
01141   VehicleID s = GB(p1, 0, 20);
01142   VehicleID d = GB(p2, 0, 20);
01143   bool move_chain = HasBit(p1, 20);
01144 
01145   Train *src = Train::GetIfValid(s);
01146   if (src == NULL) return CMD_ERROR;
01147 
01148   CommandCost ret = CheckOwnership(src->owner);
01149   if (ret.Failed()) return ret;
01150 
01151   /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
01152   if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
01153 
01154   /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
01155   Train *dst;
01156   if (d == INVALID_VEHICLE) {
01157     dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
01158   } else {
01159     dst = Train::GetIfValid(d);
01160     if (dst == NULL) return CMD_ERROR;
01161 
01162     CommandCost ret = CheckOwnership(dst->owner);
01163     if (ret.Failed()) return ret;
01164 
01165     /* Do not allow appending to crashed vehicles, too */
01166     if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
01167   }
01168 
01169   /* if an articulated part is being handled, deal with its parent vehicle */
01170   src = src->GetFirstEnginePart();
01171   if (dst != NULL) {
01172     dst = dst->GetFirstEnginePart();
01173   }
01174 
01175   /* don't move the same vehicle.. */
01176   if (src == dst) return CommandCost();
01177 
01178   /* locate the head of the two chains */
01179   Train *src_head = src->First();
01180   Train *dst_head;
01181   if (dst != NULL) {
01182     dst_head = dst->First();
01183     if (dst_head->tile != src_head->tile) return CMD_ERROR;
01184     /* Now deal with articulated part of destination wagon */
01185     dst = dst->GetLastEnginePart();
01186   } else {
01187     dst_head = NULL;
01188   }
01189 
01190   if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01191 
01192   /* When moving all wagons, we can't have the same src_head and dst_head */
01193   if (move_chain && src_head == dst_head) return CommandCost();
01194 
01195   /* When moving a multiheaded part to be place after itself, bail out. */
01196   if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
01197 
01198   /* Check if all vehicles in the source train are stopped inside a depot. */
01199   if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01200 
01201   /* Check if all vehicles in the destination train are stopped inside a depot. */
01202   if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01203 
01204   /* First make a backup of the order of the trains. That way we can do
01205    * whatever we want with the order and later on easily revert. */
01206   TrainList original_src;
01207   TrainList original_dst;
01208 
01209   MakeTrainBackup(original_src, src_head);
01210   MakeTrainBackup(original_dst, dst_head);
01211 
01212   /* Also make backup of the original heads as ArrangeTrains can change them.
01213    * For the destination head we do not care if it is the same as the source
01214    * head because in that case it's just a copy. */
01215   Train *original_src_head = src_head;
01216   Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
01217 
01218   /* We want this information from before the rearrangement, but execute this after the validation. */
01219   bool original_src_head_front_engine = original_src_head != NULL && original_src_head->IsFrontEngine();
01220   bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
01221 
01222   /* (Re)arrange the trains in the wanted arrangement. */
01223   ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
01224 
01225   if ((flags & DC_AUTOREPLACE) == 0) {
01226     /* If the autoreplace flag is set we do not need to test for the validity
01227      * because we are going to revert the train to its original state. As we
01228      * assume the original state was correct autoreplace can skip this. */
01229     CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
01230     if (ret.Failed()) {
01231       /* Restore the train we had. */
01232       RestoreTrainBackup(original_src);
01233       RestoreTrainBackup(original_dst);
01234       return ret;
01235     }
01236   }
01237 
01238   /* do it? */
01239   if (flags & DC_EXEC) {
01240     /* Remove old heads from the statistics */
01241     if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
01242     if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
01243 
01244     /* First normalise the sub types of the chains. */
01245     NormaliseSubtypes(src_head);
01246     NormaliseSubtypes(dst_head);
01247 
01248     /* There are 14 different cases:
01249      *  1) front engine gets moved to a new train, it stays a front engine.
01250      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01251      *     b) the 'next' part is an engine that becomes a front engine.
01252      *     c) there is no 'next' part, nothing else happens
01253      *  2) front engine gets moved to another train, it is not a front engine anymore
01254      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01255      *     b) the 'next' part is an engine that becomes a front engine.
01256      *     c) there is no 'next' part, nothing else happens
01257      *  3) front engine gets moved to later in the current train, it is not a front engine anymore.
01258      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01259      *     b) the 'next' part is an engine that becomes a front engine.
01260      *  4) free wagon gets moved
01261      *     a) the 'next' part is a wagon that becomes a free wagon chain.
01262      *     b) the 'next' part is an engine that becomes a front engine.
01263      *     c) there is no 'next' part, nothing else happens
01264      *  5) non front engine gets moved and becomes a new train, nothing else happens
01265      *  6) non front engine gets moved within a train / to another train, nothing hapens
01266      *  7) wagon gets moved, nothing happens
01267      */
01268     if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
01269       /* Cases #2 and #3: the front engine gets trashed. */
01270       DeleteWindowById(WC_VEHICLE_VIEW, src->index);
01271       DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
01272       DeleteWindowById(WC_VEHICLE_REFIT, src->index);
01273       DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
01274       DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
01275       SetWindowDirty(WC_COMPANY, _current_company);
01276 
01277       /* Delete orders, group stuff and the unit number as we're not the
01278        * front of any vehicle anymore. */
01279       DeleteVehicleOrders(src);
01280       RemoveVehicleFromGroup(src);
01281       src->unitnumber = 0;
01282     }
01283 
01284     /* We weren't a front engine but are becoming one. So
01285      * we should be put in the default group. */
01286     if (original_src_head != src && dst_head == src) {
01287       SetTrainGroupID(src, DEFAULT_GROUP);
01288       SetWindowDirty(WC_COMPANY, _current_company);
01289     }
01290 
01291     /* Add new heads to statistics */
01292     if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
01293     if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
01294 
01295     /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
01296     NormaliseTrainHead(src_head);
01297     NormaliseTrainHead(dst_head);
01298 
01299     if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
01300       CheckCargoCapacity(src_head);
01301       CheckCargoCapacity(dst_head);
01302     }
01303 
01304     /* We are undoubtedly changing something in the depot and train list. */
01305     InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01306     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01307   } else {
01308     /* We don't want to execute what we're just tried. */
01309     RestoreTrainBackup(original_src);
01310     RestoreTrainBackup(original_dst);
01311   }
01312 
01313   return CommandCost();
01314 }
01315 
01327 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
01328 {
01329   /* Check if we deleted a vehicle window */
01330   Window *w = NULL;
01331 
01332   /* Sell a chain of vehicles or not? */
01333   bool sell_chain = HasBit(data, 0);
01334 
01335   Train *v = Train::From(t)->GetFirstEnginePart();
01336   Train *first = v->First();
01337 
01338   if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01339 
01340   /* First make a backup of the order of the train. That way we can do
01341    * whatever we want with the order and later on easily revert. */
01342   TrainList original;
01343   MakeTrainBackup(original, first);
01344 
01345   /* We need to keep track of the new head and the head of what we're going to sell. */
01346   Train *new_head = first;
01347   Train *sell_head = NULL;
01348 
01349   /* Split the train in the wanted way. */
01350   ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
01351 
01352   /* We don't need to validate the second train; it's going to be sold. */
01353   CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
01354   if (ret.Failed()) {
01355     /* Restore the train we had. */
01356     RestoreTrainBackup(original);
01357     return ret;
01358   }
01359 
01360   CommandCost cost(EXPENSES_NEW_VEHICLES);
01361   for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
01362 
01363   if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
01364     return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01365   }
01366 
01367   /* do it? */
01368   if (flags & DC_EXEC) {
01369     /* First normalise the sub types of the chain. */
01370     NormaliseSubtypes(new_head);
01371 
01372     if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
01373       /* We are selling the front engine. In this case we want to
01374        * 'give' the order, unit number and such to the new head. */
01375       new_head->orders.list = first->orders.list;
01376       new_head->AddToShared(first);
01377       DeleteVehicleOrders(first);
01378 
01379       /* Copy other important data from the front engine */
01380       new_head->CopyVehicleConfigAndStatistics(first);
01381       GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
01382 
01383       /* If we deleted a window then open a new one for the 'new' train */
01384       if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_head);
01385     } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
01386       OrderBackup::Backup(v, user);
01387     }
01388 
01389     /* We need to update the information about the train. */
01390     NormaliseTrainHead(new_head);
01391 
01392     /* We are undoubtedly changing something in the depot and train list. */
01393     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01394     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01395 
01396     /* Actually delete the sold 'goods' */
01397     delete sell_head;
01398   } else {
01399     /* We don't want to execute what we're just tried. */
01400     RestoreTrainBackup(original);
01401   }
01402 
01403   return cost;
01404 }
01405 
01406 void Train::UpdateDeltaXY(Direction direction)
01407 {
01408   /* Set common defaults. */
01409   this->x_offs    = -1;
01410   this->y_offs    = -1;
01411   this->x_extent  =  3;
01412   this->y_extent  =  3;
01413   this->z_extent  =  6;
01414   this->x_bb_offs =  0;
01415   this->y_bb_offs =  0;
01416 
01417   if (!IsDiagonalDirection(direction)) {
01418     static const int _sign_table[] =
01419     {
01420       // x, y
01421       -1, -1, // DIR_N
01422       -1,  1, // DIR_E
01423        1,  1, // DIR_S
01424        1, -1, // DIR_W
01425     };
01426 
01427     int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
01428 
01429     /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
01430     this->x_offs -= half_shorten * _sign_table[direction];
01431     this->y_offs -= half_shorten * _sign_table[direction + 1];
01432     this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
01433     this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
01434   } else {
01435     switch (direction) {
01436         /* Shorten southern corner of the bounding box according the vehicle length
01437          * and center the bounding box on the vehicle. */
01438       case DIR_NE:
01439         this->x_offs    = 1 - (this->gcache.cached_veh_length + 1) / 2;
01440         this->x_extent  = this->gcache.cached_veh_length - 1;
01441         this->x_bb_offs = -1;
01442         break;
01443 
01444       case DIR_NW:
01445         this->y_offs    = 1 - (this->gcache.cached_veh_length + 1) / 2;
01446         this->y_extent  = this->gcache.cached_veh_length - 1;
01447         this->y_bb_offs = -1;
01448         break;
01449 
01450         /* Move northern corner of the bounding box down according to vehicle length
01451          * and center the bounding box on the vehicle. */
01452       case DIR_SW:
01453         this->x_offs    = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01454         this->x_extent  = VEHICLE_LENGTH - 1;
01455         this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01456         break;
01457 
01458       case DIR_SE:
01459         this->y_offs    = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01460         this->y_extent  = VEHICLE_LENGTH - 1;
01461         this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01462         break;
01463 
01464       default:
01465         NOT_REACHED();
01466     }
01467   }
01468 }
01469 
01474 static void MarkTrainAsStuck(Train *v)
01475 {
01476   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
01477     /* It is the first time the problem occurred, set the "train stuck" flag. */
01478     SetBit(v->flags, VRF_TRAIN_STUCK);
01479 
01480     v->wait_counter = 0;
01481 
01482     /* Stop train */
01483     v->cur_speed = 0;
01484     v->subspeed = 0;
01485     v->SetLastSpeed();
01486 
01487     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01488   }
01489 }
01490 
01498 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
01499 {
01500   uint16 flag1 = *swap_flag1;
01501   uint16 flag2 = *swap_flag2;
01502 
01503   /* Clear the flags */
01504   ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
01505   ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01506   ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
01507   ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01508 
01509   /* Reverse the rail-flags (if needed) */
01510   if (HasBit(flag1, GVF_GOINGUP_BIT)) {
01511     SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01512   } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
01513     SetBit(*swap_flag2, GVF_GOINGUP_BIT);
01514   }
01515   if (HasBit(flag2, GVF_GOINGUP_BIT)) {
01516     SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01517   } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
01518     SetBit(*swap_flag1, GVF_GOINGUP_BIT);
01519   }
01520 }
01521 
01526 static void UpdateStatusAfterSwap(Train *v)
01527 {
01528   /* Reverse the direction. */
01529   if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
01530 
01531   /* Call the proper EnterTile function unless we are in a wormhole. */
01532   if (v->track != TRACK_BIT_WORMHOLE) {
01533     VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
01534   } else {
01535     /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
01536      * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
01537      * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
01538      * when we shouldn't have. Check if this is the case. */
01539     TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
01540     if (IsTileType(vt, MP_TUNNELBRIDGE)) {
01541       VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
01542       if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
01543         /* We have just left the wormhole, possibly set the
01544          * "goingdown" bit. UpdateInclination() can be used
01545          * because we are at the border of the tile. */
01546         VehicleUpdatePosition(v);
01547         v->UpdateInclination(true, true);
01548         return;
01549       }
01550     }
01551   }
01552 
01553   VehicleUpdatePosition(v);
01554   v->UpdateViewport(true, true);
01555 }
01556 
01563 void ReverseTrainSwapVeh(Train *v, int l, int r)
01564 {
01565   Train *a, *b;
01566 
01567   /* locate vehicles to swap */
01568   for (a = v; l != 0; l--) a = a->Next();
01569   for (b = v; r != 0; r--) b = b->Next();
01570 
01571   if (a != b) {
01572     /* swap the hidden bits */
01573     {
01574       uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
01575       b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
01576       a->vehstatus = tmp;
01577     }
01578 
01579     Swap(a->track, b->track);
01580     Swap(a->direction, b->direction);
01581     Swap(a->x_pos, b->x_pos);
01582     Swap(a->y_pos, b->y_pos);
01583     Swap(a->tile,  b->tile);
01584     Swap(a->z_pos, b->z_pos);
01585 
01586     SwapTrainFlags(&a->gv_flags, &b->gv_flags);
01587 
01588     UpdateStatusAfterSwap(a);
01589     UpdateStatusAfterSwap(b);
01590   } else {
01591     /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
01592      * This is a little bit redundant way, a->gv_flags will
01593      * be (re)set twice, but it reduces code duplication */
01594     SwapTrainFlags(&a->gv_flags, &a->gv_flags);
01595     UpdateStatusAfterSwap(a);
01596   }
01597 
01598   /* Update power of the train in case tiles were different rail type. */
01599   v->RailtypeChanged();
01600 }
01601 
01602 
01608 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
01609 {
01610   return (v->type == VEH_TRAIN) ? v : NULL;
01611 }
01612 
01613 
01620 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
01621 {
01622   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
01623 
01624   Train *t = Train::From(v);
01625   if (!t->IsFrontEngine()) return NULL;
01626 
01627   TileIndex tile = *(TileIndex *)data;
01628 
01629   if (TrainApproachingCrossingTile(t) != tile) return NULL;
01630 
01631   return t;
01632 }
01633 
01634 
01641 static bool TrainApproachingCrossing(TileIndex tile)
01642 {
01643   assert(IsLevelCrossingTile(tile));
01644 
01645   DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
01646   TileIndex tile_from = tile + TileOffsByDiagDir(dir);
01647 
01648   if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
01649 
01650   dir = ReverseDiagDir(dir);
01651   tile_from = tile + TileOffsByDiagDir(dir);
01652 
01653   return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
01654 }
01655 
01656 
01663 void UpdateLevelCrossing(TileIndex tile, bool sound)
01664 {
01665   assert(IsLevelCrossingTile(tile));
01666 
01667   /* train on crossing || train approaching crossing || reserved */
01668   bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
01669 
01670   if (new_state != IsCrossingBarred(tile)) {
01671     if (new_state && sound) {
01672       SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01673     }
01674     SetCrossingBarred(tile, new_state);
01675     MarkTileDirtyByTile(tile);
01676   }
01677 }
01678 
01679 
01685 static inline void MaybeBarCrossingWithSound(TileIndex tile)
01686 {
01687   if (!IsCrossingBarred(tile)) {
01688     BarCrossing(tile);
01689     SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01690     MarkTileDirtyByTile(tile);
01691   }
01692 }
01693 
01694 
01700 static void AdvanceWagonsBeforeSwap(Train *v)
01701 {
01702   Train *base = v;
01703   Train *first = base; // first vehicle to move
01704   Train *last = v->Last(); // last vehicle to move
01705   uint length = CountVehiclesInChain(v);
01706 
01707   while (length > 2) {
01708     last = last->Previous();
01709     first = first->Next();
01710 
01711     int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
01712 
01713     /* do not update images now
01714      * negative differential will be handled in AdvanceWagonsAfterSwap() */
01715     for (int i = 0; i < differential; i++) TrainController(first, last->Next());
01716 
01717     base = first; // == base->Next()
01718     length -= 2;
01719   }
01720 }
01721 
01722 
01728 static void AdvanceWagonsAfterSwap(Train *v)
01729 {
01730   /* first of all, fix the situation when the train was entering a depot */
01731   Train *dep = v; // last vehicle in front of just left depot
01732   while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
01733     dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
01734   }
01735 
01736   Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
01737 
01738   if (leave != NULL) {
01739     /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
01740     int d = TicksToLeaveDepot(dep);
01741 
01742     if (d <= 0) {
01743       leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
01744       leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
01745       for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
01746     }
01747   } else {
01748     dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
01749   }
01750 
01751   Train *base = v;
01752   Train *first = base; // first vehicle to move
01753   Train *last = v->Last(); // last vehicle to move
01754   uint length = CountVehiclesInChain(v);
01755 
01756   /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
01757    * they have already correct spacing, so we have to make sure they are moved how they should */
01758   bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
01759 
01760   while (length > 2) {
01761     /* we reached vehicle (originally) in front of a depot, stop now
01762      * (we would move wagons that are already moved with new wagon length). */
01763     if (base == dep) break;
01764 
01765     /* the last wagon was that one leaving a depot, so do not move it anymore */
01766     if (last == dep) nomove = true;
01767 
01768     last = last->Previous();
01769     first = first->Next();
01770 
01771     int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
01772 
01773     /* do not update images now */
01774     for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
01775 
01776     base = first; // == base->Next()
01777     length -= 2;
01778   }
01779 }
01780 
01785 void ReverseTrainDirection(Train *v)
01786 {
01787   if (IsRailDepotTile(v->tile)) {
01788     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01789   }
01790 
01791   /* Clear path reservation in front if train is not stuck. */
01792   if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
01793 
01794   /* Check if we were approaching a rail/road-crossing */
01795   TileIndex crossing = TrainApproachingCrossingTile(v);
01796 
01797   /* count number of vehicles */
01798   int r = CountVehiclesInChain(v) - 1;  // number of vehicles - 1
01799 
01800   AdvanceWagonsBeforeSwap(v);
01801 
01802   /* swap start<>end, start+1<>end-1, ... */
01803   int l = 0;
01804   do {
01805     ReverseTrainSwapVeh(v, l++, r--);
01806   } while (l <= r);
01807 
01808   AdvanceWagonsAfterSwap(v);
01809 
01810   if (IsRailDepotTile(v->tile)) {
01811     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01812   }
01813 
01814   ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
01815 
01816   ClrBit(v->flags, VRF_REVERSING);
01817 
01818   /* recalculate cached data */
01819   v->ConsistChanged(true);
01820 
01821   /* update all images */
01822   for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
01823 
01824   /* update crossing we were approaching */
01825   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
01826 
01827   /* maybe we are approaching crossing now, after reversal */
01828   crossing = TrainApproachingCrossingTile(v);
01829   if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
01830 
01831   /* If we are inside a depot after reversing, don't bother with path reserving. */
01832   if (v->track == TRACK_BIT_DEPOT) {
01833     /* Can't be stuck here as inside a depot is always a safe tile. */
01834     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01835     ClrBit(v->flags, VRF_TRAIN_STUCK);
01836     return;
01837   }
01838 
01839   /* TrainExitDir does not always produce the desired dir for depots and
01840    * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
01841   DiagDirection dir = TrainExitDir(v->direction, v->track);
01842   if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
01843 
01844   if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
01845     /* If we are currently on a tile with conventional signals, we can't treat the
01846      * current tile as a safe tile or we would enter a PBS block without a reservation. */
01847     bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
01848       HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
01849       !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
01850 
01851     if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01852     if (TryPathReserve(v, false, first_tile_okay)) {
01853       /* Do a look-ahead now in case our current tile was already a safe tile. */
01854       CheckNextTrainTile(v);
01855     } else if (v->current_order.GetType() != OT_LOADING) {
01856       /* Do not wait for a way out when we're still loading */
01857       MarkTrainAsStuck(v);
01858     }
01859   } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
01860     /* A train not inside a PBS block can't be stuck. */
01861     ClrBit(v->flags, VRF_TRAIN_STUCK);
01862     v->wait_counter = 0;
01863   }
01864 }
01865 
01875 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01876 {
01877   Train *v = Train::GetIfValid(p1);
01878   if (v == NULL) return CMD_ERROR;
01879 
01880   CommandCost ret = CheckOwnership(v->owner);
01881   if (ret.Failed()) return ret;
01882 
01883   if (p2 != 0) {
01884     /* turn a single unit around */
01885 
01886     if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
01887       return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
01888     }
01889     if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
01890 
01891     Train *front = v->First();
01892     /* make sure the vehicle is stopped in the depot */
01893     if (!front->IsStoppedInDepot()) {
01894       return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01895     }
01896 
01897     if (flags & DC_EXEC) {
01898       ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
01899 
01900       front->ConsistChanged(false);
01901       SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
01902       SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
01903       SetWindowDirty(WC_VEHICLE_VIEW, front->index);
01904       SetWindowClassesDirty(WC_TRAINS_LIST);
01905     }
01906   } else {
01907     /* turn the whole train around */
01908     if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
01909 
01910     if (flags & DC_EXEC) {
01911       /* Properly leave the station if we are loading and won't be loading anymore */
01912       if (v->current_order.IsType(OT_LOADING)) {
01913         const Vehicle *last = v;
01914         while (last->Next() != NULL) last = last->Next();
01915 
01916         /* not a station || different station --> leave the station */
01917         if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
01918           v->LeaveStation();
01919         }
01920       }
01921 
01922       /* We cancel any 'skip signal at dangers' here */
01923       v->force_proceed = TFP_NONE;
01924       SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01925 
01926       if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
01927         ToggleBit(v->flags, VRF_REVERSING);
01928       } else {
01929         v->cur_speed = 0;
01930         v->SetLastSpeed();
01931         HideFillingPercent(&v->fill_percent_te_id);
01932         ReverseTrainDirection(v);
01933       }
01934     }
01935   }
01936   return CommandCost();
01937 }
01938 
01948 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01949 {
01950   Train *t = Train::GetIfValid(p1);
01951   if (t == NULL) return CMD_ERROR;
01952 
01953   CommandCost ret = CheckOwnership(t->owner);
01954   if (ret.Failed()) return ret;
01955 
01956 
01957   if (flags & DC_EXEC) {
01958     /* If we are forced to proceed, cancel that order.
01959      * If we are marked stuck we would want to force the train
01960      * to proceed to the next signal. In the other cases we
01961      * would like to pass the signal at danger and run till the
01962      * next signal we encounter. */
01963     t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsInDepot() ? TFP_STUCK : TFP_SIGNAL;
01964     SetWindowDirty(WC_VEHICLE_VIEW, t->index);
01965   }
01966 
01967   return CommandCost();
01968 }
01969 
01977 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
01978 {
01979   assert(!(v->vehstatus & VS_CRASHED));
01980 
01981   if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
01982 
01983   PBSTileInfo origin = FollowTrainReservation(v);
01984   if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
01985 
01986   switch (_settings_game.pf.pathfinder_for_trains) {
01987     case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
01988     case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
01989 
01990     default: NOT_REACHED();
01991   }
01992 }
01993 
02001 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
02002 {
02003   FindDepotData tfdd = FindClosestTrainDepot(this, 0);
02004   if (tfdd.best_length == UINT_MAX) return false;
02005 
02006   if (location    != NULL) *location    = tfdd.tile;
02007   if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
02008   if (reverse     != NULL) *reverse     = tfdd.reverse;
02009 
02010   return true;
02011 }
02012 
02014 void Train::PlayLeaveStationSound() const
02015 {
02016   static const SoundFx sfx[] = {
02017     SND_04_TRAIN,
02018     SND_0A_TRAIN_HORN,
02019     SND_0A_TRAIN_HORN,
02020     SND_47_MAGLEV_2,
02021     SND_41_MAGLEV
02022   };
02023 
02024   if (PlayVehicleSound(this, VSE_START)) return;
02025 
02026   EngineID engtype = this->engine_type;
02027   SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
02028 }
02029 
02034 static void CheckNextTrainTile(Train *v)
02035 {
02036   /* Don't do any look-ahead if path_backoff_interval is 255. */
02037   if (_settings_game.pf.path_backoff_interval == 255) return;
02038 
02039   /* Exit if we are inside a depot. */
02040   if (v->track == TRACK_BIT_DEPOT) return;
02041 
02042   switch (v->current_order.GetType()) {
02043     /* Exit if we reached our destination depot. */
02044     case OT_GOTO_DEPOT:
02045       if (v->tile == v->dest_tile) return;
02046       break;
02047 
02048     case OT_GOTO_WAYPOINT:
02049       /* If we reached our waypoint, make sure we see that. */
02050       if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
02051       break;
02052 
02053     case OT_NOTHING:
02054     case OT_LEAVESTATION:
02055     case OT_LOADING:
02056       /* Exit if the current order doesn't have a destination, but the train has orders. */
02057       if (v->GetNumOrders() > 0) return;
02058       break;
02059 
02060     default:
02061       break;
02062   }
02063   /* Exit if we are on a station tile and are going to stop. */
02064   if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
02065 
02066   Trackdir td = v->GetVehicleTrackdir();
02067 
02068   /* On a tile with a red non-pbs signal, don't look ahead. */
02069   if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
02070       !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
02071       GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
02072 
02073   CFollowTrackRail ft(v);
02074   if (!ft.Follow(v->tile, td)) return;
02075 
02076   if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
02077     /* Next tile is not reserved. */
02078     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02079       if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
02080         /* If the next tile is a PBS signal, try to make a reservation. */
02081         TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02082         if (_settings_game.pf.forbid_90_deg) {
02083           tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
02084         }
02085         ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
02086       }
02087     }
02088   }
02089 }
02090 
02096 static bool CheckTrainStayInDepot(Train *v)
02097 {
02098   /* bail out if not all wagons are in the same depot or not in a depot at all */
02099   for (const Train *u = v; u != NULL; u = u->Next()) {
02100     if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
02101   }
02102 
02103   /* if the train got no power, then keep it in the depot */
02104   if (v->gcache.cached_power == 0) {
02105     v->vehstatus |= VS_STOPPED;
02106     SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
02107     return true;
02108   }
02109 
02110   SigSegState seg_state;
02111 
02112   if (v->force_proceed == TFP_NONE) {
02113     /* force proceed was not pressed */
02114     if (++v->wait_counter < 37) {
02115       SetWindowClassesDirty(WC_TRAINS_LIST);
02116       return true;
02117     }
02118 
02119     v->wait_counter = 0;
02120 
02121     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02122     if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
02123       /* Full and no PBS signal in block or depot reserved, can't exit. */
02124       SetWindowClassesDirty(WC_TRAINS_LIST);
02125       return true;
02126     }
02127   } else {
02128     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02129   }
02130 
02131   /* We are leaving a depot, but have to go to the exact same one; re-enter */
02132   if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
02133     /* We need to have a reservation for this to work. */
02134     if (HasDepotReservation(v->tile)) return true;
02135     SetDepotReservation(v->tile, true);
02136     VehicleEnterDepot(v);
02137     return true;
02138   }
02139 
02140   /* Only leave when we can reserve a path to our destination. */
02141   if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
02142     /* No path and no force proceed. */
02143     SetWindowClassesDirty(WC_TRAINS_LIST);
02144     MarkTrainAsStuck(v);
02145     return true;
02146   }
02147 
02148   SetDepotReservation(v->tile, true);
02149   if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02150 
02151   VehicleServiceInDepot(v);
02152   SetWindowClassesDirty(WC_TRAINS_LIST);
02153   v->PlayLeaveStationSound();
02154 
02155   v->track = TRACK_BIT_X;
02156   if (v->direction & 2) v->track = TRACK_BIT_Y;
02157 
02158   v->vehstatus &= ~VS_HIDDEN;
02159   v->cur_speed = 0;
02160 
02161   v->UpdateViewport(true, true);
02162   VehicleUpdatePosition(v);
02163   UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02164   v->UpdateAcceleration();
02165   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
02166 
02167   return false;
02168 }
02169 
02176 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
02177 {
02178   DiagDirection dir = TrackdirToExitdir(track_dir);
02179 
02180   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
02181     /* Are we just leaving a tunnel/bridge? */
02182     if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
02183       TileIndex end = GetOtherTunnelBridgeEnd(tile);
02184 
02185       if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
02186         /* Free the reservation only if no other train is on the tiles. */
02187         SetTunnelBridgeReservation(tile, false);
02188         SetTunnelBridgeReservation(end, false);
02189 
02190         if (_settings_client.gui.show_track_reservation) {
02191           MarkTileDirtyByTile(tile);
02192           MarkTileDirtyByTile(end);
02193         }
02194       }
02195     }
02196   } else if (IsRailStationTile(tile)) {
02197     TileIndex new_tile = TileAddByDiagDir(tile, dir);
02198     /* If the new tile is not a further tile of the same station, we
02199      * clear the reservation for the whole platform. */
02200     if (!IsCompatibleTrainStationTile(new_tile, tile)) {
02201       SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
02202     }
02203   } else {
02204     /* Any other tile */
02205     UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
02206   }
02207 }
02208 
02215 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
02216 {
02217   assert(v->IsFrontEngine());
02218 
02219   TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
02220   Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
02221   bool      free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
02222   StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
02223 
02224   /* Don't free reservation if it's not ours. */
02225   if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
02226 
02227   CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
02228   while (ft.Follow(tile, td)) {
02229     tile = ft.m_new_tile;
02230     TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
02231     td = RemoveFirstTrackdir(&bits);
02232     assert(bits == TRACKDIR_BIT_NONE);
02233 
02234     if (!IsValidTrackdir(td)) break;
02235 
02236     if (IsTileType(tile, MP_RAILWAY)) {
02237       if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
02238         /* Conventional signal along trackdir: remove reservation and stop. */
02239         UnreserveRailTrack(tile, TrackdirToTrack(td));
02240         break;
02241       }
02242       if (HasPbsSignalOnTrackdir(tile, td)) {
02243         if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
02244           /* Red PBS signal? Can't be our reservation, would be green then. */
02245           break;
02246         } else {
02247           /* Turn the signal back to red. */
02248           SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
02249           MarkTileDirtyByTile(tile);
02250         }
02251       } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
02252         break;
02253       }
02254     }
02255 
02256     /* Don't free first station/bridge/tunnel if we are on it. */
02257     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);
02258 
02259     free_tile = true;
02260   }
02261 }
02262 
02263 static const byte _initial_tile_subcoord[6][4][3] = {
02264 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
02265 {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
02266 {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
02267 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
02268 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
02269 {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
02270 };
02271 
02284 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
02285 {
02286   switch (_settings_game.pf.pathfinder_for_trains) {
02287     case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02288     case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02289 
02290     default: NOT_REACHED();
02291   }
02292 }
02293 
02299 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
02300 {
02301   PBSTileInfo origin = FollowTrainReservation(v);
02302 
02303   CFollowTrackRail ft(v);
02304 
02305   TileIndex tile = origin.tile;
02306   Trackdir  cur_td = origin.trackdir;
02307   while (ft.Follow(tile, cur_td)) {
02308     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02309       /* Possible signal tile. */
02310       if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
02311     }
02312 
02313     if (_settings_game.pf.forbid_90_deg) {
02314       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02315       if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
02316     }
02317 
02318     /* Station, depot or waypoint are a possible target. */
02319     bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
02320     if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
02321       /* Choice found or possible target encountered.
02322        * On finding a possible target, we need to stop and let the pathfinder handle the
02323        * remaining path. This is because we don't know if this target is in one of our
02324        * orders, so we might cause pathfinding to fail later on if we find a choice.
02325        * This failure would cause a bogous call to TryReserveSafePath which might reserve
02326        * a wrong path not leading to our next destination. */
02327       if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
02328 
02329       /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
02330        * actually starts its search at the first unreserved tile. */
02331       if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
02332 
02333       /* Choice found, path valid but not okay. Save info about the choice tile as well. */
02334       if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02335       if (enterdir != NULL) *enterdir = ft.m_exitdir;
02336       return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
02337     }
02338 
02339     tile = ft.m_new_tile;
02340     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02341 
02342     if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
02343       bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
02344       if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
02345       /* Safe position is all good, path valid and okay. */
02346       return PBSTileInfo(tile, cur_td, true);
02347     }
02348 
02349     if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
02350   }
02351 
02352   if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
02353     /* End of line, path valid and okay. */
02354     return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
02355   }
02356 
02357   /* Sorry, can't reserve path, back out. */
02358   tile = origin.tile;
02359   cur_td = origin.trackdir;
02360   TileIndex stopped = ft.m_old_tile;
02361   Trackdir  stopped_td = ft.m_old_td;
02362   while (tile != stopped || cur_td != stopped_td) {
02363     if (!ft.Follow(tile, cur_td)) break;
02364 
02365     if (_settings_game.pf.forbid_90_deg) {
02366       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02367       assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
02368     }
02369     assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
02370 
02371     tile = ft.m_new_tile;
02372     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02373 
02374     UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
02375   }
02376 
02377   /* Path invalid. */
02378   return PBSTileInfo();
02379 }
02380 
02391 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
02392 {
02393   switch (_settings_game.pf.pathfinder_for_trains) {
02394     case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02395     case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02396 
02397     default: NOT_REACHED();
02398   }
02399 }
02400 
02402 class VehicleOrderSaver {
02403 private:
02404   Train          *v;
02405   Order          old_order;
02406   TileIndex      old_dest_tile;
02407   StationID      old_last_station_visited;
02408   VehicleOrderID index;
02409   bool           suppress_implicit_orders;
02410 
02411 public:
02412   VehicleOrderSaver(Train *_v) :
02413     v(_v),
02414     old_order(_v->current_order),
02415     old_dest_tile(_v->dest_tile),
02416     old_last_station_visited(_v->last_station_visited),
02417     index(_v->cur_real_order_index),
02418     suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
02419   {
02420   }
02421 
02422   ~VehicleOrderSaver()
02423   {
02424     this->v->current_order = this->old_order;
02425     this->v->dest_tile = this->old_dest_tile;
02426     this->v->last_station_visited = this->old_last_station_visited;
02427     SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
02428   }
02429 
02435   bool SwitchToNextOrder(bool skip_first)
02436   {
02437     if (this->v->GetNumOrders() == 0) return false;
02438 
02439     if (skip_first) ++this->index;
02440 
02441     int conditional_depth = 0;
02442 
02443     do {
02444       /* Wrap around. */
02445       if (this->index >= this->v->GetNumOrders()) this->index = 0;
02446 
02447       Order *order = this->v->GetOrder(this->index);
02448       assert(order != NULL);
02449 
02450       switch (order->GetType()) {
02451         case OT_GOTO_DEPOT:
02452           /* Skip service in depot orders when the train doesn't need service. */
02453           if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
02454         case OT_GOTO_STATION:
02455         case OT_GOTO_WAYPOINT:
02456           this->v->current_order = *order;
02457           return UpdateOrderDest(this->v, order, 0, true);
02458         case OT_CONDITIONAL: {
02459           if (conditional_depth > this->v->GetNumOrders()) return false;
02460           VehicleOrderID next = ProcessConditionalOrder(order, this->v);
02461           if (next != INVALID_VEH_ORDER_ID) {
02462             conditional_depth++;
02463             this->index = next;
02464             /* Don't increment next, so no break here. */
02465             continue;
02466           }
02467           break;
02468         }
02469         default:
02470           break;
02471       }
02472       /* Don't increment inside the while because otherwise conditional
02473        * orders can lead to an infinite loop. */
02474       ++this->index;
02475     } while (this->index != this->v->cur_real_order_index);
02476 
02477     return false;
02478   }
02479 };
02480 
02481 /* choose a track */
02482 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
02483 {
02484   Track best_track = INVALID_TRACK;
02485   bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
02486   bool changed_signal = false;
02487 
02488   assert((tracks & ~TRACK_BIT_MASK) == 0);
02489 
02490   if (got_reservation != NULL) *got_reservation = false;
02491 
02492   /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
02493   TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
02494   /* Do we have a suitable reserved track? */
02495   if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
02496 
02497   /* Quick return in case only one possible track is available */
02498   if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
02499     Track track = FindFirstTrack(tracks);
02500     /* We need to check for signals only here, as a junction tile can't have signals. */
02501     if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
02502       do_track_reservation = true;
02503       changed_signal = true;
02504       SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
02505     } else if (!do_track_reservation) {
02506       return track;
02507     }
02508     best_track = track;
02509   }
02510 
02511   PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
02512   DiagDirection dest_enterdir = enterdir;
02513   if (do_track_reservation) {
02514     res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
02515     if (res_dest.tile == INVALID_TILE) {
02516       /* Reservation failed? */
02517       if (mark_stuck) MarkTrainAsStuck(v);
02518       if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
02519       return FindFirstTrack(tracks);
02520     }
02521     if (res_dest.okay) {
02522       /* Got a valid reservation that ends at a safe target, quick exit. */
02523       if (got_reservation != NULL) *got_reservation = true;
02524       if (changed_signal) MarkTileDirtyByTile(tile);
02525       TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02526       return best_track;
02527     }
02528 
02529     /* Check if the train needs service here, so it has a chance to always find a depot.
02530      * Also check if the current order is a service order so we don't reserve a path to
02531      * the destination but instead to the next one if service isn't needed. */
02532     CheckIfTrainNeedsService(v);
02533     if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
02534   }
02535 
02536   /* Save the current train order. The destructor will restore the old order on function exit. */
02537   VehicleOrderSaver orders(v);
02538 
02539   /* If the current tile is the destination of the current order and
02540    * a reservation was requested, advance to the next order.
02541    * Don't advance on a depot order as depots are always safe end points
02542    * for a path and no look-ahead is necessary. This also avoids a
02543    * problem with depot orders not part of the order list when the
02544    * order list itself is empty. */
02545   if (v->current_order.IsType(OT_LEAVESTATION)) {
02546     orders.SwitchToNextOrder(false);
02547   } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
02548       v->current_order.IsType(OT_GOTO_STATION) ?
02549       IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
02550       v->tile == v->dest_tile))) {
02551     orders.SwitchToNextOrder(true);
02552   }
02553 
02554   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02555     /* Pathfinders are able to tell that route was only 'guessed'. */
02556     bool      path_found = true;
02557     TileIndex new_tile = res_dest.tile;
02558 
02559     Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
02560     if (new_tile == tile) best_track = next_track;
02561     v->HandlePathfindingResult(path_found);
02562   }
02563 
02564   /* No track reservation requested -> finished. */
02565   if (!do_track_reservation) return best_track;
02566 
02567   /* A path was found, but could not be reserved. */
02568   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02569     if (mark_stuck) MarkTrainAsStuck(v);
02570     FreeTrainTrackReservation(v);
02571     return best_track;
02572   }
02573 
02574   /* No possible reservation target found, we are probably lost. */
02575   if (res_dest.tile == INVALID_TILE) {
02576     /* Try to find any safe destination. */
02577     PBSTileInfo origin = FollowTrainReservation(v);
02578     if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
02579       TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
02580       best_track = FindFirstTrack(res);
02581       TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02582       if (got_reservation != NULL) *got_reservation = true;
02583       if (changed_signal) MarkTileDirtyByTile(tile);
02584     } else {
02585       FreeTrainTrackReservation(v);
02586       if (mark_stuck) MarkTrainAsStuck(v);
02587     }
02588     return best_track;
02589   }
02590 
02591   if (got_reservation != NULL) *got_reservation = true;
02592 
02593   /* Reservation target found and free, check if it is safe. */
02594   while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
02595     /* Extend reservation until we have found a safe position. */
02596     DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
02597     TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
02598     TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
02599     if (_settings_game.pf.forbid_90_deg) {
02600       reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
02601     }
02602 
02603     /* Get next order with destination. */
02604     if (orders.SwitchToNextOrder(true)) {
02605       PBSTileInfo cur_dest;
02606       bool path_found;
02607       DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
02608       if (cur_dest.tile != INVALID_TILE) {
02609         res_dest = cur_dest;
02610         if (res_dest.okay) continue;
02611         /* Path found, but could not be reserved. */
02612         FreeTrainTrackReservation(v);
02613         if (mark_stuck) MarkTrainAsStuck(v);
02614         if (got_reservation != NULL) *got_reservation = false;
02615         changed_signal = false;
02616         break;
02617       }
02618     }
02619     /* No order or no safe position found, try any position. */
02620     if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
02621       FreeTrainTrackReservation(v);
02622       if (mark_stuck) MarkTrainAsStuck(v);
02623       if (got_reservation != NULL) *got_reservation = false;
02624       changed_signal = false;
02625     }
02626     break;
02627   }
02628 
02629   TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02630 
02631   if (changed_signal) MarkTileDirtyByTile(tile);
02632 
02633   return best_track;
02634 }
02635 
02644 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
02645 {
02646   assert(v->IsFrontEngine());
02647 
02648   /* We have to handle depots specially as the track follower won't look
02649    * at the depot tile itself but starts from the next tile. If we are still
02650    * inside the depot, a depot reservation can never be ours. */
02651   if (v->track == TRACK_BIT_DEPOT) {
02652     if (HasDepotReservation(v->tile)) {
02653       if (mark_as_stuck) MarkTrainAsStuck(v);
02654       return false;
02655     } else {
02656       /* Depot not reserved, but the next tile might be. */
02657       TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
02658       if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
02659     }
02660   }
02661 
02662   Vehicle *other_train = NULL;
02663   PBSTileInfo origin = FollowTrainReservation(v, &other_train);
02664   /* The path we are driving on is already blocked by some other train.
02665    * This can only happen in certain situations when mixing path and
02666    * block signals or when changing tracks and/or signals.
02667    * Exit here as doing any further reservations will probably just
02668    * make matters worse. */
02669   if (other_train != NULL && other_train->index != v->index) {
02670     if (mark_as_stuck) MarkTrainAsStuck(v);
02671     return false;
02672   }
02673   /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
02674   if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
02675     /* Can't be stuck then. */
02676     if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02677     ClrBit(v->flags, VRF_TRAIN_STUCK);
02678     return true;
02679   }
02680 
02681   /* If we are in a depot, tentatively reserve the depot. */
02682   if (v->track == TRACK_BIT_DEPOT) {
02683     SetDepotReservation(v->tile, true);
02684     if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02685   }
02686 
02687   DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
02688   TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
02689   TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
02690 
02691   if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
02692 
02693   bool res_made = false;
02694   ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
02695 
02696   if (!res_made) {
02697     /* Free the depot reservation as well. */
02698     if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
02699     return false;
02700   }
02701 
02702   if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
02703     v->wait_counter = 0;
02704     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02705   }
02706   ClrBit(v->flags, VRF_TRAIN_STUCK);
02707   return true;
02708 }
02709 
02710 
02711 static bool CheckReverseTrain(const Train *v)
02712 {
02713   if (_settings_game.difficulty.line_reverse_mode != 0 ||
02714       v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
02715       !(v->direction & 1)) {
02716     return false;
02717   }
02718 
02719   assert(v->track != TRACK_BIT_NONE);
02720 
02721   switch (_settings_game.pf.pathfinder_for_trains) {
02722     case VPF_NPF: return NPFTrainCheckReverse(v);
02723     case VPF_YAPF: return YapfTrainCheckReverse(v);
02724 
02725     default: NOT_REACHED();
02726   }
02727 }
02728 
02734 TileIndex Train::GetOrderStationLocation(StationID station)
02735 {
02736   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
02737 
02738   const Station *st = Station::Get(station);
02739   if (!(st->facilities & FACIL_TRAIN)) {
02740     /* The destination station has no trainstation tiles. */
02741     this->IncrementRealOrderIndex();
02742     return 0;
02743   }
02744 
02745   return st->xy;
02746 }
02747 
02749 void Train::MarkDirty()
02750 {
02751   Train *v = this;
02752   do {
02753     v->UpdateViewport(false, false);
02754   } while ((v = v->Next()) != NULL);
02755 
02756   /* need to update acceleration and cached values since the goods on the train changed. */
02757   this->CargoChanged();
02758   this->UpdateAcceleration();
02759 }
02760 
02768 int Train::UpdateSpeed()
02769 {
02770   switch (_settings_game.vehicle.train_acceleration_model) {
02771     default: NOT_REACHED();
02772     case AM_ORIGINAL:
02773       return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->gcache.cached_max_track_speed);
02774 
02775     case AM_REALISTIC:
02776       return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
02777   }
02778 }
02779 
02785 static void TrainEnterStation(Train *v, StationID station)
02786 {
02787   v->last_station_visited = station;
02788 
02789   /* check if a train ever visited this station before */
02790   Station *st = Station::Get(station);
02791   if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
02792     st->had_vehicle_of_type |= HVOT_TRAIN;
02793     SetDParam(0, st->index);
02794     AddVehicleNewsItem(
02795       STR_NEWS_FIRST_TRAIN_ARRIVAL,
02796       v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
02797       v->index,
02798       st->index
02799     );
02800     AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
02801     Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
02802   }
02803 
02804   v->force_proceed = TFP_NONE;
02805   SetWindowDirty(WC_VEHICLE_VIEW, v->index);
02806 
02807   v->BeginLoading();
02808 
02809   TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
02810 }
02811 
02812 /* Check if the vehicle is compatible with the specified tile */
02813 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
02814 {
02815   return IsTileOwner(tile, v->owner) &&
02816       (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
02817 }
02818 
02820 struct RailtypeSlowdownParams {
02821   byte small_turn; 
02822   byte large_turn; 
02823   byte z_up;       
02824   byte z_down;     
02825 };
02826 
02828 static const RailtypeSlowdownParams _railtype_slowdown[] = {
02829   /* normal accel */
02830   {256 / 4, 256 / 2, 256 / 4, 2}, 
02831   {256 / 4, 256 / 2, 256 / 4, 2}, 
02832   {256 / 4, 256 / 2, 256 / 4, 2}, 
02833   {0,       256 / 2, 256 / 4, 2}, 
02834 };
02835 
02841 static inline void AffectSpeedByZChange(Train *v, int old_z)
02842 {
02843   if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
02844 
02845   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
02846 
02847   if (old_z < v->z_pos) {
02848     v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
02849   } else {
02850     uint16 spd = v->cur_speed + rsp->z_down;
02851     if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
02852   }
02853 }
02854 
02855 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
02856 {
02857   if (IsTileType(tile, MP_RAILWAY) &&
02858       GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
02859     TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
02860     Trackdir trackdir = FindFirstTrackdir(tracks);
02861     if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
02862       /* A PBS block with a non-PBS signal facing us? */
02863       if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
02864     }
02865   }
02866   return false;
02867 }
02868 
02870 void Train::ReserveTrackUnderConsist() const
02871 {
02872   for (const Train *u = this; u != NULL; u = u->Next()) {
02873     switch (u->track) {
02874       case TRACK_BIT_WORMHOLE:
02875         TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
02876         break;
02877       case TRACK_BIT_DEPOT:
02878         break;
02879       default:
02880         TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
02881         break;
02882     }
02883   }
02884 }
02885 
02892 uint Train::Crash(bool flooded)
02893 {
02894   uint pass = 0;
02895   if (this->IsFrontEngine()) {
02896     pass += 2; // driver
02897 
02898     /* Remove the reserved path in front of the train if it is not stuck.
02899      * Also clear all reserved tracks the train is currently on. */
02900     if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
02901     for (const Train *v = this; v != NULL; v = v->Next()) {
02902       ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
02903       if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
02904         /* ClearPathReservation will not free the wormhole exit
02905          * if the train has just entered the wormhole. */
02906         SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
02907       }
02908     }
02909 
02910     /* we may need to update crossing we were approaching,
02911      * but must be updated after the train has been marked crashed */
02912     TileIndex crossing = TrainApproachingCrossingTile(this);
02913     if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
02914 
02915     /* Remove the loading indicators (if any) */
02916     HideFillingPercent(&this->fill_percent_te_id);
02917   }
02918 
02919   pass += this->GroundVehicleBase::Crash(flooded);
02920 
02921   this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
02922   return pass;
02923 }
02924 
02931 static uint TrainCrashed(Train *v)
02932 {
02933   uint num = 0;
02934 
02935   /* do not crash train twice */
02936   if (!(v->vehstatus & VS_CRASHED)) {
02937     num = v->Crash();
02938     AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02939     Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02940   }
02941 
02942   /* Try to re-reserve track under already crashed train too.
02943    * Crash() clears the reservation! */
02944   v->ReserveTrackUnderConsist();
02945 
02946   return num;
02947 }
02948 
02950 struct TrainCollideChecker {
02951   Train *v; 
02952   uint num; 
02953 };
02954 
02961 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
02962 {
02963   TrainCollideChecker *tcc = (TrainCollideChecker*)data;
02964 
02965   /* not a train or in depot */
02966   if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
02967 
02968   /* do not crash into trains of another company. */
02969   if (v->owner != tcc->v->owner) return NULL;
02970 
02971   /* get first vehicle now to make most usual checks faster */
02972   Train *coll = Train::From(v)->First();
02973 
02974   /* can't collide with own wagons */
02975   if (coll == tcc->v) return NULL;
02976 
02977   int x_diff = v->x_pos - tcc->v->x_pos;
02978   int y_diff = v->y_pos - tcc->v->y_pos;
02979 
02980   /* Do fast calculation to check whether trains are not in close vicinity
02981    * and quickly reject trains distant enough for any collision.
02982    * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
02983    * Differences are then ORed and then we check for any higher bits */
02984   uint hash = (y_diff + 7) | (x_diff + 7);
02985   if (hash & ~15) return NULL;
02986 
02987   /* Slower check using multiplication */
02988   int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
02989   if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
02990 
02991   /* Happens when there is a train under bridge next to bridge head */
02992   if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
02993 
02994   /* crash both trains */
02995   tcc->num += TrainCrashed(tcc->v);
02996   tcc->num += TrainCrashed(coll);
02997 
02998   return NULL; // continue searching
02999 }
03000 
03008 static bool CheckTrainCollision(Train *v)
03009 {
03010   /* can't collide in depot */
03011   if (v->track == TRACK_BIT_DEPOT) return false;
03012 
03013   assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
03014 
03015   TrainCollideChecker tcc;
03016   tcc.v = v;
03017   tcc.num = 0;
03018 
03019   /* find colliding vehicles */
03020   if (v->track == TRACK_BIT_WORMHOLE) {
03021     FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
03022     FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
03023   } else {
03024     FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
03025   }
03026 
03027   /* any dead -> no crash */
03028   if (tcc.num == 0) return false;
03029 
03030   SetDParam(0, tcc.num);
03031   AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH,
03032     NS_ACCIDENT,
03033     v->index
03034   );
03035 
03036   ModifyStationRatingAround(v->tile, v->owner, -160, 30);
03037   SndPlayVehicleFx(SND_13_BIG_CRASH, v);
03038   return true;
03039 }
03040 
03041 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
03042 {
03043   if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
03044 
03045   Train *t = Train::From(v);
03046   DiagDirection exitdir = *(DiagDirection *)data;
03047 
03048   /* not front engine of a train, inside wormhole or depot, crashed */
03049   if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
03050 
03051   if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
03052 
03053   return t;
03054 }
03055 
03063 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
03064 {
03065   Train *first = v->First();
03066   Train *prev;
03067   bool direction_changed = false; // has direction of any part changed?
03068 
03069   /* For every vehicle after and including the given vehicle */
03070   for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
03071     DiagDirection enterdir = DIAGDIR_BEGIN;
03072     bool update_signals_crossing = false; // will we update signals or crossing state?
03073 
03074     GetNewVehiclePosResult gp = GetNewVehiclePos(v);
03075     if (v->track != TRACK_BIT_WORMHOLE) {
03076       /* Not inside tunnel */
03077       if (gp.old_tile == gp.new_tile) {
03078         /* Staying in the old tile */
03079         if (v->track == TRACK_BIT_DEPOT) {
03080           /* Inside depot */
03081           gp.x = v->x_pos;
03082           gp.y = v->y_pos;
03083         } else {
03084           /* Not inside depot */
03085 
03086           /* Reverse when we are at the end of the track already, do not move to the new position */
03087           if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
03088 
03089           uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03090           if (HasBit(r, VETS_CANNOT_ENTER)) {
03091             goto invalid_rail;
03092           }
03093           if (HasBit(r, VETS_ENTERED_STATION)) {
03094             /* The new position is the end of the platform */
03095             TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03096           }
03097         }
03098       } else {
03099         /* A new tile is about to be entered. */
03100 
03101         /* Determine what direction we're entering the new tile from */
03102         enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
03103         assert(IsValidDiagDirection(enterdir));
03104 
03105         /* Get the status of the tracks in the new tile and mask
03106          * away the bits that aren't reachable. */
03107         TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
03108         TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
03109 
03110         TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03111         TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
03112 
03113         TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03114         if (_settings_game.pf.forbid_90_deg && prev == NULL) {
03115           /* We allow wagons to make 90 deg turns, because forbid_90_deg
03116            * can be switched on halfway a turn */
03117           bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03118         }
03119 
03120         if (bits == TRACK_BIT_NONE) goto invalid_rail;
03121 
03122         /* Check if the new tile constrains tracks that are compatible
03123          * with the current train, if not, bail out. */
03124         if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
03125 
03126         TrackBits chosen_track;
03127         if (prev == NULL) {
03128           /* Currently the locomotive is active. Determine which one of the
03129            * available tracks to choose */
03130           chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
03131           assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
03132 
03133           if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
03134             /* For each signal we find decrease the counter by one.
03135              * We start at two, so the first signal we pass decreases
03136              * this to one, then if we reach the next signal it is
03137              * decreased to zero and we won't pass that new signal. */
03138             Trackdir dir = FindFirstTrackdir(trackdirbits);
03139             if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
03140                 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
03141               /* However, we do not want to be stopped by PBS signals
03142                * entered via the back. */
03143               v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
03144               SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03145             }
03146           }
03147 
03148           /* Check if it's a red signal and that force proceed is not clicked. */
03149           if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
03150             /* In front of a red signal */
03151             Trackdir i = FindFirstTrackdir(trackdirbits);
03152 
03153             /* Don't handle stuck trains here. */
03154             if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
03155 
03156             if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
03157               v->cur_speed = 0;
03158               v->subspeed = 0;
03159               v->progress = 255 - 100;
03160               if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
03161             } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
03162               v->cur_speed = 0;
03163               v->subspeed = 0;
03164               v->progress = 255 - 10;
03165               if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
03166                 DiagDirection exitdir = TrackdirToExitdir(i);
03167                 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
03168 
03169                 exitdir = ReverseDiagDir(exitdir);
03170 
03171                 /* check if a train is waiting on the other side */
03172                 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
03173               }
03174             }
03175 
03176             /* If we would reverse but are currently in a PBS block and
03177              * reversing of stuck trains is disabled, don't reverse.
03178              * This does not apply if the reason for reversing is a one-way
03179              * signal blocking us, because a train would then be stuck forever. */
03180             if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
03181                 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
03182               v->wait_counter = 0;
03183               return false;
03184             }
03185             goto reverse_train_direction;
03186           } else {
03187             TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
03188           }
03189         } else {
03190           /* The wagon is active, simply follow the prev vehicle. */
03191           if (prev->tile == gp.new_tile) {
03192             /* Choose the same track as prev */
03193             if (prev->track == TRACK_BIT_WORMHOLE) {
03194               /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
03195                * However, just choose the track into the wormhole. */
03196               assert(IsTunnel(prev->tile));
03197               chosen_track = bits;
03198             } else {
03199               chosen_track = prev->track;
03200             }
03201           } else {
03202             /* Choose the track that leads to the tile where prev is.
03203              * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
03204              * I.e. when the tile between them has only space for a single vehicle like
03205              *  1) horizontal/vertical track tiles and
03206              *  2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
03207              *     Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
03208              */
03209             static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
03210               {TRACK_BIT_X,     TRACK_BIT_LOWER, TRACK_BIT_NONE,  TRACK_BIT_LEFT },
03211               {TRACK_BIT_UPPER, TRACK_BIT_Y,     TRACK_BIT_LEFT,  TRACK_BIT_NONE },
03212               {TRACK_BIT_NONE,  TRACK_BIT_RIGHT, TRACK_BIT_X,     TRACK_BIT_UPPER},
03213               {TRACK_BIT_RIGHT, TRACK_BIT_NONE,  TRACK_BIT_LOWER, TRACK_BIT_Y    }
03214             };
03215             DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
03216             assert(IsValidDiagDirection(exitdir));
03217             chosen_track = _connecting_track[enterdir][exitdir];
03218           }
03219           chosen_track &= bits;
03220         }
03221 
03222         /* Make sure chosen track is a valid track */
03223         assert(
03224             chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
03225             chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
03226             chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
03227 
03228         /* Update XY to reflect the entrance to the new tile, and select the direction to use */
03229         const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
03230         gp.x = (gp.x & ~0xF) | b[0];
03231         gp.y = (gp.y & ~0xF) | b[1];
03232         Direction chosen_dir = (Direction)b[2];
03233 
03234         /* Call the landscape function and tell it that the vehicle entered the tile */
03235         uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03236         if (HasBit(r, VETS_CANNOT_ENTER)) {
03237           goto invalid_rail;
03238         }
03239 
03240         if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
03241           Track track = FindFirstTrack(chosen_track);
03242           Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
03243           if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
03244             SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
03245             MarkTileDirtyByTile(gp.new_tile);
03246           }
03247 
03248           /* Clear any track reservation when the last vehicle leaves the tile */
03249           if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
03250 
03251           v->tile = gp.new_tile;
03252 
03253           if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
03254             v->First()->RailtypeChanged();
03255           }
03256 
03257           v->track = chosen_track;
03258           assert(v->track);
03259         }
03260 
03261         /* We need to update signal status, but after the vehicle position hash
03262          * has been updated by UpdateInclination() */
03263         update_signals_crossing = true;
03264 
03265         if (chosen_dir != v->direction) {
03266           if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
03267             const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
03268             DirDiff diff = DirDifference(v->direction, chosen_dir);
03269             v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
03270           }
03271           direction_changed = true;
03272           v->direction = chosen_dir;
03273         }
03274 
03275         if (v->IsFrontEngine()) {
03276           v->wait_counter = 0;
03277 
03278           /* If we are approaching a crossing that is reserved, play the sound now. */
03279           TileIndex crossing = TrainApproachingCrossingTile(v);
03280           if (crossing != INVALID_TILE && HasCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
03281 
03282           /* Always try to extend the reservation when entering a tile. */
03283           CheckNextTrainTile(v);
03284         }
03285 
03286         if (HasBit(r, VETS_ENTERED_STATION)) {
03287           /* The new position is the location where we want to stop */
03288           TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03289         }
03290       }
03291     } else {
03292       /* In a tunnel or on a bridge
03293        * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
03294        * - for bridges, only the middle part - without the bridge heads */
03295       if (!(v->vehstatus & VS_HIDDEN)) {
03296         Train *first = v->First();
03297         first->cur_speed = min(first->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
03298       }
03299 
03300       if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
03301         /* Perform look-ahead on tunnel exit. */
03302         if (v->IsFrontEngine()) {
03303           TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
03304           CheckNextTrainTile(v);
03305         }
03306         /* Prevent v->UpdateInclination() being called with wrong parameters.
03307          * This could happen if the train was reversed inside the tunnel/bridge. */
03308         if (gp.old_tile == gp.new_tile) {
03309           gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
03310         }
03311       } else {
03312         v->x_pos = gp.x;
03313         v->y_pos = gp.y;
03314         VehicleUpdatePosition(v);
03315         if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
03316         continue;
03317       }
03318     }
03319 
03320     /* update image of train, as well as delta XY */
03321     v->UpdateDeltaXY(v->direction);
03322 
03323     v->x_pos = gp.x;
03324     v->y_pos = gp.y;
03325     VehicleUpdatePosition(v);
03326 
03327     /* update the Z position of the vehicle */
03328     int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
03329 
03330     if (prev == NULL) {
03331       /* This is the first vehicle in the train */
03332       AffectSpeedByZChange(v, old_z);
03333     }
03334 
03335     if (update_signals_crossing) {
03336       if (v->IsFrontEngine()) {
03337         if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
03338           /* We are entering a block with PBS signals right now, but
03339            * not through a PBS signal. This means we don't have a
03340            * reservation right now. As a conventional signal will only
03341            * ever be green if no other train is in the block, getting
03342            * a path should always be possible. If the player built
03343            * such a strange network that it is not possible, the train
03344            * will be marked as stuck and the player has to deal with
03345            * the problem. */
03346           if ((!HasReservedTracks(gp.new_tile, v->track) &&
03347               !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
03348               !TryPathReserve(v)) {
03349             MarkTrainAsStuck(v);
03350           }
03351         }
03352       }
03353 
03354       /* Signals can only change when the first
03355        * (above) or the last vehicle moves. */
03356       if (v->Next() == NULL) {
03357         TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
03358         if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
03359       }
03360     }
03361 
03362     /* Do not check on every tick to save some computing time. */
03363     if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
03364   }
03365 
03366   if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
03367 
03368   return true;
03369 
03370 invalid_rail:
03371   /* We've reached end of line?? */
03372   if (prev != NULL) error("Disconnecting train");
03373 
03374 reverse_train_direction:
03375   if (reverse) {
03376     v->wait_counter = 0;
03377     v->cur_speed = 0;
03378     v->subspeed = 0;
03379     ReverseTrainDirection(v);
03380   }
03381 
03382   return false;
03383 }
03384 
03391 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
03392 {
03393   TrackBits *trackbits = (TrackBits *)data;
03394 
03395   if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
03396     TrackBits train_tbits = Train::From(v)->track;
03397     if (train_tbits == TRACK_BIT_WORMHOLE) {
03398       /* Vehicle is inside a wormhole, v->track contains no useful value then. */
03399       *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
03400     } else if (train_tbits != TRACK_BIT_DEPOT) {
03401       *trackbits |= train_tbits;
03402     }
03403   }
03404 
03405   return NULL;
03406 }
03407 
03415 static void DeleteLastWagon(Train *v)
03416 {
03417   Train *first = v->First();
03418 
03419   /* Go to the last wagon and delete the link pointing there
03420    * *u is then the one-before-last wagon, and *v the last
03421    * one which will physically be removed */
03422   Train *u = v;
03423   for (; v->Next() != NULL; v = v->Next()) u = v;
03424   u->SetNext(NULL);
03425 
03426   if (first != v) {
03427     /* Recalculate cached train properties */
03428     first->ConsistChanged(false);
03429     /* Update the depot window if the first vehicle is in depot -
03430      * if v == first, then it is updated in PreDestructor() */
03431     if (first->track == TRACK_BIT_DEPOT) {
03432       SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
03433     }
03434   }
03435 
03436   /* 'v' shouldn't be accessed after it has been deleted */
03437   TrackBits trackbits = v->track;
03438   TileIndex tile = v->tile;
03439   Owner owner = v->owner;
03440 
03441   delete v;
03442   v = NULL; // make sure nobody will try to read 'v' anymore
03443 
03444   if (trackbits == TRACK_BIT_WORMHOLE) {
03445     /* Vehicle is inside a wormhole, v->track contains no useful value then. */
03446     trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
03447   }
03448 
03449   Track track = TrackBitsToTrack(trackbits);
03450   if (HasReservedTracks(tile, trackbits)) {
03451     UnreserveRailTrack(tile, track);
03452 
03453     /* If there are still crashed vehicles on the tile, give the track reservation to them */
03454     TrackBits remaining_trackbits = TRACK_BIT_NONE;
03455     FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
03456 
03457     /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
03458     assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
03459     Track t;
03460     FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
03461   }
03462 
03463   /* check if the wagon was on a road/rail-crossing */
03464   if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
03465 
03466   /* Update signals */
03467   if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
03468     UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
03469   } else {
03470     SetSignalsOnBothDir(tile, track, owner);
03471   }
03472 }
03473 
03478 static void ChangeTrainDirRandomly(Train *v)
03479 {
03480   static const DirDiff delta[] = {
03481     DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
03482   };
03483 
03484   do {
03485     /* We don't need to twist around vehicles if they're not visible */
03486     if (!(v->vehstatus & VS_HIDDEN)) {
03487       v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
03488       v->UpdateDeltaXY(v->direction);
03489       v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
03490       /* Refrain from updating the z position of the vehicle when on
03491        * a bridge, because UpdateInclination() will put the vehicle under
03492        * the bridge in that case */
03493       if (v->track != TRACK_BIT_WORMHOLE) {
03494         VehicleUpdatePosition(v);
03495         v->UpdateInclination(false, false);
03496       }
03497     }
03498   } while ((v = v->Next()) != NULL);
03499 }
03500 
03506 static bool HandleCrashedTrain(Train *v)
03507 {
03508   int state = ++v->crash_anim_pos;
03509 
03510   if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
03511     CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
03512   }
03513 
03514   uint32 r;
03515   if (state <= 200 && Chance16R(1, 7, r)) {
03516     int index = (r * 10 >> 16);
03517 
03518     Vehicle *u = v;
03519     do {
03520       if (--index < 0) {
03521         r = Random();
03522 
03523         CreateEffectVehicleRel(u,
03524           GB(r,  8, 3) + 2,
03525           GB(r, 16, 3) + 2,
03526           GB(r,  0, 3) + 5,
03527           EV_EXPLOSION_SMALL);
03528         break;
03529       }
03530     } while ((u = u->Next()) != NULL);
03531   }
03532 
03533   if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
03534 
03535   if (state >= 4440 && !(v->tick_counter & 0x1F)) {
03536     bool ret = v->Next() != NULL;
03537     DeleteLastWagon(v);
03538     return ret;
03539   }
03540 
03541   return true;
03542 }
03543 
03545 static const uint16 _breakdown_speeds[16] = {
03546   225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
03547 };
03548 
03549 
03558 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
03559 {
03560   /* Calc position within the current tile */
03561   uint x = v->x_pos & 0xF;
03562   uint y = v->y_pos & 0xF;
03563 
03564   /* for diagonal directions, 'x' will be 0..15 -
03565    * for other directions, it will be 1, 3, 5, ..., 15 */
03566   switch (v->direction) {
03567     case DIR_N : x = ~x + ~y + 25; break;
03568     case DIR_NW: x = y;            // FALL THROUGH
03569     case DIR_NE: x = ~x + 16;      break;
03570     case DIR_E : x = ~x + y + 9;   break;
03571     case DIR_SE: x = y;            break;
03572     case DIR_S : x = x + y - 7;    break;
03573     case DIR_W : x = ~y + x + 9;   break;
03574     default: break;
03575   }
03576 
03577   /* Do not reverse when approaching red signal. Make sure the vehicle's front
03578    * does not cross the tile boundary when we do reverse, but as the vehicle's
03579    * location is based on their center, use half a vehicle's length as offset.
03580    * Multiply the half-length by two for straight directions to compensate that
03581    * we only get odd x offsets there. */
03582   if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
03583     /* we are too near the tile end, reverse now */
03584     v->cur_speed = 0;
03585     if (reverse) ReverseTrainDirection(v);
03586     return false;
03587   }
03588 
03589   /* slow down */
03590   v->vehstatus |= VS_TRAIN_SLOWING;
03591   uint16 break_speed = _breakdown_speeds[x & 0xF];
03592   if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03593 
03594   return true;
03595 }
03596 
03597 
03603 static bool TrainCanLeaveTile(const Train *v)
03604 {
03605   /* Exit if inside a tunnel/bridge or a depot */
03606   if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
03607 
03608   TileIndex tile = v->tile;
03609 
03610   /* entering a tunnel/bridge? */
03611   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
03612     DiagDirection dir = GetTunnelBridgeDirection(tile);
03613     if (DiagDirToDir(dir) == v->direction) return false;
03614   }
03615 
03616   /* entering a depot? */
03617   if (IsRailDepotTile(tile)) {
03618     DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
03619     if (DiagDirToDir(dir) == v->direction) return false;
03620   }
03621 
03622   return true;
03623 }
03624 
03625 
03633 static TileIndex TrainApproachingCrossingTile(const Train *v)
03634 {
03635   assert(v->IsFrontEngine());
03636   assert(!(v->vehstatus & VS_CRASHED));
03637 
03638   if (!TrainCanLeaveTile(v)) return INVALID_TILE;
03639 
03640   DiagDirection dir = TrainExitDir(v->direction, v->track);
03641   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03642 
03643   /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
03644   if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
03645       !CheckCompatibleRail(v, tile)) {
03646     return INVALID_TILE;
03647   }
03648 
03649   return tile;
03650 }
03651 
03652 
03660 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
03661 {
03662   /* First, handle broken down train */
03663 
03664   int t = v->breakdown_ctr;
03665   if (t > 1) {
03666     v->vehstatus |= VS_TRAIN_SLOWING;
03667 
03668     uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
03669     if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03670   } else {
03671     v->vehstatus &= ~VS_TRAIN_SLOWING;
03672   }
03673 
03674   if (!TrainCanLeaveTile(v)) return true;
03675 
03676   /* Determine the non-diagonal direction in which we will exit this tile */
03677   DiagDirection dir = TrainExitDir(v->direction, v->track);
03678   /* Calculate next tile */
03679   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03680 
03681   /* Determine the track status on the next tile */
03682   TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
03683   TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
03684 
03685   TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03686   TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
03687 
03688   /* We are sure the train is not entering a depot, it is detected above */
03689 
03690   /* mask unreachable track bits if we are forbidden to do 90deg turns */
03691   TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03692   if (_settings_game.pf.forbid_90_deg) {
03693     bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03694   }
03695 
03696   /* no suitable trackbits at all || unusable rail (wrong type or owner) */
03697   if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
03698     return TrainApproachingLineEnd(v, false, reverse);
03699   }
03700 
03701   /* approaching red signal */
03702   if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
03703 
03704   /* approaching a rail/road crossing? then make it red */
03705   if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
03706 
03707   return true;
03708 }
03709 
03710 
03711 static bool TrainLocoHandler(Train *v, bool mode)
03712 {
03713   /* train has crashed? */
03714   if (v->vehstatus & VS_CRASHED) {
03715     return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
03716   }
03717 
03718   if (v->force_proceed != TFP_NONE) {
03719     ClrBit(v->flags, VRF_TRAIN_STUCK);
03720     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03721   }
03722 
03723   /* train is broken down? */
03724   if (v->HandleBreakdown()) return true;
03725 
03726   if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
03727     ReverseTrainDirection(v);
03728   }
03729 
03730   /* exit if train is stopped */
03731   if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
03732 
03733   bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
03734   if (ProcessOrders(v) && CheckReverseTrain(v)) {
03735     v->wait_counter = 0;
03736     v->cur_speed = 0;
03737     v->subspeed = 0;
03738     ClrBit(v->flags, VRF_LEAVING_STATION);
03739     ReverseTrainDirection(v);
03740     return true;
03741   } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
03742     /* Try to reserve a path when leaving the station as we
03743      * might not be marked as wanting a reservation, e.g.
03744      * when an overlength train gets turned around in a station. */
03745     DiagDirection dir = TrainExitDir(v->direction, v->track);
03746     if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
03747 
03748     if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
03749       TryPathReserve(v, true, true);
03750     }
03751     ClrBit(v->flags, VRF_LEAVING_STATION);
03752   }
03753 
03754   v->HandleLoading(mode);
03755 
03756   if (v->current_order.IsType(OT_LOADING)) return true;
03757 
03758   if (CheckTrainStayInDepot(v)) return true;
03759 
03760   if (!mode) v->ShowVisualEffect();
03761 
03762   /* We had no order but have an order now, do look ahead. */
03763   if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
03764     CheckNextTrainTile(v);
03765   }
03766 
03767   /* Handle stuck trains. */
03768   if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
03769     ++v->wait_counter;
03770 
03771     /* Should we try reversing this tick if still stuck? */
03772     bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
03773 
03774     if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
03775     if (!TryPathReserve(v)) {
03776       /* Still stuck. */
03777       if (turn_around) ReverseTrainDirection(v);
03778 
03779       if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
03780         /* Show message to player. */
03781         if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
03782           SetDParam(0, v->index);
03783           AddVehicleNewsItem(
03784             STR_NEWS_TRAIN_IS_STUCK,
03785             NS_ADVICE,
03786             v->index
03787           );
03788         }
03789         v->wait_counter = 0;
03790       }
03791       /* Exit if force proceed not pressed, else reset stuck flag anyway. */
03792       if (v->force_proceed == TFP_NONE) return true;
03793       ClrBit(v->flags, VRF_TRAIN_STUCK);
03794       v->wait_counter = 0;
03795       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03796     }
03797   }
03798 
03799   if (v->current_order.IsType(OT_LEAVESTATION)) {
03800     v->current_order.Free();
03801     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03802     return true;
03803   }
03804 
03805   int j = v->UpdateSpeed();
03806 
03807   /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
03808   if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
03809     /* If we manually stopped, we're not force-proceeding anymore. */
03810     v->force_proceed = TFP_NONE;
03811     SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03812   }
03813 
03814   int adv_spd = v->GetAdvanceDistance();
03815   if (j < adv_spd) {
03816     /* if the vehicle has speed 0, update the last_speed field. */
03817     if (v->cur_speed == 0) v->SetLastSpeed();
03818   } else {
03819     TrainCheckIfLineEnds(v);
03820     /* Loop until the train has finished moving. */
03821     for (;;) {
03822       j -= adv_spd;
03823       TrainController(v, NULL);
03824       /* Don't continue to move if the train crashed. */
03825       if (CheckTrainCollision(v)) break;
03826       /* Determine distance to next map position */
03827       adv_spd = v->GetAdvanceDistance();
03828 
03829       /* No more moving this tick */
03830       if (j < adv_spd || v->cur_speed == 0) break;
03831 
03832       OrderType order_type = v->current_order.GetType();
03833       /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
03834       if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
03835             (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
03836             IsTileType(v->tile, MP_STATION) &&
03837             v->current_order.GetDestination() == GetStationIndex(v->tile)) {
03838         ProcessOrders(v);
03839       }
03840     }
03841     v->SetLastSpeed();
03842   }
03843 
03844   for (Train *u = v; u != NULL; u = u->Next()) {
03845     if ((u->vehstatus & VS_HIDDEN) != 0) continue;
03846 
03847     u->UpdateViewport(false, false);
03848   }
03849 
03850   if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
03851 
03852   return true;
03853 }
03854 
03859 Money Train::GetRunningCost() const
03860 {
03861   Money cost = 0;
03862   const Train *v = this;
03863 
03864   do {
03865     const Engine *e = v->GetEngine();
03866     if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
03867 
03868     uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
03869     if (cost_factor == 0) continue;
03870 
03871     /* Halve running cost for multiheaded parts */
03872     if (v->IsMultiheaded()) cost_factor /= 2;
03873 
03874     cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
03875   } while ((v = v->GetNextVehicle()) != NULL);
03876 
03877   return cost;
03878 }
03879 
03884 bool Train::Tick()
03885 {
03886   this->tick_counter++;
03887 
03888   if (this->IsFrontEngine()) {
03889     if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
03890 
03891     this->current_order_time++;
03892 
03893     if (!TrainLocoHandler(this, false)) return false;
03894 
03895     return TrainLocoHandler(this, true);
03896   } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
03897     /* Delete flooded standalone wagon chain */
03898     if (++this->crash_anim_pos >= 4400) {
03899       delete this;
03900       return false;
03901     }
03902   }
03903 
03904   return true;
03905 }
03906 
03911 static void CheckIfTrainNeedsService(Train *v)
03912 {
03913   if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
03914   if (v->IsInDepot()) {
03915     VehicleServiceInDepot(v);
03916     return;
03917   }
03918 
03919   uint max_penalty;
03920   switch (_settings_game.pf.pathfinder_for_trains) {
03921     case VPF_NPF:  max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty;  break;
03922     case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
03923     default: NOT_REACHED();
03924   }
03925 
03926   FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
03927   /* Only go to the depot if it is not too far out of our way. */
03928   if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
03929     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
03930       /* If we were already heading for a depot but it has
03931        * suddenly moved farther away, we continue our normal
03932        * schedule? */
03933       v->current_order.MakeDummy();
03934       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03935     }
03936     return;
03937   }
03938 
03939   DepotID depot = GetDepotIndex(tfdd.tile);
03940 
03941   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
03942       v->current_order.GetDestination() != depot &&
03943       !Chance16(3, 16)) {
03944     return;
03945   }
03946 
03947   SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
03948   v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
03949   v->dest_tile = tfdd.tile;
03950   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03951 }
03952 
03954 void Train::OnNewDay()
03955 {
03956   AgeVehicle(this);
03957 
03958   if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
03959 
03960   if (this->IsFrontEngine()) {
03961     CheckVehicleBreakdown(this);
03962 
03963     CheckIfTrainNeedsService(this);
03964 
03965     CheckOrders(this);
03966 
03967     /* update destination */
03968     if (this->current_order.IsType(OT_GOTO_STATION)) {
03969       TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
03970       if (tile != INVALID_TILE) this->dest_tile = tile;
03971     }
03972 
03973     if (this->running_ticks != 0) {
03974       /* running costs */
03975       CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR  * DAY_TICKS));
03976 
03977       this->profit_this_year -= cost.GetCost();
03978       this->running_ticks = 0;
03979 
03980       SubtractMoneyFromCompanyFract(this->owner, cost);
03981 
03982       SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
03983       SetWindowClassesDirty(WC_TRAINS_LIST);
03984     }
03985   }
03986 }
03987 
03992 Trackdir Train::GetVehicleTrackdir() const
03993 {
03994   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
03995 
03996   if (this->track == TRACK_BIT_DEPOT) {
03997     /* We'll assume the train is facing outwards */
03998     return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
03999   }
04000 
04001   if (this->track == TRACK_BIT_WORMHOLE) {
04002     /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
04003     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
04004   }
04005 
04006   return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
04007 }