train_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: train_cmd.cpp 15617 2009-03-04 23:32:23Z rubidium $ */
00002 
00005 #include "stdafx.h"
00006 #include "gui.h"
00007 #include "articulated_vehicles.h"
00008 #include "command_func.h"
00009 #include "npf.h"
00010 #include "news_func.h"
00011 #include "engine_func.h"
00012 #include "engine_base.h"
00013 #include "company_func.h"
00014 #include "depot_base.h"
00015 #include "vehicle_gui.h"
00016 #include "train.h"
00017 #include "newgrf_engine.h"
00018 #include "newgrf_sound.h"
00019 #include "newgrf_text.h"
00020 #include "yapf/follow_track.hpp"
00021 #include "group.h"
00022 #include "table/sprites.h"
00023 #include "strings_func.h"
00024 #include "functions.h"
00025 #include "window_func.h"
00026 #include "vehicle_func.h"
00027 #include "sound_func.h"
00028 #include "variables.h"
00029 #include "autoreplace_gui.h"
00030 #include "gfx_func.h"
00031 #include "ai/ai.hpp"
00032 #include "newgrf_station.h"
00033 #include "effectvehicle_func.h"
00034 #include "gamelog.h"
00035 #include "network/network.h"
00036 
00037 #include "table/strings.h"
00038 #include "table/train_cmd.h"
00039 
00040 static Track ChooseTrainTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
00041 static bool TrainCheckIfLineEnds(Vehicle *v);
00042 static void TrainController(Vehicle *v, Vehicle *nomove, bool update_image);
00043 static TileIndex TrainApproachingCrossingTile(const Vehicle *v);
00044 static void CheckIfTrainNeedsService(Vehicle *v);
00045 static void CheckNextTrainTile(Vehicle *v);
00046 
00047 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4,  8};
00048 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
00049 
00050 
00058 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
00059 {
00060   static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
00061 
00062   DiagDirection diagdir = DirToDiagDir(direction);
00063 
00064   /* Determine the diagonal direction in which we will exit this tile */
00065   if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
00066     diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
00067   }
00068 
00069   return diagdir;
00070 }
00071 
00072 
00077 byte FreightWagonMult(CargoID cargo)
00078 {
00079   if (!GetCargo(cargo)->is_freight) return 1;
00080   return _settings_game.vehicle.freight_trains;
00081 }
00082 
00083 
00088 void TrainPowerChanged(Vehicle *v)
00089 {
00090   uint32 total_power = 0;
00091   uint32 max_te = 0;
00092 
00093   for (const Vehicle *u = v; u != NULL; u = u->Next()) {
00094     RailType railtype = GetRailType(u->tile);
00095 
00096     /* Power is not added for articulated parts */
00097     if (!IsArticulatedPart(u)) {
00098       bool engine_has_power = HasPowerOnRail(u->u.rail.railtype, railtype);
00099 
00100       const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
00101 
00102       if (engine_has_power) {
00103         uint16 power = GetVehicleProperty(u, 0x0B, rvi_u->power);
00104         if (power != 0) {
00105           /* Halve power for multiheaded parts */
00106           if (IsMultiheaded(u)) power /= 2;
00107 
00108           total_power += power;
00109           /* Tractive effort in (tonnes * 1000 * 10 =) N */
00110           max_te += (u->u.rail.cached_veh_weight * 10000 * GetVehicleProperty(u, 0x1F, rvi_u->tractive_effort)) / 256;
00111         }
00112       }
00113     }
00114 
00115     if (HasBit(u->u.rail.flags, VRF_POWEREDWAGON) && HasPowerOnRail(v->u.rail.railtype, railtype)) {
00116       total_power += RailVehInfo(u->u.rail.first_engine)->pow_wag_power;
00117     }
00118   }
00119 
00120   if (v->u.rail.cached_power != total_power || v->u.rail.cached_max_te != max_te) {
00121     /* If it has no power (no catenary), stop the train */
00122     if (total_power == 0) v->vehstatus |= VS_STOPPED;
00123 
00124     v->u.rail.cached_power = total_power;
00125     v->u.rail.cached_max_te = max_te;
00126     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
00127     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00128   }
00129 }
00130 
00131 
00137 static void TrainCargoChanged(Vehicle *v)
00138 {
00139   uint32 weight = 0;
00140 
00141   for (Vehicle *u = v; u != NULL; u = u->Next()) {
00142     uint32 vweight = GetCargo(u->cargo_type)->weight * u->cargo.Count() * FreightWagonMult(u->cargo_type) / 16;
00143 
00144     /* Vehicle weight is not added for articulated parts. */
00145     if (!IsArticulatedPart(u)) {
00146       /* vehicle weight is the sum of the weight of the vehicle and the weight of its cargo */
00147       vweight += GetVehicleProperty(u, 0x16, RailVehInfo(u->engine_type)->weight);
00148     }
00149 
00150     /* powered wagons have extra weight added */
00151     if (HasBit(u->u.rail.flags, VRF_POWEREDWAGON)) {
00152       vweight += RailVehInfo(u->u.rail.first_engine)->pow_wag_weight;
00153     }
00154 
00155     /* consist weight is the sum of the weight of all vehicles in the consist */
00156     weight += vweight;
00157 
00158     /* store vehicle weight in cache */
00159     u->u.rail.cached_veh_weight = vweight;
00160   }
00161 
00162   /* store consist weight in cache */
00163   v->u.rail.cached_weight = weight;
00164 
00165   /* Now update train power (tractive effort is dependent on weight) */
00166   TrainPowerChanged(v);
00167 }
00168 
00169 
00174 static void RailVehicleLengthChanged(const Vehicle *u)
00175 {
00176   /* show a warning once for each engine in whole game and once for each GRF after each game load */
00177   const Engine *engine = GetEngine(u->engine_type);
00178   uint32 grfid = engine->grffile->grfid;
00179   GRFConfig *grfconfig = GetGRFConfig(grfid);
00180   if (GamelogGRFBugReverse(grfid, engine->internal_id) || !HasBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH)) {
00181     SetBit(grfconfig->grf_bugs, GBUG_VEH_LENGTH);
00182     SetDParamStr(0, grfconfig->name);
00183     SetDParam(1, u->engine_type);
00184     ShowErrorMessage(STR_NEWGRF_BROKEN_VEHICLE_LENGTH, STR_NEWGRF_BROKEN, 0, 0);
00185 
00186     /* debug output */
00187     char buffer[512];
00188 
00189     SetDParamStr(0, grfconfig->name);
00190     GetString(buffer, STR_NEWGRF_BROKEN, lastof(buffer));
00191     DEBUG(grf, 0, "%s", buffer + 3);
00192 
00193     SetDParam(1, u->engine_type);
00194     GetString(buffer, STR_NEWGRF_BROKEN_VEHICLE_LENGTH, lastof(buffer));
00195     DEBUG(grf, 0, "%s", buffer + 3);
00196 
00197     if (!_networking) _pause_game = -1;
00198   }
00199 }
00200 
00202 void CheckTrainsLengths()
00203 {
00204   const Vehicle *v;
00205 
00206   FOR_ALL_VEHICLES(v) {
00207     if (v->type == VEH_TRAIN && v->First() == v && !(v->vehstatus & VS_CRASHED)) {
00208       for (const Vehicle *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
00209         if (u->u.rail.track != TRACK_BIT_DEPOT) {
00210           if ((w->u.rail.track != TRACK_BIT_DEPOT &&
00211               max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->u.rail.cached_veh_length) ||
00212               (w->u.rail.track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
00213             SetDParam(0, v->index);
00214             SetDParam(1, v->owner);
00215             ShowErrorMessage(INVALID_STRING_ID, STR_BROKEN_VEHICLE_LENGTH, 0, 0);
00216 
00217             if (!_networking) _pause_game = -1;
00218           }
00219         }
00220       }
00221     }
00222   }
00223 }
00224 
00232 void TrainConsistChanged(Vehicle *v, bool same_length)
00233 {
00234   uint16 max_speed = UINT16_MAX;
00235 
00236   assert(v->type == VEH_TRAIN);
00237   assert(IsFrontEngine(v) || IsFreeWagon(v));
00238 
00239   const RailVehicleInfo *rvi_v = RailVehInfo(v->engine_type);
00240   EngineID first_engine = IsFrontEngine(v) ? v->engine_type : INVALID_ENGINE;
00241   v->u.rail.cached_total_length = 0;
00242   v->u.rail.compatible_railtypes = RAILTYPES_NONE;
00243 
00244   bool train_can_tilt = true;
00245 
00246   for (Vehicle *u = v; u != NULL; u = u->Next()) {
00247     const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
00248 
00249     /* Check the v->first cache. */
00250     assert(u->First() == v);
00251 
00252     /* update the 'first engine' */
00253     u->u.rail.first_engine = v == u ? INVALID_ENGINE : first_engine;
00254     u->u.rail.railtype = rvi_u->railtype;
00255 
00256     if (IsTrainEngine(u)) first_engine = u->engine_type;
00257 
00258     /* Set user defined data to its default value */
00259     u->u.rail.user_def_data = rvi_u->user_def_data;
00260     u->cache_valid = 0;
00261   }
00262 
00263   for (Vehicle *u = v; u != NULL; u = u->Next()) {
00264     /* Update user defined data (must be done before other properties) */
00265     u->u.rail.user_def_data = GetVehicleProperty(u, 0x25, u->u.rail.user_def_data);
00266     u->cache_valid = 0;
00267   }
00268 
00269   for (Vehicle *u = v; u != NULL; u = u->Next()) {
00270     const Engine *e_u = GetEngine(u->engine_type);
00271     const RailVehicleInfo *rvi_u = &e_u->u.rail;
00272 
00273     if (!HasBit(EngInfo(u->engine_type)->misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
00274 
00275     /* Cache wagon override sprite group. NULL is returned if there is none */
00276     u->u.rail.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->u.rail.first_engine);
00277 
00278     /* Reset colour map */
00279     u->colourmap = PAL_NONE;
00280 
00281     if (rvi_u->visual_effect != 0) {
00282       u->u.rail.cached_vis_effect = rvi_u->visual_effect;
00283     } else {
00284       if (IsTrainWagon(u) || IsArticulatedPart(u)) {
00285         /* Wagons and articulated parts have no effect by default */
00286         u->u.rail.cached_vis_effect = 0x40;
00287       } else if (rvi_u->engclass == 0) {
00288         /* Steam is offset by -4 units */
00289         u->u.rail.cached_vis_effect = 4;
00290       } else {
00291         /* Diesel fumes and sparks come from the centre */
00292         u->u.rail.cached_vis_effect = 8;
00293       }
00294     }
00295 
00296     /* Check powered wagon / visual effect callback */
00297     if (HasBit(EngInfo(u->engine_type)->callbackmask, CBM_TRAIN_WAGON_POWER)) {
00298       uint16 callback = GetVehicleCallback(CBID_TRAIN_WAGON_POWER, 0, 0, u->engine_type, u);
00299 
00300       if (callback != CALLBACK_FAILED) u->u.rail.cached_vis_effect = GB(callback, 0, 8);
00301     }
00302 
00303     if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
00304       UsesWagonOverride(u) && !HasBit(u->u.rail.cached_vis_effect, 7)) {
00305       /* wagon is powered */
00306       SetBit(u->u.rail.flags, VRF_POWEREDWAGON); // cache 'powered' status
00307     } else {
00308       ClrBit(u->u.rail.flags, VRF_POWEREDWAGON);
00309     }
00310 
00311     if (!IsArticulatedPart(u)) {
00312       /* Do not count powered wagons for the compatible railtypes, as wagons always
00313          have railtype normal */
00314       if (rvi_u->power > 0) {
00315         v->u.rail.compatible_railtypes |= GetRailTypeInfo(u->u.rail.railtype)->powered_railtypes;
00316       }
00317 
00318       /* Some electric engines can be allowed to run on normal rail. It happens to all
00319        * existing electric engines when elrails are disabled and then re-enabled */
00320       if (HasBit(u->u.rail.flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
00321         u->u.rail.railtype = RAILTYPE_RAIL;
00322         u->u.rail.compatible_railtypes |= RAILTYPES_RAIL;
00323       }
00324 
00325       /* max speed is the minimum of the speed limits of all vehicles in the consist */
00326       if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
00327         uint16 speed = GetVehicleProperty(u, 0x09, rvi_u->max_speed);
00328         if (speed != 0) max_speed = min(speed, max_speed);
00329       }
00330     }
00331 
00332     if (e_u->CanCarryCargo() && u->cargo_type == e_u->GetDefaultCargoType() && u->cargo_subtype == 0) {
00333       /* Set cargo capacity if we've not been refitted */
00334       u->cargo_cap = GetVehicleProperty(u, 0x14, rvi_u->capacity);
00335     }
00336 
00337     /* check the vehicle length (callback) */
00338     uint16 veh_len = CALLBACK_FAILED;
00339     if (HasBit(EngInfo(u->engine_type)->callbackmask, CBM_VEHICLE_LENGTH)) {
00340       veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
00341     }
00342     if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
00343     veh_len = 8 - Clamp(veh_len, 0, u->Next() == NULL ? 7 : 5); // the clamp on vehicles not the last in chain is stricter, as too short wagons can break the 'follow next vehicle' code
00344 
00345     /* verify length hasn't changed */
00346     if (same_length && veh_len != u->u.rail.cached_veh_length) RailVehicleLengthChanged(u);
00347 
00348     /* update vehicle length? */
00349     if (!same_length) u->u.rail.cached_veh_length = veh_len;
00350 
00351     v->u.rail.cached_total_length += u->u.rail.cached_veh_length;
00352     u->cache_valid = 0;
00353   }
00354 
00355   /* store consist weight/max speed in cache */
00356   v->u.rail.cached_max_speed = max_speed;
00357   v->u.rail.cached_tilt = train_can_tilt;
00358 
00359   /* 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) */
00360   TrainCargoChanged(v);
00361 
00362   if (IsFrontEngine(v)) {
00363     UpdateTrainAcceleration(v);
00364     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
00365   }
00366 }
00367 
00368 enum AccelType {
00369   AM_ACCEL,
00370   AM_BRAKE
00371 };
00372 
00374 static int GetTrainAcceleration(Vehicle *v, bool mode)
00375 {
00376   static const int absolute_max_speed = UINT16_MAX;
00377   int max_speed = absolute_max_speed;
00378   int speed = v->cur_speed * 10 / 16; // km-ish/h -> mp/h
00379   int curvecount[2] = {0, 0};
00380 
00381   /*first find the curve speed limit */
00382   int numcurve = 0;
00383   int sum = 0;
00384   int pos = 0;
00385   int lastpos = -1;
00386   for (const Vehicle *u = v; u->Next() != NULL; u = u->Next(), pos++) {
00387     Direction this_dir = u->direction;
00388     Direction next_dir = u->Next()->direction;
00389 
00390     DirDiff dirdiff = DirDifference(this_dir, next_dir);
00391     if (dirdiff == DIRDIFF_SAME) continue;
00392 
00393     if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
00394     if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
00395     if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
00396       if (lastpos != -1) {
00397         numcurve++;
00398         sum += pos - lastpos;
00399         if (pos - lastpos == 1) {
00400           max_speed = 88;
00401         }
00402       }
00403       lastpos = pos;
00404     }
00405 
00406     /*if we have a 90 degree turn, fix the speed limit to 60 */
00407     if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
00408       max_speed = 61;
00409     }
00410   }
00411 
00412   if ((curvecount[0] != 0 || curvecount[1] != 0) && max_speed > 88) {
00413     int total = curvecount[0] + curvecount[1];
00414 
00415     if (curvecount[0] == 1 && curvecount[1] == 1) {
00416       max_speed = absolute_max_speed;
00417     } else if (total > 1) {
00418       if (numcurve > 0) sum /= numcurve;
00419       max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
00420     }
00421   }
00422 
00423   if (max_speed != absolute_max_speed) {
00424     /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
00425     const RailtypeInfo *rti = GetRailTypeInfo(v->u.rail.railtype);
00426     max_speed += (max_speed / 2) * rti->curve_speed;
00427 
00428     if (v->u.rail.cached_tilt) {
00429       /* Apply max_speed bonus of 20% for a tilting train */
00430       max_speed += max_speed / 5;
00431     }
00432   }
00433 
00434   if (IsTileType(v->tile, MP_STATION) && IsFrontEngine(v)) {
00435     if (v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) {
00436       int station_length = GetStationByTile(v->tile)->GetPlatformLength(v->tile, DirToDiagDir(v->direction));
00437 
00438       int st_max_speed = 120;
00439 
00440       int delta_v = v->cur_speed / (station_length + 1);
00441       if (v->max_speed > (v->cur_speed - delta_v)) {
00442         st_max_speed = v->cur_speed - (delta_v / 10);
00443       }
00444 
00445       st_max_speed = max(st_max_speed, 25 * station_length);
00446       max_speed = min(max_speed, st_max_speed);
00447     }
00448   }
00449 
00450   int mass = v->u.rail.cached_weight;
00451   int power = v->u.rail.cached_power * 746;
00452   max_speed = min(max_speed, v->u.rail.cached_max_speed);
00453 
00454   int num = 0; //number of vehicles, change this into the number of axles later
00455   int incl = 0;
00456   int drag_coeff = 20; //[1e-4]
00457   for (const Vehicle *u = v; u != NULL; u = u->Next()) {
00458     num++;
00459     drag_coeff += 3;
00460 
00461     if (u->u.rail.track == TRACK_BIT_DEPOT) max_speed = min(max_speed, 61);
00462 
00463     if (HasBit(u->u.rail.flags, VRF_GOINGUP)) {
00464       incl += u->u.rail.cached_veh_weight * 60; //3% slope, quite a bit actually
00465     } else if (HasBit(u->u.rail.flags, VRF_GOINGDOWN)) {
00466       incl -= u->u.rail.cached_veh_weight * 60;
00467     }
00468   }
00469 
00470   v->max_speed = max_speed;
00471 
00472   const int area = 120;
00473   const int friction = 35; //[1e-3]
00474   int resistance;
00475   if (v->u.rail.railtype != RAILTYPE_MAGLEV) {
00476     resistance = 13 * mass / 10;
00477     resistance += 60 * num;
00478     resistance += friction * mass * speed / 1000;
00479     resistance += (area * drag_coeff * speed * speed) / 10000;
00480   } else {
00481     resistance = (area * (drag_coeff / 2) * speed * speed) / 10000;
00482   }
00483   resistance += incl;
00484   resistance *= 4; //[N]
00485 
00486   const int max_te = v->u.rail.cached_max_te; // [N]
00487   int force;
00488   if (speed > 0) {
00489     switch (v->u.rail.railtype) {
00490       case RAILTYPE_RAIL:
00491       case RAILTYPE_ELECTRIC:
00492       case RAILTYPE_MONO:
00493         force = power / speed; //[N]
00494         force *= 22;
00495         force /= 10;
00496         if (mode == AM_ACCEL && force > max_te) force = max_te;
00497         break;
00498 
00499       default: NOT_REACHED();
00500       case RAILTYPE_MAGLEV:
00501         force = power / 25;
00502         break;
00503     }
00504   } else {
00505     /* "kickoff" acceleration */
00506     force = (mode == AM_ACCEL && v->u.rail.railtype != RAILTYPE_MAGLEV) ? min(max_te, power) : power;
00507     force = max(force, (mass * 8) + resistance);
00508   }
00509 
00510   if (mode == AM_ACCEL) {
00511     return (force - resistance) / (mass * 2);
00512   } else {
00513     return min(-force - resistance, -10000) / mass;
00514   }
00515 }
00516 
00517 void UpdateTrainAcceleration(Vehicle *v)
00518 {
00519   assert(IsFrontEngine(v));
00520 
00521   v->max_speed = v->u.rail.cached_max_speed;
00522 
00523   uint power = v->u.rail.cached_power;
00524   uint weight = v->u.rail.cached_weight;
00525   assert(weight != 0);
00526   v->acceleration = Clamp(power / weight * 4, 1, 255);
00527 }
00528 
00529 SpriteID Train::GetImage(Direction direction) const
00530 {
00531   uint8 spritenum = this->spritenum;
00532   SpriteID sprite;
00533 
00534   if (HasBit(this->u.rail.flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
00535 
00536   if (is_custom_sprite(spritenum)) {
00537     sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)));
00538     if (sprite != 0) return sprite;
00539 
00540     spritenum = GetEngine(this->engine_type)->image_index;
00541   }
00542 
00543   sprite = _engine_sprite_base[spritenum] + ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]);
00544 
00545   if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
00546 
00547   return sprite;
00548 }
00549 
00550 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y)
00551 {
00552   Direction dir = rear_head ? DIR_E : DIR_W;
00553   uint8 spritenum = RailVehInfo(engine)->image_index;
00554 
00555   if (is_custom_sprite(spritenum)) {
00556     SpriteID sprite = GetCustomVehicleIcon(engine, dir);
00557     if (sprite != 0) {
00558       y += _traininfo_vehicle_pitch; // TODO Make this per-GRF
00559       return sprite;
00560     }
00561 
00562     spritenum = GetEngine(engine)->image_index;
00563   }
00564 
00565   if (rear_head) spritenum++;
00566 
00567   return ((6 + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
00568 }
00569 
00570 void DrawTrainEngine(int x, int y, EngineID engine, SpriteID pal)
00571 {
00572   if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00573     int yf = y;
00574     int yr = y;
00575 
00576     SpriteID spritef = GetRailIcon(engine, false, yf);
00577     SpriteID spriter = GetRailIcon(engine, true, yr);
00578     DrawSprite(spritef, pal, x - 14, yf);
00579     DrawSprite(spriter, pal, x + 15, yr);
00580   } else {
00581     SpriteID sprite = GetRailIcon(engine, false, y);
00582     DrawSprite(sprite, pal, x, y);
00583   }
00584 }
00585 
00586 static CommandCost CmdBuildRailWagon(EngineID engine, TileIndex tile, DoCommandFlag flags)
00587 {
00588   const Engine *e = GetEngine(engine);
00589   const RailVehicleInfo *rvi = &e->u.rail;
00590   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
00591 
00592   /* Engines without valid cargo should not be available */
00593   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
00594 
00595   if (flags & DC_QUERY_COST) return value;
00596 
00597   /* Check that the wagon can drive on the track in question */
00598   if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00599 
00600   uint num_vehicles = 1 + CountArticulatedParts(engine, false);
00601 
00602   /* Allow for the wagon and the articulated parts, plus one to "terminate" the list. */
00603   Vehicle **vl = AllocaM(Vehicle*, num_vehicles + 1);
00604   memset(vl, 0, sizeof(*vl) * (num_vehicles + 1));
00605 
00606   if (!Vehicle::AllocateList(vl, num_vehicles)) {
00607     return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
00608   }
00609 
00610   if (flags & DC_EXEC) {
00611     Vehicle *v = vl[0];
00612     v->spritenum = rvi->image_index;
00613 
00614     Vehicle *u = NULL;
00615 
00616     Vehicle *w;
00617     FOR_ALL_VEHICLES(w) {
00618       if (w->type == VEH_TRAIN && w->tile == tile &&
00619           IsFreeWagon(w) && w->engine_type == engine &&
00620           !HASBITS(w->vehstatus, VS_CRASHED)) {          
00621         u = GetLastVehicleInChain(w);
00622         break;
00623       }
00624     }
00625 
00626     v = new (v) Train();
00627     v->engine_type = engine;
00628 
00629     DiagDirection dir = GetRailDepotDirection(tile);
00630 
00631     v->direction = DiagDirToDir(dir);
00632     v->tile = tile;
00633 
00634     int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
00635     int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
00636 
00637     v->x_pos = x;
00638     v->y_pos = y;
00639     v->z_pos = GetSlopeZ(x, y);
00640     v->owner = _current_company;
00641     v->u.rail.track = TRACK_BIT_DEPOT;
00642     v->vehstatus = VS_HIDDEN | VS_DEFPAL;
00643 
00644 //    v->subtype = 0;
00645     SetTrainWagon(v);
00646 
00647     if (u != NULL) {
00648       u->SetNext(v);
00649     } else {
00650       SetFreeWagon(v);
00651       InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00652     }
00653 
00654     v->cargo_type = e->GetDefaultCargoType();
00655 //    v->cargo_subtype = 0;
00656     v->cargo_cap = rvi->capacity;
00657     v->value = value.GetCost();
00658 //    v->day_counter = 0;
00659 
00660     v->u.rail.railtype = rvi->railtype;
00661 
00662     v->build_year = _cur_year;
00663     v->cur_image = 0xAC2;
00664     v->random_bits = VehicleRandomBits();
00665 
00666     v->group_id = DEFAULT_GROUP;
00667 
00668     AddArticulatedParts(vl, VEH_TRAIN);
00669 
00670     _new_vehicle_id = v->index;
00671 
00672     VehiclePositionChanged(v);
00673     TrainConsistChanged(v->First(), false);
00674     UpdateTrainGroupID(v->First());
00675 
00676     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
00677     if (IsLocalCompany()) {
00678       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
00679     }
00680     GetCompany(_current_company)->num_engines[engine]++;
00681   }
00682 
00683   return value;
00684 }
00685 
00687 static void NormalizeTrainVehInDepot(const Vehicle *u)
00688 {
00689   const Vehicle *v;
00690 
00691   FOR_ALL_VEHICLES(v) {
00692     if (v->type == VEH_TRAIN && IsFreeWagon(v) &&
00693         v->tile == u->tile &&
00694         v->u.rail.track == TRACK_BIT_DEPOT) {
00695       if (CmdFailed(DoCommand(0, v->index | (u->index << 16), 1, DC_EXEC,
00696           CMD_MOVE_RAIL_VEHICLE)))
00697         break;
00698     }
00699   }
00700 }
00701 
00702 static void AddRearEngineToMultiheadedTrain(Vehicle *v, Vehicle *u, bool building)
00703 {
00704   u = new (u) Train();
00705   u->direction = v->direction;
00706   u->owner = v->owner;
00707   u->tile = v->tile;
00708   u->x_pos = v->x_pos;
00709   u->y_pos = v->y_pos;
00710   u->z_pos = v->z_pos;
00711   u->u.rail.track = TRACK_BIT_DEPOT;
00712   u->vehstatus = v->vehstatus & ~VS_STOPPED;
00713 //  u->subtype = 0;
00714   SetMultiheaded(u);
00715   u->spritenum = v->spritenum + 1;
00716   u->cargo_type = v->cargo_type;
00717   u->cargo_subtype = v->cargo_subtype;
00718   u->cargo_cap = v->cargo_cap;
00719   u->u.rail.railtype = v->u.rail.railtype;
00720   if (building) v->SetNext(u);
00721   u->engine_type = v->engine_type;
00722   u->build_year = v->build_year;
00723   if (building) v->value >>= 1;
00724   u->value = v->value;
00725   u->cur_image = 0xAC2;
00726   u->random_bits = VehicleRandomBits();
00727   VehiclePositionChanged(u);
00728 }
00729 
00736 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00737 {
00738   /* Check if the engine-type is valid (for the company) */
00739   if (!IsEngineBuildable(p1, VEH_TRAIN, _current_company)) return_cmd_error(STR_RAIL_VEHICLE_NOT_AVAILABLE);
00740 
00741   const Engine *e = GetEngine(p1);
00742   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
00743 
00744   /* Engines with CT_INVALID should not be available */
00745   if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR;
00746 
00747   if (flags & DC_QUERY_COST) return value;
00748 
00749   /* Check if the train is actually being built in a depot belonging
00750    * to the company. Doesn't matter if only the cost is queried */
00751   if (!IsRailDepotTile(tile)) return CMD_ERROR;
00752   if (!IsTileOwner(tile, _current_company)) return CMD_ERROR;
00753 
00754   const RailVehicleInfo *rvi = RailVehInfo(p1);
00755   if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(p1, tile, flags);
00756 
00757   uint num_vehicles =
00758     (rvi->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) +
00759     CountArticulatedParts(p1, false);
00760 
00761   /* Check if depot and new engine uses the same kind of tracks *
00762    * We need to see if the engine got power on the tile to avoid eletric engines in non-electric depots */
00763   if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00764 
00765   /* Allow for the dual-heads and the articulated parts, plus one to "terminate" the list. */
00766   Vehicle **vl = AllocaM(Vehicle*, num_vehicles + 1);
00767   memset(vl, 0, sizeof(*vl) * (num_vehicles + 1));
00768 
00769   if (!Vehicle::AllocateList(vl, num_vehicles)) {
00770     return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
00771   }
00772 
00773   Vehicle *v = vl[0];
00774 
00775   UnitID unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_TRAIN);
00776   if (unit_num > _settings_game.vehicle.max_trains) {
00777     return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
00778   }
00779 
00780   if (flags & DC_EXEC) {
00781     DiagDirection dir = GetRailDepotDirection(tile);
00782     int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
00783     int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
00784 
00785     v = new (v) Train();
00786     v->unitnumber = unit_num;
00787     v->direction = DiagDirToDir(dir);
00788     v->tile = tile;
00789     v->owner = _current_company;
00790     v->x_pos = x;
00791     v->y_pos = y;
00792     v->z_pos = GetSlopeZ(x, y);
00793 //    v->running_ticks = 0;
00794     v->u.rail.track = TRACK_BIT_DEPOT;
00795     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00796     v->spritenum = rvi->image_index;
00797     v->cargo_type = e->GetDefaultCargoType();
00798 //    v->cargo_subtype = 0;
00799     v->cargo_cap = rvi->capacity;
00800     v->max_speed = rvi->max_speed;
00801     v->value = value.GetCost();
00802     v->last_station_visited = INVALID_STATION;
00803 //    v->dest_tile = 0;
00804 
00805     v->engine_type = p1;
00806 
00807     v->reliability = e->reliability;
00808     v->reliability_spd_dec = e->reliability_spd_dec;
00809     v->max_age = e->lifelength * DAYS_IN_LEAP_YEAR;
00810 
00811     v->name = NULL;
00812     v->u.rail.railtype = rvi->railtype;
00813     _new_vehicle_id = v->index;
00814 
00815     v->service_interval = _settings_game.vehicle.servint_trains;
00816     v->date_of_last_service = _date;
00817     v->build_year = _cur_year;
00818     v->cur_image = 0xAC2;
00819     v->random_bits = VehicleRandomBits();
00820 
00821 //    v->vehicle_flags = 0;
00822     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00823 
00824     v->group_id = DEFAULT_GROUP;
00825 
00826 //    v->subtype = 0;
00827     SetFrontEngine(v);
00828     SetTrainEngine(v);
00829 
00830     VehiclePositionChanged(v);
00831 
00832     if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
00833       SetMultiheaded(v);
00834       AddRearEngineToMultiheadedTrain(vl[0], vl[1], true);
00835       /* Now we need to link the front and rear engines together
00836        * other_multiheaded_part is the pointer that links to the other half of the engine
00837        * vl[0] is the front and vl[1] is the rear
00838        */
00839       vl[0]->u.rail.other_multiheaded_part = vl[1];
00840       vl[1]->u.rail.other_multiheaded_part = vl[0];
00841     } else {
00842       AddArticulatedParts(vl, VEH_TRAIN);
00843     }
00844 
00845     TrainConsistChanged(v, false);
00846     UpdateTrainGroupID(v);
00847 
00848     if (!HasBit(p2, 1) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
00849       NormalizeTrainVehInDepot(v);
00850     }
00851 
00852     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00853     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
00854     InvalidateWindow(WC_COMPANY, v->owner);
00855     if (IsLocalCompany()) {
00856       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Train window
00857     }
00858 
00859     GetCompany(_current_company)->num_engines[p1]++;
00860   }
00861 
00862   return value;
00863 }
00864 
00865 
00866 /* Check if all the wagons of the given train are in a depot, returns the
00867  * number of cars (including loco) then. If not it returns -1 */
00868 int CheckTrainInDepot(const Vehicle *v, bool needs_to_be_stopped)
00869 {
00870   TileIndex tile = v->tile;
00871 
00872   /* check if stopped in a depot */
00873   if (!IsRailDepotTile(tile) || v->cur_speed != 0) return -1;
00874 
00875   int count = 0;
00876   for (; v != NULL; v = v->Next()) {
00877     /* This count is used by the depot code to determine the number of engines
00878      * in the consist. Exclude articulated parts so that autoreplacing to
00879      * engines with more articulated parts than before works correctly.
00880      *
00881      * Also skip counting rear ends of multiheaded engines */
00882     if (!IsArticulatedPart(v) && !IsRearDualheaded(v)) count++;
00883     if (v->u.rail.track != TRACK_BIT_DEPOT || v->tile != tile ||
00884         (IsFrontEngine(v) && needs_to_be_stopped && !(v->vehstatus & VS_STOPPED))) {
00885       return -1;
00886     }
00887   }
00888 
00889   return count;
00890 }
00891 
00892 /* Used to check if the train is inside the depot and verifying that the VS_STOPPED flag is set */
00893 int CheckTrainStoppedInDepot(const Vehicle *v)
00894 {
00895   return CheckTrainInDepot(v, true);
00896 }
00897 
00898 /* Used to check if the train is inside the depot, but not checking the VS_STOPPED flag */
00899 inline bool CheckTrainIsInsideDepot(const Vehicle *v)
00900 {
00901   return CheckTrainInDepot(v, false) > 0;
00902 }
00903 
00910 static Vehicle *UnlinkWagon(Vehicle *v, Vehicle *first)
00911 {
00912   /* unlinking the first vehicle of the chain? */
00913   if (v == first) {
00914     v = GetNextVehicle(v);
00915     if (v == NULL) return NULL;
00916 
00917     if (IsTrainWagon(v)) SetFreeWagon(v);
00918 
00919     /* First can be an articulated engine, meaning GetNextVehicle() isn't
00920      * v->Next(). Thus set the next vehicle of the last articulated part
00921      * and the last articulated part is just before the next vehicle (v). */
00922     v->Previous()->SetNext(NULL);
00923 
00924     return v;
00925   }
00926 
00927   Vehicle *u;
00928   for (u = first; GetNextVehicle(u) != v; u = GetNextVehicle(u)) {}
00929   GetLastEnginePart(u)->SetNext(GetNextVehicle(v));
00930   return first;
00931 }
00932 
00933 static Vehicle *FindGoodVehiclePos(const Vehicle *src)
00934 {
00935   Vehicle *dst;
00936   EngineID eng = src->engine_type;
00937   TileIndex tile = src->tile;
00938 
00939   FOR_ALL_VEHICLES(dst) {
00940     if (dst->type == VEH_TRAIN && IsFreeWagon(dst) && dst->tile == tile && !HASBITS(dst->vehstatus, VS_CRASHED)) {
00941       /* check so all vehicles in the line have the same engine. */
00942       Vehicle *v = dst;
00943 
00944       while (v->engine_type == eng) {
00945         v = v->Next();
00946         if (v == NULL) return dst;
00947       }
00948     }
00949   }
00950 
00951   return NULL;
00952 }
00953 
00954 /*
00955  * add a vehicle v behind vehicle dest
00956  * use this function since it sets flags as needed
00957  */
00958 static void AddWagonToConsist(Vehicle *v, Vehicle *dest)
00959 {
00960   UnlinkWagon(v, v->First());
00961   if (dest == NULL) return;
00962 
00963   Vehicle *next = dest->Next();
00964   v->SetNext(NULL);
00965   dest->SetNext(v);
00966   v->SetNext(next);
00967   ClearFreeWagon(v);
00968   ClearFrontEngine(v);
00969 }
00970 
00971 /*
00972  * move around on the train so rear engines are placed correctly according to the other engines
00973  * always call with the front engine
00974  */
00975 static void NormaliseTrainConsist(Vehicle *v)
00976 {
00977   if (IsFreeWagon(v)) return;
00978 
00979   assert(IsFrontEngine(v));
00980 
00981   for (; v != NULL; v = GetNextVehicle(v)) {
00982     if (!IsMultiheaded(v) || !IsTrainEngine(v)) continue;
00983 
00984     /* make sure that there are no free cars before next engine */
00985     Vehicle *u;
00986     for (u = v; u->Next() != NULL && !IsTrainEngine(u->Next()); u = u->Next()) {}
00987 
00988     if (u == v->u.rail.other_multiheaded_part) continue;
00989     AddWagonToConsist(v->u.rail.other_multiheaded_part, u);
00990   }
00991 }
00992 
01002 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01003 {
01004   VehicleID s = GB(p1, 0, 16);
01005   VehicleID d = GB(p1, 16, 16);
01006 
01007   if (!IsValidVehicleID(s)) return CMD_ERROR;
01008 
01009   Vehicle *src = GetVehicle(s);
01010 
01011   if (src->type != VEH_TRAIN || !CheckOwnership(src->owner)) return CMD_ERROR;
01012 
01013   /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
01014   if (HASBITS(src->vehstatus, VS_CRASHED)) return CMD_ERROR;
01015 
01016   /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
01017   Vehicle *dst;
01018   if (d == INVALID_VEHICLE) {
01019     dst = IsTrainEngine(src) ? NULL : FindGoodVehiclePos(src);
01020   } else {
01021     if (!IsValidVehicleID(d)) return CMD_ERROR;
01022     dst = GetVehicle(d);
01023     if (dst->type != VEH_TRAIN || !CheckOwnership(dst->owner)) return CMD_ERROR;
01024 
01025     /* Do not allow appending to crashed vehicles, too */
01026     if (HASBITS(dst->vehstatus, VS_CRASHED)) return CMD_ERROR;
01027   }
01028 
01029   /* if an articulated part is being handled, deal with its parent vehicle */
01030   while (IsArticulatedPart(src)) src = src->Previous();
01031   if (dst != NULL) {
01032     while (IsArticulatedPart(dst)) dst = dst->Previous();
01033   }
01034 
01035   /* don't move the same vehicle.. */
01036   if (src == dst) return CommandCost();
01037 
01038   /* locate the head of the two chains */
01039   Vehicle *src_head = src->First();
01040   Vehicle *dst_head;
01041   if (dst != NULL) {
01042     dst_head = dst->First();
01043     if (dst_head->tile != src_head->tile) return CMD_ERROR;
01044     /* Now deal with articulated part of destination wagon */
01045     dst = GetLastEnginePart(dst);
01046   } else {
01047     dst_head = NULL;
01048   }
01049 
01050   if (IsRearDualheaded(src)) return_cmd_error(STR_REAR_ENGINE_FOLLOW_FRONT_ERROR);
01051 
01052   /* when moving all wagons, we can't have the same src_head and dst_head */
01053   if (HasBit(p2, 0) && src_head == dst_head) return CommandCost();
01054 
01055   /* check if all vehicles in the source train are stopped inside a depot. */
01056   int src_len = CheckTrainStoppedInDepot(src_head);
01057   if (src_len < 0) return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
01058 
01059   if ((flags & DC_AUTOREPLACE) == 0) {
01060     /* Check whether there are more than 'max_len' train units (articulated parts and rear heads do not count) in the new chain */
01061     int max_len = _settings_game.vehicle.mammoth_trains ? 100 : 10;
01062 
01063     /* check the destination row if the source and destination aren't the same. */
01064     if (src_head != dst_head) {
01065       int dst_len = 0;
01066 
01067       if (dst_head != NULL) {
01068         /* check if all vehicles in the dest train are stopped. */
01069         dst_len = CheckTrainStoppedInDepot(dst_head);
01070         if (dst_len < 0) return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
01071       }
01072 
01073       /* We are moving between rows, so only count the wagons from the source
01074        * row that are being moved. */
01075       if (HasBit(p2, 0)) {
01076         const Vehicle *u;
01077         for (u = src_head; u != src && u != NULL; u = GetNextVehicle(u))
01078           src_len--;
01079       } else {
01080         /* If moving only one vehicle, just count that. */
01081         src_len = 1;
01082       }
01083 
01084       if (src_len + dst_len > max_len) {
01085         /* Abort if we're adding too many wagons to a train. */
01086         if (dst_head != NULL && IsFrontEngine(dst_head)) return_cmd_error(STR_8819_TRAIN_TOO_LONG);
01087         /* Abort if we're making a train on a new row. */
01088         if (dst_head == NULL && IsTrainEngine(src)) return_cmd_error(STR_8819_TRAIN_TOO_LONG);
01089       }
01090     } else {
01091       /* Abort if we're creating a new train on an existing row. */
01092       if (src_len > max_len && src == src_head && IsTrainEngine(GetNextVehicle(src_head)))
01093         return_cmd_error(STR_8819_TRAIN_TOO_LONG);
01094     }
01095   }
01096 
01097   /* moving a loco to a new line?, then we need to assign a unitnumber. */
01098   if (dst == NULL && !IsFrontEngine(src) && IsTrainEngine(src)) {
01099     UnitID unit_num = ((flags & DC_AUTOREPLACE) != 0 ? 0 : GetFreeUnitNumber(VEH_TRAIN));
01100     if (unit_num > _settings_game.vehicle.max_trains)
01101       return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
01102 
01103     if (flags & DC_EXEC) src->unitnumber = unit_num;
01104   }
01105 
01106   /* When we move the front vehicle, the second vehicle might need a unitnumber */
01107   if (!HasBit(p2, 0) && (IsFreeWagon(src) || (IsFrontEngine(src) && dst == NULL)) && (flags & DC_AUTOREPLACE) == 0) {
01108     Vehicle *second = GetNextUnit(src);
01109     if (second != NULL && IsTrainEngine(second) && GetFreeUnitNumber(VEH_TRAIN) > _settings_game.vehicle.max_trains) {
01110       return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
01111     }
01112   }
01113 
01114   /*
01115    * Check whether the vehicles in the source chain are in the destination
01116    * chain. This can easily be done by checking whether the first vehicle
01117    * of the source chain is in the destination chain as the Next/Previous
01118    * pointers always make a doubly linked list of it where the assumption
01119    * v->Next()->Previous() == v holds (assuming v->Next() != NULL).
01120    */
01121   bool src_in_dst = false;
01122   for (Vehicle *v = dst_head; !src_in_dst && v != NULL; v = v->Next()) src_in_dst = v == src;
01123 
01124   /*
01125    * If the source chain is in the destination chain then the user is
01126    * only reordering the vehicles, thus not attaching a new vehicle.
01127    * Therefor the 'allow wagon attach' callback does not need to be
01128    * called. If it would be called strange things would happen because
01129    * one 'attaches' an already 'attached' vehicle causing more trouble
01130    * than it actually solves (infinite loops and such).
01131    */
01132   if (dst_head != NULL && !src_in_dst && (flags & DC_AUTOREPLACE) == 0) {
01133     /*
01134      * When performing the 'allow wagon attach' callback, we have to check
01135      * that for each and every wagon, not only the first one. This means
01136      * that we have to test one wagon, attach it to the train and then test
01137      * the next wagon till we have reached the end. We have to restore it
01138      * to the state it was before we 'tried' attaching the train when the
01139      * attaching fails or succeeds because we are not 'only' doing this
01140      * in the DC_EXEC state.
01141      */
01142     Vehicle *dst_tail = dst_head;
01143     while (dst_tail->Next() != NULL) dst_tail = dst_tail->Next();
01144 
01145     Vehicle *orig_tail = dst_tail;
01146     Vehicle *next_to_attach = src;
01147     Vehicle *src_previous = src->Previous();
01148 
01149     while (next_to_attach != NULL) {
01150       /* Don't check callback for articulated or rear dual headed parts */
01151       if (!IsArticulatedPart(next_to_attach) && !IsRearDualheaded(next_to_attach)) {
01152         /* Back up and clear the first_engine data to avoid using wagon override group */
01153         EngineID first_engine = next_to_attach->u.rail.first_engine;
01154         next_to_attach->u.rail.first_engine = INVALID_ENGINE;
01155 
01156         uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, dst_head->engine_type, next_to_attach, dst_head);
01157 
01158         /* Restore original first_engine data */
01159         next_to_attach->u.rail.first_engine = first_engine;
01160 
01161         if (callback != CALLBACK_FAILED) {
01162           StringID error = STR_NULL;
01163 
01164           if (callback == 0xFD) error = STR_INCOMPATIBLE_RAIL_TYPES;
01165           if (callback < 0xFD) error = GetGRFStringID(GetEngineGRFID(dst_head->engine_type), 0xD000 + callback);
01166 
01167           if (error != STR_NULL) {
01168             /*
01169              * The attaching is not allowed. In this case 'next_to_attach'
01170              * can contain some vehicles of the 'source' and the destination
01171              * train can have some too. We 'just' add the to-be added wagons
01172              * to the chain and then split it where it was previously
01173              * separated, i.e. the tail of the original destination train.
01174              * Furthermore the 'previous' link of the original source vehicle needs
01175              * to be restored, otherwise the train goes missing in the depot.
01176              */
01177             dst_tail->SetNext(next_to_attach);
01178             orig_tail->SetNext(NULL);
01179             if (src_previous != NULL) src_previous->SetNext(src);
01180 
01181             return_cmd_error(error);
01182           }
01183         }
01184       }
01185 
01186       /* Only check further wagons if told to move the chain */
01187       if (!HasBit(p2, 0)) break;
01188 
01189       /*
01190        * Adding a next wagon to the chain so we can test the other wagons.
01191        * First 'take' the first wagon from 'next_to_attach' and move it
01192        * to the next wagon. Then add that to the tail of the destination
01193        * train and update the tail with the new vehicle.
01194        */
01195       Vehicle *to_add = next_to_attach;
01196       next_to_attach = next_to_attach->Next();
01197 
01198       to_add->SetNext(NULL);
01199       dst_tail->SetNext(to_add);
01200       dst_tail = dst_tail->Next();
01201     }
01202 
01203     /*
01204      * When we reach this the attaching is allowed. It also means that the
01205      * chain of vehicles to attach is empty, so we do not need to merge that.
01206      * This means only the splitting needs to be done.
01207      * Furthermore the 'previous' link of the original source vehicle needs
01208      * to be restored, otherwise the train goes missing in the depot.
01209      */
01210     orig_tail->SetNext(NULL);
01211     if (src_previous != NULL) src_previous->SetNext(src);
01212   }
01213 
01214   /* do it? */
01215   if (flags & DC_EXEC) {
01216     /* If we move the front Engine and if the second vehicle is not an engine
01217        add the whole vehicle to the DEFAULT_GROUP */
01218     if (IsFrontEngine(src) && !IsDefaultGroupID(src->group_id)) {
01219       Vehicle *v = GetNextVehicle(src);
01220 
01221       if (v != NULL && IsTrainEngine(v)) {
01222         v->group_id   = src->group_id;
01223         src->group_id = DEFAULT_GROUP;
01224       }
01225     }
01226 
01227     if (HasBit(p2, 0)) {
01228       /* unlink ALL wagons */
01229       if (src != src_head) {
01230         Vehicle *v = src_head;
01231         while (GetNextVehicle(v) != src) v = GetNextVehicle(v);
01232         GetLastEnginePart(v)->SetNext(NULL);
01233       } else {
01234         InvalidateWindowData(WC_VEHICLE_DEPOT, src_head->tile); // We removed a line
01235         src_head = NULL;
01236       }
01237     } else {
01238       /* if moving within the same chain, dont use dst_head as it may get invalidated */
01239       if (src_head == dst_head) dst_head = NULL;
01240       /* unlink single wagon from linked list */
01241       src_head = UnlinkWagon(src, src_head);
01242       GetLastEnginePart(src)->SetNext(NULL);
01243     }
01244 
01245     if (dst == NULL) {
01246       /* We make a new line in the depot, so we know already that we invalidate the window data */
01247       InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01248 
01249       /* move the train to an empty line. for locomotives, we set the type to TS_Front. for wagons, 4. */
01250       if (IsTrainEngine(src)) {
01251         if (!IsFrontEngine(src)) {
01252           /* setting the type to 0 also involves setting up the orders field. */
01253           SetFrontEngine(src);
01254           assert(src->orders.list == NULL);
01255 
01256           /* Decrease the engines number of the src engine_type */
01257           if (!IsDefaultGroupID(src->group_id) && IsValidGroupID(src->group_id)) {
01258             GetGroup(src->group_id)->num_engines[src->engine_type]--;
01259           }
01260 
01261           /* If we move an engine to a new line affect it to the DEFAULT_GROUP */
01262           src->group_id = DEFAULT_GROUP;
01263         }
01264       } else {
01265         SetFreeWagon(src);
01266       }
01267       dst_head = src;
01268     } else {
01269       if (IsFrontEngine(src)) {
01270         /* the vehicle was previously a loco. need to free the order list and delete vehicle windows etc. */
01271         DeleteWindowById(WC_VEHICLE_VIEW, src->index);
01272         DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
01273         DeleteWindowById(WC_VEHICLE_REFIT, src->index);
01274         DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
01275         DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
01276         DeleteVehicleOrders(src);
01277         RemoveVehicleFromGroup(src);
01278       }
01279 
01280       if (IsFrontEngine(src) || IsFreeWagon(src)) {
01281         InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01282         ClearFrontEngine(src);
01283         ClearFreeWagon(src);
01284         src->unitnumber = 0; // doesn't occupy a unitnumber anymore.
01285       }
01286 
01287       /* link in the wagon(s) in the chain. */
01288       {
01289         Vehicle *v;
01290 
01291         for (v = src; GetNextVehicle(v) != NULL; v = GetNextVehicle(v)) {}
01292         GetLastEnginePart(v)->SetNext(dst->Next());
01293       }
01294       dst->SetNext(src);
01295     }
01296 
01297     if (src->u.rail.other_multiheaded_part != NULL) {
01298       if (src->u.rail.other_multiheaded_part == src_head) {
01299         src_head = src_head->Next();
01300       }
01301       AddWagonToConsist(src->u.rail.other_multiheaded_part, src);
01302     }
01303 
01304     /* If there is an engine behind first_engine we moved away, it should become new first_engine
01305      * To do this, CmdMoveRailVehicle must be called once more
01306      * we can't loop forever here because next time we reach this line we will have a front engine */
01307     if (src_head != NULL && !IsFrontEngine(src_head) && IsTrainEngine(src_head)) {
01308       /* As in CmdMoveRailVehicle src_head->group_id will be equal to DEFAULT_GROUP
01309        * we need to save the group and reaffect it to src_head */
01310       const GroupID tmp_g = src_head->group_id;
01311       CmdMoveRailVehicle(0, flags, src_head->index | (INVALID_VEHICLE << 16), 1, text);
01312       SetTrainGroupID(src_head, tmp_g);
01313       src_head = NULL; // don't do anything more to this train since the new call will do it
01314     }
01315 
01316     if (src_head != NULL) {
01317       NormaliseTrainConsist(src_head);
01318       TrainConsistChanged(src_head, false);
01319       UpdateTrainGroupID(src_head);
01320       if (IsFrontEngine(src_head)) {
01321         /* Update the refit button and window */
01322         InvalidateWindow(WC_VEHICLE_REFIT, src_head->index);
01323         InvalidateWindowWidget(WC_VEHICLE_VIEW, src_head->index, VVW_WIDGET_REFIT_VEH);
01324       }
01325       /* Update the depot window */
01326       InvalidateWindow(WC_VEHICLE_DEPOT, src_head->tile);
01327     }
01328 
01329     if (dst_head != NULL) {
01330       NormaliseTrainConsist(dst_head);
01331       TrainConsistChanged(dst_head, false);
01332       UpdateTrainGroupID(dst_head);
01333       if (IsFrontEngine(dst_head)) {
01334         /* Update the refit button and window */
01335         InvalidateWindowWidget(WC_VEHICLE_VIEW, dst_head->index, VVW_WIDGET_REFIT_VEH);
01336         InvalidateWindow(WC_VEHICLE_REFIT, dst_head->index);
01337       }
01338       /* Update the depot window */
01339       InvalidateWindow(WC_VEHICLE_DEPOT, dst_head->tile);
01340     }
01341 
01342     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01343   }
01344 
01345   return CommandCost();
01346 }
01347 
01357 CommandCost CmdSellRailWagon(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01358 {
01359   /* Check if we deleted a vehicle window */
01360   Window *w = NULL;
01361 
01362   if (!IsValidVehicleID(p1) || p2 > 1) return CMD_ERROR;
01363 
01364   Vehicle *v = GetVehicle(p1);
01365 
01366   if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
01367 
01368   if (HASBITS(v->vehstatus, VS_CRASHED)) return_cmd_error(STR_CAN_T_SELL_DESTROYED_VEHICLE);
01369 
01370   while (IsArticulatedPart(v)) v = v->Previous();
01371   Vehicle *first = v->First();
01372 
01373   /* make sure the vehicle is stopped in the depot */
01374   if (CheckTrainStoppedInDepot(first) < 0) {
01375     return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
01376   }
01377 
01378   if (IsRearDualheaded(v)) return_cmd_error(STR_REAR_ENGINE_FOLLOW_FRONT_ERROR);
01379 
01380   if (flags & DC_EXEC) {
01381     if (v == first && IsFrontEngine(first)) {
01382       DeleteWindowById(WC_VEHICLE_VIEW, first->index);
01383       DeleteWindowById(WC_VEHICLE_ORDERS, first->index);
01384       DeleteWindowById(WC_VEHICLE_REFIT, first->index);
01385       DeleteWindowById(WC_VEHICLE_DETAILS, first->index);
01386       DeleteWindowById(WC_VEHICLE_TIMETABLE, first->index);
01387     }
01388     InvalidateWindow(WC_VEHICLE_DEPOT, first->tile);
01389     InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01390   }
01391 
01392   CommandCost cost(EXPENSES_NEW_VEHICLES);
01393   switch (p2) {
01394     case 0: { /* Delete given wagon */
01395       bool switch_engine = false;    // update second wagon to engine?
01396 
01397       /* 1. Delete the engine, if it is dualheaded also delete the matching
01398        * rear engine of the loco (from the point of deletion onwards) */
01399       Vehicle *rear = (IsMultiheaded(v) &&
01400         IsTrainEngine(v)) ? v->u.rail.other_multiheaded_part : NULL;
01401 
01402       if (rear != NULL) {
01403         cost.AddCost(-rear->value);
01404         if (flags & DC_EXEC) {
01405           UnlinkWagon(rear, first);
01406           delete rear;
01407         }
01408       }
01409 
01410       /* 2. We are selling the front vehicle, some special action might be required
01411        * here, so take attention */
01412       if (v == first) {
01413         Vehicle *new_f = GetNextVehicle(first);
01414 
01415         /* 2.2 If there are wagons present after the deleted front engine, check
01416          * if the second wagon (which will be first) is an engine. If it is one,
01417          * promote it as a new train, retaining the unitnumber, orders */
01418         if (new_f != NULL && IsTrainEngine(new_f)) {
01419           if (IsTrainEngine(first)) {
01420             /* Let the new front engine take over the setup of the old engine */
01421             switch_engine = true;
01422 
01423             if (flags & DC_EXEC) {
01424               /* Make sure the group counts stay correct. */
01425               new_f->group_id        = first->group_id;
01426               first->group_id        = DEFAULT_GROUP;
01427 
01428               /* Copy orders (by sharing) */
01429               new_f->orders.list     = first->orders.list;
01430               new_f->AddToShared(first);
01431               DeleteVehicleOrders(first);
01432 
01433               /* Copy other important data from the front engine */
01434               new_f->CopyVehicleConfigAndStatistics(first);
01435 
01436               /* If we deleted a window then open a new one for the 'new' train */
01437               if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_f);
01438             }
01439           } else {
01440             /* We are selling a free wagon, and construct a new train at the same time.
01441              * This needs lots of extra checks (e.g. train limit), which are done by first moving
01442              * the remaining vehicles to a new row */
01443             cost.AddCost(DoCommand(0, new_f->index | INVALID_VEHICLE << 16, 1, flags, CMD_MOVE_RAIL_VEHICLE));
01444             if (cost.Failed()) return cost;
01445           }
01446         }
01447       }
01448 
01449       /* 3. Delete the requested wagon */
01450       cost.AddCost(-v->value);
01451       if (flags & DC_EXEC) {
01452         first = UnlinkWagon(v, first);
01453         delete v;
01454 
01455         /* 4 If the second wagon was an engine, update it to front_engine
01456          * which UnlinkWagon() has changed to TS_Free_Car */
01457         if (switch_engine) SetFrontEngine(first);
01458 
01459         /* 5. If the train still exists, update its acceleration, window, etc. */
01460         if (first != NULL) {
01461           NormaliseTrainConsist(first);
01462           TrainConsistChanged(first, false);
01463           UpdateTrainGroupID(first);
01464           if (IsFrontEngine(first)) InvalidateWindow(WC_VEHICLE_REFIT, first->index);
01465         }
01466 
01467       }
01468     } break;
01469     case 1: { /* Delete wagon and all wagons after it given certain criteria */
01470       /* Start deleting every vehicle after the selected one
01471        * If we encounter a matching rear-engine to a front-engine
01472        * earlier in the chain (before deletion), leave it alone */
01473       for (Vehicle *tmp; v != NULL; v = tmp) {
01474         tmp = GetNextVehicle(v);
01475 
01476         if (IsMultiheaded(v)) {
01477           if (IsTrainEngine(v)) {
01478             /* We got a front engine of a multiheaded set. Now we will sell the rear end too */
01479             Vehicle *rear = v->u.rail.other_multiheaded_part;
01480 
01481             if (rear != NULL) {
01482               cost.AddCost(-rear->value);
01483 
01484               /* If this is a multiheaded vehicle with nothing
01485                * between the parts, tmp will be pointing to the
01486                * rear part, which is unlinked from the train and
01487                * deleted here. However, because tmp has already
01488                * been set it needs to be updated now so that the
01489                * loop never sees the rear part. */
01490               if (tmp == rear) tmp = GetNextVehicle(tmp);
01491 
01492               if (flags & DC_EXEC) {
01493                 first = UnlinkWagon(rear, first);
01494                 delete rear;
01495               }
01496             }
01497           } else if (v->u.rail.other_multiheaded_part != NULL) {
01498             /* The front to this engine is earlier in this train. Do nothing */
01499             continue;
01500           }
01501         }
01502 
01503         cost.AddCost(-v->value);
01504         if (flags & DC_EXEC) {
01505           first = UnlinkWagon(v, first);
01506           delete v;
01507         }
01508       }
01509 
01510       /* 3. If it is still a valid train after selling, update its acceleration and cached values */
01511       if (flags & DC_EXEC && first != NULL) {
01512         NormaliseTrainConsist(first);
01513         TrainConsistChanged(first, false);
01514         UpdateTrainGroupID(first);
01515         InvalidateWindow(WC_VEHICLE_REFIT, first->index);
01516       }
01517     } break;
01518   }
01519   return cost;
01520 }
01521 
01522 void Train::UpdateDeltaXY(Direction direction)
01523 {
01524 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
01525   static const uint32 _delta_xy_table[8] = {
01526     MKIT(3, 3, -1, -1),
01527     MKIT(3, 7, -1, -3),
01528     MKIT(3, 3, -1, -1),
01529     MKIT(7, 3, -3, -1),
01530     MKIT(3, 3, -1, -1),
01531     MKIT(3, 7, -1, -3),
01532     MKIT(3, 3, -1, -1),
01533     MKIT(7, 3, -3, -1),
01534   };
01535 #undef MKIT
01536 
01537   uint32 x = _delta_xy_table[direction];
01538   this->x_offs        = GB(x,  0, 8);
01539   this->y_offs        = GB(x,  8, 8);
01540   this->x_extent      = GB(x, 16, 8);
01541   this->y_extent      = GB(x, 24, 8);
01542   this->z_extent      = 6;
01543 }
01544 
01545 static void UpdateVarsAfterSwap(Vehicle *v)
01546 {
01547   v->UpdateDeltaXY(v->direction);
01548   v->cur_image = v->GetImage(v->direction);
01549   BeginVehicleMove(v);
01550   VehiclePositionChanged(v);
01551   EndVehicleMove(v);
01552 }
01553 
01554 static inline void SetLastSpeed(Vehicle *v, int spd)
01555 {
01556   int old = v->u.rail.last_speed;
01557   if (spd != old) {
01558     v->u.rail.last_speed = spd;
01559     if (_settings_client.gui.vehicle_speed || (old == 0) != (spd == 0)) {
01560       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
01561     }
01562   }
01563 }
01564 
01566 static void MarkTrainAsStuck(Vehicle *v)
01567 {
01568   if (!HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
01569     /* It is the first time the problem occured, set the "train stuck" flag. */
01570     SetBit(v->u.rail.flags, VRF_TRAIN_STUCK);
01571     v->load_unload_time_rem = 0;
01572 
01573     /* Stop train */
01574     v->cur_speed = 0;
01575     v->subspeed = 0;
01576     SetLastSpeed(v, 0);
01577 
01578     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
01579   }
01580 }
01581 
01582 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
01583 {
01584   uint16 flag1 = *swap_flag1;
01585   uint16 flag2 = *swap_flag2;
01586 
01587   /* Clear the flags */
01588   ClrBit(*swap_flag1, VRF_GOINGUP);
01589   ClrBit(*swap_flag1, VRF_GOINGDOWN);
01590   ClrBit(*swap_flag2, VRF_GOINGUP);
01591   ClrBit(*swap_flag2, VRF_GOINGDOWN);
01592 
01593   /* Reverse the rail-flags (if needed) */
01594   if (HasBit(flag1, VRF_GOINGUP)) {
01595     SetBit(*swap_flag2, VRF_GOINGDOWN);
01596   } else if (HasBit(flag1, VRF_GOINGDOWN)) {
01597     SetBit(*swap_flag2, VRF_GOINGUP);
01598   }
01599   if (HasBit(flag2, VRF_GOINGUP)) {
01600     SetBit(*swap_flag1, VRF_GOINGDOWN);
01601   } else if (HasBit(flag2, VRF_GOINGDOWN)) {
01602     SetBit(*swap_flag1, VRF_GOINGUP);
01603   }
01604 }
01605 
01606 static void ReverseTrainSwapVeh(Vehicle *v, int l, int r)
01607 {
01608   Vehicle *a, *b;
01609 
01610   /* locate vehicles to swap */
01611   for (a = v; l != 0; l--) a = a->Next();
01612   for (b = v; r != 0; r--) b = b->Next();
01613 
01614   if (a != b) {
01615     /* swap the hidden bits */
01616     {
01617       uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus&VS_HIDDEN);
01618       b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus&VS_HIDDEN);
01619       a->vehstatus = tmp;
01620     }
01621 
01622     Swap(a->u.rail.track, b->u.rail.track);
01623     Swap(a->direction,    b->direction);
01624 
01625     /* toggle direction */
01626     if (a->u.rail.track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
01627     if (b->u.rail.track != TRACK_BIT_DEPOT) b->direction = ReverseDir(b->direction);
01628 
01629     Swap(a->x_pos, b->x_pos);
01630     Swap(a->y_pos, b->y_pos);
01631     Swap(a->tile,  b->tile);
01632     Swap(a->z_pos, b->z_pos);
01633 
01634     SwapTrainFlags(&a->u.rail.flags, &b->u.rail.flags);
01635 
01636     /* update other vars */
01637     UpdateVarsAfterSwap(a);
01638     UpdateVarsAfterSwap(b);
01639 
01640     /* call the proper EnterTile function unless we are in a wormhole */
01641     if (a->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
01642     if (b->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(b, b->tile, b->x_pos, b->y_pos);
01643   } else {
01644     if (a->u.rail.track != TRACK_BIT_DEPOT) a->direction = ReverseDir(a->direction);
01645     UpdateVarsAfterSwap(a);
01646 
01647     if (a->u.rail.track != TRACK_BIT_WORMHOLE) VehicleEnterTile(a, a->tile, a->x_pos, a->y_pos);
01648   }
01649 
01650   /* Update train's power incase tiles were different rail type */
01651   TrainPowerChanged(v);
01652 }
01653 
01654 
01660 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
01661 {
01662   return (v->type == VEH_TRAIN) ? v : NULL;
01663 }
01664 
01665 
01672 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
01673 {
01674   /* not a train || not front engine || crashed */
01675   if (v->type != VEH_TRAIN || !IsFrontEngine(v) || v->vehstatus & VS_CRASHED) return NULL;
01676 
01677   TileIndex tile = *(TileIndex*)data;
01678 
01679   if (TrainApproachingCrossingTile(v) != tile) return NULL;
01680 
01681   return v;
01682 }
01683 
01684 
01691 static bool TrainApproachingCrossing(TileIndex tile)
01692 {
01693   assert(IsLevelCrossingTile(tile));
01694 
01695   DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
01696   TileIndex tile_from = tile + TileOffsByDiagDir(dir);
01697 
01698   if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
01699 
01700   dir = ReverseDiagDir(dir);
01701   tile_from = tile + TileOffsByDiagDir(dir);
01702 
01703   return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
01704 }
01705 
01706 
01713 void UpdateLevelCrossing(TileIndex tile, bool sound)
01714 {
01715   assert(IsLevelCrossingTile(tile));
01716 
01717   /* train on crossing || train approaching crossing || reserved */
01718   bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || GetCrossingReservation(tile);
01719 
01720   if (new_state != IsCrossingBarred(tile)) {
01721     if (new_state && sound) {
01722       SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01723     }
01724     SetCrossingBarred(tile, new_state);
01725     MarkTileDirtyByTile(tile);
01726   }
01727 }
01728 
01729 
01735 static inline void MaybeBarCrossingWithSound(TileIndex tile)
01736 {
01737   if (!IsCrossingBarred(tile)) {
01738     BarCrossing(tile);
01739     SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01740     MarkTileDirtyByTile(tile);
01741   }
01742 }
01743 
01744 
01750 static void AdvanceWagonsBeforeSwap(Vehicle *v)
01751 {
01752   Vehicle *base = v;
01753   Vehicle *first = base;                    // first vehicle to move
01754   Vehicle *last = GetLastVehicleInChain(v); // last vehicle to move
01755   uint length = CountVehiclesInChain(v);
01756 
01757   while (length > 2) {
01758     last = last->Previous();
01759     first = first->Next();
01760 
01761     int differential = base->u.rail.cached_veh_length - last->u.rail.cached_veh_length;
01762 
01763     /* do not update images now
01764      * negative differential will be handled in AdvanceWagonsAfterSwap() */
01765     for (int i = 0; i < differential; i++) TrainController(first, last->Next(), false);
01766 
01767     base = first; // == base->Next()
01768     length -= 2;
01769   }
01770 }
01771 
01772 
01778 static void AdvanceWagonsAfterSwap(Vehicle *v)
01779 {
01780   /* first of all, fix the situation when the train was entering a depot */
01781   Vehicle *dep = v; // last vehicle in front of just left depot
01782   while (dep->Next() != NULL && (dep->u.rail.track == TRACK_BIT_DEPOT || dep->Next()->u.rail.track != TRACK_BIT_DEPOT)) {
01783     dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
01784   }
01785 
01786   Vehicle *leave = dep->Next(); // first vehicle in a depot we are leaving now
01787 
01788   if (leave != NULL) {
01789     /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
01790     int d = TicksToLeaveDepot(dep);
01791 
01792     if (d <= 0) {
01793       leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
01794       leave->u.rail.track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
01795       for (int i = 0; i >= d; i--) TrainController(leave, NULL, false); // maybe move it, and maybe let another wagon leave
01796     }
01797   } else {
01798     dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
01799   }
01800 
01801   Vehicle *base = v;
01802   Vehicle *first = base;                    // first vehicle to move
01803   Vehicle *last = GetLastVehicleInChain(v); // last vehicle to move
01804   uint length = CountVehiclesInChain(v);
01805 
01806   /* we have to make sure all wagons that leave a depot because of train reversing are moved coorectly
01807    * they have already correct spacing, so we have to make sure they are moved how they should */
01808   bool nomove = (dep == NULL); // if there is no vehicle leaving a depot, limit the number of wagons moved immediatelly
01809 
01810   while (length > 2) {
01811     /* we reached vehicle (originally) in front of a depot, stop now
01812      * (we would move wagons that are alredy moved with new wagon length) */
01813     if (base == dep) break;
01814 
01815     /* the last wagon was that one leaving a depot, so do not move it anymore */
01816     if (last == dep) nomove = true;
01817 
01818     last = last->Previous();
01819     first = first->Next();
01820 
01821     int differential = last->u.rail.cached_veh_length - base->u.rail.cached_veh_length;
01822 
01823     /* do not update images now */
01824     for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL), false);
01825 
01826     base = first; // == base->Next()
01827     length -= 2;
01828   }
01829 }
01830 
01831 
01832 static void ReverseTrainDirection(Vehicle *v)
01833 {
01834   if (IsRailDepotTile(v->tile)) {
01835     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01836   }
01837 
01838   /* Clear path reservation in front. */
01839   FreeTrainTrackReservation(v);
01840 
01841   /* Check if we were approaching a rail/road-crossing */
01842   TileIndex crossing = TrainApproachingCrossingTile(v);
01843 
01844   /* count number of vehicles */
01845   int r = CountVehiclesInChain(v) - 1;  // number of vehicles - 1
01846 
01847   AdvanceWagonsBeforeSwap(v);
01848 
01849   /* swap start<>end, start+1<>end-1, ... */
01850   int l = 0;
01851   do {
01852     ReverseTrainSwapVeh(v, l++, r--);
01853   } while (l <= r);
01854 
01855   AdvanceWagonsAfterSwap(v);
01856 
01857   if (IsRailDepotTile(v->tile)) {
01858     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01859   }
01860 
01861   ToggleBit(v->u.rail.flags, VRF_TOGGLE_REVERSE);
01862 
01863   ClrBit(v->u.rail.flags, VRF_REVERSING);
01864 
01865   /* recalculate cached data */
01866   TrainConsistChanged(v, true);
01867 
01868   /* update all images */
01869   for (Vehicle *u = v; u != NULL; u = u->Next()) u->cur_image = u->GetImage(u->direction);
01870 
01871   /* update crossing we were approaching */
01872   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
01873 
01874   /* maybe we are approaching crossing now, after reversal */
01875   crossing = TrainApproachingCrossingTile(v);
01876   if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
01877 
01878   /* If we are inside a depot after reversing, don't bother with path reserving. */
01879   if (v->u.rail.track & TRACK_BIT_DEPOT) {
01880     /* Can't be stuck here as inside a depot is always a safe tile. */
01881     if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
01882     ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
01883     return;
01884   }
01885 
01886   /* TrainExitDir does not always produce the desired dir for depots and
01887    * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
01888   DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
01889   if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
01890 
01891   if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
01892     /* If we are currently on a tile with conventional signals, we can't treat the
01893      * current tile as a safe tile or we would enter a PBS block without a reservation. */
01894     bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
01895       HasSignalOnTrackdir(v->tile, GetVehicleTrackdir(v)) &&
01896       !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->u.rail.track))));
01897 
01898     if (IsRailwayStationTile(v->tile)) SetRailwayStationPlatformReservation(v->tile, TrackdirToExitdir(GetVehicleTrackdir(v)), true);
01899     if (TryPathReserve(v, false, first_tile_okay)) {
01900       /* Do a look-ahead now in case our current tile was already a safe tile. */
01901       CheckNextTrainTile(v);
01902     } else if (v->current_order.GetType() != OT_LOADING) {
01903       /* Do not wait for a way out when we're still loading */
01904       MarkTrainAsStuck(v);
01905     }
01906   } else if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
01907     /* A train not inside a PBS block can't be stuck. */
01908     ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
01909     v->load_unload_time_rem = 0;
01910   }
01911 }
01912 
01919 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01920 {
01921   if (!IsValidVehicleID(p1)) return CMD_ERROR;
01922 
01923   Vehicle *v = GetVehicle(p1);
01924 
01925   if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
01926 
01927   if (p2 != 0) {
01928     /* turn a single unit around */
01929 
01930     if (IsMultiheaded(v) || HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_ARTIC_ENGINE)) {
01931       return_cmd_error(STR_ONLY_TURN_SINGLE_UNIT);
01932     }
01933 
01934     Vehicle *front = v->First();
01935     /* make sure the vehicle is stopped in the depot */
01936     if (CheckTrainStoppedInDepot(front) < 0) {
01937       return_cmd_error(STR_881A_TRAINS_CAN_ONLY_BE_ALTERED);
01938     }
01939 
01940     if (flags & DC_EXEC) {
01941       ToggleBit(v->u.rail.flags, VRF_REVERSE_DIRECTION);
01942       InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
01943       InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
01944     }
01945   } else {
01946     /* turn the whole train around */
01947     if (v->vehstatus & VS_CRASHED || v->breakdown_ctr != 0) return CMD_ERROR;
01948 
01949     if (flags & DC_EXEC) {
01950       /* Properly leave the station if we are loading and won't be loading anymore */
01951       if (v->current_order.IsType(OT_LOADING)) {
01952         const Vehicle *last = v;
01953         while (last->Next() != NULL) last = last->Next();
01954 
01955         /* not a station || different station --> leave the station */
01956         if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
01957           v->LeaveStation();
01958         }
01959       }
01960 
01961       if (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && v->cur_speed != 0) {
01962         ToggleBit(v->u.rail.flags, VRF_REVERSING);
01963       } else {
01964         v->cur_speed = 0;
01965         SetLastSpeed(v, 0);
01966         HideFillingPercent(&v->fill_percent_te_id);
01967         ReverseTrainDirection(v);
01968       }
01969     }
01970   }
01971   return CommandCost();
01972 }
01973 
01980 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01981 {
01982   if (!IsValidVehicleID(p1)) return CMD_ERROR;
01983 
01984   Vehicle *v = GetVehicle(p1);
01985 
01986   if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
01987 
01988   if (flags & DC_EXEC) v->u.rail.force_proceed = 0x50;
01989 
01990   return CommandCost();
01991 }
01992 
02003 CommandCost CmdRefitRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02004 {
02005   CargoID new_cid = GB(p2, 0, 8);
02006   byte new_subtype = GB(p2, 8, 8);
02007   bool only_this = HasBit(p2, 16);
02008 
02009   if (!IsValidVehicleID(p1)) return CMD_ERROR;
02010 
02011   Vehicle *v = GetVehicle(p1);
02012 
02013   if (v->type != VEH_TRAIN || !CheckOwnership(v->owner)) return CMD_ERROR;
02014   if (CheckTrainStoppedInDepot(v) < 0) return_cmd_error(STR_TRAIN_MUST_BE_STOPPED);
02015   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_CAN_T_REFIT_DESTROYED_VEHICLE);
02016 
02017   /* Check cargo */
02018   if (new_cid >= NUM_CARGO) return CMD_ERROR;
02019 
02020   CommandCost cost(EXPENSES_TRAIN_RUN);
02021   uint num = 0;
02022 
02023   do {
02024     /* XXX: We also refit all the attached wagons en-masse if they
02025      * can be refitted. This is how TTDPatch does it.  TODO: Have
02026      * some nice [Refit] button near each wagon. --pasky */
02027     if (!CanRefitTo(v->engine_type, new_cid)) continue;
02028 
02029     const Engine *e = GetEngine(v->engine_type);
02030     if (e->CanCarryCargo()) {
02031       uint16 amount = CALLBACK_FAILED;
02032 
02033       if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
02034         /* Back up the vehicle's cargo type */
02035         CargoID temp_cid = v->cargo_type;
02036         byte temp_subtype = v->cargo_subtype;
02037         v->cargo_type = new_cid;
02038         v->cargo_subtype = new_subtype;
02039         /* Check the refit capacity callback */
02040         amount = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
02041         /* Restore the original cargo type */
02042         v->cargo_type = temp_cid;
02043         v->cargo_subtype = temp_subtype;
02044       }
02045 
02046       if (amount == CALLBACK_FAILED) { // callback failed or not used, use default
02047         CargoID old_cid = e->GetDefaultCargoType();
02048         /* normally, the capacity depends on the cargo type, a rail vehicle can
02049          * carry twice as much mail/goods as normal cargo, and four times as
02050          * many passengers
02051          */
02052         amount = e->u.rail.capacity;
02053         switch (old_cid) {
02054           case CT_PASSENGERS: break;
02055           case CT_MAIL:
02056           case CT_GOODS: amount *= 2; break;
02057           default:       amount *= 4; break;
02058         }
02059         switch (new_cid) {
02060           case CT_PASSENGERS: break;
02061           case CT_MAIL:
02062           case CT_GOODS: amount /= 2; break;
02063           default:       amount /= 4; break;
02064         }
02065       }
02066 
02067       if (new_cid != v->cargo_type) {
02068         cost.AddCost(GetRefitCost(v->engine_type));
02069       }
02070 
02071       num += amount;
02072       if (flags & DC_EXEC) {
02073         v->cargo.Truncate((v->cargo_type == new_cid) ? amount : 0);
02074         v->cargo_type = new_cid;
02075         v->cargo_cap = amount;
02076         v->cargo_subtype = new_subtype;
02077         InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
02078         InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
02079         InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
02080       }
02081     }
02082   } while ((v = v->Next()) != NULL && !only_this);
02083 
02084   _returned_refit_capacity = num;
02085 
02086   /* Update the train's cached variables */
02087   if (flags & DC_EXEC) TrainConsistChanged(GetVehicle(p1)->First(), false);
02088 
02089   return cost;
02090 }
02091 
02092 struct TrainFindDepotData {
02093   uint best_length;
02094   TileIndex tile;
02095   Owner owner;
02100   bool reverse;
02101 };
02102 
02103 static bool NtpCallbFindDepot(TileIndex tile, TrainFindDepotData *tfdd, int track, uint length)
02104 {
02105   if (IsTileType(tile, MP_RAILWAY) &&
02106       IsTileOwner(tile, tfdd->owner) &&
02107       IsRailDepot(tile)) {
02108     /* approximate number of tiles by dividing by DIAG_FACTOR */
02109     tfdd->best_length = length / DIAG_FACTOR;
02110     tfdd->tile = tile;
02111     return true;
02112   }
02113 
02114   return false;
02115 }
02116 
02119 static TrainFindDepotData FindClosestTrainDepot(Vehicle *v, int max_distance)
02120 {
02121   assert(!(v->vehstatus & VS_CRASHED));
02122 
02123   TrainFindDepotData tfdd;
02124   tfdd.owner = v->owner;
02125   tfdd.reverse = false;
02126 
02127   if (IsRailDepotTile(v->tile)) {
02128     tfdd.tile = v->tile;
02129     tfdd.best_length = 0;
02130     return tfdd;
02131   }
02132 
02133   PBSTileInfo origin = FollowTrainReservation(v);
02134   if (IsRailDepotTile(origin.tile)) {
02135     tfdd.tile = origin.tile;
02136     tfdd.best_length = 0;
02137     return tfdd;
02138   }
02139 
02140   tfdd.best_length = UINT_MAX;
02141 
02142   uint8 pathfinder = _settings_game.pf.pathfinder_for_trains;
02143   if ((_settings_game.pf.reserve_paths || HasReservedTracks(v->tile, v->u.rail.track)) && pathfinder == VPF_NTP) pathfinder = VPF_NPF;
02144 
02145   switch (pathfinder) {
02146     case VPF_YAPF: { /* YAPF */
02147       bool found = YapfFindNearestRailDepotTwoWay(v, max_distance, NPF_INFINITE_PENALTY, &tfdd.tile, &tfdd.reverse);
02148       tfdd.best_length = found ? max_distance / 2 : UINT_MAX; // some fake distance or NOT_FOUND
02149     } break;
02150 
02151     case VPF_NPF: { /* NPF */
02152       const Vehicle *last = GetLastVehicleInChain(v);
02153       Trackdir trackdir = GetVehicleTrackdir(v);
02154       Trackdir trackdir_rev = ReverseTrackdir(GetVehicleTrackdir(last));
02155 
02156       assert(trackdir != INVALID_TRACKDIR);
02157       NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes, NPF_INFINITE_PENALTY);
02158       if (ftd.best_bird_dist == 0) {
02159         /* Found target */
02160         tfdd.tile = ftd.node.tile;
02161         /* Our caller expects a number of tiles, so we just approximate that
02162          * number by this. It might not be completely what we want, but it will
02163          * work for now :-) We can possibly change this when the old pathfinder
02164          * is removed. */
02165         tfdd.best_length = ftd.best_path_dist / NPF_TILE_LENGTH;
02166         if (NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE)) tfdd.reverse = true;
02167       }
02168     } break;
02169 
02170     default:
02171     case VPF_NTP: { /* NTP */
02172       /* search in the forward direction first. */
02173       DiagDirection i = TrainExitDir(v->direction, v->u.rail.track);
02174       NewTrainPathfind(v->tile, 0, v->u.rail.compatible_railtypes, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd);
02175       if (tfdd.best_length == UINT_MAX){
02176         tfdd.reverse = true;
02177         /* search in backwards direction */
02178         i = TrainExitDir(ReverseDir(v->direction), v->u.rail.track);
02179         NewTrainPathfind(v->tile, 0, v->u.rail.compatible_railtypes, i, (NTPEnumProc*)NtpCallbFindDepot, &tfdd);
02180       }
02181     } break;
02182   }
02183 
02184   return tfdd;
02185 }
02186 
02187 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
02188 {
02189   TrainFindDepotData tfdd = FindClosestTrainDepot(this, 0);
02190   if (tfdd.best_length == UINT_MAX) return false;
02191 
02192   if (location    != NULL) *location    = tfdd.tile;
02193   if (destination != NULL) *destination = GetDepotByTile(tfdd.tile)->index;
02194   if (reverse     != NULL) *reverse     = tfdd.reverse;
02195 
02196   return true;
02197 }
02198 
02207 CommandCost CmdSendTrainToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02208 {
02209   if (p2 & DEPOT_MASS_SEND) {
02210     /* Mass goto depot requested */
02211     if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
02212     return SendAllVehiclesToDepot(VEH_TRAIN, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
02213   }
02214 
02215   if (!IsValidVehicleID(p1)) return CMD_ERROR;
02216 
02217   Vehicle *v = GetVehicle(p1);
02218 
02219   if (v->type != VEH_TRAIN) return CMD_ERROR;
02220 
02221   return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
02222 }
02223 
02224 
02225 void OnTick_Train()
02226 {
02227   _age_cargo_skip_counter = (_age_cargo_skip_counter == 0) ? 184 : (_age_cargo_skip_counter - 1);
02228 }
02229 
02230 static const int8 _vehicle_smoke_pos[8] = {
02231   1, 1, 1, 0, -1, -1, -1, 0
02232 };
02233 
02234 static void HandleLocomotiveSmokeCloud(const Vehicle *v)
02235 {
02236   bool sound = false;
02237 
02238   if (v->vehstatus & VS_TRAIN_SLOWING || v->load_unload_time_rem != 0 || v->cur_speed < 2) {
02239     return;
02240   }
02241 
02242   const Vehicle *u = v;
02243 
02244   do {
02245     const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
02246     int effect_offset = GB(v->u.rail.cached_vis_effect, 0, 4) - 8;
02247     byte effect_type = GB(v->u.rail.cached_vis_effect, 4, 2);
02248     bool disable_effect = HasBit(v->u.rail.cached_vis_effect, 6);
02249 
02250     /* no smoke? */
02251     if ((rvi->railveh_type == RAILVEH_WAGON && effect_type == 0) ||
02252         disable_effect ||
02253         v->vehstatus & VS_HIDDEN) {
02254       continue;
02255     }
02256 
02257     /* No smoke in depots or tunnels */
02258     if (IsRailDepotTile(v->tile) || IsTunnelTile(v->tile)) continue;
02259 
02260     /* No sparks for electric vehicles on nonelectrified tracks */
02261     if (!HasPowerOnRail(v->u.rail.railtype, GetTileRailType(v->tile))) continue;
02262 
02263     if (effect_type == 0) {
02264       /* Use default effect type for engine class. */
02265       effect_type = rvi->engclass;
02266     } else {
02267       effect_type--;
02268     }
02269 
02270     int x = _vehicle_smoke_pos[v->direction] * effect_offset;
02271     int y = _vehicle_smoke_pos[(v->direction + 2) % 8] * effect_offset;
02272 
02273     if (HasBit(v->u.rail.flags, VRF_REVERSE_DIRECTION)) {
02274       x = -x;
02275       y = -y;
02276     }
02277 
02278     switch (effect_type) {
02279       case 0:
02280         /* steam smoke. */
02281         if (GB(v->tick_counter, 0, 4) == 0) {
02282           CreateEffectVehicleRel(v, x, y, 10, EV_STEAM_SMOKE);
02283           sound = true;
02284         }
02285         break;
02286 
02287       case 1:
02288         /* diesel smoke */
02289         if (u->cur_speed <= 40 && Chance16(15, 128)) {
02290           CreateEffectVehicleRel(v, 0, 0, 10, EV_DIESEL_SMOKE);
02291           sound = true;
02292         }
02293         break;
02294 
02295       case 2:
02296         /* blue spark */
02297         if (GB(v->tick_counter, 0, 2) == 0 && Chance16(1, 45)) {
02298           CreateEffectVehicleRel(v, 0, 0, 10, EV_ELECTRIC_SPARK);
02299           sound = true;
02300         }
02301         break;
02302 
02303       default:
02304         break;
02305     }
02306   } while ((v = v->Next()) != NULL);
02307 
02308   if (sound) PlayVehicleSound(u, VSE_TRAIN_EFFECT);
02309 }
02310 
02311 void Train::PlayLeaveStationSound() const
02312 {
02313   static const SoundFx sfx[] = {
02314     SND_04_TRAIN,
02315     SND_0A_TRAIN_HORN,
02316     SND_0A_TRAIN_HORN,
02317     SND_47_MAGLEV_2,
02318     SND_41_MAGLEV
02319   };
02320 
02321   if (PlayVehicleSound(this, VSE_START)) return;
02322 
02323   EngineID engtype = this->engine_type;
02324   SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
02325 }
02326 
02328 static void CheckNextTrainTile(Vehicle *v)
02329 {
02330   /* Don't do any look-ahead if path_backoff_interval is 255. */
02331   if (_settings_game.pf.path_backoff_interval == 255) return;
02332 
02333   /* Exit if we reached our destination depot or are inside a depot. */
02334   if ((v->tile == v->dest_tile && v->current_order.IsType(OT_GOTO_DEPOT)) || v->u.rail.track & TRACK_BIT_DEPOT) return;
02335   /* Exit if we are on a station tile and are going to stop. */
02336   if (IsRailwayStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
02337   /* Exit if the current order doesn't have a destination, but the train has orders. */
02338   if ((v->current_order.IsType(OT_NOTHING) || v->current_order.IsType(OT_LEAVESTATION) || v->current_order.IsType(OT_LOADING)) && v->GetNumOrders() > 0) return;
02339 
02340   Trackdir td = GetVehicleTrackdir(v);
02341 
02342   /* On a tile with a red non-pbs signal, don't look ahead. */
02343   if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
02344       !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
02345       GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
02346 
02347   CFollowTrackRail ft(v);
02348   if (!ft.Follow(v->tile, td)) return;
02349 
02350   if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
02351     /* Next tile is not reserved. */
02352     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02353       if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
02354         /* If the next tile is a PBS signal, try to make a reservation. */
02355         TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02356         if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
02357           tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
02358         }
02359         ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
02360       }
02361     }
02362   }
02363 }
02364 
02365 static bool CheckTrainStayInDepot(Vehicle *v)
02366 {
02367   /* bail out if not all wagons are in the same depot or not in a depot at all */
02368   for (const Vehicle *u = v; u != NULL; u = u->Next()) {
02369     if (u->u.rail.track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
02370   }
02371 
02372   /* if the train got no power, then keep it in the depot */
02373   if (v->u.rail.cached_power == 0) {
02374     v->vehstatus |= VS_STOPPED;
02375     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
02376     return true;
02377   }
02378 
02379   SigSegState seg_state;
02380 
02381   if (v->u.rail.force_proceed == 0) {
02382     /* force proceed was not pressed */
02383     if (++v->load_unload_time_rem < 37) {
02384       InvalidateWindowClasses(WC_TRAINS_LIST);
02385       return true;
02386     }
02387 
02388     v->load_unload_time_rem = 0;
02389 
02390     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02391     if (seg_state == SIGSEG_FULL || GetDepotWaypointReservation(v->tile)) {
02392       /* Full and no PBS signal in block or depot reserved, can't exit. */
02393       InvalidateWindowClasses(WC_TRAINS_LIST);
02394       return true;
02395     }
02396   } else {
02397     seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02398   }
02399 
02400   /* Only leave when we can reserve a path to our destination. */
02401   if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->u.rail.force_proceed == 0) {
02402     /* No path and no force proceed. */
02403     InvalidateWindowClasses(WC_TRAINS_LIST);
02404     MarkTrainAsStuck(v);
02405     return true;
02406   }
02407 
02408   SetDepotWaypointReservation(v->tile, true);
02409   if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02410 
02411   VehicleServiceInDepot(v);
02412   InvalidateWindowClasses(WC_TRAINS_LIST);
02413   v->PlayLeaveStationSound();
02414 
02415   v->u.rail.track = TRACK_BIT_X;
02416   if (v->direction & 2) v->u.rail.track = TRACK_BIT_Y;
02417 
02418   v->vehstatus &= ~VS_HIDDEN;
02419   v->cur_speed = 0;
02420 
02421   v->UpdateDeltaXY(v->direction);
02422   v->cur_image = v->GetImage(v->direction);
02423   VehiclePositionChanged(v);
02424   UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02425   UpdateTrainAcceleration(v);
02426   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
02427 
02428   return false;
02429 }
02430 
02432 static void ClearPathReservation(const Vehicle *v, TileIndex tile, Trackdir track_dir)
02433 {
02434   DiagDirection dir = TrackdirToExitdir(track_dir);
02435 
02436   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
02437     /* Are we just leaving a tunnel/bridge? */
02438     if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
02439       TileIndex end = GetOtherTunnelBridgeEnd(tile);
02440 
02441       if (!HasVehicleOnTunnelBridge(tile, end, v)) {
02442         /* Free the reservation only if no other train is on the tiles. */
02443         SetTunnelBridgeReservation(tile, false);
02444         SetTunnelBridgeReservation(end, false);
02445 
02446         if (_settings_client.gui.show_track_reservation) {
02447           MarkTileDirtyByTile(tile);
02448           MarkTileDirtyByTile(end);
02449         }
02450       }
02451     }
02452   } else if (IsRailwayStationTile(tile)) {
02453     TileIndex new_tile = TileAddByDiagDir(tile, dir);
02454     /* If the new tile is not a further tile of the same station, we
02455      * clear the reservation for the whole platform. */
02456     if (!IsCompatibleTrainStationTile(new_tile, tile)) {
02457       SetRailwayStationPlatformReservation(tile, ReverseDiagDir(dir), false);
02458     }
02459   } else {
02460     /* Any other tile */
02461     UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
02462   }
02463 }
02464 
02466 void FreeTrainTrackReservation(const Vehicle *v, TileIndex origin, Trackdir orig_td)
02467 {
02468   assert(IsFrontEngine(v));
02469 
02470   TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
02471   Trackdir  td = orig_td != INVALID_TRACKDIR ? orig_td : GetVehicleTrackdir(v);
02472   bool      free_tile = tile != v->tile || !(IsRailwayStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
02473   StationID station_id = IsRailwayStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
02474 
02475   /* Don't free reservation if it's not ours. */
02476   if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
02477 
02478   CFollowTrackRail ft(v, GetRailTypeInfo(v->u.rail.railtype)->compatible_railtypes);
02479   while (ft.Follow(tile, td)) {
02480     tile = ft.m_new_tile;
02481     TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
02482     td = RemoveFirstTrackdir(&bits);
02483     assert(bits == TRACKDIR_BIT_NONE);
02484 
02485     if (!IsValidTrackdir(td)) break;
02486 
02487     if (IsTileType(tile, MP_RAILWAY)) {
02488       if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
02489         /* Conventional signal along trackdir: remove reservation and stop. */
02490         UnreserveRailTrack(tile, TrackdirToTrack(td));
02491         break;
02492       }
02493       if (HasPbsSignalOnTrackdir(tile, td)) {
02494         if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
02495           /* Red PBS signal? Can't be our reservation, would be green then. */
02496           break;
02497         } else {
02498           /* Turn the signal back to red. */
02499           SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
02500           MarkTileDirtyByTile(tile);
02501         }
02502       } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
02503         break;
02504       }
02505     }
02506 
02507     /* Don't free first station/bridge/tunnel if we are on it. */
02508     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);
02509 
02510     free_tile = true;
02511   }
02512 }
02513 
02515 struct TrainTrackFollowerData {
02516   TileIndex dest_coords;
02517   StationID station_index; 
02518   uint best_bird_dist;
02519   uint best_track_dist;
02520   TrackdirByte best_track;
02521 };
02522 
02523 static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, Trackdir track, uint length)
02524 {
02525   /* heading for nowhere? */
02526   if (ttfd->dest_coords == 0) return false;
02527 
02528   /* did we reach the final station? */
02529   if ((ttfd->station_index == INVALID_STATION && tile == ttfd->dest_coords) || (
02530         IsTileType(tile, MP_STATION) &&
02531         IsRailwayStation(tile) &&
02532         GetStationIndex(tile) == ttfd->station_index
02533       )) {
02534     /* We do not check for dest_coords if we have a station_index,
02535      * because in that case the dest_coords are just an
02536      * approximation of where the station is */
02537 
02538     /* found station */
02539     ttfd->best_track = track;
02540     ttfd->best_bird_dist = 0;
02541     return true;
02542   } else {
02543     /* didn't find station, keep track of the best path so far. */
02544     uint dist = DistanceManhattan(tile, ttfd->dest_coords);
02545     if (dist < ttfd->best_bird_dist) {
02546       ttfd->best_bird_dist = dist;
02547       ttfd->best_track = track;
02548     }
02549     return false;
02550   }
02551 }
02552 
02553 static void FillWithStationData(TrainTrackFollowerData *fd, const Vehicle *v)
02554 {
02555   fd->dest_coords = v->dest_tile;
02556   fd->station_index = v->current_order.IsType(OT_GOTO_STATION) ? v->current_order.GetDestination() : INVALID_STATION;
02557 }
02558 
02559 static const byte _initial_tile_subcoord[6][4][3] = {
02560 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0,  0, 0 }},
02561 {{  0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
02562 {{  0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0,  0, 0 }},
02563 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
02564 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0,  0, 0 }},
02565 {{  0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
02566 };
02567 
02568 static const byte _search_directions[6][4] = {
02569   { 0, 9, 2, 9 }, 
02570   { 9, 1, 9, 3 }, 
02571   { 9, 0, 3, 9 }, 
02572   { 1, 9, 9, 2 }, 
02573   { 3, 2, 9, 9 }, 
02574   { 9, 9, 1, 0 }, 
02575 };
02576 
02577 static const byte _pick_track_table[6] = {1, 3, 2, 2, 0, 0};
02578 
02591 static Track DoTrainPathfind(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool do_track_reservation, PBSTileInfo *dest)
02592 {
02593   Track best_track;
02594 
02595 #ifdef PF_BENCHMARK
02596   TIC()
02597 #endif
02598 
02599   if (path_not_found) *path_not_found = false;
02600 
02601   uint8 pathfinder = _settings_game.pf.pathfinder_for_trains;
02602   if (do_track_reservation && pathfinder == VPF_NTP) pathfinder = VPF_NPF;
02603 
02604   switch (pathfinder) {
02605     case VPF_YAPF: { /* YAPF */
02606       Trackdir trackdir = YapfChooseRailTrack(v, tile, enterdir, tracks, path_not_found, do_track_reservation, dest);
02607       if (trackdir != INVALID_TRACKDIR) {
02608         best_track = TrackdirToTrack(trackdir);
02609       } else {
02610         best_track = FindFirstTrack(tracks);
02611       }
02612     } break;
02613 
02614     case VPF_NPF: { /* NPF */
02615       void *perf = NpfBeginInterval();
02616 
02617       NPFFindStationOrTileData fstd;
02618       NPFFillWithOrderData(&fstd, v, do_track_reservation);
02619 
02620       PBSTileInfo origin = FollowTrainReservation(v);
02621       assert(IsValidTrackdir(origin.trackdir));
02622 
02623       NPFFoundTargetData ftd = NPFRouteToStationOrTile(origin.tile, origin.trackdir, true, &fstd, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes);
02624 
02625       if (dest != NULL) {
02626         dest->tile = ftd.node.tile;
02627         dest->trackdir = (Trackdir)ftd.node.direction;
02628         dest->okay = ftd.res_okay;
02629       }
02630 
02631       if (ftd.best_trackdir == INVALID_TRACKDIR) {
02632         /* We are already at our target. Just do something
02633          * @todo maybe display error?
02634          * @todo: go straight ahead if possible? */
02635         best_track = FindFirstTrack(tracks);
02636       } else {
02637         /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
02638          * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
02639          * we did not find our target, but ftd.best_trackdir contains the direction leading
02640          * to the tile closest to our target. */
02641         if (ftd.best_bird_dist != 0 && path_not_found != NULL) *path_not_found = true;
02642         /* Discard enterdir information, making it a normal track */
02643         best_track = TrackdirToTrack(ftd.best_trackdir);
02644       }
02645 
02646       int time = NpfEndInterval(perf);
02647       DEBUG(yapf, 4, "[NPFT] %d us - %d rounds - %d open - %d closed -- ", time, 0, _aystar_stats_open_size, _aystar_stats_closed_size);
02648     } break;
02649 
02650     default:
02651     case VPF_NTP: { /* NTP */
02652       void *perf = NpfBeginInterval();
02653 
02654       TrainTrackFollowerData fd;
02655       FillWithStationData(&fd, v);
02656 
02657       /* New train pathfinding */
02658       fd.best_bird_dist = UINT_MAX;
02659       fd.best_track_dist = UINT_MAX;
02660       fd.best_track = INVALID_TRACKDIR;
02661 
02662       NewTrainPathfind(tile - TileOffsByDiagDir(enterdir), v->dest_tile,
02663         v->u.rail.compatible_railtypes, enterdir, (NTPEnumProc*)NtpCallbFindStation, &fd);
02664 
02665       /* check whether the path was found or only 'guessed' */
02666       if (fd.best_bird_dist != 0 && path_not_found != NULL) *path_not_found = true;
02667 
02668       if (fd.best_track == INVALID_TRACKDIR) {
02669         /* blaha */
02670         best_track = FindFirstTrack(tracks);
02671       } else {
02672         best_track = TrackdirToTrack(fd.best_track);
02673       }
02674 
02675       int time = NpfEndInterval(perf);
02676       DEBUG(yapf, 4, "[NTPT] %d us - %d rounds - %d open - %d closed -- ", time, 0, 0, 0);
02677     } break;
02678   }
02679 
02680 #ifdef PF_BENCHMARK
02681   TOC("PF time = ", 1)
02682 #endif
02683 
02684   return best_track;
02685 }
02686 
02692 static PBSTileInfo ExtendTrainReservation(const Vehicle *v, TrackBits *new_tracks, DiagDirection *enterdir)
02693 {
02694   bool no_90deg_turns = _settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg;
02695   PBSTileInfo origin = FollowTrainReservation(v);
02696 
02697   CFollowTrackRail ft(v);
02698 
02699   TileIndex tile = origin.tile;
02700   Trackdir  cur_td = origin.trackdir;
02701   while (ft.Follow(tile, cur_td)) {
02702     if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02703       /* Possible signal tile. */
02704       if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
02705     }
02706 
02707     if (no_90deg_turns) {
02708       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02709       if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
02710     }
02711 
02712     /* Station, depot or waypoint are a possible target. */
02713     bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRailTile(ft.m_new_tile));
02714     if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
02715       /* Choice found or possible target encountered.
02716        * On finding a possible target, we need to stop and let the pathfinder handle the
02717        * remaining path. This is because we don't know if this target is in one of our
02718        * orders, so we might cause pathfinding to fail later on if we find a choice.
02719        * This failure would cause a bogous call to TryReserveSafePath which might reserve
02720        * a wrong path not leading to our next destination. */
02721       if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
02722 
02723       /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
02724        * actually starts its search at the first unreserved tile. */
02725       if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
02726 
02727       /* Choice found, path valid but not okay. Save info about the choice tile as well. */
02728       if (new_tracks) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02729       if (enterdir) *enterdir = ft.m_exitdir;
02730       return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
02731     }
02732 
02733     tile = ft.m_new_tile;
02734     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02735 
02736     if (IsSafeWaitingPosition(v, tile, cur_td, true, no_90deg_turns)) {
02737       bool wp_free = IsWaitingPositionFree(v, tile, cur_td, no_90deg_turns);
02738       if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
02739       /* Safe position is all good, path valid and okay. */
02740       return PBSTileInfo(tile, cur_td, true);
02741     }
02742 
02743     if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
02744   }
02745 
02746   if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
02747     /* End of line, path valid and okay. */
02748     return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
02749   }
02750 
02751   /* Sorry, can't reserve path, back out. */
02752   tile = origin.tile;
02753   cur_td = origin.trackdir;
02754   TileIndex stopped = ft.m_old_tile;
02755   Trackdir  stopped_td = ft.m_old_td;
02756   while (tile != stopped || cur_td != stopped_td) {
02757     if (!ft.Follow(tile, cur_td)) break;
02758 
02759     if (no_90deg_turns) {
02760       ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02761       assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
02762     }
02763     assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
02764 
02765     tile = ft.m_new_tile;
02766     cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02767 
02768     UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
02769   }
02770 
02771   /* Path invalid. */
02772   return PBSTileInfo();
02773 }
02774 
02785 static bool TryReserveSafeTrack(const Vehicle *v, TileIndex tile, Trackdir td, bool override_tailtype)
02786 {
02787   if (_settings_game.pf.pathfinder_for_trains == VPF_YAPF) {
02788     return YapfRailFindNearestSafeTile(v, tile, td, override_tailtype);
02789   } else {
02790     return NPFRouteToSafeTile(v, tile, td, override_tailtype).res_okay;
02791   }
02792 }
02793 
02795 class VehicleOrderSaver
02796 {
02797 private:
02798   Vehicle        *v;
02799   Order          old_order;
02800   TileIndex      old_dest_tile;
02801   StationID      old_last_station_visited;
02802   VehicleOrderID index;
02803 
02804 public:
02805   VehicleOrderSaver(Vehicle *_v) :
02806     v(_v),
02807     old_order(_v->current_order),
02808     old_dest_tile(_v->dest_tile),
02809     old_last_station_visited(_v->last_station_visited),
02810     index(_v->cur_order_index)
02811   {
02812   }
02813 
02814   ~VehicleOrderSaver()
02815   {
02816     this->v->current_order = this->old_order;
02817     this->v->dest_tile = this->old_dest_tile;
02818     this->v->last_station_visited = this->old_last_station_visited;
02819   }
02820 
02826   bool SwitchToNextOrder(bool skip_first)
02827   {
02828     if (this->v->GetNumOrders() == 0) return false;
02829 
02830     if (skip_first) ++this->index;
02831 
02832     int conditional_depth = 0;
02833 
02834     do {
02835       /* Wrap around. */
02836       if (this->index >= this->v->GetNumOrders()) this->index = 0;
02837 
02838       Order *order = GetVehicleOrder(this->v, this->index);
02839       assert(order != NULL);
02840 
02841       switch (order->GetType()) {
02842         case OT_GOTO_DEPOT:
02843           /* Skip service in depot orders when the train doesn't need service. */
02844           if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
02845         case OT_GOTO_STATION:
02846         case OT_GOTO_WAYPOINT:
02847           this->v->current_order = *order;
02848           UpdateOrderDest(this->v, order);
02849           return true;
02850         case OT_CONDITIONAL: {
02851           if (conditional_depth > this->v->GetNumOrders()) return false;
02852           VehicleOrderID next = ProcessConditionalOrder(order, this->v);
02853           if (next != INVALID_VEH_ORDER_ID) {
02854             conditional_depth++;
02855             this->index = next;
02856             /* Don't increment next, so no break here. */
02857             continue;
02858           }
02859           break;
02860         }
02861         default:
02862           break;
02863       }
02864       /* Don't increment inside the while because otherwise conditional
02865        * orders can lead to an infinite loop. */
02866       ++this->index;
02867     } while (this->index != this->v->cur_order_index);
02868 
02869     return false;
02870   }
02871 };
02872 
02873 /* choose a track */
02874 static Track ChooseTrainTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
02875 {
02876   Track best_track = INVALID_TRACK;
02877   bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
02878   bool changed_signal = false;
02879 
02880   assert((tracks & ~TRACK_BIT_MASK) == 0);
02881 
02882   if (got_reservation != NULL) *got_reservation = false;
02883 
02884   /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
02885   TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
02886   /* Do we have a suitable reserved track? */
02887   if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
02888 
02889   /* Quick return in case only one possible track is available */
02890   if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
02891     Track track = FindFirstTrack(tracks);
02892     /* We need to check for signals only here, as a junction tile can't have signals. */
02893     if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
02894       do_track_reservation = true;
02895       changed_signal = true;
02896       SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
02897     } else if (!do_track_reservation) {
02898       return track;
02899     }
02900     best_track = track;
02901   }
02902 
02903   PBSTileInfo   res_dest(tile, INVALID_TRACKDIR, false);
02904   DiagDirection dest_enterdir = enterdir;
02905   if (do_track_reservation) {
02906     /* Check if the train needs service here, so it has a chance to always find a depot.
02907      * Also check if the current order is a service order so we don't reserve a path to
02908      * the destination but instead to the next one if service isn't needed. */
02909     CheckIfTrainNeedsService(v);
02910     if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
02911 
02912     res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
02913     if (res_dest.tile == INVALID_TILE) {
02914       /* Reservation failed? */
02915       if (mark_stuck) MarkTrainAsStuck(v);
02916       if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
02917       return FindFirstTrack(tracks);
02918     }
02919   }
02920 
02921   /* Save the current train order. The destructor will restore the old order on function exit. */
02922   VehicleOrderSaver orders(v);
02923 
02924   /* If the current tile is the destination of the current order and
02925    * a reservation was requested, advance to the next order.
02926    * Don't advance on a depot order as depots are always safe end points
02927    * for a path and no look-ahead is necessary. This also avoids a
02928    * problem with depot orders not part of the order list when the
02929    * order list itself is empty. */
02930   if (v->current_order.IsType(OT_LEAVESTATION)) {
02931     orders.SwitchToNextOrder(false);
02932   } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
02933       v->current_order.IsType(OT_GOTO_STATION) ?
02934       IsRailwayStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
02935       v->tile == v->dest_tile))) {
02936     orders.SwitchToNextOrder(true);
02937   }
02938 
02939   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02940     /* Pathfinders are able to tell that route was only 'guessed'. */
02941     bool      path_not_found = false;
02942     TileIndex new_tile = res_dest.tile;
02943 
02944     Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, &path_not_found, do_track_reservation, &res_dest);
02945     if (new_tile == tile) best_track = next_track;
02946 
02947     /* handle "path not found" state */
02948     if (path_not_found) {
02949       /* PF didn't find the route */
02950       if (!HasBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION)) {
02951         /* it is first time the problem occurred, set the "path not found" flag */
02952         SetBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION);
02953         /* and notify user about the event */
02954         AI::NewEvent(v->owner, new AIEventVehicleLost(v->index));
02955         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
02956           SetDParam(0, v->index);
02957           AddNewsItem(
02958             STR_TRAIN_IS_LOST,
02959             NS_ADVICE,
02960             v->index,
02961             0);
02962         }
02963       }
02964     } else {
02965       /* route found, is the train marked with "path not found" flag? */
02966       if (HasBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION)) {
02967         /* clear the flag as the PF's problem was solved */
02968         ClrBit(v->u.rail.flags, VRF_NO_PATH_TO_DESTINATION);
02969         /* can we also delete the "News" item somehow? */
02970       }
02971     }
02972   }
02973 
02974   /* No track reservation requested -> finished. */
02975   if (!do_track_reservation) return best_track;
02976 
02977   /* A path was found, but could not be reserved. */
02978   if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02979     if (mark_stuck) MarkTrainAsStuck(v);
02980     FreeTrainTrackReservation(v);
02981     return best_track;
02982   }
02983 
02984   /* No possible reservation target found, we are probably lost. */
02985   if (res_dest.tile == INVALID_TILE) {
02986     /* Try to find any safe destination. */
02987     PBSTileInfo origin = FollowTrainReservation(v);
02988     if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
02989       TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
02990       best_track = FindFirstTrack(res);
02991       TryReserveRailTrack(v->tile, TrackdirToTrack(GetVehicleTrackdir(v)));
02992       if (got_reservation != NULL) *got_reservation = true;
02993       if (changed_signal) MarkTileDirtyByTile(tile);
02994     } else {
02995       FreeTrainTrackReservation(v);
02996       if (mark_stuck) MarkTrainAsStuck(v);
02997     }
02998     return best_track;
02999   }
03000 
03001   if (got_reservation != NULL) *got_reservation = true;
03002 
03003   /* Reservation target found and free, check if it is safe. */
03004   while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
03005     /* Extend reservation until we have found a safe position. */
03006     DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
03007     TileIndex     next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
03008     TrackBits     reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
03009     if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
03010       reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
03011     }
03012 
03013     /* Get next order with destination. */
03014     if (orders.SwitchToNextOrder(true)) {
03015       PBSTileInfo cur_dest;
03016       DoTrainPathfind(v, next_tile, exitdir, reachable, NULL, true, &cur_dest);
03017       if (cur_dest.tile != INVALID_TILE) {
03018         res_dest = cur_dest;
03019         if (res_dest.okay) continue;
03020         /* Path found, but could not be reserved. */
03021         FreeTrainTrackReservation(v);
03022         if (mark_stuck) MarkTrainAsStuck(v);
03023         if (got_reservation != NULL) *got_reservation = false;
03024         changed_signal = false;
03025         break;
03026       }
03027     }
03028     /* No order or no safe position found, try any position. */
03029     if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
03030       FreeTrainTrackReservation(v);
03031       if (mark_stuck) MarkTrainAsStuck(v);
03032       if (got_reservation != NULL) *got_reservation = false;
03033       changed_signal = false;
03034     }
03035     break;
03036   }
03037 
03038   TryReserveRailTrack(v->tile, TrackdirToTrack(GetVehicleTrackdir(v)));
03039 
03040   if (changed_signal) MarkTileDirtyByTile(tile);
03041 
03042   return best_track;
03043 }
03044 
03053 bool TryPathReserve(Vehicle *v, bool mark_as_stuck, bool first_tile_okay)
03054 {
03055   assert(v->type == VEH_TRAIN && IsFrontEngine(v));
03056 
03057   /* We have to handle depots specially as the track follower won't look
03058    * at the depot tile itself but starts from the next tile. If we are still
03059    * inside the depot, a depot reservation can never be ours. */
03060   if (v->u.rail.track & TRACK_BIT_DEPOT) {
03061     if (GetDepotWaypointReservation(v->tile)) {
03062       if (mark_as_stuck) MarkTrainAsStuck(v);
03063       return false;
03064     } else {
03065       /* Depot not reserved, but the next tile might be. */
03066       TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
03067       if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
03068     }
03069   }
03070 
03071   /* Special check if we are in front of a two-sided conventional signal. */
03072   DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
03073   TileIndex next_tile = TileAddByDiagDir(v->tile, dir);
03074   if (IsTileType(next_tile, MP_RAILWAY) && HasReservedTracks(next_tile, DiagdirReachesTracks(dir))) {
03075     /* Can have only one reserved trackdir. */
03076     Trackdir td = FindFirstTrackdir(TrackBitsToTrackdirBits(GetReservedTrackbits(next_tile)) & DiagdirReachesTrackdirs(dir));
03077     if (HasSignalOnTrackdir(next_tile, td) && HasSignalOnTrackdir(next_tile, ReverseTrackdir(td)) &&
03078         !IsPbsSignal(GetSignalType(next_tile, TrackdirToTrack(td)))) {
03079       /* Signal already reserved, is not ours. */
03080       if (mark_as_stuck) MarkTrainAsStuck(v);
03081       return false;
03082     }
03083   }
03084 
03085   bool other_train = false;
03086   PBSTileInfo origin = FollowTrainReservation(v, &other_train);
03087   /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
03088   if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
03089     /* Can't be stuck then. */
03090     if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03091     ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
03092     return true;
03093   }
03094   /* The path we are driving on is alread blocked by some other train.
03095    * This can only happen when tracks and signals are changed. A crash
03096    * is probably imminent, don't do any further reservation because
03097    * it might cause stale reservations. */
03098   if (other_train && v->tile != origin.tile) {
03099     if (mark_as_stuck) MarkTrainAsStuck(v);
03100     return false;
03101   }
03102 
03103   /* If we are in a depot, tentativly reserve the depot. */
03104   if (v->u.rail.track & TRACK_BIT_DEPOT) {
03105     SetDepotWaypointReservation(v->tile, true);
03106     if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
03107   }
03108 
03109   DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
03110   TileIndex     new_tile = TileAddByDiagDir(origin.tile, exitdir);
03111   TrackBits     reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
03112 
03113   if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
03114 
03115   bool res_made = false;
03116   ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
03117 
03118   if (!res_made) {
03119     /* Free the depot reservation as well. */
03120     if (v->u.rail.track & TRACK_BIT_DEPOT) SetDepotWaypointReservation(v->tile, false);
03121     return false;
03122   }
03123 
03124   if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
03125     v->load_unload_time_rem = 0;
03126     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03127   }
03128   ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
03129   return true;
03130 }
03131 
03132 
03133 static bool CheckReverseTrain(Vehicle *v)
03134 {
03135   if (_settings_game.difficulty.line_reverse_mode != 0 ||
03136       v->u.rail.track == TRACK_BIT_DEPOT || v->u.rail.track == TRACK_BIT_WORMHOLE ||
03137       !(v->direction & 1)) {
03138     return false;
03139   }
03140 
03141   uint reverse_best = 0;
03142 
03143   assert(v->u.rail.track);
03144 
03145   switch (_settings_game.pf.pathfinder_for_trains) {
03146     case VPF_YAPF: /* YAPF */
03147       reverse_best = YapfCheckReverseTrain(v);
03148       break;
03149 
03150     case VPF_NPF: { /* NPF */
03151       NPFFindStationOrTileData fstd;
03152       NPFFoundTargetData ftd;
03153       Vehicle *last = GetLastVehicleInChain(v);
03154 
03155       NPFFillWithOrderData(&fstd, v);
03156 
03157       Trackdir trackdir = GetVehicleTrackdir(v);
03158       Trackdir trackdir_rev = ReverseTrackdir(GetVehicleTrackdir(last));
03159       assert(trackdir != INVALID_TRACKDIR);
03160       assert(trackdir_rev != INVALID_TRACKDIR);
03161 
03162       ftd = NPFRouteToStationOrTileTwoWay(v->tile, trackdir, false, last->tile, trackdir_rev, false, &fstd, TRANSPORT_RAIL, 0, v->owner, v->u.rail.compatible_railtypes);
03163       if (ftd.best_bird_dist != 0) {
03164         /* We didn't find anything, just keep on going straight ahead */
03165         reverse_best = false;
03166       } else {
03167         if (NPFGetFlag(&ftd.node, NPF_FLAG_REVERSE)) {
03168           reverse_best = true;
03169         } else {
03170           reverse_best = false;
03171         }
03172       }
03173     } break;
03174 
03175     default:
03176     case VPF_NTP: { /* NTP */
03177       TrainTrackFollowerData fd;
03178       FillWithStationData(&fd, v);
03179 
03180       int i = _search_directions[FindFirstTrack(v->u.rail.track)][DirToDiagDir(v->direction)];
03181 
03182       int best_track = -1;
03183       uint reverse = 0;
03184       uint best_bird_dist  = 0;
03185       uint best_track_dist = 0;
03186 
03187       for (;;) {
03188         fd.best_bird_dist = UINT_MAX;
03189         fd.best_track_dist = UINT_MAX;
03190 
03191         NewTrainPathfind(v->tile, v->dest_tile, v->u.rail.compatible_railtypes, (DiagDirection)(reverse ^ i), (NTPEnumProc*)NtpCallbFindStation, &fd);
03192 
03193         if (best_track != -1) {
03194           if (best_bird_dist != 0) {
03195             if (fd.best_bird_dist != 0) {
03196               /* neither reached the destination, pick the one with the smallest bird dist */
03197               if (fd.best_bird_dist > best_bird_dist) goto bad;
03198               if (fd.best_bird_dist < best_bird_dist) goto good;
03199             } else {
03200               /* we found the destination for the first time */
03201               goto good;
03202             }
03203           } else {
03204             if (fd.best_bird_dist != 0) {
03205               /* didn't find destination, but we've found the destination previously */
03206               goto bad;
03207             } else {
03208               /* both old & new reached the destination, compare track length */
03209               if (fd.best_track_dist > best_track_dist) goto bad;
03210               if (fd.best_track_dist < best_track_dist) goto good;
03211             }
03212           }
03213 
03214           /* if we reach this position, there's two paths of equal value so far.
03215            * pick one randomly. */
03216           int r = GB(Random(), 0, 8);
03217           if (_pick_track_table[i] == (v->direction & 3)) r += 80;
03218           if (_pick_track_table[best_track] == (v->direction & 3)) r -= 80;
03219           if (r <= 127) goto bad;
03220         }
03221 good:;
03222         best_track = i;
03223         best_bird_dist = fd.best_bird_dist;
03224         best_track_dist = fd.best_track_dist;
03225         reverse_best = reverse;
03226 bad:;
03227         if (reverse != 0) break;
03228         reverse = 2;
03229       }
03230     } break;
03231   }
03232 
03233   return reverse_best != 0;
03234 }
03235 
03236 TileIndex Train::GetOrderStationLocation(StationID station)
03237 {
03238   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
03239 
03240   const Station *st = GetStation(station);
03241   if (!(st->facilities & FACIL_TRAIN)) {
03242     /* The destination station has no trainstation tiles. */
03243     this->cur_order_index++;
03244     return 0;
03245   }
03246 
03247   return st->xy;
03248 }
03249 
03250 void Train::MarkDirty()
03251 {
03252   Vehicle *v = this;
03253   do {
03254     v->cur_image = v->GetImage(v->direction);
03255     MarkSingleVehicleDirty(v);
03256   } while ((v = v->Next()) != NULL);
03257 
03258   /* need to update acceleration and cached values since the goods on the train changed. */
03259   TrainCargoChanged(this);
03260   UpdateTrainAcceleration(this);
03261 }
03262 
03273 static int UpdateTrainSpeed(Vehicle *v)
03274 {
03275   uint accel;
03276 
03277   if (v->vehstatus & VS_STOPPED || HasBit(v->u.rail.flags, VRF_REVERSING) || HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
03278     switch (_settings_game.vehicle.train_acceleration_model) {
03279       default: NOT_REACHED();
03280       case TAM_ORIGINAL:  accel = v->acceleration * -4; break;
03281       case TAM_REALISTIC: accel = GetTrainAcceleration(v, AM_BRAKE); break;
03282     }
03283   } else {
03284     switch (_settings_game.vehicle.train_acceleration_model) {
03285       default: NOT_REACHED();
03286       case TAM_ORIGINAL:  accel = v->acceleration * 2; break;
03287       case TAM_REALISTIC: accel = GetTrainAcceleration(v, AM_ACCEL); break;
03288     }
03289   }
03290 
03291   uint spd = v->subspeed + accel;
03292   v->subspeed = (byte)spd;
03293   {
03294     int tempmax = v->max_speed;
03295     if (v->cur_speed > v->max_speed)
03296       tempmax = v->cur_speed - (v->cur_speed / 10) - 1;
03297     v->cur_speed = spd = Clamp(v->cur_speed + ((int)spd >> 8), 0, tempmax);
03298   }
03299 
03300   /* Scale speed by 3/4. Previously this was only done when the train was
03301    * facing diagonally and would apply to however many moves the train made
03302    * regardless the of direction actually moved in. Now it is always scaled,
03303    * 256 spd is used to go straight and 192 is used to go diagonally
03304    * (3/4 of 256). This results in the same effect, but without the error the
03305    * previous method caused.
03306    *
03307    * The scaling is done in this direction and not by multiplying the amount
03308    * to be subtracted by 4/3 so that the leftover speed can be saved in a
03309    * byte in v->progress.
03310    */
03311   int scaled_spd = spd * 3 >> 2;
03312 
03313   scaled_spd += v->progress;
03314   v->progress = 0; // set later in TrainLocoHandler or TrainController
03315   return scaled_spd;
03316 }
03317 
03318 static void TrainEnterStation(Vehicle *v, StationID station)
03319 {
03320   v->last_station_visited = station;
03321 
03322   /* check if a train ever visited this station before */
03323   Station *st = GetStation(station);
03324   if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
03325     st->had_vehicle_of_type |= HVOT_TRAIN;
03326     SetDParam(0, st->index);
03327     AddNewsItem(
03328       STR_8801_CITIZENS_CELEBRATE_FIRST,
03329       v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
03330       v->index,
03331       st->index
03332     );
03333     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
03334   }
03335 
03336   v->BeginLoading();
03337 
03338   StationAnimationTrigger(st, v->tile, STAT_ANIM_TRAIN_ARRIVES);
03339 }
03340 
03341 static byte AfterSetTrainPos(Vehicle *v, bool new_tile)
03342 {
03343   byte old_z = v->z_pos;
03344   v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
03345 
03346   if (new_tile) {
03347     ClrBit(v->u.rail.flags, VRF_GOINGUP);
03348     ClrBit(v->u.rail.flags, VRF_GOINGDOWN);
03349 
03350     if (v->u.rail.track == TRACK_BIT_X || v->u.rail.track == TRACK_BIT_Y) {
03351       /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped.
03352        * To check whether the current tile is sloped, and in which
03353        * direction it is sloped, we get the 'z' at the center of
03354        * the tile (middle_z) and the edge of the tile (old_z),
03355        * which we then can compare. */
03356       static const int HALF_TILE_SIZE = TILE_SIZE / 2;
03357       static const int INV_TILE_SIZE_MASK = ~(TILE_SIZE - 1);
03358 
03359       byte middle_z = GetSlopeZ((v->x_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE, (v->y_pos & INV_TILE_SIZE_MASK) | HALF_TILE_SIZE);
03360 
03361       /* For some reason tunnel tiles are always given as sloped :(
03362        * But they are not sloped... */
03363       if (middle_z != v->z_pos && !IsTunnelTile(TileVirtXY(v->x_pos, v->y_pos))) {
03364         SetBit(v->u.rail.flags, (middle_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN);
03365       }
03366     }
03367   }
03368 
03369   VehiclePositionChanged(v);
03370   EndVehicleMove(v);
03371   return old_z;
03372 }
03373 
03374 static const Direction _new_vehicle_direction_table[11] = {
03375   DIR_N , DIR_NW, DIR_W , INVALID_DIR,
03376   DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
03377   DIR_E , DIR_SE, DIR_S
03378 };
03379 
03380 static inline Direction GetNewVehicleDirectionByTile(TileIndex new_tile, TileIndex old_tile)
03381 {
03382   uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
03383               TileX(new_tile) - TileX(old_tile) + 1;
03384   assert(offs < 11);
03385   return _new_vehicle_direction_table[offs];
03386 }
03387 
03388 static inline int GetDirectionToVehicle(const Vehicle *v, int x, int y)
03389 {
03390   byte offs;
03391 
03392   x -= v->x_pos;
03393   if (x >= 0) {
03394     offs = (x > 2) ? 0 : 1;
03395   } else {
03396     offs = (x < -2) ? 2 : 1;
03397   }
03398 
03399   y -= v->y_pos;
03400   if (y >= 0) {
03401     offs += ((y > 2) ? 0 : 1) * 4;
03402   } else {
03403     offs += ((y < -2) ? 2 : 1) * 4;
03404   }
03405 
03406   assert(offs < 11);
03407   return _new_vehicle_direction_table[offs];
03408 }
03409 
03410 /* Check if the vehicle is compatible with the specified tile */
03411 static inline bool CheckCompatibleRail(const Vehicle *v, TileIndex tile)
03412 {
03413   return
03414     IsTileOwner(tile, v->owner) && (
03415       !IsFrontEngine(v) ||
03416       HasBit(v->u.rail.compatible_railtypes, GetRailType(tile))
03417     );
03418 }
03419 
03420 struct RailtypeSlowdownParams {
03421   byte small_turn, large_turn;
03422   byte z_up; // fraction to remove when moving up
03423   byte z_down; // fraction to remove when moving down
03424 };
03425 
03426 static const RailtypeSlowdownParams _railtype_slowdown[] = {
03427   // normal accel
03428   {256 / 4, 256 / 2, 256 / 4, 2}, 
03429   {256 / 4, 256 / 2, 256 / 4, 2}, 
03430   {256 / 4, 256 / 2, 256 / 4, 2}, 
03431   {0,       256 / 2, 256 / 4, 2}, 
03432 };
03433 
03435 static inline void AffectSpeedByDirChange(Vehicle *v, Direction new_dir)
03436 {
03437   if (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL) return;
03438 
03439   DirDiff diff = DirDifference(v->direction, new_dir);
03440   if (diff == DIRDIFF_SAME) return;
03441 
03442   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->u.rail.railtype];
03443   v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
03444 }
03445 
03447 static inline void AffectSpeedByZChange(Vehicle *v, byte old_z)
03448 {
03449   if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL) return;
03450 
03451   const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->u.rail.railtype];
03452 
03453   if (old_z < v->z_pos) {
03454     v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
03455   } else {
03456     uint16 spd = v->cur_speed + rsp->z_down;
03457     if (spd <= v->max_speed) v->cur_speed = spd;
03458   }
03459 }
03460 
03461 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
03462 {
03463   if (IsTileType(tile, MP_RAILWAY) &&
03464       GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
03465     TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
03466     Trackdir trackdir = FindFirstTrackdir(tracks);
03467     if (UpdateSignalsOnSegment(tile,  TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
03468       /* A PBS block with a non-PBS signal facing us? */
03469       if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
03470     }
03471   }
03472   return false;
03473 }
03474 
03475 
03476 static void SetVehicleCrashed(Vehicle *v)
03477 {
03478   if (v->u.rail.crash_anim_pos != 0) return;
03479 
03480   /* Free a possible path reservation and try to mark all tiles occupied by the train reserved. */
03481   if (IsFrontEngine(v)) {
03482     /* Remove all reservations, also the ones currently under the train
03483      * and any railway station paltform reservation. */
03484     FreeTrainTrackReservation(v);
03485     for (const Vehicle *u = v; u != NULL; u = u->Next()) {
03486       ClearPathReservation(u, u->tile, GetVehicleTrackdir(u));
03487       if (IsTileType(u->tile, MP_TUNNELBRIDGE)) {
03488         /* ClearPathReservation will not free the wormhole exit
03489          * if the train has just entered the wormhole. */
03490         SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(u->tile), false);
03491       }
03492     }
03493   }
03494 
03495   /* we may need to update crossing we were approaching */
03496   TileIndex crossing = TrainApproachingCrossingTile(v);
03497 
03498   v->u.rail.crash_anim_pos++;
03499 
03500   InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
03501   InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
03502 
03503   if (v->u.rail.track == TRACK_BIT_DEPOT) {
03504     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
03505   }
03506 
03507   InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
03508 
03509   for (; v != NULL; v = v->Next()) {
03510     v->vehstatus |= VS_CRASHED;
03511     MarkSingleVehicleDirty(v);
03512   }
03513 
03514   /* must be updated after the train has been marked crashed */
03515   if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
03516 }
03517 
03518 static uint CountPassengersInTrain(const Vehicle *v)
03519 {
03520   uint num = 0;
03521 
03522   for (; v != NULL; v = v->Next()) {
03523     if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) num += v->cargo.Count();
03524   }
03525 
03526   return num;
03527 }
03528 
03535 static uint TrainCrashed(Vehicle *v)
03536 {
03537   /* do not crash train twice */
03538   if (v->vehstatus & VS_CRASHED) return 0;
03539 
03540   /* two drivers + passengers */
03541   uint num = 2 + CountPassengersInTrain(v);
03542 
03543   SetVehicleCrashed(v);
03544   AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_TRAIN));
03545 
03546   return num;
03547 }
03548 
03549 struct TrainCollideChecker {
03550   Vehicle *v;  
03551   uint num;    
03552 };
03553 
03554 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
03555 {
03556   TrainCollideChecker *tcc = (TrainCollideChecker*)data;
03557 
03558   if (v->type != VEH_TRAIN) return NULL;
03559 
03560   /* get first vehicle now to make most usual checks faster */
03561   Vehicle *coll = v->First();
03562 
03563   /* can't collide with own wagons && can't crash in depot && the same height level */
03564   if (coll != tcc->v && v->u.rail.track != TRACK_BIT_DEPOT && abs(v->z_pos - tcc->v->z_pos) < 6) {
03565     int x_diff = v->x_pos - tcc->v->x_pos;
03566     int y_diff = v->y_pos - tcc->v->y_pos;
03567 
03568     /* needed to disable possible crash of competitor train in station by building diagonal track at its end */
03569     if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
03570 
03571     /* crash both trains */
03572     tcc->num += TrainCrashed(tcc->v);
03573     tcc->num += TrainCrashed(coll);
03574 
03575     /* Try to reserve all tiles directly under the crashed trains.
03576      * As there might be more than two trains involved, we have to do that for all vehicles */
03577     const Vehicle *u;
03578     FOR_ALL_VEHICLES(u) {
03579       if (u->type == VEH_TRAIN && HASBITS(u->vehstatus, VS_CRASHED) && (u->u.rail.track & TRACK_BIT_DEPOT) == TRACK_BIT_NONE) {
03580         TrackBits trackbits = u->u.rail.track;
03581         if ((trackbits & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
03582           /* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
03583           trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(u->tile));
03584         }
03585         TryReserveRailTrack(u->tile, TrackBitsToTrack(trackbits));
03586       }
03587     }
03588   }
03589 
03590   return NULL;
03591 }
03592 
03599 static bool CheckTrainCollision(Vehicle *v)
03600 {
03601   /* can't collide in depot */
03602   if (v->u.rail.track == TRACK_BIT_DEPOT) return false;
03603 
03604   assert(v->u.rail.track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
03605 
03606   TrainCollideChecker tcc;
03607   tcc.v = v;
03608   tcc.num = 0;
03609 
03610   /* find colliding vehicles */
03611   if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
03612     FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
03613     FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
03614   } else {
03615     FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
03616   }
03617 
03618   /* any dead -> no crash */
03619   if (tcc.num == 0) return false;
03620 
03621   SetDParam(0, tcc.num);
03622   AddNewsItem(STR_8868_TRAIN_CRASH_DIE_IN_FIREBALL,
03623     NS_ACCIDENT_VEHICLE,
03624     v->index,
03625     0
03626   );
03627 
03628   ModifyStationRatingAround(v->tile, v->owner, -160, 30);
03629   SndPlayVehicleFx(SND_13_BIG_CRASH, v);
03630   return true;
03631 }
03632 
03633 static Vehicle *CheckVehicleAtSignal(Vehicle *v, void *data)
03634 {
03635   DiagDirection exitdir = *(DiagDirection *)data;
03636 
03637   /* front engine of a train, not inside wormhole or depot, not crashed */
03638   if (v->type == VEH_TRAIN && IsFrontEngine(v) && (v->u.rail.track & TRACK_BIT_MASK) != 0 && !(v->vehstatus & VS_CRASHED)) {
03639     if (v->cur_speed <= 5 && TrainExitDir(v->direction, v->u.rail.track) == exitdir) return v;
03640   }
03641 
03642   return NULL;
03643 }
03644 
03645 static void TrainController(Vehicle *v, Vehicle *nomove, bool update_image)
03646 {
03647   Vehicle *prev;
03648 
03649   /* For every vehicle after and including the given vehicle */
03650   for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
03651     DiagDirection enterdir = DIAGDIR_BEGIN;
03652     bool update_signals_crossing = false; // will we update signals or crossing state?
03653     BeginVehicleMove(v);
03654 
03655     GetNewVehiclePosResult gp = GetNewVehiclePos(v);
03656     if (v->u.rail.track != TRACK_BIT_WORMHOLE) {
03657       /* Not inside tunnel */
03658       if (gp.old_tile == gp.new_tile) {
03659         /* Staying in the old tile */
03660         if (v->u.rail.track == TRACK_BIT_DEPOT) {
03661           /* Inside depot */
03662           gp.x = v->x_pos;
03663           gp.y = v->y_pos;
03664         } else {
03665           /* Not inside depot */
03666 
03667           /* Reverse when we are at the end of the track already, do not move to the new position */
03668           if (IsFrontEngine(v) && !TrainCheckIfLineEnds(v)) return;
03669 
03670           uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03671           if (HasBit(r, VETS_CANNOT_ENTER)) {
03672             goto invalid_rail;
03673           }
03674           if (HasBit(r, VETS_ENTERED_STATION)) {
03675             /* The new position is the end of the platform */
03676             TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03677           }
03678         }
03679       } else {
03680         /* A new tile is about to be entered. */
03681 
03682         /* Determine what direction we're entering the new tile from */
03683         Direction dir = GetNewVehicleDirectionByTile(gp.new_tile, gp.old_tile);
03684         enterdir = DirToDiagDir(dir);
03685         assert(IsValidDiagDirection(enterdir));
03686 
03687         /* Get the status of the tracks in the new tile and mask
03688          * away the bits that aren't reachable. */
03689         TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
03690         TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
03691 
03692         TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03693         TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
03694 
03695         TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03696         if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg && prev == NULL) {
03697           /* We allow wagons to make 90 deg turns, because forbid_90_deg
03698            * can be switched on halfway a turn */
03699           bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track));
03700         }
03701 
03702         if (bits == TRACK_BIT_NONE) goto invalid_rail;
03703 
03704         /* Check if the new tile contrains tracks that are compatible
03705          * with the current train, if not, bail out. */
03706         if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
03707 
03708         TrackBits chosen_track;
03709         if (prev == NULL) {
03710           /* Currently the locomotive is active. Determine which one of the
03711            * available tracks to choose */
03712           chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
03713           assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
03714 
03715           /* Check if it's a red signal and that force proceed is not clicked. */
03716           if (red_signals & chosen_track && v->u.rail.force_proceed == 0) {
03717             /* In front of a red signal */
03718             Trackdir i = FindFirstTrackdir(trackdirbits);
03719 
03720             /* Don't handle stuck trains here. */
03721             if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) return;
03722 
03723             if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
03724               v->cur_speed = 0;
03725               v->subspeed = 0;
03726               v->progress = 255 - 100;
03727               if (_settings_game.pf.wait_oneway_signal == 255 || ++v->load_unload_time_rem < _settings_game.pf.wait_oneway_signal * 20) return;
03728             } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
03729               v->cur_speed = 0;
03730               v->subspeed = 0;
03731               v->progress = 255 - 10;
03732               if (_settings_game.pf.wait_twoway_signal == 255 || ++v->load_unload_time_rem < _settings_game.pf.wait_twoway_signal * 73) {
03733                 DiagDirection exitdir = TrackdirToExitdir(i);
03734                 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
03735 
03736                 exitdir = ReverseDiagDir(exitdir);
03737 
03738                 /* check if a train is waiting on the other side */
03739                 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckVehicleAtSignal)) return;
03740               }
03741             }
03742 
03743             /* If we would reverse but are currently in a PBS block and
03744              * reversing of stuck trains is disabled, don't reverse. */
03745             if (_settings_game.pf.wait_for_pbs_path == 255 && UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
03746               v->load_unload_time_rem = 0;
03747               return;
03748             }
03749             goto reverse_train_direction;
03750           } else {
03751             TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
03752           }
03753         } else {
03754           static const TrackBits _matching_tracks[8] = {
03755               TRACK_BIT_LEFT  | TRACK_BIT_RIGHT, TRACK_BIT_X,
03756               TRACK_BIT_UPPER | TRACK_BIT_LOWER, TRACK_BIT_Y,
03757               TRACK_BIT_LEFT  | TRACK_BIT_RIGHT, TRACK_BIT_X,
03758               TRACK_BIT_UPPER | TRACK_BIT_LOWER, TRACK_BIT_Y
03759           };
03760 
03761           /* The wagon is active, simply follow the prev vehicle. */
03762           chosen_track = (TrackBits)(byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits);
03763         }
03764 
03765         /* Make sure chosen track is a valid track */
03766         assert(
03767             chosen_track == TRACK_BIT_X     || chosen_track == TRACK_BIT_Y ||
03768             chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
03769             chosen_track == TRACK_BIT_LEFT  || chosen_track == TRACK_BIT_RIGHT);
03770 
03771         /* Update XY to reflect the entrance to the new tile, and select the direction to use */
03772         const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
03773         gp.x = (gp.x & ~0xF) | b[0];
03774         gp.y = (gp.y & ~0xF) | b[1];
03775         Direction chosen_dir = (Direction)b[2];
03776 
03777         /* Call the landscape function and tell it that the vehicle entered the tile */
03778         uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03779         if (HasBit(r, VETS_CANNOT_ENTER)) {
03780           goto invalid_rail;
03781         }
03782 
03783         if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
03784           Track track = FindFirstTrack(chosen_track);
03785           Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
03786           if (IsFrontEngine(v) && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
03787             SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
03788             MarkTileDirtyByTile(gp.new_tile);
03789           }
03790 
03791           /* Clear any track reservation when the last vehicle leaves the tile */
03792           if (v->Next() == NULL) ClearPathReservation(v, v->tile, GetVehicleTrackdir(v));
03793 
03794           v->tile = gp.new_tile;
03795 
03796           if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
03797             TrainPowerChanged(v->First());
03798           }
03799 
03800           v->u.rail.track = chosen_track;
03801           assert(v->u.rail.track);
03802         }
03803 
03804         /* We need to update signal status, but after the vehicle position hash
03805          * has been updated by AfterSetTrainPos() */
03806         update_signals_crossing = true;
03807 
03808         if (prev == NULL) AffectSpeedByDirChange(v, chosen_dir);
03809 
03810         v->direction = chosen_dir;
03811 
03812         if (IsFrontEngine(v)) {
03813           v->load_unload_time_rem = 0;
03814 
03815           /* If we are approching a crossing that is reserved, play the sound now. */
03816           TileIndex crossing = TrainApproachingCrossingTile(v);
03817           if (crossing != INVALID_TILE && GetCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
03818 
03819           /* Always try to extend the reservation when entering a tile. */
03820           CheckNextTrainTile(v);
03821         }
03822       }
03823     } else {
03824       /* In a tunnel or on a bridge
03825        * - for tunnels, only the part when the vehicle is not visible (part of enter/exit tile too)
03826        * - for bridges, only the middle part - without the bridge heads */
03827       if (!(v->vehstatus & VS_HIDDEN)) {
03828         v->cur_speed =
03829           min(v->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
03830       }
03831 
03832       if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
03833         /* Perform look-ahead on tunnel exit. */
03834         if (IsFrontEngine(v)) {
03835           TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
03836           CheckNextTrainTile(v);
03837         }
03838       } else {
03839         v->x_pos = gp.x;
03840         v->y_pos = gp.y;
03841         VehiclePositionChanged(v);
03842         if (!(v->vehstatus & VS_HIDDEN)) EndVehicleMove(v);
03843         continue;
03844       }
03845     }
03846 
03847     /* update image of train, as well as delta XY */
03848     v->UpdateDeltaXY(v->direction);
03849     if (update_image) v->cur_image = v->GetImage(v->direction);
03850 
03851     v->x_pos = gp.x;
03852     v->y_pos = gp.y;
03853 
03854     /* update the Z position of the vehicle */
03855     byte old_z = AfterSetTrainPos(v, (gp.new_tile != gp.old_tile));
03856 
03857     if (prev == NULL) {
03858       /* This is the first vehicle in the train */
03859       AffectSpeedByZChange(v, old_z);
03860     }
03861 
03862     if (update_signals_crossing) {
03863       if (IsFrontEngine(v)) {
03864         if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
03865           /* We are entering a block with PBS signals right now, but
03866            * not through a PBS signal. This means we don't have a
03867            * reservation right now. As a conventional signal will only
03868            * ever be green if no other train is in the block, getting
03869            * a path should always be possible. If the player built
03870            * such a strange network that it is not possible, the train
03871            * will be marked as stuck and the player has to deal with
03872            * the problem. */
03873           if ((!HasReservedTracks(gp.new_tile, v->u.rail.track) &&
03874               !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->u.rail.track))) ||
03875               !TryPathReserve(v)) {
03876             MarkTrainAsStuck(v);
03877           }
03878         }
03879       }
03880 
03881       /* Signals can only change when the first
03882        * (above) or the last vehicle moves. */
03883       if (v->Next() == NULL) {
03884         TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
03885         if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
03886       }
03887     }
03888 
03889     /* Do not check on every tick to save some computing time. */
03890     if (IsFrontEngine(v) && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
03891   }
03892   return;
03893 
03894 invalid_rail:
03895   /* We've reached end of line?? */
03896   if (prev != NULL) error("Disconnecting train");
03897 
03898 reverse_train_direction:
03899   v->load_unload_time_rem = 0;
03900   v->cur_speed = 0;
03901   v->subspeed = 0;
03902   ReverseTrainDirection(v);
03903 }
03904 
03910 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
03911 {
03912   TrackBits *trackbits = (TrackBits *)data;
03913 
03914   if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
03915     if ((v->u.rail.track & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
03916       /* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
03917       *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
03918     } else {
03919       *trackbits |= v->u.rail.track;
03920     }
03921   }
03922 
03923   return NULL;
03924 }
03925 
03933 static void DeleteLastWagon(Vehicle *v)
03934 {
03935   Vehicle *first = v->First();
03936 
03937   /* Go to the last wagon and delete the link pointing there
03938    * *u is then the one-before-last wagon, and *v the last
03939    * one which will physicially be removed */
03940   Vehicle *u = v;
03941   for (; v->Next() != NULL; v = v->Next()) u = v;
03942   u->SetNext(NULL);
03943 
03944   if (first != v) {
03945     /* Recalculate cached train properties */
03946     TrainConsistChanged(first, false);
03947     /* Update the depot window if the first vehicle is in depot -
03948      * if v == first, then it is updated in PreDestructor() */
03949     if (first->u.rail.track == TRACK_BIT_DEPOT) {
03950       InvalidateWindow(WC_VEHICLE_DEPOT, first->tile);
03951     }
03952   }
03953 
03954   /* 'v' shouldn't be accessed after it has been deleted */
03955   TrackBits trackbits = v->u.rail.track;
03956   TileIndex tile = v->tile;
03957   Owner owner = v->owner;
03958 
03959   delete v;
03960   v = NULL; // make sure nobody will try to read 'v' anymore
03961 
03962   if ((trackbits & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
03963     /* Vehicle is inside a wormhole, v->u.rail.track contains no useful value then. */
03964     trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
03965   }
03966 
03967   Track track = TrackBitsToTrack(trackbits);
03968   if (HasReservedTracks(tile, trackbits)) {
03969     UnreserveRailTrack(tile, track);
03970 
03971     /* If there are still crashed vehicles on the tile, give the track reservation to them */
03972     TrackBits remaining_trackbits = TRACK_BIT_NONE;
03973     FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
03974 
03975     /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
03976     assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
03977     for (Track t = TRACK_BEGIN; t < TRACK_END; t++) {
03978       if (HasBit(remaining_trackbits, t)) {
03979         TryReserveRailTrack(tile, t);
03980       }
03981     }
03982   }
03983 
03984   /* check if the wagon was on a road/rail-crossing */
03985   if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
03986 
03987   /* Update signals */
03988   if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
03989     UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
03990   } else {
03991     SetSignalsOnBothDir(tile, track, owner);
03992   }
03993 }
03994 
03995 static void ChangeTrainDirRandomly(Vehicle *v)
03996 {
03997   static const DirDiff delta[] = {
03998     DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
03999   };
04000 
04001   do {
04002     /* We don't need to twist around vehicles if they're not visible */
04003     if (!(v->vehstatus & VS_HIDDEN)) {
04004       v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
04005       BeginVehicleMove(v);
04006       v->UpdateDeltaXY(v->direction);
04007       v->cur_image = v->GetImage(v->direction);
04008       /* Refrain from updating the z position of the vehicle when on
04009        * a bridge, because AfterSetTrainPos will put the vehicle under
04010        * the bridge in that case */
04011       if (v->u.rail.track != TRACK_BIT_WORMHOLE) AfterSetTrainPos(v, false);
04012     }
04013   } while ((v = v->Next()) != NULL);
04014 }
04015 
04016 static void HandleCrashedTrain(Vehicle *v)
04017 {
04018   int state = ++v->u.rail.crash_anim_pos;
04019 
04020   if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
04021     CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
04022   }
04023 
04024   uint32 r;
04025   if (state <= 200 && Chance16R(1, 7, r)) {
04026     int index = (r * 10 >> 16);
04027 
04028     Vehicle *u = v;
04029     do {
04030       if (--index < 0) {
04031         r = Random();
04032 
04033         CreateEffectVehicleRel(u,
04034           GB(r,  8, 3) + 2,
04035           GB(r, 16, 3) + 2,
04036           GB(r,  0, 3) + 5,
04037           EV_EXPLOSION_SMALL);
04038         break;
04039       }
04040     } while ((u = u->Next()) != NULL);
04041   }
04042 
04043   if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
04044 
04045   if (state >= 4440 && !(v->tick_counter & 0x1F)) {
04046     DeleteLastWagon(v);
04047     InvalidateWindow(WC_REPLACE_VEHICLE, (v->group_id << 16) | VEH_TRAIN);
04048   }
04049 }
04050 
04051 static void HandleBrokenTrain(Vehicle *v)
04052 {
04053   if (v->breakdown_ctr != 1) {
04054     v->breakdown_ctr = 1;
04055     v->cur_speed = 0;
04056 
04057     if (v->breakdowns_since_last_service != 255)
04058       v->breakdowns_since_last_service++;
04059 
04060     InvalidateWindow(WC_VEHICLE_VIEW, v->index);
04061     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
04062 
04063     if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
04064       SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
04065         SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
04066     }
04067 
04068     if (!(v->vehstatus & VS_HIDDEN)) {
04069       Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
04070       if (u != NULL) u->u.effect.animation_state = v->breakdown_delay * 2;
04071     }
04072   }
04073 
04074   if (!(v->tick_counter & 3)) {
04075     if (!--v->breakdown_delay) {
04076       v->breakdown_ctr = 0;
04077       InvalidateWindow(WC_VEHICLE_VIEW, v->index);
04078     }
04079   }
04080 }
04081 
04083 static const uint16 _breakdown_speeds[16] = {
04084   225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
04085 };
04086 
04087 
04095 static bool TrainApproachingLineEnd(Vehicle *v, bool signal)
04096 {
04097   /* Calc position within the current tile */
04098   uint x = v->x_pos & 0xF;
04099   uint y = v->y_pos & 0xF;
04100 
04101   /* for diagonal directions, 'x' will be 0..15 -
04102    * for other directions, it will be 1, 3, 5, ..., 15 */
04103   switch (v->direction) {
04104     case DIR_N : x = ~x + ~y + 25; break;
04105     case DIR_NW: x = y;            /* FALLTHROUGH */
04106     case DIR_NE: x = ~x + 16;      break;
04107     case DIR_E : x = ~x + y + 9;   break;
04108     case DIR_SE: x = y;            break;
04109     case DIR_S : x = x + y - 7;    break;
04110     case DIR_W : x = ~y + x + 9;   break;
04111     default: break;
04112   }
04113 
04114   /* do not reverse when approaching red signal */
04115   if (!signal && x + (v->u.rail.cached_veh_length + 1) / 2 >= TILE_SIZE) {
04116     /* we are too near the tile end, reverse now */
04117     v->cur_speed = 0;
04118     ReverseTrainDirection(v);
04119     return false;
04120   }
04121 
04122   /* slow down */
04123   v->vehstatus |= VS_TRAIN_SLOWING;
04124   uint16 break_speed = _breakdown_speeds[x & 0xF];
04125   if (break_speed < v->cur_speed) v->cur_speed = break_speed;
04126 
04127   return true;
04128 }
04129 
04130 
04136 static bool TrainCanLeaveTile(const Vehicle *v)
04137 {
04138   /* Exit if inside a tunnel/bridge or a depot */
04139   if (v->u.rail.track == TRACK_BIT_WORMHOLE || v->u.rail.track == TRACK_BIT_DEPOT) return false;
04140 
04141   TileIndex tile = v->tile;
04142 
04143   /* entering a tunnel/bridge? */
04144   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
04145     DiagDirection dir = GetTunnelBridgeDirection(tile);
04146     if (DiagDirToDir(dir) == v->direction) return false;
04147   }
04148 
04149   /* entering a depot? */
04150   if (IsRailDepotTile(tile)) {
04151     DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
04152     if (DiagDirToDir(dir) == v->direction) return false;
04153   }
04154 
04155   return true;
04156 }
04157 
04158 
04166 static TileIndex TrainApproachingCrossingTile(const Vehicle *v)
04167 {
04168   assert(IsFrontEngine(v));
04169   assert(!(v->vehstatus & VS_CRASHED));
04170 
04171   if (!TrainCanLeaveTile(v)) return INVALID_TILE;
04172 
04173   DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
04174   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
04175 
04176   /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
04177   if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
04178       !CheckCompatibleRail(v, tile)) {
04179     return INVALID_TILE;
04180   }
04181 
04182   return tile;
04183 }
04184 
04185 
04192 static bool TrainCheckIfLineEnds(Vehicle *v)
04193 {
04194   /* First, handle broken down train */
04195 
04196   int t = v->breakdown_ctr;
04197   if (t > 1) {
04198     v->vehstatus |= VS_TRAIN_SLOWING;
04199 
04200     uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
04201     if (break_speed < v->cur_speed) v->cur_speed = break_speed;
04202   } else {
04203     v->vehstatus &= ~VS_TRAIN_SLOWING;
04204   }
04205 
04206   if (!TrainCanLeaveTile(v)) return true;
04207 
04208   /* Determine the non-diagonal direction in which we will exit this tile */
04209   DiagDirection dir = TrainExitDir(v->direction, v->u.rail.track);
04210   /* Calculate next tile */
04211   TileIndex tile = v->tile + TileOffsByDiagDir(dir);
04212 
04213   /* Determine the track status on the next tile */
04214   TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
04215   TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
04216 
04217   TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
04218   TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
04219 
04220   /* We are sure the train is not entering a depot, it is detected above */
04221 
04222   /* mask unreachable track bits if we are forbidden to do 90deg turns */
04223   TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
04224   if (_settings_game.pf.pathfinder_for_trains != VPF_NTP && _settings_game.pf.forbid_90_deg) {
04225     bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track));
04226   }
04227 
04228   /* no suitable trackbits at all || unusable rail (wrong type or owner) */
04229   if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
04230     return TrainApproachingLineEnd(v, false);
04231   }
04232 
04233   /* approaching red signal */
04234   if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true);
04235 
04236   /* approaching a rail/road crossing? then make it red */
04237   if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
04238 
04239   return true;
04240 }
04241 
04242 
04243 static void TrainLocoHandler(Vehicle *v, bool mode)
04244 {
04245   /* train has crashed? */
04246   if (v->vehstatus & VS_CRASHED) {
04247     if (!mode) HandleCrashedTrain(v);
04248     return;
04249   }
04250 
04251   if (v->u.rail.force_proceed != 0) {
04252     v->u.rail.force_proceed--;
04253     ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
04254     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
04255   }
04256 
04257   /* train is broken down? */
04258   if (v->breakdown_ctr != 0) {
04259     if (v->breakdown_ctr <= 2) {
04260       HandleBrokenTrain(v);
04261       return;
04262     }
04263     if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
04264   }
04265 
04266   if (HasBit(v->u.rail.flags, VRF_REVERSING) && v->cur_speed == 0) {
04267     ReverseTrainDirection(v);
04268   }
04269 
04270   /* exit if train is stopped */
04271   if (v->vehstatus & VS_STOPPED && v->cur_speed == 0) return;
04272 
04273   bool valid_order = v->current_order.IsValid() && v->current_order.GetType() != OT_CONDITIONAL;
04274   if (ProcessOrders(v) && CheckReverseTrain(v)) {
04275     v->load_unload_time_rem = 0;
04276     v->cur_speed = 0;
04277     v->subspeed = 0;
04278     ReverseTrainDirection(v);
04279     return;
04280   }
04281 
04282   v->HandleLoading(mode);
04283 
04284   if (v->current_order.IsType(OT_LOADING)) return;
04285 
04286   if (CheckTrainStayInDepot(v)) return;
04287 
04288   if (!mode) HandleLocomotiveSmokeCloud(v);
04289 
04290   /* We had no order but have an order now, do look ahead. */
04291   if (!valid_order && v->current_order.IsValid()) {
04292     CheckNextTrainTile(v);
04293   }
04294 
04295   /* Handle stuck trains. */
04296   if (!mode && HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
04297     ++v->load_unload_time_rem;
04298 
04299     /* Should we try reversing this tick if still stuck? */
04300     bool turn_around = v->load_unload_time_rem % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.wait_for_pbs_path < 255;
04301 
04302     if (!turn_around && v->load_unload_time_rem % _settings_game.pf.path_backoff_interval != 0 && v->u.rail.force_proceed == 0) return;
04303     if (!TryPathReserve(v)) {
04304       /* Still stuck. */
04305       if (turn_around) ReverseTrainDirection(v);
04306 
04307       if (HasBit(v->u.rail.flags, VRF_TRAIN_STUCK) && v->load_unload_time_rem > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
04308         /* Show message to player. */
04309         if (_settings_client.gui.lost_train_warn && v->owner == _local_company) {
04310           SetDParam(0, v->index);
04311           AddNewsItem(
04312             STR_TRAIN_IS_STUCK,
04313             NS_ADVICE,
04314             v->index,
04315             0);
04316         }
04317         v->load_unload_time_rem = 0;
04318       }
04319       /* Exit if force proceed not pressed, else reset stuck flag anyway. */
04320       if (v->u.rail.force_proceed == 0) return;
04321       ClrBit(v->u.rail.flags, VRF_TRAIN_STUCK);
04322       v->load_unload_time_rem = 0;
04323       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
04324     }
04325   }
04326 
04327   if (v->current_order.IsType(OT_LEAVESTATION)) {
04328     v->current_order.Free();
04329     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
04330     return;
04331   }
04332 
04333   int j = UpdateTrainSpeed(v);
04334 
04335   /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
04336   if (v->cur_speed == 0 && v->u.rail.last_speed == 0 && v->vehstatus & VS_STOPPED) {
04337     InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
04338   }
04339 
04340   int adv_spd = (v->direction & 1) ? 192 : 256;
04341   if (j < adv_spd) {
04342     /* if the vehicle has speed 0, update the last_speed field. */
04343     if (v->cur_speed == 0) SetLastSpeed(v, v->cur_speed);
04344   } else {
04345     TrainCheckIfLineEnds(v);
04346     /* Loop until the train has finished moving. */
04347     do {
04348       j -= adv_spd;
04349       TrainController(v, NULL, true);
04350       /* Don't continue to move if the train crashed. */
04351       if (CheckTrainCollision(v)) break;
04352       /* 192 spd used for going straight, 256 for going diagonally. */
04353       adv_spd = (v->direction & 1) ? 192 : 256;
04354     } while (j >= adv_spd);
04355     SetLastSpeed(v, v->cur_speed);
04356   }
04357 
04358   if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
04359 }
04360 
04361 
04362 
04363 Money Train::GetRunningCost() const
04364 {
04365   Money cost = 0;
04366   const Vehicle *v = this;
04367 
04368   do {
04369     const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
04370 
04371     byte cost_factor = GetVehicleProperty(v, 0x0D, rvi->running_cost);
04372     if (cost_factor == 0) continue;
04373 
04374     /* Halve running cost for multiheaded parts */
04375     if (IsMultiheaded(v)) cost_factor /= 2;
04376 
04377     cost += cost_factor * GetPriceByIndex(rvi->running_cost_class);
04378   } while ((v = GetNextVehicle(v)) != NULL);
04379 
04380   return cost;
04381 }
04382 
04383 
04384 void Train::Tick()
04385 {
04386   if (_age_cargo_skip_counter == 0) this->cargo.AgeCargo();
04387 
04388   this->tick_counter++;
04389 
04390   if (IsFrontEngine(this)) {
04391     if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
04392     this->current_order_time++;
04393 
04394     TrainLocoHandler(this, false);
04395 
04396     /* make sure vehicle wasn't deleted. */
04397     if (this->type == VEH_TRAIN && IsFrontEngine(this))
04398       TrainLocoHandler(this, true);
04399   } else if (IsFreeWagon(this) && HASBITS(this->vehstatus, VS_CRASHED)) {
04400     /* Delete flooded standalone wagon chain */
04401     if (++this->u.rail.crash_anim_pos >= 4400) delete this;
04402   }
04403 }
04404 
04405 static void CheckIfTrainNeedsService(Vehicle *v)
04406 {
04407   static const uint MAX_ACCEPTABLE_DEPOT_DIST = 16;
04408 
04409   if (_settings_game.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
04410   if (v->IsInDepot()) {
04411     VehicleServiceInDepot(v);
04412     return;
04413   }
04414 
04415   TrainFindDepotData tfdd = FindClosestTrainDepot(v, MAX_ACCEPTABLE_DEPOT_DIST);
04416   /* Only go to the depot if it is not too far out of our way. */
04417   if (tfdd.best_length == UINT_MAX || tfdd.best_length > MAX_ACCEPTABLE_DEPOT_DIST) {
04418     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
04419       /* If we were already heading for a depot but it has
04420        * suddenly moved farther away, we continue our normal
04421        * schedule? */
04422       v->current_order.MakeDummy();
04423       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
04424     }
04425     return;
04426   }
04427 
04428   const Depot *depot = GetDepotByTile(tfdd.tile);
04429 
04430   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
04431       v->current_order.GetDestination() != depot->index &&
04432       !Chance16(3, 16)) {
04433     return;
04434   }
04435 
04436   v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
04437   v->dest_tile = tfdd.tile;
04438   InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
04439 }
04440 
04441 void Train::OnNewDay()
04442 {
04443   if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
04444 
04445   if (IsFrontEngine(this)) {
04446     CheckVehicleBreakdown(this);
04447     AgeVehicle(this);
04448 
04449     CheckIfTrainNeedsService(this);
04450 
04451     CheckOrders(this);
04452 
04453     /* update destination */
04454     if (this->current_order.IsType(OT_GOTO_STATION)) {
04455       TileIndex tile = GetStation(this->current_order.GetDestination())->train_tile;
04456       if (tile != INVALID_TILE) this->dest_tile = tile;
04457     }
04458 
04459     if (this->running_ticks != 0) {
04460       /* running costs */
04461       CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR  * DAY_TICKS));
04462 
04463       this->profit_this_year -= cost.GetCost();
04464       this->running_ticks = 0;
04465 
04466       SubtractMoneyFromCompanyFract(this->owner, cost);
04467 
04468       InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
04469       InvalidateWindowClasses(WC_TRAINS_LIST);
04470     }
04471   } else if (IsTrainEngine(this)) {
04472     /* Also age engines that aren't front engines */
04473     AgeVehicle(this);
04474   }
04475 }
04476 
04477 void InitializeTrains()
04478 {
04479   _age_cargo_skip_counter = 1;
04480 }

Generated on Mon Mar 9 23:33:52 2009 for openttd by  doxygen 1.5.6