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