train_cmd.cpp

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

Generated on Fri May 27 04:19:51 2011 for OpenTTD by  doxygen 1.6.1