00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013 #include "error.h"
00014 #include "articulated_vehicles.h"
00015 #include "command_func.h"
00016 #include "pathfinder/npf/npf_func.h"
00017 #include "pathfinder/yapf/yapf.hpp"
00018 #include "news_func.h"
00019 #include "company_func.h"
00020 #include "newgrf_sound.h"
00021 #include "newgrf_text.h"
00022 #include "strings_func.h"
00023 #include "viewport_func.h"
00024 #include "vehicle_func.h"
00025 #include "sound_func.h"
00026 #include "ai/ai.hpp"
00027 #include "game/game.hpp"
00028 #include "newgrf_station.h"
00029 #include "effectvehicle_func.h"
00030 #include "network/network.h"
00031 #include "spritecache.h"
00032 #include "core/random_func.hpp"
00033 #include "company_base.h"
00034 #include "newgrf.h"
00035 #include "order_backup.h"
00036 #include "zoom_func.h"
00037
00038 #include "table/strings.h"
00039 #include "table/train_cmd.h"
00040
00041 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
00042 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
00043 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true);
00044 static TileIndex TrainApproachingCrossingTile(const Train *v);
00045 static void CheckIfTrainNeedsService(Train *v);
00046 static void CheckNextTrainTile(Train *v);
00047
00048 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
00049 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
00050
00051
00059 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
00060 {
00061 static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
00062
00063 DiagDirection diagdir = DirToDiagDir(direction);
00064
00065
00066 if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
00067 diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
00068 }
00069
00070 return diagdir;
00071 }
00072
00073
00079 byte FreightWagonMult(CargoID cargo)
00080 {
00081 if (!CargoSpec::Get(cargo)->is_freight) return 1;
00082 return _settings_game.vehicle.freight_trains;
00083 }
00084
00086 void CheckTrainsLengths()
00087 {
00088 const Train *v;
00089 bool first = true;
00090
00091 FOR_ALL_TRAINS(v) {
00092 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
00093 for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
00094 if (u->track != TRACK_BIT_DEPOT) {
00095 if ((w->track != TRACK_BIT_DEPOT &&
00096 max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
00097 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
00098 SetDParam(0, v->index);
00099 SetDParam(1, v->owner);
00100 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
00101
00102 if (!_networking && first) {
00103 first = false;
00104 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
00105 }
00106
00107 break;
00108 }
00109 }
00110 }
00111 }
00112 }
00113 }
00114
00121 void Train::ConsistChanged(bool same_length)
00122 {
00123 uint16 max_speed = UINT16_MAX;
00124
00125 assert(this->IsFrontEngine() || this->IsFreeWagon());
00126
00127 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
00128 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
00129 this->gcache.cached_total_length = 0;
00130 this->compatible_railtypes = RAILTYPES_NONE;
00131
00132 bool train_can_tilt = true;
00133
00134 for (Train *u = this; u != NULL; u = u->Next()) {
00135 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
00136
00137
00138 assert(u->First() == this);
00139
00140
00141 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
00142 u->railtype = rvi_u->railtype;
00143
00144 if (u->IsEngine()) first_engine = u->engine_type;
00145
00146
00147 u->tcache.user_def_data = rvi_u->user_def_data;
00148 this->InvalidateNewGRFCache();
00149 u->InvalidateNewGRFCache();
00150 }
00151
00152 for (Train *u = this; u != NULL; u = u->Next()) {
00153
00154 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
00155 this->InvalidateNewGRFCache();
00156 u->InvalidateNewGRFCache();
00157 }
00158
00159 for (Train *u = this; u != NULL; u = u->Next()) {
00160 const Engine *e_u = u->GetEngine();
00161 const RailVehicleInfo *rvi_u = &e_u->u.rail;
00162
00163 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
00164
00165
00166 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
00167
00168
00169 u->colourmap = PAL_NONE;
00170
00171
00172 u->UpdateVisualEffect(true);
00173
00174 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
00175 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
00176
00177 SetBit(u->flags, VRF_POWEREDWAGON);
00178 } else {
00179 ClrBit(u->flags, VRF_POWEREDWAGON);
00180 }
00181
00182 if (!u->IsArticulatedPart()) {
00183
00184
00185 if (rvi_u->power > 0) {
00186 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
00187 }
00188
00189
00190
00191 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
00192 u->railtype = RAILTYPE_RAIL;
00193 u->compatible_railtypes |= RAILTYPES_RAIL;
00194 }
00195
00196
00197 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
00198 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
00199 if (speed != 0) max_speed = min(speed, max_speed);
00200 }
00201 }
00202
00203 u->cargo_cap = e_u->DetermineCapacity(u);
00204 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
00205
00206
00207 uint16 veh_len = CALLBACK_FAILED;
00208 if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
00209
00210 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
00211
00212 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
00213 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
00214 }
00215 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
00216
00217 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
00218 }
00219 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
00220 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
00221
00222
00223 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
00224
00225
00226 if (!same_length) u->gcache.cached_veh_length = veh_len;
00227
00228 this->gcache.cached_total_length += u->gcache.cached_veh_length;
00229 this->InvalidateNewGRFCache();
00230 u->InvalidateNewGRFCache();
00231 }
00232
00233
00234 this->vcache.cached_max_speed = max_speed;
00235 this->tcache.cached_tilt = train_can_tilt;
00236 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
00237
00238
00239 this->CargoChanged();
00240
00241 if (this->IsFrontEngine()) {
00242 this->UpdateAcceleration();
00243 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00244 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
00245 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
00246 }
00247 }
00248
00259 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
00260 {
00261 const Station *st = Station::Get(station_id);
00262 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
00263 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
00264
00265
00266
00267 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
00268 if (v->gcache.cached_total_length >= *station_length) {
00269
00270 osl = OSL_PLATFORM_FAR_END;
00271 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
00272 osl = v->current_order.GetStopLocation();
00273 }
00274
00275
00276 int stop;
00277 switch (osl) {
00278 default: NOT_REACHED();
00279
00280 case OSL_PLATFORM_NEAR_END:
00281 stop = v->gcache.cached_total_length;
00282 break;
00283
00284 case OSL_PLATFORM_MIDDLE:
00285 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
00286 break;
00287
00288 case OSL_PLATFORM_FAR_END:
00289 stop = *station_length;
00290 break;
00291 }
00292
00293
00294
00295 return stop - (v->gcache.cached_veh_length + 1) / 2;
00296 }
00297
00298
00303 int Train::GetCurveSpeedLimit() const
00304 {
00305 assert(this->First() == this);
00306
00307 static const int absolute_max_speed = UINT16_MAX;
00308 int max_speed = absolute_max_speed;
00309
00310 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
00311
00312 int curvecount[2] = {0, 0};
00313
00314
00315 int numcurve = 0;
00316 int sum = 0;
00317 int pos = 0;
00318 int lastpos = -1;
00319 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
00320 Direction this_dir = u->direction;
00321 Direction next_dir = u->Next()->direction;
00322
00323 DirDiff dirdiff = DirDifference(this_dir, next_dir);
00324 if (dirdiff == DIRDIFF_SAME) continue;
00325
00326 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
00327 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
00328 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
00329 if (lastpos != -1) {
00330 numcurve++;
00331 sum += pos - lastpos;
00332 if (pos - lastpos == 1 && max_speed > 88) {
00333 max_speed = 88;
00334 }
00335 }
00336 lastpos = pos;
00337 }
00338
00339
00340 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
00341 max_speed = 61;
00342 }
00343 }
00344
00345 if (numcurve > 0 && max_speed > 88) {
00346 if (curvecount[0] == 1 && curvecount[1] == 1) {
00347 max_speed = absolute_max_speed;
00348 } else {
00349 sum /= numcurve;
00350 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
00351 }
00352 }
00353
00354 if (max_speed != absolute_max_speed) {
00355
00356 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
00357 max_speed += (max_speed / 2) * rti->curve_speed;
00358
00359 if (this->tcache.cached_tilt) {
00360
00361 max_speed += max_speed / 5;
00362 }
00363 }
00364
00365 return max_speed;
00366 }
00367
00372 int Train::GetCurrentMaxSpeed() const
00373 {
00374 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return min(this->gcache.cached_max_track_speed, this->current_order.max_speed);
00375
00376 int max_speed = this->tcache.cached_max_curve_speed;
00377 if (IsRailStationTile(this->tile)) {
00378 StationID sid = GetStationIndex(this->tile);
00379 if (this->current_order.ShouldStopAtStation(this, sid)) {
00380 int station_ahead;
00381 int station_length;
00382 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
00383
00384
00385
00386 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
00387
00388 if (distance_to_go > 0) {
00389 int st_max_speed = 120;
00390
00391 int delta_v = this->cur_speed / (distance_to_go + 1);
00392 if (max_speed > (this->cur_speed - delta_v)) {
00393 st_max_speed = this->cur_speed - (delta_v / 10);
00394 }
00395
00396 st_max_speed = max(st_max_speed, 25 * distance_to_go);
00397 max_speed = min(max_speed, st_max_speed);
00398 }
00399 }
00400 }
00401
00402 for (const Train *u = this; u != NULL; u = u->Next()) {
00403 if (u->track == TRACK_BIT_DEPOT) {
00404 max_speed = min(max_speed, 61);
00405 break;
00406 }
00407
00408
00409 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
00410 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
00411 }
00412 }
00413
00414 max_speed = min(max_speed, this->current_order.max_speed);
00415 return min(max_speed, this->gcache.cached_max_track_speed);
00416 }
00417
00419 void Train::UpdateAcceleration()
00420 {
00421 assert(this->IsFrontEngine());
00422
00423 uint power = this->gcache.cached_power;
00424 uint weight = this->gcache.cached_weight;
00425 assert(weight != 0);
00426 this->acceleration = Clamp(power / weight * 4, 1, 255);
00427 }
00428
00434 int Train::GetDisplayImageWidth(Point *offset) const
00435 {
00436 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
00437 int vehicle_pitch = 0;
00438
00439 const Engine *e = this->GetEngine();
00440 if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
00441 reference_width = e->GetGRF()->traininfo_vehicle_width;
00442 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
00443 }
00444
00445 if (offset != NULL) {
00446 offset->x = reference_width / 2;
00447 offset->y = vehicle_pitch;
00448 }
00449 return this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
00450 }
00451
00452 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
00453 {
00454 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
00455 }
00456
00463 SpriteID Train::GetImage(Direction direction, EngineImageType image_type) const
00464 {
00465 uint8 spritenum = this->spritenum;
00466 SpriteID sprite;
00467
00468 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
00469
00470 if (is_custom_sprite(spritenum)) {
00471 sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
00472 if (sprite != 0) return sprite;
00473
00474 spritenum = this->GetEngine()->original_image_index;
00475 }
00476
00477 sprite = GetDefaultTrainSprite(spritenum, direction);
00478
00479 if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
00480
00481 return sprite;
00482 }
00483
00484 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type)
00485 {
00486 const Engine *e = Engine::Get(engine);
00487 Direction dir = rear_head ? DIR_E : DIR_W;
00488 uint8 spritenum = e->u.rail.image_index;
00489
00490 if (is_custom_sprite(spritenum)) {
00491 SpriteID sprite = GetCustomVehicleIcon(engine, dir, image_type);
00492 if (sprite != 0) {
00493 if (e->GetGRF() != NULL) {
00494 y += e->GetGRF()->traininfo_vehicle_pitch;
00495 }
00496 return sprite;
00497 }
00498
00499 spritenum = Engine::Get(engine)->original_image_index;
00500 }
00501
00502 if (rear_head) spritenum++;
00503
00504 return GetDefaultTrainSprite(spritenum, DIR_W);
00505 }
00506
00507 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
00508 {
00509 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00510 int yf = y;
00511 int yr = y;
00512
00513 SpriteID spritef = GetRailIcon(engine, false, yf, image_type);
00514 SpriteID spriter = GetRailIcon(engine, true, yr, image_type);
00515 const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
00516 const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
00517
00518 preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_spritef->x_offs, ZOOM_LVL_GUI) + 14, right - UnScaleByZoom(real_spriter->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_spriter->x_offs, ZOOM_LVL_GUI) - 15);
00519
00520 DrawSprite(spritef, pal, preferred_x - 14, yf);
00521 DrawSprite(spriter, pal, preferred_x + 15, yr);
00522 } else {
00523 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
00524 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00525 preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI), right - UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI));
00526 DrawSprite(sprite, pal, preferred_x, y);
00527 }
00528 }
00529
00539 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
00540 {
00541 int y = 0;
00542
00543 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
00544 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00545
00546 width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
00547 height = UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI);
00548 xoffs = UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI);
00549 yoffs = UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI);
00550
00551 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00552 sprite = GetRailIcon(engine, true, y, image_type);
00553 real_sprite = GetSprite(sprite, ST_NORMAL);
00554
00555
00556 width = TRAININFO_DEFAULT_VEHICLE_WIDTH + UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) + UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI) - xoffs;
00557 height = max<uint>(height, UnScaleByZoom(real_sprite->height, ZOOM_LVL_GUI));
00558 xoffs = xoffs - TRAININFO_DEFAULT_VEHICLE_WIDTH / 2;
00559 yoffs = min(yoffs, UnScaleByZoom(real_sprite->y_offs, ZOOM_LVL_GUI));
00560 }
00561 }
00562
00571 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
00572 {
00573 const RailVehicleInfo *rvi = &e->u.rail;
00574
00575
00576 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00577
00578 if (flags & DC_EXEC) {
00579 Train *v = new Train();
00580 *ret = v;
00581 v->spritenum = rvi->image_index;
00582
00583 v->engine_type = e->index;
00584 v->gcache.first_engine = INVALID_ENGINE;
00585
00586 DiagDirection dir = GetRailDepotDirection(tile);
00587
00588 v->direction = DiagDirToDir(dir);
00589 v->tile = tile;
00590
00591 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
00592 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
00593
00594 v->x_pos = x;
00595 v->y_pos = y;
00596 v->z_pos = GetSlopePixelZ(x, y);
00597 v->owner = _current_company;
00598 v->track = TRACK_BIT_DEPOT;
00599 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
00600
00601 v->SetWagon();
00602
00603 v->SetFreeWagon();
00604 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00605
00606 v->cargo_type = e->GetDefaultCargoType();
00607 v->cargo_cap = rvi->capacity;
00608
00609 v->railtype = rvi->railtype;
00610
00611 v->build_year = _cur_year;
00612 v->cur_image = SPR_IMG_QUERY;
00613 v->random_bits = VehicleRandomBits();
00614
00615 v->group_id = DEFAULT_GROUP;
00616
00617 AddArticulatedParts(v);
00618
00619 _new_vehicle_id = v->index;
00620
00621 VehicleUpdatePosition(v);
00622 v->First()->ConsistChanged(false);
00623 UpdateTrainGroupID(v->First());
00624
00625 CheckConsistencyOfArticulatedVehicle(v);
00626
00627
00628 Train *w;
00629 FOR_ALL_TRAINS(w) {
00630 if (w->tile == tile &&
00631 w->IsFreeWagon() &&
00632 w->engine_type == e->index &&
00633 w->First() != v &&
00634 !(w->vehstatus & VS_CRASHED)) {
00635 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
00636 break;
00637 }
00638 }
00639 }
00640
00641 return CommandCost();
00642 }
00643
00645 static void NormalizeTrainVehInDepot(const Train *u)
00646 {
00647 const Train *v;
00648 FOR_ALL_TRAINS(v) {
00649 if (v->IsFreeWagon() && v->tile == u->tile &&
00650 v->track == TRACK_BIT_DEPOT) {
00651 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
00652 CMD_MOVE_RAIL_VEHICLE).Failed())
00653 break;
00654 }
00655 }
00656 }
00657
00658 static void AddRearEngineToMultiheadedTrain(Train *v)
00659 {
00660 Train *u = new Train();
00661 v->value >>= 1;
00662 u->value = v->value;
00663 u->direction = v->direction;
00664 u->owner = v->owner;
00665 u->tile = v->tile;
00666 u->x_pos = v->x_pos;
00667 u->y_pos = v->y_pos;
00668 u->z_pos = v->z_pos;
00669 u->track = TRACK_BIT_DEPOT;
00670 u->vehstatus = v->vehstatus & ~VS_STOPPED;
00671 u->spritenum = v->spritenum + 1;
00672 u->cargo_type = v->cargo_type;
00673 u->cargo_subtype = v->cargo_subtype;
00674 u->cargo_cap = v->cargo_cap;
00675 u->railtype = v->railtype;
00676 u->engine_type = v->engine_type;
00677 u->build_year = v->build_year;
00678 u->cur_image = SPR_IMG_QUERY;
00679 u->random_bits = VehicleRandomBits();
00680 v->SetMultiheaded();
00681 u->SetMultiheaded();
00682 v->SetNext(u);
00683 VehicleUpdatePosition(u);
00684
00685
00686 v->other_multiheaded_part = u;
00687 u->other_multiheaded_part = v;
00688 }
00689
00699 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00700 {
00701 const RailVehicleInfo *rvi = &e->u.rail;
00702
00703 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
00704
00705
00706
00707 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00708
00709 if (flags & DC_EXEC) {
00710 DiagDirection dir = GetRailDepotDirection(tile);
00711 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
00712 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
00713
00714 Train *v = new Train();
00715 *ret = v;
00716 v->direction = DiagDirToDir(dir);
00717 v->tile = tile;
00718 v->owner = _current_company;
00719 v->x_pos = x;
00720 v->y_pos = y;
00721 v->z_pos = GetSlopePixelZ(x, y);
00722 v->track = TRACK_BIT_DEPOT;
00723 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00724 v->spritenum = rvi->image_index;
00725 v->cargo_type = e->GetDefaultCargoType();
00726 v->cargo_cap = rvi->capacity;
00727 v->last_station_visited = INVALID_STATION;
00728
00729 v->engine_type = e->index;
00730 v->gcache.first_engine = INVALID_ENGINE;
00731
00732 v->reliability = e->reliability;
00733 v->reliability_spd_dec = e->reliability_spd_dec;
00734 v->max_age = e->GetLifeLengthInDays();
00735
00736 v->railtype = rvi->railtype;
00737 _new_vehicle_id = v->index;
00738
00739 v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_trains;
00740 v->date_of_last_service = _date;
00741 v->build_year = _cur_year;
00742 v->cur_image = SPR_IMG_QUERY;
00743 v->random_bits = VehicleRandomBits();
00744
00745 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00746
00747 v->group_id = DEFAULT_GROUP;
00748
00749 v->SetFrontEngine();
00750 v->SetEngine();
00751
00752 VehicleUpdatePosition(v);
00753
00754 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
00755 AddRearEngineToMultiheadedTrain(v);
00756 } else {
00757 AddArticulatedParts(v);
00758 }
00759
00760 v->ConsistChanged(false);
00761 UpdateTrainGroupID(v);
00762
00763 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) {
00764 NormalizeTrainVehInDepot(v);
00765 }
00766
00767 CheckConsistencyOfArticulatedVehicle(v);
00768 }
00769
00770 return CommandCost();
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 (head->GetGRF()->grf_version < 8) {
00995 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
00996 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
00997 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
00998 } else {
00999 if (callback < 0x400) {
01000 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
01001 } else {
01002 switch (callback) {
01003 case 0x400:
01004 case 0x401:
01005 break;
01006
01007 default:
01008 case 0x402:
01009 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01010 break;
01011 }
01012 }
01013 }
01014
01015 if (error != STR_NULL) return_cmd_error(error);
01016 }
01017 }
01018
01019
01020 prev->SetNext(t);
01021 prev = t;
01022 t = next;
01023 }
01024
01025 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
01026 return CommandCost();
01027 }
01028
01039 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
01040 {
01041
01042 CommandCost ret = CheckTrainAttachment(src);
01043 if (ret.Failed()) return ret;
01044 ret = CheckTrainAttachment(dst);
01045 if (ret.Failed()) return ret;
01046
01047
01048 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
01049 }
01050
01059 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
01060 {
01061
01062 if (*src_head == *dst_head) {
01063
01064
01065 *dst_head = NULL;
01066 } else if (*dst_head == NULL) {
01067
01068
01069 *dst_head = src;
01070 }
01071
01072 if (src == *src_head) {
01073
01074
01075
01076
01077
01078
01079 *src_head = move_chain ? NULL :
01080 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
01081 }
01082
01083
01084
01085
01086 RemoveFromConsist(src, move_chain);
01087 if (*dst_head != src) InsertInConsist(dst, src);
01088
01089
01090
01091 NormaliseDualHeads(*src_head);
01092 NormaliseDualHeads(*dst_head);
01093 }
01094
01100 static void NormaliseTrainHead(Train *head)
01101 {
01102
01103 if (head == NULL) return;
01104
01105
01106 head->ConsistChanged(false);
01107 UpdateTrainGroupID(head);
01108
01109
01110 if (!head->IsFrontEngine()) return;
01111
01112
01113 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
01114 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
01115
01116
01117 if (head->unitnumber != 0) return;
01118 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
01119 }
01120
01133 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01134 {
01135 VehicleID s = GB(p1, 0, 20);
01136 VehicleID d = GB(p2, 0, 20);
01137 bool move_chain = HasBit(p1, 20);
01138
01139 Train *src = Train::GetIfValid(s);
01140 if (src == NULL) return CMD_ERROR;
01141
01142 CommandCost ret = CheckOwnership(src->owner);
01143 if (ret.Failed()) return ret;
01144
01145
01146 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
01147
01148
01149 Train *dst;
01150 if (d == INVALID_VEHICLE) {
01151 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
01152 } else {
01153 dst = Train::GetIfValid(d);
01154 if (dst == NULL) return CMD_ERROR;
01155
01156 CommandCost ret = CheckOwnership(dst->owner);
01157 if (ret.Failed()) return ret;
01158
01159
01160 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
01161 }
01162
01163
01164 src = src->GetFirstEnginePart();
01165 if (dst != NULL) {
01166 dst = dst->GetFirstEnginePart();
01167 }
01168
01169
01170 if (src == dst) return CommandCost();
01171
01172
01173 Train *src_head = src->First();
01174 Train *dst_head;
01175 if (dst != NULL) {
01176 dst_head = dst->First();
01177 if (dst_head->tile != src_head->tile) return CMD_ERROR;
01178
01179 dst = dst->GetLastEnginePart();
01180 } else {
01181 dst_head = NULL;
01182 }
01183
01184 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01185
01186
01187 if (move_chain && src_head == dst_head) return CommandCost();
01188
01189
01190 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
01191
01192
01193 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01194
01195
01196 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01197
01198
01199
01200 TrainList original_src;
01201 TrainList original_dst;
01202
01203 MakeTrainBackup(original_src, src_head);
01204 MakeTrainBackup(original_dst, dst_head);
01205
01206
01207
01208
01209 Train *original_src_head = src_head;
01210 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
01211
01212
01213 bool original_src_head_front_engine = original_src_head != NULL && original_src_head->IsFrontEngine();
01214 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
01215
01216
01217 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
01218
01219 if ((flags & DC_AUTOREPLACE) == 0) {
01220
01221
01222
01223 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
01224 if (ret.Failed()) {
01225
01226 RestoreTrainBackup(original_src);
01227 RestoreTrainBackup(original_dst);
01228 return ret;
01229 }
01230 }
01231
01232
01233 if (flags & DC_EXEC) {
01234
01235 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
01236 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
01237
01238
01239 NormaliseSubtypes(src_head);
01240 NormaliseSubtypes(dst_head);
01241
01242
01243
01244
01245
01246
01247
01248
01249
01250
01251
01252
01253
01254
01255
01256
01257
01258
01259
01260
01261
01262 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
01263
01264 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
01265 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
01266 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
01267 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
01268 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
01269 SetWindowDirty(WC_COMPANY, _current_company);
01270
01271
01272
01273 DeleteVehicleOrders(src);
01274 RemoveVehicleFromGroup(src);
01275 src->unitnumber = 0;
01276 }
01277
01278
01279
01280 if (original_src_head != src && dst_head == src) {
01281 SetTrainGroupID(src, DEFAULT_GROUP);
01282 SetWindowDirty(WC_COMPANY, _current_company);
01283 }
01284
01285
01286 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
01287 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
01288
01289
01290 NormaliseTrainHead(src_head);
01291 NormaliseTrainHead(dst_head);
01292
01293 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
01294 CheckCargoCapacity(src_head);
01295 CheckCargoCapacity(dst_head);
01296 }
01297
01298
01299 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01300 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01301 } else {
01302
01303 RestoreTrainBackup(original_src);
01304 RestoreTrainBackup(original_dst);
01305 }
01306
01307 return CommandCost();
01308 }
01309
01321 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
01322 {
01323
01324 Window *w = NULL;
01325
01326
01327 bool sell_chain = HasBit(data, 0);
01328
01329 Train *v = Train::From(t)->GetFirstEnginePart();
01330 Train *first = v->First();
01331
01332 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01333
01334
01335
01336 TrainList original;
01337 MakeTrainBackup(original, first);
01338
01339
01340 Train *new_head = first;
01341 Train *sell_head = NULL;
01342
01343
01344 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
01345
01346
01347 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
01348 if (ret.Failed()) {
01349
01350 RestoreTrainBackup(original);
01351 return ret;
01352 }
01353
01354 CommandCost cost(EXPENSES_NEW_VEHICLES);
01355 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
01356
01357 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
01358 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01359 }
01360
01361
01362 if (flags & DC_EXEC) {
01363
01364 NormaliseSubtypes(new_head);
01365
01366 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
01367
01368
01369 new_head->orders.list = first->orders.list;
01370 new_head->AddToShared(first);
01371 DeleteVehicleOrders(first);
01372
01373
01374 new_head->CopyVehicleConfigAndStatistics(first);
01375 GroupStatistics::CountVehicle(new_head, 1);
01376
01377
01378 if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_head);
01379 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
01380 OrderBackup::Backup(v, user);
01381 }
01382
01383
01384 NormaliseTrainHead(new_head);
01385
01386
01387 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01388 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01389
01390
01391 delete sell_head;
01392 } else {
01393
01394 RestoreTrainBackup(original);
01395 }
01396
01397 return cost;
01398 }
01399
01400 void Train::UpdateDeltaXY(Direction direction)
01401 {
01402
01403 this->x_offs = -1;
01404 this->y_offs = -1;
01405 this->x_extent = 3;
01406 this->y_extent = 3;
01407 this->z_extent = 6;
01408 this->x_bb_offs = 0;
01409 this->y_bb_offs = 0;
01410
01411 if (!IsDiagonalDirection(direction)) {
01412 static const int _sign_table[] =
01413 {
01414
01415 -1, -1,
01416 -1, 1,
01417 1, 1,
01418 1, -1,
01419 };
01420
01421 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
01422
01423
01424 this->x_offs -= half_shorten * _sign_table[direction];
01425 this->y_offs -= half_shorten * _sign_table[direction + 1];
01426 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
01427 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
01428 } else {
01429 switch (direction) {
01430
01431
01432 case DIR_NE:
01433 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
01434 this->x_extent = this->gcache.cached_veh_length - 1;
01435 this->x_bb_offs = -1;
01436 break;
01437
01438 case DIR_NW:
01439 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
01440 this->y_extent = this->gcache.cached_veh_length - 1;
01441 this->y_bb_offs = -1;
01442 break;
01443
01444
01445
01446 case DIR_SW:
01447 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01448 this->x_extent = VEHICLE_LENGTH - 1;
01449 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01450 break;
01451
01452 case DIR_SE:
01453 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01454 this->y_extent = VEHICLE_LENGTH - 1;
01455 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01456 break;
01457
01458 default:
01459 NOT_REACHED();
01460 }
01461 }
01462 }
01463
01468 static void MarkTrainAsStuck(Train *v)
01469 {
01470 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
01471
01472 SetBit(v->flags, VRF_TRAIN_STUCK);
01473
01474 v->wait_counter = 0;
01475
01476
01477 v->cur_speed = 0;
01478 v->subspeed = 0;
01479 v->SetLastSpeed();
01480
01481 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01482 }
01483 }
01484
01492 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
01493 {
01494 uint16 flag1 = *swap_flag1;
01495 uint16 flag2 = *swap_flag2;
01496
01497
01498 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
01499 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01500 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
01501 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01502
01503
01504 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
01505 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01506 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
01507 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
01508 }
01509 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
01510 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01511 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
01512 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
01513 }
01514 }
01515
01520 static void UpdateStatusAfterSwap(Train *v)
01521 {
01522
01523 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
01524
01525
01526 if (v->track != TRACK_BIT_WORMHOLE) {
01527 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
01528 } else {
01529
01530
01531
01532
01533 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
01534 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
01535 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
01536 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
01537
01538
01539
01540 VehicleUpdatePosition(v);
01541 v->UpdateInclination(true, true);
01542 return;
01543 }
01544 }
01545 }
01546
01547 VehicleUpdatePosition(v);
01548 v->UpdateViewport(true, true);
01549 }
01550
01557 void ReverseTrainSwapVeh(Train *v, int l, int r)
01558 {
01559 Train *a, *b;
01560
01561
01562 for (a = v; l != 0; l--) a = a->Next();
01563 for (b = v; r != 0; r--) b = b->Next();
01564
01565 if (a != b) {
01566
01567 {
01568 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
01569 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
01570 a->vehstatus = tmp;
01571 }
01572
01573 Swap(a->track, b->track);
01574 Swap(a->direction, b->direction);
01575 Swap(a->x_pos, b->x_pos);
01576 Swap(a->y_pos, b->y_pos);
01577 Swap(a->tile, b->tile);
01578 Swap(a->z_pos, b->z_pos);
01579
01580 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
01581
01582 UpdateStatusAfterSwap(a);
01583 UpdateStatusAfterSwap(b);
01584 } else {
01585
01586
01587
01588 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
01589 UpdateStatusAfterSwap(a);
01590 }
01591 }
01592
01593
01599 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
01600 {
01601 return (v->type == VEH_TRAIN) ? v : NULL;
01602 }
01603
01604
01611 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
01612 {
01613 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
01614
01615 Train *t = Train::From(v);
01616 if (!t->IsFrontEngine()) return NULL;
01617
01618 TileIndex tile = *(TileIndex *)data;
01619
01620 if (TrainApproachingCrossingTile(t) != tile) return NULL;
01621
01622 return t;
01623 }
01624
01625
01632 static bool TrainApproachingCrossing(TileIndex tile)
01633 {
01634 assert(IsLevelCrossingTile(tile));
01635
01636 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
01637 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
01638
01639 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
01640
01641 dir = ReverseDiagDir(dir);
01642 tile_from = tile + TileOffsByDiagDir(dir);
01643
01644 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
01645 }
01646
01647
01654 void UpdateLevelCrossing(TileIndex tile, bool sound)
01655 {
01656 assert(IsLevelCrossingTile(tile));
01657
01658
01659 bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
01660
01661 if (new_state != IsCrossingBarred(tile)) {
01662 if (new_state && sound) {
01663 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01664 }
01665 SetCrossingBarred(tile, new_state);
01666 MarkTileDirtyByTile(tile);
01667 }
01668 }
01669
01670
01676 static inline void MaybeBarCrossingWithSound(TileIndex tile)
01677 {
01678 if (!IsCrossingBarred(tile)) {
01679 BarCrossing(tile);
01680 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01681 MarkTileDirtyByTile(tile);
01682 }
01683 }
01684
01685
01691 static void AdvanceWagonsBeforeSwap(Train *v)
01692 {
01693 Train *base = v;
01694 Train *first = base;
01695 Train *last = v->Last();
01696 uint length = CountVehiclesInChain(v);
01697
01698 while (length > 2) {
01699 last = last->Previous();
01700 first = first->Next();
01701
01702 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
01703
01704
01705
01706 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
01707
01708 base = first;
01709 length -= 2;
01710 }
01711 }
01712
01713
01719 static void AdvanceWagonsAfterSwap(Train *v)
01720 {
01721
01722 Train *dep = v;
01723 while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
01724 dep = dep->Next();
01725 }
01726
01727 Train *leave = dep->Next();
01728
01729 if (leave != NULL) {
01730
01731 int d = TicksToLeaveDepot(dep);
01732
01733 if (d <= 0) {
01734 leave->vehstatus &= ~VS_HIDDEN;
01735 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
01736 for (int i = 0; i >= d; i--) TrainController(leave, NULL);
01737 }
01738 } else {
01739 dep = NULL;
01740 }
01741
01742 Train *base = v;
01743 Train *first = base;
01744 Train *last = v->Last();
01745 uint length = CountVehiclesInChain(v);
01746
01747
01748
01749 bool nomove = (dep == NULL);
01750
01751 while (length > 2) {
01752
01753
01754 if (base == dep) break;
01755
01756
01757 if (last == dep) nomove = true;
01758
01759 last = last->Previous();
01760 first = first->Next();
01761
01762 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
01763
01764
01765 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
01766
01767 base = first;
01768 length -= 2;
01769 }
01770 }
01771
01776 void ReverseTrainDirection(Train *v)
01777 {
01778 if (IsRailDepotTile(v->tile)) {
01779 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01780 }
01781
01782
01783 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
01784
01785
01786 TileIndex crossing = TrainApproachingCrossingTile(v);
01787
01788
01789 int r = CountVehiclesInChain(v) - 1;
01790
01791 AdvanceWagonsBeforeSwap(v);
01792
01793
01794 int l = 0;
01795 do {
01796 ReverseTrainSwapVeh(v, l++, r--);
01797 } while (l <= r);
01798
01799 AdvanceWagonsAfterSwap(v);
01800
01801 if (IsRailDepotTile(v->tile)) {
01802 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01803 }
01804
01805 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
01806
01807 ClrBit(v->flags, VRF_REVERSING);
01808
01809
01810 v->ConsistChanged(true);
01811
01812
01813 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
01814
01815
01816 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
01817
01818
01819 crossing = TrainApproachingCrossingTile(v);
01820 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
01821
01822
01823 if (v->track == TRACK_BIT_DEPOT) {
01824
01825 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01826 ClrBit(v->flags, VRF_TRAIN_STUCK);
01827 return;
01828 }
01829
01830
01831
01832 DiagDirection dir = TrainExitDir(v->direction, v->track);
01833 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
01834
01835 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
01836
01837
01838 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
01839 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
01840 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
01841
01842
01843 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
01844
01845 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01846 if (TryPathReserve(v, false, first_tile_okay)) {
01847
01848 CheckNextTrainTile(v);
01849 } else if (v->current_order.GetType() != OT_LOADING) {
01850
01851 MarkTrainAsStuck(v);
01852 }
01853 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
01854
01855 ClrBit(v->flags, VRF_TRAIN_STUCK);
01856 v->wait_counter = 0;
01857 }
01858 }
01859
01869 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01870 {
01871 Train *v = Train::GetIfValid(p1);
01872 if (v == NULL) return CMD_ERROR;
01873
01874 CommandCost ret = CheckOwnership(v->owner);
01875 if (ret.Failed()) return ret;
01876
01877 if (p2 != 0) {
01878
01879
01880 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
01881 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
01882 }
01883 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
01884
01885 Train *front = v->First();
01886
01887 if (!front->IsStoppedInDepot()) {
01888 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01889 }
01890
01891 if (flags & DC_EXEC) {
01892 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
01893
01894 front->ConsistChanged(false);
01895 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
01896 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
01897 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
01898 SetWindowClassesDirty(WC_TRAINS_LIST);
01899 }
01900 } else {
01901
01902 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
01903
01904 if (flags & DC_EXEC) {
01905
01906 if (v->current_order.IsType(OT_LOADING)) {
01907 const Vehicle *last = v;
01908 while (last->Next() != NULL) last = last->Next();
01909
01910
01911 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
01912 v->LeaveStation();
01913 }
01914 }
01915
01916
01917 v->force_proceed = TFP_NONE;
01918 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01919
01920 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
01921 ToggleBit(v->flags, VRF_REVERSING);
01922 } else {
01923 v->cur_speed = 0;
01924 v->SetLastSpeed();
01925 HideFillingPercent(&v->fill_percent_te_id);
01926 ReverseTrainDirection(v);
01927 }
01928 }
01929 }
01930 return CommandCost();
01931 }
01932
01942 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01943 {
01944 Train *t = Train::GetIfValid(p1);
01945 if (t == NULL) return CMD_ERROR;
01946
01947 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
01948
01949 CommandCost ret = CheckOwnership(t->owner);
01950 if (ret.Failed()) return ret;
01951
01952
01953 if (flags & DC_EXEC) {
01954
01955
01956
01957
01958
01959 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
01960 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
01961 }
01962
01963 return CommandCost();
01964 }
01965
01973 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
01974 {
01975 assert(!(v->vehstatus & VS_CRASHED));
01976
01977 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
01978
01979 PBSTileInfo origin = FollowTrainReservation(v);
01980 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
01981
01982 switch (_settings_game.pf.pathfinder_for_trains) {
01983 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
01984 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
01985
01986 default: NOT_REACHED();
01987 }
01988 }
01989
01997 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
01998 {
01999 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
02000 if (tfdd.best_length == UINT_MAX) return false;
02001
02002 if (location != NULL) *location = tfdd.tile;
02003 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
02004 if (reverse != NULL) *reverse = tfdd.reverse;
02005
02006 return true;
02007 }
02008
02010 void Train::PlayLeaveStationSound() const
02011 {
02012 static const SoundFx sfx[] = {
02013 SND_04_TRAIN,
02014 SND_0A_TRAIN_HORN,
02015 SND_0A_TRAIN_HORN,
02016 SND_47_MAGLEV_2,
02017 SND_41_MAGLEV
02018 };
02019
02020 if (PlayVehicleSound(this, VSE_START)) return;
02021
02022 EngineID engtype = this->engine_type;
02023 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
02024 }
02025
02030 static void CheckNextTrainTile(Train *v)
02031 {
02032
02033 if (_settings_game.pf.path_backoff_interval == 255) return;
02034
02035
02036 if (v->track == TRACK_BIT_DEPOT) return;
02037
02038 switch (v->current_order.GetType()) {
02039
02040 case OT_GOTO_DEPOT:
02041 if (v->tile == v->dest_tile) return;
02042 break;
02043
02044 case OT_GOTO_WAYPOINT:
02045
02046 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
02047 break;
02048
02049 case OT_NOTHING:
02050 case OT_LEAVESTATION:
02051 case OT_LOADING:
02052
02053 if (v->GetNumOrders() > 0) return;
02054 break;
02055
02056 default:
02057 break;
02058 }
02059
02060 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
02061
02062 Trackdir td = v->GetVehicleTrackdir();
02063
02064
02065 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
02066 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
02067 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
02068
02069 CFollowTrackRail ft(v);
02070 if (!ft.Follow(v->tile, td)) return;
02071
02072 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
02073
02074 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02075 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
02076
02077 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02078 if (_settings_game.pf.forbid_90_deg) {
02079 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
02080 }
02081 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
02082 }
02083 }
02084 }
02085 }
02086
02092 static bool CheckTrainStayInDepot(Train *v)
02093 {
02094
02095 for (const Train *u = v; u != NULL; u = u->Next()) {
02096 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
02097 }
02098
02099
02100 if (v->gcache.cached_power == 0) {
02101 v->vehstatus |= VS_STOPPED;
02102 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
02103 return true;
02104 }
02105
02106 SigSegState seg_state;
02107
02108 if (v->force_proceed == TFP_NONE) {
02109
02110 if (++v->wait_counter < 37) {
02111 SetWindowClassesDirty(WC_TRAINS_LIST);
02112 return true;
02113 }
02114
02115 v->wait_counter = 0;
02116
02117 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02118 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
02119
02120 SetWindowClassesDirty(WC_TRAINS_LIST);
02121 return true;
02122 }
02123 } else {
02124 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02125 }
02126
02127
02128 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
02129
02130 if (HasDepotReservation(v->tile)) return true;
02131 SetDepotReservation(v->tile, true);
02132 VehicleEnterDepot(v);
02133 return true;
02134 }
02135
02136
02137 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
02138
02139 SetWindowClassesDirty(WC_TRAINS_LIST);
02140 MarkTrainAsStuck(v);
02141 return true;
02142 }
02143
02144 SetDepotReservation(v->tile, true);
02145 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02146
02147 VehicleServiceInDepot(v);
02148 SetWindowClassesDirty(WC_TRAINS_LIST);
02149 v->PlayLeaveStationSound();
02150
02151 v->track = TRACK_BIT_X;
02152 if (v->direction & 2) v->track = TRACK_BIT_Y;
02153
02154 v->vehstatus &= ~VS_HIDDEN;
02155 v->cur_speed = 0;
02156
02157 v->UpdateViewport(true, true);
02158 VehicleUpdatePosition(v);
02159 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
02160 v->UpdateAcceleration();
02161 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
02162
02163 return false;
02164 }
02165
02172 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
02173 {
02174 DiagDirection dir = TrackdirToExitdir(track_dir);
02175
02176 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
02177
02178 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
02179 TileIndex end = GetOtherTunnelBridgeEnd(tile);
02180
02181 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
02182
02183 SetTunnelBridgeReservation(tile, false);
02184 SetTunnelBridgeReservation(end, false);
02185
02186 if (_settings_client.gui.show_track_reservation) {
02187 MarkTileDirtyByTile(tile);
02188 MarkTileDirtyByTile(end);
02189 }
02190 }
02191 }
02192 } else if (IsRailStationTile(tile)) {
02193 TileIndex new_tile = TileAddByDiagDir(tile, dir);
02194
02195
02196 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
02197 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
02198 }
02199 } else {
02200
02201 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
02202 }
02203 }
02204
02211 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
02212 {
02213 assert(v->IsFrontEngine());
02214
02215 TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
02216 Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
02217 bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
02218 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
02219
02220
02221 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
02222 if (v->track == TRACK_BIT_DEPOT) {
02223
02224 for (const Train *u = v; u != NULL; u = u->Next()) {
02225 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
02226 }
02227 }
02228
02229 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
02230
02231 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
02232 while (ft.Follow(tile, td)) {
02233 tile = ft.m_new_tile;
02234 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
02235 td = RemoveFirstTrackdir(&bits);
02236 assert(bits == TRACKDIR_BIT_NONE);
02237
02238 if (!IsValidTrackdir(td)) break;
02239
02240 if (IsTileType(tile, MP_RAILWAY)) {
02241 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
02242
02243 UnreserveRailTrack(tile, TrackdirToTrack(td));
02244 break;
02245 }
02246 if (HasPbsSignalOnTrackdir(tile, td)) {
02247 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
02248
02249 break;
02250 } else {
02251
02252 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
02253 MarkTileDirtyByTile(tile);
02254 }
02255 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
02256 break;
02257 }
02258 }
02259
02260
02261 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);
02262
02263 free_tile = true;
02264 }
02265 }
02266
02267 static const byte _initial_tile_subcoord[6][4][3] = {
02268 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
02269 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
02270 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
02271 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
02272 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
02273 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
02274 };
02275
02288 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
02289 {
02290 switch (_settings_game.pf.pathfinder_for_trains) {
02291 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02292 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02293
02294 default: NOT_REACHED();
02295 }
02296 }
02297
02303 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
02304 {
02305 PBSTileInfo origin = FollowTrainReservation(v);
02306
02307 CFollowTrackRail ft(v);
02308
02309 TileIndex tile = origin.tile;
02310 Trackdir cur_td = origin.trackdir;
02311 while (ft.Follow(tile, cur_td)) {
02312 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02313
02314 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
02315 }
02316
02317 if (_settings_game.pf.forbid_90_deg) {
02318 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02319 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
02320 }
02321
02322
02323 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
02324 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
02325
02326
02327
02328
02329
02330
02331 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
02332
02333
02334
02335 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
02336
02337
02338 if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02339 if (enterdir != NULL) *enterdir = ft.m_exitdir;
02340 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
02341 }
02342
02343 tile = ft.m_new_tile;
02344 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02345
02346 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
02347 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
02348 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
02349
02350 return PBSTileInfo(tile, cur_td, true);
02351 }
02352
02353 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
02354 }
02355
02356 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
02357
02358 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
02359 }
02360
02361
02362 tile = origin.tile;
02363 cur_td = origin.trackdir;
02364 TileIndex stopped = ft.m_old_tile;
02365 Trackdir stopped_td = ft.m_old_td;
02366 while (tile != stopped || cur_td != stopped_td) {
02367 if (!ft.Follow(tile, cur_td)) break;
02368
02369 if (_settings_game.pf.forbid_90_deg) {
02370 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02371 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
02372 }
02373 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
02374
02375 tile = ft.m_new_tile;
02376 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02377
02378 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
02379 }
02380
02381
02382 return PBSTileInfo();
02383 }
02384
02395 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
02396 {
02397 switch (_settings_game.pf.pathfinder_for_trains) {
02398 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02399 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02400
02401 default: NOT_REACHED();
02402 }
02403 }
02404
02406 class VehicleOrderSaver {
02407 private:
02408 Train *v;
02409 Order old_order;
02410 TileIndex old_dest_tile;
02411 StationID old_last_station_visited;
02412 VehicleOrderID index;
02413 bool suppress_implicit_orders;
02414
02415 public:
02416 VehicleOrderSaver(Train *_v) :
02417 v(_v),
02418 old_order(_v->current_order),
02419 old_dest_tile(_v->dest_tile),
02420 old_last_station_visited(_v->last_station_visited),
02421 index(_v->cur_real_order_index),
02422 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
02423 {
02424 }
02425
02426 ~VehicleOrderSaver()
02427 {
02428 this->v->current_order = this->old_order;
02429 this->v->dest_tile = this->old_dest_tile;
02430 this->v->last_station_visited = this->old_last_station_visited;
02431 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
02432 }
02433
02439 bool SwitchToNextOrder(bool skip_first)
02440 {
02441 if (this->v->GetNumOrders() == 0) return false;
02442
02443 if (skip_first) ++this->index;
02444
02445 int depth = 0;
02446
02447 do {
02448
02449 if (this->index >= this->v->GetNumOrders()) this->index = 0;
02450
02451 Order *order = this->v->GetOrder(this->index);
02452 assert(order != NULL);
02453
02454 switch (order->GetType()) {
02455 case OT_GOTO_DEPOT:
02456
02457 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
02458 case OT_GOTO_STATION:
02459 case OT_GOTO_WAYPOINT:
02460 this->v->current_order = *order;
02461 return UpdateOrderDest(this->v, order, 0, true);
02462 case OT_CONDITIONAL: {
02463 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
02464 if (next != INVALID_VEH_ORDER_ID) {
02465 depth++;
02466 this->index = next;
02467
02468 continue;
02469 }
02470 break;
02471 }
02472 default:
02473 break;
02474 }
02475
02476
02477 ++this->index;
02478 depth++;
02479 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
02480
02481 return false;
02482 }
02483 };
02484
02485
02486 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
02487 {
02488 Track best_track = INVALID_TRACK;
02489 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
02490 bool changed_signal = false;
02491
02492 assert((tracks & ~TRACK_BIT_MASK) == 0);
02493
02494 if (got_reservation != NULL) *got_reservation = false;
02495
02496
02497 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
02498
02499 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
02500
02501
02502 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
02503 Track track = FindFirstTrack(tracks);
02504
02505 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
02506 do_track_reservation = true;
02507 changed_signal = true;
02508 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
02509 } else if (!do_track_reservation) {
02510 return track;
02511 }
02512 best_track = track;
02513 }
02514
02515 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
02516 DiagDirection dest_enterdir = enterdir;
02517 if (do_track_reservation) {
02518 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
02519 if (res_dest.tile == INVALID_TILE) {
02520
02521 if (mark_stuck) MarkTrainAsStuck(v);
02522 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
02523 return FindFirstTrack(tracks);
02524 }
02525 if (res_dest.okay) {
02526
02527 if (got_reservation != NULL) *got_reservation = true;
02528 if (changed_signal) MarkTileDirtyByTile(tile);
02529 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02530 return best_track;
02531 }
02532
02533
02534
02535
02536 CheckIfTrainNeedsService(v);
02537 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
02538 }
02539
02540
02541 VehicleOrderSaver orders(v);
02542
02543
02544
02545
02546
02547
02548
02549 if (v->current_order.IsType(OT_LEAVESTATION)) {
02550 orders.SwitchToNextOrder(false);
02551 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
02552 v->current_order.IsType(OT_GOTO_STATION) ?
02553 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
02554 v->tile == v->dest_tile))) {
02555 orders.SwitchToNextOrder(true);
02556 }
02557
02558 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02559
02560 bool path_found = true;
02561 TileIndex new_tile = res_dest.tile;
02562
02563 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
02564 if (new_tile == tile) best_track = next_track;
02565 v->HandlePathfindingResult(path_found);
02566 }
02567
02568
02569 if (!do_track_reservation) return best_track;
02570
02571
02572 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02573 if (mark_stuck) MarkTrainAsStuck(v);
02574 FreeTrainTrackReservation(v);
02575 return best_track;
02576 }
02577
02578
02579 if (res_dest.tile == INVALID_TILE) {
02580
02581 PBSTileInfo origin = FollowTrainReservation(v);
02582 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
02583 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
02584 best_track = FindFirstTrack(res);
02585 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02586 if (got_reservation != NULL) *got_reservation = true;
02587 if (changed_signal) MarkTileDirtyByTile(tile);
02588 } else {
02589 FreeTrainTrackReservation(v);
02590 if (mark_stuck) MarkTrainAsStuck(v);
02591 }
02592 return best_track;
02593 }
02594
02595 if (got_reservation != NULL) *got_reservation = true;
02596
02597
02598 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
02599
02600 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
02601 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
02602 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
02603 if (_settings_game.pf.forbid_90_deg) {
02604 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
02605 }
02606
02607
02608 if (orders.SwitchToNextOrder(true)) {
02609 PBSTileInfo cur_dest;
02610 bool path_found;
02611 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
02612 if (cur_dest.tile != INVALID_TILE) {
02613 res_dest = cur_dest;
02614 if (res_dest.okay) continue;
02615
02616 FreeTrainTrackReservation(v);
02617 if (mark_stuck) MarkTrainAsStuck(v);
02618 if (got_reservation != NULL) *got_reservation = false;
02619 changed_signal = false;
02620 break;
02621 }
02622 }
02623
02624 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
02625 FreeTrainTrackReservation(v);
02626 if (mark_stuck) MarkTrainAsStuck(v);
02627 if (got_reservation != NULL) *got_reservation = false;
02628 changed_signal = false;
02629 }
02630 break;
02631 }
02632
02633 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02634
02635 if (changed_signal) MarkTileDirtyByTile(tile);
02636
02637 return best_track;
02638 }
02639
02648 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
02649 {
02650 assert(v->IsFrontEngine());
02651
02652
02653
02654
02655 if (v->track == TRACK_BIT_DEPOT) {
02656 if (HasDepotReservation(v->tile)) {
02657 if (mark_as_stuck) MarkTrainAsStuck(v);
02658 return false;
02659 } else {
02660
02661 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
02662 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
02663 }
02664 }
02665
02666 Vehicle *other_train = NULL;
02667 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
02668
02669
02670
02671
02672
02673 if (other_train != NULL && other_train->index != v->index) {
02674 if (mark_as_stuck) MarkTrainAsStuck(v);
02675 return false;
02676 }
02677
02678 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
02679
02680 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02681 ClrBit(v->flags, VRF_TRAIN_STUCK);
02682 return true;
02683 }
02684
02685
02686 if (v->track == TRACK_BIT_DEPOT) {
02687 SetDepotReservation(v->tile, true);
02688 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02689 }
02690
02691 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
02692 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
02693 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
02694
02695 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
02696
02697 bool res_made = false;
02698 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
02699
02700 if (!res_made) {
02701
02702 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
02703 return false;
02704 }
02705
02706 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
02707 v->wait_counter = 0;
02708 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02709 }
02710 ClrBit(v->flags, VRF_TRAIN_STUCK);
02711 return true;
02712 }
02713
02714
02715 static bool CheckReverseTrain(const Train *v)
02716 {
02717 if (_settings_game.difficulty.line_reverse_mode != 0 ||
02718 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
02719 !(v->direction & 1)) {
02720 return false;
02721 }
02722
02723 assert(v->track != TRACK_BIT_NONE);
02724
02725 switch (_settings_game.pf.pathfinder_for_trains) {
02726 case VPF_NPF: return NPFTrainCheckReverse(v);
02727 case VPF_YAPF: return YapfTrainCheckReverse(v);
02728
02729 default: NOT_REACHED();
02730 }
02731 }
02732
02738 TileIndex Train::GetOrderStationLocation(StationID station)
02739 {
02740 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
02741
02742 const Station *st = Station::Get(station);
02743 if (!(st->facilities & FACIL_TRAIN)) {
02744
02745 this->IncrementRealOrderIndex();
02746 return 0;
02747 }
02748
02749 return st->xy;
02750 }
02751
02753 void Train::MarkDirty()
02754 {
02755 Train *v = this;
02756 do {
02757 v->UpdateViewport(false, false);
02758 } while ((v = v->Next()) != NULL);
02759
02760
02761 this->CargoChanged();
02762 this->UpdateAcceleration();
02763 }
02764
02772 int Train::UpdateSpeed()
02773 {
02774 switch (_settings_game.vehicle.train_acceleration_model) {
02775 default: NOT_REACHED();
02776 case AM_ORIGINAL:
02777 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, min(this->gcache.cached_max_track_speed, this->current_order.max_speed));
02778
02779 case AM_REALISTIC:
02780 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
02781 }
02782 }
02783
02789 static void TrainEnterStation(Train *v, StationID station)
02790 {
02791 v->last_station_visited = station;
02792
02793
02794 Station *st = Station::Get(station);
02795 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
02796 st->had_vehicle_of_type |= HVOT_TRAIN;
02797 SetDParam(0, st->index);
02798 AddVehicleNewsItem(
02799 STR_NEWS_FIRST_TRAIN_ARRIVAL,
02800 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
02801 v->index,
02802 st->index
02803 );
02804 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
02805 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
02806 }
02807
02808 v->force_proceed = TFP_NONE;
02809 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
02810
02811 v->BeginLoading();
02812
02813 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
02814 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
02815 }
02816
02817
02818 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
02819 {
02820 return IsTileOwner(tile, v->owner) &&
02821 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
02822 }
02823
02825 struct AccelerationSlowdownParams {
02826 byte small_turn;
02827 byte large_turn;
02828 byte z_up;
02829 byte z_down;
02830 };
02831
02833 static const AccelerationSlowdownParams _accel_slowdown[] = {
02834
02835 {256 / 4, 256 / 2, 256 / 4, 2},
02836 {256 / 4, 256 / 2, 256 / 4, 2},
02837 {0, 256 / 2, 256 / 4, 2},
02838 };
02839
02845 static inline void AffectSpeedByZChange(Train *v, int old_z)
02846 {
02847 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
02848
02849 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
02850
02851 if (old_z < v->z_pos) {
02852 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
02853 } else {
02854 uint16 spd = v->cur_speed + asp->z_down;
02855 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
02856 }
02857 }
02858
02859 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
02860 {
02861 if (IsTileType(tile, MP_RAILWAY) &&
02862 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
02863 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
02864 Trackdir trackdir = FindFirstTrackdir(tracks);
02865 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
02866
02867 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
02868 }
02869 }
02870 return false;
02871 }
02872
02874 void Train::ReserveTrackUnderConsist() const
02875 {
02876 for (const Train *u = this; u != NULL; u = u->Next()) {
02877 switch (u->track) {
02878 case TRACK_BIT_WORMHOLE:
02879 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
02880 break;
02881 case TRACK_BIT_DEPOT:
02882 break;
02883 default:
02884 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
02885 break;
02886 }
02887 }
02888 }
02889
02896 uint Train::Crash(bool flooded)
02897 {
02898 uint pass = 0;
02899 if (this->IsFrontEngine()) {
02900 pass += 2;
02901
02902
02903
02904 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
02905 for (const Train *v = this; v != NULL; v = v->Next()) {
02906 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
02907 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
02908
02909
02910 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
02911 }
02912 }
02913
02914
02915
02916 TileIndex crossing = TrainApproachingCrossingTile(this);
02917 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
02918
02919
02920 HideFillingPercent(&this->fill_percent_te_id);
02921 }
02922
02923 pass += this->GroundVehicleBase::Crash(flooded);
02924
02925 this->crash_anim_pos = flooded ? 4000 : 1;
02926 return pass;
02927 }
02928
02935 static uint TrainCrashed(Train *v)
02936 {
02937 uint num = 0;
02938
02939
02940 if (!(v->vehstatus & VS_CRASHED)) {
02941 num = v->Crash();
02942 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02943 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02944 }
02945
02946
02947
02948 v->ReserveTrackUnderConsist();
02949
02950 return num;
02951 }
02952
02954 struct TrainCollideChecker {
02955 Train *v;
02956 uint num;
02957 };
02958
02965 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
02966 {
02967 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
02968
02969
02970 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
02971
02972
02973 if (v->owner != tcc->v->owner) return NULL;
02974
02975
02976 Train *coll = Train::From(v)->First();
02977
02978
02979 if (coll == tcc->v) return NULL;
02980
02981 int x_diff = v->x_pos - tcc->v->x_pos;
02982 int y_diff = v->y_pos - tcc->v->y_pos;
02983
02984
02985
02986
02987
02988 uint hash = (y_diff + 7) | (x_diff + 7);
02989 if (hash & ~15) return NULL;
02990
02991
02992 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
02993 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
02994
02995
02996 if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
02997
02998
02999 tcc->num += TrainCrashed(tcc->v);
03000 tcc->num += TrainCrashed(coll);
03001
03002 return NULL;
03003 }
03004
03012 static bool CheckTrainCollision(Train *v)
03013 {
03014
03015 if (v->track == TRACK_BIT_DEPOT) return false;
03016
03017 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
03018
03019 TrainCollideChecker tcc;
03020 tcc.v = v;
03021 tcc.num = 0;
03022
03023
03024 if (v->track == TRACK_BIT_WORMHOLE) {
03025 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
03026 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
03027 } else {
03028 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
03029 }
03030
03031
03032 if (tcc.num == 0) return false;
03033
03034 SetDParam(0, tcc.num);
03035 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
03036
03037 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
03038 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
03039 return true;
03040 }
03041
03042 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
03043 {
03044 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
03045
03046 Train *t = Train::From(v);
03047 DiagDirection exitdir = *(DiagDirection *)data;
03048
03049
03050 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
03051
03052 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
03053
03054 return t;
03055 }
03056
03064 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
03065 {
03066 Train *first = v->First();
03067 Train *prev;
03068 bool direction_changed = false;
03069
03070
03071 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
03072 DiagDirection enterdir = DIAGDIR_BEGIN;
03073 bool update_signals_crossing = false;
03074
03075 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
03076 if (v->track != TRACK_BIT_WORMHOLE) {
03077
03078 if (gp.old_tile == gp.new_tile) {
03079
03080 if (v->track == TRACK_BIT_DEPOT) {
03081
03082 gp.x = v->x_pos;
03083 gp.y = v->y_pos;
03084 } else {
03085
03086
03087
03088 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
03089
03090 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03091 if (HasBit(r, VETS_CANNOT_ENTER)) {
03092 goto invalid_rail;
03093 }
03094 if (HasBit(r, VETS_ENTERED_STATION)) {
03095
03096 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03097 }
03098 }
03099 } else {
03100
03101
03102
03103 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
03104 assert(IsValidDiagDirection(enterdir));
03105
03106
03107
03108 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
03109 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
03110
03111 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03112 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
03113
03114 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03115 if (_settings_game.pf.forbid_90_deg && prev == NULL) {
03116
03117
03118 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03119 }
03120
03121 if (bits == TRACK_BIT_NONE) goto invalid_rail;
03122
03123
03124
03125 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
03126
03127 TrackBits chosen_track;
03128 if (prev == NULL) {
03129
03130
03131 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
03132 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
03133
03134 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
03135
03136
03137
03138
03139 Trackdir dir = FindFirstTrackdir(trackdirbits);
03140 if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
03141 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
03142
03143
03144 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
03145 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03146 }
03147 }
03148
03149
03150 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
03151
03152 Trackdir i = FindFirstTrackdir(trackdirbits);
03153
03154
03155 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
03156
03157 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
03158 v->cur_speed = 0;
03159 v->subspeed = 0;
03160 v->progress = 255 - 100;
03161 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
03162 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
03163 v->cur_speed = 0;
03164 v->subspeed = 0;
03165 v->progress = 255 - 10;
03166 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
03167 DiagDirection exitdir = TrackdirToExitdir(i);
03168 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
03169
03170 exitdir = ReverseDiagDir(exitdir);
03171
03172
03173 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
03174 }
03175 }
03176
03177
03178
03179
03180
03181 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
03182 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
03183 v->wait_counter = 0;
03184 return false;
03185 }
03186 goto reverse_train_direction;
03187 } else {
03188 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
03189 }
03190 } else {
03191
03192 if (prev->tile == gp.new_tile) {
03193
03194 if (prev->track == TRACK_BIT_WORMHOLE) {
03195
03196
03197 assert(IsTunnel(prev->tile));
03198 chosen_track = bits;
03199 } else {
03200 chosen_track = prev->track;
03201 }
03202 } else {
03203
03204
03205
03206
03207
03208
03209
03210 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
03211 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
03212 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
03213 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
03214 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
03215 };
03216 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
03217 assert(IsValidDiagDirection(exitdir));
03218 chosen_track = _connecting_track[enterdir][exitdir];
03219 }
03220 chosen_track &= bits;
03221 }
03222
03223
03224 assert(
03225 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
03226 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
03227 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
03228
03229
03230 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
03231 gp.x = (gp.x & ~0xF) | b[0];
03232 gp.y = (gp.y & ~0xF) | b[1];
03233 Direction chosen_dir = (Direction)b[2];
03234
03235
03236 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03237 if (HasBit(r, VETS_CANNOT_ENTER)) {
03238 goto invalid_rail;
03239 }
03240
03241 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
03242 Track track = FindFirstTrack(chosen_track);
03243 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
03244 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
03245 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
03246 MarkTileDirtyByTile(gp.new_tile);
03247 }
03248
03249
03250 if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
03251
03252 v->tile = gp.new_tile;
03253
03254 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
03255 v->First()->ConsistChanged(true);
03256 }
03257
03258 v->track = chosen_track;
03259 assert(v->track);
03260 }
03261
03262
03263
03264 update_signals_crossing = true;
03265
03266 if (chosen_dir != v->direction) {
03267 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
03268 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
03269 DirDiff diff = DirDifference(v->direction, chosen_dir);
03270 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
03271 }
03272 direction_changed = true;
03273 v->direction = chosen_dir;
03274 }
03275
03276 if (v->IsFrontEngine()) {
03277 v->wait_counter = 0;
03278
03279
03280 TileIndex crossing = TrainApproachingCrossingTile(v);
03281 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.new_year) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
03282
03283
03284 CheckNextTrainTile(v);
03285 }
03286
03287 if (HasBit(r, VETS_ENTERED_STATION)) {
03288
03289 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03290 }
03291 }
03292 } else {
03293 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
03294
03295 if (v->IsFrontEngine()) {
03296 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
03297 CheckNextTrainTile(v);
03298 }
03299
03300
03301 if (gp.old_tile == gp.new_tile) {
03302 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
03303 }
03304 } else {
03305 v->x_pos = gp.x;
03306 v->y_pos = gp.y;
03307 VehicleUpdatePosition(v);
03308 if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
03309 continue;
03310 }
03311 }
03312
03313
03314 v->UpdateDeltaXY(v->direction);
03315
03316 v->x_pos = gp.x;
03317 v->y_pos = gp.y;
03318 VehicleUpdatePosition(v);
03319
03320
03321 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
03322
03323 if (prev == NULL) {
03324
03325 AffectSpeedByZChange(v, old_z);
03326 }
03327
03328 if (update_signals_crossing) {
03329 if (v->IsFrontEngine()) {
03330 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
03331
03332
03333
03334
03335
03336
03337
03338
03339 if ((!HasReservedTracks(gp.new_tile, v->track) &&
03340 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
03341 !TryPathReserve(v)) {
03342 MarkTrainAsStuck(v);
03343 }
03344 }
03345 }
03346
03347
03348
03349 if (v->Next() == NULL) {
03350 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
03351 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
03352 }
03353 }
03354
03355
03356 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
03357 }
03358
03359 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
03360
03361 return true;
03362
03363 invalid_rail:
03364
03365 if (prev != NULL) error("Disconnecting train");
03366
03367 reverse_train_direction:
03368 if (reverse) {
03369 v->wait_counter = 0;
03370 v->cur_speed = 0;
03371 v->subspeed = 0;
03372 ReverseTrainDirection(v);
03373 }
03374
03375 return false;
03376 }
03377
03384 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
03385 {
03386 TrackBits *trackbits = (TrackBits *)data;
03387
03388 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
03389 TrackBits train_tbits = Train::From(v)->track;
03390 if (train_tbits == TRACK_BIT_WORMHOLE) {
03391
03392 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
03393 } else if (train_tbits != TRACK_BIT_DEPOT) {
03394 *trackbits |= train_tbits;
03395 }
03396 }
03397
03398 return NULL;
03399 }
03400
03408 static void DeleteLastWagon(Train *v)
03409 {
03410 Train *first = v->First();
03411
03412
03413
03414
03415 Train *u = v;
03416 for (; v->Next() != NULL; v = v->Next()) u = v;
03417 u->SetNext(NULL);
03418
03419 if (first != v) {
03420
03421 first->ConsistChanged(false);
03422
03423
03424 if (first->track == TRACK_BIT_DEPOT) {
03425 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
03426 }
03427 }
03428
03429
03430 TrackBits trackbits = v->track;
03431 TileIndex tile = v->tile;
03432 Owner owner = v->owner;
03433
03434 delete v;
03435 v = NULL;
03436
03437 if (trackbits == TRACK_BIT_WORMHOLE) {
03438
03439 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
03440 }
03441
03442 Track track = TrackBitsToTrack(trackbits);
03443 if (HasReservedTracks(tile, trackbits)) {
03444 UnreserveRailTrack(tile, track);
03445
03446
03447 TrackBits remaining_trackbits = TRACK_BIT_NONE;
03448 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
03449
03450
03451 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
03452 Track t;
03453 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
03454 }
03455
03456
03457 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
03458
03459
03460 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
03461 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
03462 } else {
03463 SetSignalsOnBothDir(tile, track, owner);
03464 }
03465 }
03466
03471 static void ChangeTrainDirRandomly(Train *v)
03472 {
03473 static const DirDiff delta[] = {
03474 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
03475 };
03476
03477 do {
03478
03479 if (!(v->vehstatus & VS_HIDDEN)) {
03480 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
03481 v->UpdateDeltaXY(v->direction);
03482 v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
03483
03484
03485
03486 if (v->track != TRACK_BIT_WORMHOLE) {
03487 VehicleUpdatePosition(v);
03488 v->UpdateInclination(false, false);
03489 }
03490 }
03491 } while ((v = v->Next()) != NULL);
03492 }
03493
03499 static bool HandleCrashedTrain(Train *v)
03500 {
03501 int state = ++v->crash_anim_pos;
03502
03503 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
03504 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
03505 }
03506
03507 uint32 r;
03508 if (state <= 200 && Chance16R(1, 7, r)) {
03509 int index = (r * 10 >> 16);
03510
03511 Vehicle *u = v;
03512 do {
03513 if (--index < 0) {
03514 r = Random();
03515
03516 CreateEffectVehicleRel(u,
03517 GB(r, 8, 3) + 2,
03518 GB(r, 16, 3) + 2,
03519 GB(r, 0, 3) + 5,
03520 EV_EXPLOSION_SMALL);
03521 break;
03522 }
03523 } while ((u = u->Next()) != NULL);
03524 }
03525
03526 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
03527
03528 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
03529 bool ret = v->Next() != NULL;
03530 DeleteLastWagon(v);
03531 return ret;
03532 }
03533
03534 return true;
03535 }
03536
03538 static const uint16 _breakdown_speeds[16] = {
03539 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
03540 };
03541
03542
03551 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
03552 {
03553
03554 uint x = v->x_pos & 0xF;
03555 uint y = v->y_pos & 0xF;
03556
03557
03558
03559 switch (v->direction) {
03560 case DIR_N : x = ~x + ~y + 25; break;
03561 case DIR_NW: x = y;
03562 case DIR_NE: x = ~x + 16; break;
03563 case DIR_E : x = ~x + y + 9; break;
03564 case DIR_SE: x = y; break;
03565 case DIR_S : x = x + y - 7; break;
03566 case DIR_W : x = ~y + x + 9; break;
03567 default: break;
03568 }
03569
03570
03571
03572
03573
03574
03575 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
03576
03577 v->cur_speed = 0;
03578 if (reverse) ReverseTrainDirection(v);
03579 return false;
03580 }
03581
03582
03583 v->vehstatus |= VS_TRAIN_SLOWING;
03584 uint16 break_speed = _breakdown_speeds[x & 0xF];
03585 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03586
03587 return true;
03588 }
03589
03590
03596 static bool TrainCanLeaveTile(const Train *v)
03597 {
03598
03599 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
03600
03601 TileIndex tile = v->tile;
03602
03603
03604 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
03605 DiagDirection dir = GetTunnelBridgeDirection(tile);
03606 if (DiagDirToDir(dir) == v->direction) return false;
03607 }
03608
03609
03610 if (IsRailDepotTile(tile)) {
03611 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
03612 if (DiagDirToDir(dir) == v->direction) return false;
03613 }
03614
03615 return true;
03616 }
03617
03618
03626 static TileIndex TrainApproachingCrossingTile(const Train *v)
03627 {
03628 assert(v->IsFrontEngine());
03629 assert(!(v->vehstatus & VS_CRASHED));
03630
03631 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
03632
03633 DiagDirection dir = TrainExitDir(v->direction, v->track);
03634 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03635
03636
03637 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
03638 !CheckCompatibleRail(v, tile)) {
03639 return INVALID_TILE;
03640 }
03641
03642 return tile;
03643 }
03644
03645
03653 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
03654 {
03655
03656
03657 int t = v->breakdown_ctr;
03658 if (t > 1) {
03659 v->vehstatus |= VS_TRAIN_SLOWING;
03660
03661 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
03662 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03663 } else {
03664 v->vehstatus &= ~VS_TRAIN_SLOWING;
03665 }
03666
03667 if (!TrainCanLeaveTile(v)) return true;
03668
03669
03670 DiagDirection dir = TrainExitDir(v->direction, v->track);
03671
03672 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03673
03674
03675 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
03676 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
03677
03678 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03679 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
03680
03681
03682
03683
03684 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03685 if (_settings_game.pf.forbid_90_deg) {
03686 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03687 }
03688
03689
03690 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
03691 return TrainApproachingLineEnd(v, false, reverse);
03692 }
03693
03694
03695 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
03696
03697
03698 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
03699
03700 return true;
03701 }
03702
03703
03704 static bool TrainLocoHandler(Train *v, bool mode)
03705 {
03706
03707 if (v->vehstatus & VS_CRASHED) {
03708 return mode ? true : HandleCrashedTrain(v);
03709 }
03710
03711 if (v->force_proceed != TFP_NONE) {
03712 ClrBit(v->flags, VRF_TRAIN_STUCK);
03713 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03714 }
03715
03716
03717 if (v->HandleBreakdown()) return true;
03718
03719 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
03720 ReverseTrainDirection(v);
03721 }
03722
03723
03724 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
03725
03726 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
03727 if (ProcessOrders(v) && CheckReverseTrain(v)) {
03728 v->wait_counter = 0;
03729 v->cur_speed = 0;
03730 v->subspeed = 0;
03731 ClrBit(v->flags, VRF_LEAVING_STATION);
03732 ReverseTrainDirection(v);
03733 return true;
03734 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
03735
03736
03737
03738 DiagDirection dir = TrainExitDir(v->direction, v->track);
03739 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
03740
03741 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
03742 TryPathReserve(v, true, true);
03743 }
03744 ClrBit(v->flags, VRF_LEAVING_STATION);
03745 }
03746
03747 v->HandleLoading(mode);
03748
03749 if (v->current_order.IsType(OT_LOADING)) return true;
03750
03751 if (CheckTrainStayInDepot(v)) return true;
03752
03753 if (!mode) v->ShowVisualEffect();
03754
03755
03756 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
03757 CheckNextTrainTile(v);
03758 }
03759
03760
03761 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
03762 ++v->wait_counter;
03763
03764
03765 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
03766
03767 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
03768 if (!TryPathReserve(v)) {
03769
03770 if (turn_around) ReverseTrainDirection(v);
03771
03772 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
03773
03774 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
03775 SetDParam(0, v->index);
03776 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
03777 }
03778 v->wait_counter = 0;
03779 }
03780
03781 if (v->force_proceed == TFP_NONE) return true;
03782 ClrBit(v->flags, VRF_TRAIN_STUCK);
03783 v->wait_counter = 0;
03784 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03785 }
03786 }
03787
03788 if (v->current_order.IsType(OT_LEAVESTATION)) {
03789 v->current_order.Free();
03790 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03791 return true;
03792 }
03793
03794 int j = v->UpdateSpeed();
03795
03796
03797 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
03798
03799 v->force_proceed = TFP_NONE;
03800 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03801 }
03802
03803 int adv_spd = v->GetAdvanceDistance();
03804 if (j < adv_spd) {
03805
03806 if (v->cur_speed == 0) v->SetLastSpeed();
03807 } else {
03808 TrainCheckIfLineEnds(v);
03809
03810 for (;;) {
03811 j -= adv_spd;
03812 TrainController(v, NULL);
03813
03814 if (CheckTrainCollision(v)) break;
03815
03816 adv_spd = v->GetAdvanceDistance();
03817
03818
03819 if (j < adv_spd || v->cur_speed == 0) break;
03820
03821 OrderType order_type = v->current_order.GetType();
03822
03823 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
03824 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
03825 IsTileType(v->tile, MP_STATION) &&
03826 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
03827 ProcessOrders(v);
03828 }
03829 }
03830 v->SetLastSpeed();
03831 }
03832
03833 for (Train *u = v; u != NULL; u = u->Next()) {
03834 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
03835
03836 u->UpdateViewport(false, false);
03837 }
03838
03839 if (v->progress == 0) v->progress = j;
03840
03841 return true;
03842 }
03843
03848 Money Train::GetRunningCost() const
03849 {
03850 Money cost = 0;
03851 const Train *v = this;
03852
03853 do {
03854 const Engine *e = v->GetEngine();
03855 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
03856
03857 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
03858 if (cost_factor == 0) continue;
03859
03860
03861 if (v->IsMultiheaded()) cost_factor /= 2;
03862
03863 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
03864 } while ((v = v->GetNextVehicle()) != NULL);
03865
03866 return cost;
03867 }
03868
03873 bool Train::Tick()
03874 {
03875 this->tick_counter++;
03876
03877 if (this->IsFrontEngine()) {
03878 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
03879
03880 this->current_order_time++;
03881
03882 if (!TrainLocoHandler(this, false)) return false;
03883
03884 return TrainLocoHandler(this, true);
03885 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
03886
03887 if (++this->crash_anim_pos >= 4400) {
03888 delete this;
03889 return false;
03890 }
03891 }
03892
03893 return true;
03894 }
03895
03900 static void CheckIfTrainNeedsService(Train *v)
03901 {
03902 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
03903 if (v->IsChainInDepot()) {
03904 VehicleServiceInDepot(v);
03905 return;
03906 }
03907
03908 uint max_penalty;
03909 switch (_settings_game.pf.pathfinder_for_trains) {
03910 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
03911 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
03912 default: NOT_REACHED();
03913 }
03914
03915 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
03916
03917 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
03918 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
03919
03920
03921
03922 v->current_order.MakeDummy();
03923 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03924 }
03925 return;
03926 }
03927
03928 DepotID depot = GetDepotIndex(tfdd.tile);
03929
03930 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
03931 v->current_order.GetDestination() != depot &&
03932 !Chance16(3, 16)) {
03933 return;
03934 }
03935
03936 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
03937 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
03938 v->dest_tile = tfdd.tile;
03939 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03940 }
03941
03943 void Train::OnNewDay()
03944 {
03945 AgeVehicle(this);
03946
03947 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
03948
03949 if (this->IsFrontEngine()) {
03950 CheckVehicleBreakdown(this);
03951
03952 CheckIfTrainNeedsService(this);
03953
03954 CheckOrders(this);
03955
03956
03957 if (this->current_order.IsType(OT_GOTO_STATION)) {
03958 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
03959 if (tile != INVALID_TILE) this->dest_tile = tile;
03960 }
03961
03962 if (this->running_ticks != 0) {
03963
03964 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
03965
03966 this->profit_this_year -= cost.GetCost();
03967 this->running_ticks = 0;
03968
03969 SubtractMoneyFromCompanyFract(this->owner, cost);
03970
03971 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
03972 SetWindowClassesDirty(WC_TRAINS_LIST);
03973 }
03974 }
03975 }
03976
03981 Trackdir Train::GetVehicleTrackdir() const
03982 {
03983 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
03984
03985 if (this->track == TRACK_BIT_DEPOT) {
03986
03987 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile));
03988 }
03989
03990 if (this->track == TRACK_BIT_WORMHOLE) {
03991
03992 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
03993 }
03994
03995 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
03996 }