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
00119 void Train::RailtypeChanged()
00120 {
00121 for (Train *u = this; u != NULL; u = u->Next()) {
00122
00123 u->UpdateVisualEffect(false);
00124 }
00125 this->PowerChanged();
00126 if (this->IsFrontEngine()) this->UpdateAcceleration();
00127 }
00128
00135 void Train::ConsistChanged(bool same_length)
00136 {
00137 uint16 max_speed = UINT16_MAX;
00138
00139 assert(this->IsFrontEngine() || this->IsFreeWagon());
00140
00141 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
00142 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
00143 this->gcache.cached_total_length = 0;
00144 this->compatible_railtypes = RAILTYPES_NONE;
00145
00146 bool train_can_tilt = true;
00147
00148 for (Train *u = this; u != NULL; u = u->Next()) {
00149 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
00150
00151
00152 assert(u->First() == this);
00153
00154
00155 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
00156 u->railtype = rvi_u->railtype;
00157
00158 if (u->IsEngine()) first_engine = u->engine_type;
00159
00160
00161 u->tcache.user_def_data = rvi_u->user_def_data;
00162 this->InvalidateNewGRFCache();
00163 u->InvalidateNewGRFCache();
00164 }
00165
00166 for (Train *u = this; u != NULL; u = u->Next()) {
00167
00168 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
00169 this->InvalidateNewGRFCache();
00170 u->InvalidateNewGRFCache();
00171 }
00172
00173 for (Train *u = this; u != NULL; u = u->Next()) {
00174 const Engine *e_u = u->GetEngine();
00175 const RailVehicleInfo *rvi_u = &e_u->u.rail;
00176
00177 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
00178
00179
00180 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
00181
00182
00183 u->colourmap = PAL_NONE;
00184
00185
00186 u->UpdateVisualEffect(true);
00187
00188 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
00189 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
00190
00191 SetBit(u->flags, VRF_POWEREDWAGON);
00192 } else {
00193 ClrBit(u->flags, VRF_POWEREDWAGON);
00194 }
00195
00196 if (!u->IsArticulatedPart()) {
00197
00198
00199 if (rvi_u->power > 0) {
00200 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
00201 }
00202
00203
00204
00205 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
00206 u->railtype = RAILTYPE_RAIL;
00207 u->compatible_railtypes |= RAILTYPES_RAIL;
00208 }
00209
00210
00211 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
00212 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
00213 if (speed != 0) max_speed = min(speed, max_speed);
00214 }
00215 }
00216
00217 u->cargo_cap = e_u->DetermineCapacity(u);
00218 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
00219
00220
00221 uint16 veh_len = CALLBACK_FAILED;
00222 if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
00223
00224 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
00225 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
00226
00227 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
00228 }
00229 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
00230 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
00231 }
00232 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
00233 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
00234
00235
00236 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
00237
00238
00239 if (!same_length) u->gcache.cached_veh_length = veh_len;
00240
00241 this->gcache.cached_total_length += u->gcache.cached_veh_length;
00242 this->InvalidateNewGRFCache();
00243 u->InvalidateNewGRFCache();
00244 }
00245
00246
00247 this->vcache.cached_max_speed = max_speed;
00248 this->tcache.cached_tilt = train_can_tilt;
00249 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
00250
00251
00252 this->CargoChanged();
00253
00254 if (this->IsFrontEngine()) {
00255 this->UpdateAcceleration();
00256 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00257 InvalidateWindowData(WC_VEHICLE_REFIT, this->index);
00258 }
00259 }
00260
00271 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
00272 {
00273 const Station *st = Station::Get(station_id);
00274 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
00275 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
00276
00277
00278
00279 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
00280 if (v->gcache.cached_total_length >= *station_length) {
00281
00282 osl = OSL_PLATFORM_FAR_END;
00283 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
00284 osl = v->current_order.GetStopLocation();
00285 }
00286
00287
00288 int stop;
00289 switch (osl) {
00290 default: NOT_REACHED();
00291
00292 case OSL_PLATFORM_NEAR_END:
00293 stop = v->gcache.cached_total_length;
00294 break;
00295
00296 case OSL_PLATFORM_MIDDLE:
00297 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
00298 break;
00299
00300 case OSL_PLATFORM_FAR_END:
00301 stop = *station_length;
00302 break;
00303 }
00304
00305
00306
00307 return stop - (v->gcache.cached_veh_length + 1) / 2;
00308 }
00309
00310
00315 int Train::GetCurveSpeedLimit() const
00316 {
00317 assert(this->First() == this);
00318
00319 static const int absolute_max_speed = UINT16_MAX;
00320 int max_speed = absolute_max_speed;
00321
00322 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
00323
00324 int curvecount[2] = {0, 0};
00325
00326
00327 int numcurve = 0;
00328 int sum = 0;
00329 int pos = 0;
00330 int lastpos = -1;
00331 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
00332 Direction this_dir = u->direction;
00333 Direction next_dir = u->Next()->direction;
00334
00335 DirDiff dirdiff = DirDifference(this_dir, next_dir);
00336 if (dirdiff == DIRDIFF_SAME) continue;
00337
00338 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
00339 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
00340 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
00341 if (lastpos != -1) {
00342 numcurve++;
00343 sum += pos - lastpos;
00344 if (pos - lastpos == 1 && max_speed > 88) {
00345 max_speed = 88;
00346 }
00347 }
00348 lastpos = pos;
00349 }
00350
00351
00352 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
00353 max_speed = 61;
00354 }
00355 }
00356
00357 if (numcurve > 0 && max_speed > 88) {
00358 if (curvecount[0] == 1 && curvecount[1] == 1) {
00359 max_speed = absolute_max_speed;
00360 } else {
00361 sum /= numcurve;
00362 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
00363 }
00364 }
00365
00366 if (max_speed != absolute_max_speed) {
00367
00368 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
00369 max_speed += (max_speed / 2) * rti->curve_speed;
00370
00371 if (this->tcache.cached_tilt) {
00372
00373 max_speed += max_speed / 5;
00374 }
00375 }
00376
00377 return max_speed;
00378 }
00379
00384 int Train::GetCurrentMaxSpeed() const
00385 {
00386 int max_speed = this->tcache.cached_max_curve_speed;
00387 assert(max_speed == this->GetCurveSpeedLimit());
00388
00389 if (IsRailStationTile(this->tile)) {
00390 StationID sid = GetStationIndex(this->tile);
00391 if (this->current_order.ShouldStopAtStation(this, sid)) {
00392 int station_ahead;
00393 int station_length;
00394 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
00395
00396
00397
00398 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
00399
00400 if (distance_to_go > 0) {
00401 int st_max_speed = 120;
00402
00403 int delta_v = this->cur_speed / (distance_to_go + 1);
00404 if (max_speed > (this->cur_speed - delta_v)) {
00405 st_max_speed = this->cur_speed - (delta_v / 10);
00406 }
00407
00408 st_max_speed = max(st_max_speed, 25 * distance_to_go);
00409 max_speed = min(max_speed, st_max_speed);
00410 }
00411 }
00412 }
00413
00414 for (const Train *u = this; u != NULL; u = u->Next()) {
00415 if (u->track == TRACK_BIT_DEPOT) {
00416 max_speed = min(max_speed, 61);
00417 break;
00418 }
00419 }
00420
00421 return min(max_speed, this->gcache.cached_max_track_speed);
00422 }
00423
00425 void Train::UpdateAcceleration()
00426 {
00427 assert(this->IsFrontEngine());
00428
00429 uint power = this->gcache.cached_power;
00430 uint weight = this->gcache.cached_weight;
00431 assert(weight != 0);
00432 this->acceleration = Clamp(power / weight * 4, 1, 255);
00433 }
00434
00440 int Train::GetDisplayImageWidth(Point *offset) const
00441 {
00442 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
00443 int vehicle_pitch = 0;
00444
00445 const Engine *e = this->GetEngine();
00446 if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
00447 reference_width = e->GetGRF()->traininfo_vehicle_width;
00448 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
00449 }
00450
00451 if (offset != NULL) {
00452 offset->x = reference_width / 2;
00453 offset->y = vehicle_pitch;
00454 }
00455 return this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
00456 }
00457
00458 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
00459 {
00460 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
00461 }
00462
00469 SpriteID Train::GetImage(Direction direction, EngineImageType image_type) const
00470 {
00471 uint8 spritenum = this->spritenum;
00472 SpriteID sprite;
00473
00474 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
00475
00476 if (is_custom_sprite(spritenum)) {
00477 sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
00478 if (sprite != 0) return sprite;
00479
00480 spritenum = this->GetEngine()->original_image_index;
00481 }
00482
00483 sprite = GetDefaultTrainSprite(spritenum, direction);
00484
00485 if (this->cargo.Count() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
00486
00487 return sprite;
00488 }
00489
00490 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type)
00491 {
00492 const Engine *e = Engine::Get(engine);
00493 Direction dir = rear_head ? DIR_E : DIR_W;
00494 uint8 spritenum = e->u.rail.image_index;
00495
00496 if (is_custom_sprite(spritenum)) {
00497 SpriteID sprite = GetCustomVehicleIcon(engine, dir, image_type);
00498 if (sprite != 0) {
00499 if (e->GetGRF() != NULL) {
00500 y += e->GetGRF()->traininfo_vehicle_pitch;
00501 }
00502 return sprite;
00503 }
00504
00505 spritenum = Engine::Get(engine)->original_image_index;
00506 }
00507
00508 if (rear_head) spritenum++;
00509
00510 return GetDefaultTrainSprite(spritenum, DIR_W);
00511 }
00512
00513 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
00514 {
00515 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
00516 int yf = y;
00517 int yr = y;
00518
00519 SpriteID spritef = GetRailIcon(engine, false, yf, image_type);
00520 SpriteID spriter = GetRailIcon(engine, true, yr, image_type);
00521 const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
00522 const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
00523
00524 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);
00525
00526 DrawSprite(spritef, pal, preferred_x - 14, yf);
00527 DrawSprite(spriter, pal, preferred_x + 15, yr);
00528 } else {
00529 SpriteID sprite = GetRailIcon(engine, false, y, image_type);
00530 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00531 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));
00532 DrawSprite(sprite, pal, preferred_x, y);
00533 }
00534 }
00535
00544 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
00545 {
00546 const RailVehicleInfo *rvi = &e->u.rail;
00547
00548
00549 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00550
00551 if (flags & DC_EXEC) {
00552 Train *v = new Train();
00553 *ret = v;
00554 v->spritenum = rvi->image_index;
00555
00556 v->engine_type = e->index;
00557 v->gcache.first_engine = INVALID_ENGINE;
00558
00559 DiagDirection dir = GetRailDepotDirection(tile);
00560
00561 v->direction = DiagDirToDir(dir);
00562 v->tile = tile;
00563
00564 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
00565 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
00566
00567 v->x_pos = x;
00568 v->y_pos = y;
00569 v->z_pos = GetSlopePixelZ(x, y);
00570 v->owner = _current_company;
00571 v->track = TRACK_BIT_DEPOT;
00572 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
00573
00574 v->SetWagon();
00575
00576 v->SetFreeWagon();
00577 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00578
00579 v->cargo_type = e->GetDefaultCargoType();
00580 v->cargo_cap = rvi->capacity;
00581
00582 v->railtype = rvi->railtype;
00583
00584 v->build_year = _cur_year;
00585 v->cur_image = SPR_IMG_QUERY;
00586 v->random_bits = VehicleRandomBits();
00587
00588 v->group_id = DEFAULT_GROUP;
00589
00590 AddArticulatedParts(v);
00591
00592 _new_vehicle_id = v->index;
00593
00594 VehicleUpdatePosition(v);
00595 v->First()->ConsistChanged(false);
00596 UpdateTrainGroupID(v->First());
00597
00598 CheckConsistencyOfArticulatedVehicle(v);
00599
00600
00601 Train *w;
00602 FOR_ALL_TRAINS(w) {
00603 if (w->tile == tile &&
00604 w->IsFreeWagon() &&
00605 w->engine_type == e->index &&
00606 w->First() != v &&
00607 !(w->vehstatus & VS_CRASHED)) {
00608 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
00609 break;
00610 }
00611 }
00612 }
00613
00614 return CommandCost();
00615 }
00616
00618 static void NormalizeTrainVehInDepot(const Train *u)
00619 {
00620 const Train *v;
00621 FOR_ALL_TRAINS(v) {
00622 if (v->IsFreeWagon() && v->tile == u->tile &&
00623 v->track == TRACK_BIT_DEPOT) {
00624 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
00625 CMD_MOVE_RAIL_VEHICLE).Failed())
00626 break;
00627 }
00628 }
00629 }
00630
00631 static void AddRearEngineToMultiheadedTrain(Train *v)
00632 {
00633 Train *u = new Train();
00634 v->value >>= 1;
00635 u->value = v->value;
00636 u->direction = v->direction;
00637 u->owner = v->owner;
00638 u->tile = v->tile;
00639 u->x_pos = v->x_pos;
00640 u->y_pos = v->y_pos;
00641 u->z_pos = v->z_pos;
00642 u->track = TRACK_BIT_DEPOT;
00643 u->vehstatus = v->vehstatus & ~VS_STOPPED;
00644 u->spritenum = v->spritenum + 1;
00645 u->cargo_type = v->cargo_type;
00646 u->cargo_subtype = v->cargo_subtype;
00647 u->cargo_cap = v->cargo_cap;
00648 u->railtype = v->railtype;
00649 u->engine_type = v->engine_type;
00650 u->build_year = v->build_year;
00651 u->cur_image = SPR_IMG_QUERY;
00652 u->random_bits = VehicleRandomBits();
00653 v->SetMultiheaded();
00654 u->SetMultiheaded();
00655 v->SetNext(u);
00656 VehicleUpdatePosition(u);
00657
00658
00659 v->other_multiheaded_part = u;
00660 u->other_multiheaded_part = v;
00661 }
00662
00672 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00673 {
00674 const RailVehicleInfo *rvi = &e->u.rail;
00675
00676 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
00677
00678
00679
00680 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
00681
00682 if (flags & DC_EXEC) {
00683 DiagDirection dir = GetRailDepotDirection(tile);
00684 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
00685 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
00686
00687 Train *v = new Train();
00688 *ret = v;
00689 v->direction = DiagDirToDir(dir);
00690 v->tile = tile;
00691 v->owner = _current_company;
00692 v->x_pos = x;
00693 v->y_pos = y;
00694 v->z_pos = GetSlopePixelZ(x, y);
00695 v->track = TRACK_BIT_DEPOT;
00696 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00697 v->spritenum = rvi->image_index;
00698 v->cargo_type = e->GetDefaultCargoType();
00699 v->cargo_cap = rvi->capacity;
00700 v->last_station_visited = INVALID_STATION;
00701 v->last_loading_station = INVALID_STATION;
00702
00703 v->engine_type = e->index;
00704 v->gcache.first_engine = INVALID_ENGINE;
00705
00706 v->reliability = e->reliability;
00707 v->reliability_spd_dec = e->reliability_spd_dec;
00708 v->max_age = e->GetLifeLengthInDays();
00709
00710 v->railtype = rvi->railtype;
00711 _new_vehicle_id = v->index;
00712
00713 v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_trains;
00714 v->date_of_last_service = _date;
00715 v->build_year = _cur_year;
00716 v->cur_image = SPR_IMG_QUERY;
00717 v->random_bits = VehicleRandomBits();
00718
00719 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00720
00721 v->group_id = DEFAULT_GROUP;
00722
00723 v->SetFrontEngine();
00724 v->SetEngine();
00725
00726 VehicleUpdatePosition(v);
00727
00728 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
00729 AddRearEngineToMultiheadedTrain(v);
00730 } else {
00731 AddArticulatedParts(v);
00732 }
00733
00734 v->ConsistChanged(false);
00735 UpdateTrainGroupID(v);
00736
00737 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) {
00738 NormalizeTrainVehInDepot(v);
00739 }
00740
00741 CheckConsistencyOfArticulatedVehicle(v);
00742 }
00743
00744 return CommandCost();
00745 }
00746
00751 bool Train::IsInDepot() const
00752 {
00753
00754 if (!IsRailDepotTile(this->tile) || this->cur_speed != 0) return false;
00755
00756
00757 for (const Train *v = this; v != NULL; v = v->Next()) {
00758 if (v->track != TRACK_BIT_DEPOT || v->tile != this->tile) return false;
00759 }
00760
00761 return true;
00762 }
00763
00768 bool Train::IsStoppedInDepot() const
00769 {
00770
00771 if (this->IsFrontEngine() && !(this->vehstatus & VS_STOPPED)) return false;
00772 return this->IsInDepot();
00773 }
00774
00775 static Train *FindGoodVehiclePos(const Train *src)
00776 {
00777 EngineID eng = src->engine_type;
00778 TileIndex tile = src->tile;
00779
00780 Train *dst;
00781 FOR_ALL_TRAINS(dst) {
00782 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
00783
00784 Train *t = dst;
00785 while (t->engine_type == eng) {
00786 t = t->Next();
00787 if (t == NULL) return dst;
00788 }
00789 }
00790 }
00791
00792 return NULL;
00793 }
00794
00796 typedef SmallVector<Train *, 16> TrainList;
00797
00803 static void MakeTrainBackup(TrainList &list, Train *t)
00804 {
00805 for (; t != NULL; t = t->Next()) *list.Append() = t;
00806 }
00807
00812 static void RestoreTrainBackup(TrainList &list)
00813 {
00814
00815 if (list.Length() == 0) return;
00816
00817 Train *prev = NULL;
00818
00819 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
00820 Train *t = *iter;
00821 if (prev != NULL) {
00822 prev->SetNext(t);
00823 } else if (t->Previous() != NULL) {
00824
00825 t->Previous()->SetNext(NULL);
00826 }
00827 prev = t;
00828 }
00829 }
00830
00836 static void RemoveFromConsist(Train *part, bool chain = false)
00837 {
00838 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
00839
00840
00841
00842 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
00843
00844
00845 tail->SetNext(NULL);
00846 }
00847
00853 static void InsertInConsist(Train *dst, Train *chain)
00854 {
00855
00856 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
00857
00858 chain->Last()->SetNext(dst->Next());
00859 dst->SetNext(chain);
00860 }
00861
00867 static void NormaliseDualHeads(Train *t)
00868 {
00869 for (; t != NULL; t = t->GetNextVehicle()) {
00870 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
00871
00872
00873 Train *u;
00874 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
00875
00876 if (u == t->other_multiheaded_part) continue;
00877
00878
00879 RemoveFromConsist(t->other_multiheaded_part);
00880
00881 InsertInConsist(u, t->other_multiheaded_part);
00882 }
00883 }
00884
00889 static void NormaliseSubtypes(Train *chain)
00890 {
00891
00892 if (chain == NULL) return;
00893
00894
00895 assert(chain->Previous() == NULL);
00896
00897
00898 if (chain->IsWagon()) {
00899 chain->SetFreeWagon();
00900 } else {
00901 assert(chain->IsEngine());
00902 chain->SetFrontEngine();
00903 }
00904
00905
00906 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
00907 t->ClearFreeWagon();
00908 t->ClearFrontEngine();
00909 }
00910 }
00911
00921 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
00922 {
00923
00924
00925
00926 if ((src != NULL && src->IsEngine() ? 1 : 0) +
00927 (dst != NULL && dst->IsEngine() ? 1 : 0) -
00928 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
00929 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
00930 return CommandCost();
00931 }
00932
00933
00934
00935 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
00936
00937 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
00938 }
00939
00945 static CommandCost CheckTrainAttachment(Train *t)
00946 {
00947
00948 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
00949
00950
00951
00952 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
00953
00954 Train *head = t;
00955 Train *prev = t;
00956
00957
00958 t = t->Next();
00959 prev->SetNext(NULL);
00960
00961
00962 head->InvalidateNewGRFCache();
00963
00964 while (t != NULL) {
00965 allowed_len -= t->gcache.cached_veh_length;
00966
00967 Train *next = t->Next();
00968
00969
00970
00971 t->SetNext(NULL);
00972
00973
00974 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
00975
00976 EngineID first_engine = t->gcache.first_engine;
00977 t->gcache.first_engine = INVALID_ENGINE;
00978
00979
00980
00981 t->InvalidateNewGRFCache();
00982
00983 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
00984
00985
00986 t->gcache.first_engine = first_engine;
00987
00988
00989 t->InvalidateNewGRFCache();
00990 head->InvalidateNewGRFCache();
00991
00992 if (callback != CALLBACK_FAILED) {
00993
00994 StringID error = STR_NULL;
00995
00996 if (head->GetGRF()->grf_version < 8) {
00997 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
00998 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
00999 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
01000 } else {
01001 if (callback < 0x400) {
01002 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
01003 } else {
01004 switch (callback) {
01005 case 0x400:
01006 case 0x401:
01007 break;
01008
01009 default:
01010 case 0x402:
01011 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
01012 break;
01013 }
01014 }
01015 }
01016
01017 if (error != STR_NULL) return_cmd_error(error);
01018 }
01019 }
01020
01021
01022 prev->SetNext(t);
01023 prev = t;
01024 t = next;
01025 }
01026
01027 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
01028 return CommandCost();
01029 }
01030
01041 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
01042 {
01043
01044 CommandCost ret = CheckTrainAttachment(src);
01045 if (ret.Failed()) return ret;
01046 ret = CheckTrainAttachment(dst);
01047 if (ret.Failed()) return ret;
01048
01049
01050 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
01051 }
01052
01061 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
01062 {
01063
01064 if (*src_head == *dst_head) {
01065
01066
01067 *dst_head = NULL;
01068 } else if (*dst_head == NULL) {
01069
01070
01071 *dst_head = src;
01072 }
01073
01074 if (src == *src_head) {
01075
01076
01077
01078
01079
01080
01081 *src_head = move_chain ? NULL :
01082 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
01083 }
01084
01085
01086
01087
01088 RemoveFromConsist(src, move_chain);
01089 if (*dst_head != src) InsertInConsist(dst, src);
01090
01091
01092
01093 NormaliseDualHeads(*src_head);
01094 NormaliseDualHeads(*dst_head);
01095 }
01096
01102 static void NormaliseTrainHead(Train *head)
01103 {
01104
01105 if (head == NULL) return;
01106
01107
01108 head->ConsistChanged(false);
01109 UpdateTrainGroupID(head);
01110
01111
01112 if (!head->IsFrontEngine()) return;
01113
01114
01115 InvalidateWindowData(WC_VEHICLE_REFIT, head->index);
01116 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
01117
01118
01119 if (head->unitnumber != 0) return;
01120 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
01121 }
01122
01135 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01136 {
01137 VehicleID s = GB(p1, 0, 20);
01138 VehicleID d = GB(p2, 0, 20);
01139 bool move_chain = HasBit(p1, 20);
01140
01141 Train *src = Train::GetIfValid(s);
01142 if (src == NULL) return CMD_ERROR;
01143
01144 CommandCost ret = CheckOwnership(src->owner);
01145 if (ret.Failed()) return ret;
01146
01147
01148 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
01149
01150
01151 Train *dst;
01152 if (d == INVALID_VEHICLE) {
01153 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
01154 } else {
01155 dst = Train::GetIfValid(d);
01156 if (dst == NULL) return CMD_ERROR;
01157
01158 CommandCost ret = CheckOwnership(dst->owner);
01159 if (ret.Failed()) return ret;
01160
01161
01162 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
01163 }
01164
01165
01166 src = src->GetFirstEnginePart();
01167 if (dst != NULL) {
01168 dst = dst->GetFirstEnginePart();
01169 }
01170
01171
01172 if (src == dst) return CommandCost();
01173
01174
01175 Train *src_head = src->First();
01176 Train *dst_head;
01177 if (dst != NULL) {
01178 dst_head = dst->First();
01179 if (dst_head->tile != src_head->tile) return CMD_ERROR;
01180
01181 dst = dst->GetLastEnginePart();
01182 } else {
01183 dst_head = NULL;
01184 }
01185
01186 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01187
01188
01189 if (move_chain && src_head == dst_head) return CommandCost();
01190
01191
01192 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
01193
01194
01195 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01196
01197
01198 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01199
01200
01201
01202 TrainList original_src;
01203 TrainList original_dst;
01204
01205 MakeTrainBackup(original_src, src_head);
01206 MakeTrainBackup(original_dst, dst_head);
01207
01208
01209
01210
01211 Train *original_src_head = src_head;
01212 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
01213
01214
01215 bool original_src_head_front_engine = original_src_head != NULL && original_src_head->IsFrontEngine();
01216 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
01217
01218
01219 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
01220
01221 if ((flags & DC_AUTOREPLACE) == 0) {
01222
01223
01224
01225 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
01226 if (ret.Failed()) {
01227
01228 RestoreTrainBackup(original_src);
01229 RestoreTrainBackup(original_dst);
01230 return ret;
01231 }
01232 }
01233
01234
01235 if (flags & DC_EXEC) {
01236
01237 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
01238 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
01239
01240
01241 NormaliseSubtypes(src_head);
01242 NormaliseSubtypes(dst_head);
01243
01244
01245
01246
01247
01248
01249
01250
01251
01252
01253
01254
01255
01256
01257
01258
01259
01260
01261
01262
01263
01264 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
01265
01266 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
01267 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
01268 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
01269 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
01270 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
01271 SetWindowDirty(WC_COMPANY, _current_company);
01272
01273
01274
01275 DeleteVehicleOrders(src);
01276 RemoveVehicleFromGroup(src);
01277 src->unitnumber = 0;
01278 }
01279
01280
01281
01282 if (original_src_head != src && dst_head == src) {
01283 SetTrainGroupID(src, DEFAULT_GROUP);
01284 SetWindowDirty(WC_COMPANY, _current_company);
01285 }
01286
01287
01288 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
01289 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
01290
01291
01292 NormaliseTrainHead(src_head);
01293 NormaliseTrainHead(dst_head);
01294
01295 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
01296 CheckCargoCapacity(src_head);
01297 CheckCargoCapacity(dst_head);
01298 }
01299
01300
01301 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
01302 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01303 } else {
01304
01305 RestoreTrainBackup(original_src);
01306 RestoreTrainBackup(original_dst);
01307 }
01308
01309 return CommandCost();
01310 }
01311
01323 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
01324 {
01325
01326 Window *w = NULL;
01327
01328
01329 bool sell_chain = HasBit(data, 0);
01330
01331 Train *v = Train::From(t)->GetFirstEnginePart();
01332 Train *first = v->First();
01333
01334 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
01335
01336
01337
01338 TrainList original;
01339 MakeTrainBackup(original, first);
01340
01341
01342 Train *new_head = first;
01343 Train *sell_head = NULL;
01344
01345
01346 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
01347
01348
01349 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
01350 if (ret.Failed()) {
01351
01352 RestoreTrainBackup(original);
01353 return ret;
01354 }
01355
01356 CommandCost cost(EXPENSES_NEW_VEHICLES);
01357 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
01358
01359 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
01360 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
01361 }
01362
01363
01364 if (flags & DC_EXEC) {
01365
01366 NormaliseSubtypes(new_head);
01367
01368 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
01369
01370
01371 new_head->orders.list = first->orders.list;
01372 new_head->AddToShared(first);
01373 DeleteVehicleOrders(first);
01374
01375
01376 new_head->CopyVehicleConfigAndStatistics(first);
01377 GroupStatistics::CountVehicle(new_head, 1);
01378
01379
01380 if (IsLocalCompany() && w != NULL) ShowVehicleViewWindow(new_head);
01381 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
01382 OrderBackup::Backup(v, user);
01383 }
01384
01385
01386 NormaliseTrainHead(new_head);
01387
01388
01389 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01390 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01391
01392
01393 delete sell_head;
01394 } else {
01395
01396 RestoreTrainBackup(original);
01397 }
01398
01399 return cost;
01400 }
01401
01402 void Train::UpdateDeltaXY(Direction direction)
01403 {
01404
01405 this->x_offs = -1;
01406 this->y_offs = -1;
01407 this->x_extent = 3;
01408 this->y_extent = 3;
01409 this->z_extent = 6;
01410 this->x_bb_offs = 0;
01411 this->y_bb_offs = 0;
01412
01413 if (!IsDiagonalDirection(direction)) {
01414 static const int _sign_table[] =
01415 {
01416
01417 -1, -1,
01418 -1, 1,
01419 1, 1,
01420 1, -1,
01421 };
01422
01423 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
01424
01425
01426 this->x_offs -= half_shorten * _sign_table[direction];
01427 this->y_offs -= half_shorten * _sign_table[direction + 1];
01428 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
01429 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
01430 } else {
01431 switch (direction) {
01432
01433
01434 case DIR_NE:
01435 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
01436 this->x_extent = this->gcache.cached_veh_length - 1;
01437 this->x_bb_offs = -1;
01438 break;
01439
01440 case DIR_NW:
01441 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
01442 this->y_extent = this->gcache.cached_veh_length - 1;
01443 this->y_bb_offs = -1;
01444 break;
01445
01446
01447
01448 case DIR_SW:
01449 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01450 this->x_extent = VEHICLE_LENGTH - 1;
01451 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01452 break;
01453
01454 case DIR_SE:
01455 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
01456 this->y_extent = VEHICLE_LENGTH - 1;
01457 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
01458 break;
01459
01460 default:
01461 NOT_REACHED();
01462 }
01463 }
01464 }
01465
01470 static void MarkTrainAsStuck(Train *v)
01471 {
01472 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
01473
01474 SetBit(v->flags, VRF_TRAIN_STUCK);
01475
01476 v->wait_counter = 0;
01477
01478
01479 v->cur_speed = 0;
01480 v->subspeed = 0;
01481 v->SetLastSpeed();
01482
01483 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01484 }
01485 }
01486
01494 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
01495 {
01496 uint16 flag1 = *swap_flag1;
01497 uint16 flag2 = *swap_flag2;
01498
01499
01500 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
01501 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01502 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
01503 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01504
01505
01506 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
01507 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
01508 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
01509 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
01510 }
01511 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
01512 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
01513 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
01514 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
01515 }
01516 }
01517
01522 static void UpdateStatusAfterSwap(Train *v)
01523 {
01524
01525 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
01526
01527
01528 if (v->track != TRACK_BIT_WORMHOLE) {
01529 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
01530 } else {
01531
01532
01533
01534
01535 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
01536 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
01537 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
01538 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
01539
01540
01541
01542 VehicleUpdatePosition(v);
01543 v->UpdateInclination(true, true);
01544 return;
01545 }
01546 }
01547 }
01548
01549 VehicleUpdatePosition(v);
01550 v->UpdateViewport(true, true);
01551 }
01552
01559 void ReverseTrainSwapVeh(Train *v, int l, int r)
01560 {
01561 Train *a, *b;
01562
01563
01564 for (a = v; l != 0; l--) a = a->Next();
01565 for (b = v; r != 0; r--) b = b->Next();
01566
01567 if (a != b) {
01568
01569 {
01570 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
01571 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
01572 a->vehstatus = tmp;
01573 }
01574
01575 Swap(a->track, b->track);
01576 Swap(a->direction, b->direction);
01577 Swap(a->x_pos, b->x_pos);
01578 Swap(a->y_pos, b->y_pos);
01579 Swap(a->tile, b->tile);
01580 Swap(a->z_pos, b->z_pos);
01581
01582 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
01583
01584 UpdateStatusAfterSwap(a);
01585 UpdateStatusAfterSwap(b);
01586 } else {
01587
01588
01589
01590 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
01591 UpdateStatusAfterSwap(a);
01592 }
01593
01594
01595 v->RailtypeChanged();
01596 }
01597
01598
01604 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
01605 {
01606 return (v->type == VEH_TRAIN) ? v : NULL;
01607 }
01608
01609
01616 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
01617 {
01618 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
01619
01620 Train *t = Train::From(v);
01621 if (!t->IsFrontEngine()) return NULL;
01622
01623 TileIndex tile = *(TileIndex *)data;
01624
01625 if (TrainApproachingCrossingTile(t) != tile) return NULL;
01626
01627 return t;
01628 }
01629
01630
01637 static bool TrainApproachingCrossing(TileIndex tile)
01638 {
01639 assert(IsLevelCrossingTile(tile));
01640
01641 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
01642 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
01643
01644 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
01645
01646 dir = ReverseDiagDir(dir);
01647 tile_from = tile + TileOffsByDiagDir(dir);
01648
01649 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
01650 }
01651
01652
01659 void UpdateLevelCrossing(TileIndex tile, bool sound)
01660 {
01661 assert(IsLevelCrossingTile(tile));
01662
01663
01664 bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
01665
01666 if (new_state != IsCrossingBarred(tile)) {
01667 if (new_state && sound) {
01668 SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01669 }
01670 SetCrossingBarred(tile, new_state);
01671 MarkTileDirtyByTile(tile);
01672 }
01673 }
01674
01675
01681 static inline void MaybeBarCrossingWithSound(TileIndex tile)
01682 {
01683 if (!IsCrossingBarred(tile)) {
01684 BarCrossing(tile);
01685 SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
01686 MarkTileDirtyByTile(tile);
01687 }
01688 }
01689
01690
01696 static void AdvanceWagonsBeforeSwap(Train *v)
01697 {
01698 Train *base = v;
01699 Train *first = base;
01700 Train *last = v->Last();
01701 uint length = CountVehiclesInChain(v);
01702
01703 while (length > 2) {
01704 last = last->Previous();
01705 first = first->Next();
01706
01707 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
01708
01709
01710
01711 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
01712
01713 base = first;
01714 length -= 2;
01715 }
01716 }
01717
01718
01724 static void AdvanceWagonsAfterSwap(Train *v)
01725 {
01726
01727 Train *dep = v;
01728 while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
01729 dep = dep->Next();
01730 }
01731
01732 Train *leave = dep->Next();
01733
01734 if (leave != NULL) {
01735
01736 int d = TicksToLeaveDepot(dep);
01737
01738 if (d <= 0) {
01739 leave->vehstatus &= ~VS_HIDDEN;
01740 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
01741 for (int i = 0; i >= d; i--) TrainController(leave, NULL);
01742 }
01743 } else {
01744 dep = NULL;
01745 }
01746
01747 Train *base = v;
01748 Train *first = base;
01749 Train *last = v->Last();
01750 uint length = CountVehiclesInChain(v);
01751
01752
01753
01754 bool nomove = (dep == NULL);
01755
01756 while (length > 2) {
01757
01758
01759 if (base == dep) break;
01760
01761
01762 if (last == dep) nomove = true;
01763
01764 last = last->Previous();
01765 first = first->Next();
01766
01767 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
01768
01769
01770 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
01771
01772 base = first;
01773 length -= 2;
01774 }
01775 }
01776
01781 void ReverseTrainDirection(Train *v)
01782 {
01783 if (IsRailDepotTile(v->tile)) {
01784 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01785 }
01786
01787
01788 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
01789
01790
01791 TileIndex crossing = TrainApproachingCrossingTile(v);
01792
01793
01794 int r = CountVehiclesInChain(v) - 1;
01795
01796 AdvanceWagonsBeforeSwap(v);
01797
01798
01799 int l = 0;
01800 do {
01801 ReverseTrainSwapVeh(v, l++, r--);
01802 } while (l <= r);
01803
01804 AdvanceWagonsAfterSwap(v);
01805
01806 if (IsRailDepotTile(v->tile)) {
01807 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
01808 }
01809
01810 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
01811
01812 ClrBit(v->flags, VRF_REVERSING);
01813
01814
01815 v->ConsistChanged(true);
01816
01817
01818 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
01819
01820
01821 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
01822
01823
01824 crossing = TrainApproachingCrossingTile(v);
01825 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
01826
01827
01828 if (v->track == TRACK_BIT_DEPOT) {
01829
01830 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
01831 ClrBit(v->flags, VRF_TRAIN_STUCK);
01832 return;
01833 }
01834
01835
01836
01837 DiagDirection dir = TrainExitDir(v->direction, v->track);
01838 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
01839
01840 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
01841
01842
01843 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
01844 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
01845 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
01846
01847 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01848 if (TryPathReserve(v, false, first_tile_okay)) {
01849
01850 CheckNextTrainTile(v);
01851 } else if (v->current_order.GetType() != OT_LOADING) {
01852
01853 MarkTrainAsStuck(v);
01854 }
01855 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
01856
01857 ClrBit(v->flags, VRF_TRAIN_STUCK);
01858 v->wait_counter = 0;
01859 }
01860 }
01861
01871 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01872 {
01873 Train *v = Train::GetIfValid(p1);
01874 if (v == NULL) return CMD_ERROR;
01875
01876 CommandCost ret = CheckOwnership(v->owner);
01877 if (ret.Failed()) return ret;
01878
01879 if (p2 != 0) {
01880
01881
01882 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
01883 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
01884 }
01885 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
01886
01887 Train *front = v->First();
01888
01889 if (!front->IsStoppedInDepot()) {
01890 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
01891 }
01892
01893 if (flags & DC_EXEC) {
01894 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
01895
01896 front->ConsistChanged(false);
01897 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
01898 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
01899 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
01900 SetWindowClassesDirty(WC_TRAINS_LIST);
01901 }
01902 } else {
01903
01904 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
01905
01906 if (flags & DC_EXEC) {
01907
01908 if (v->current_order.IsType(OT_LOADING)) {
01909 const Vehicle *last = v;
01910 while (last->Next() != NULL) last = last->Next();
01911
01912
01913 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
01914 v->LeaveStation();
01915 }
01916 }
01917
01918
01919 v->force_proceed = TFP_NONE;
01920 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
01921
01922 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
01923 ToggleBit(v->flags, VRF_REVERSING);
01924 } else {
01925 v->cur_speed = 0;
01926 v->SetLastSpeed();
01927 HideFillingPercent(&v->fill_percent_te_id);
01928 ReverseTrainDirection(v);
01929 }
01930 }
01931 }
01932 return CommandCost();
01933 }
01934
01944 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01945 {
01946 Train *t = Train::GetIfValid(p1);
01947 if (t == NULL) 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->IsInDepot() ? 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 (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
02222
02223 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
02224 while (ft.Follow(tile, td)) {
02225 tile = ft.m_new_tile;
02226 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
02227 td = RemoveFirstTrackdir(&bits);
02228 assert(bits == TRACKDIR_BIT_NONE);
02229
02230 if (!IsValidTrackdir(td)) break;
02231
02232 if (IsTileType(tile, MP_RAILWAY)) {
02233 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
02234
02235 UnreserveRailTrack(tile, TrackdirToTrack(td));
02236 break;
02237 }
02238 if (HasPbsSignalOnTrackdir(tile, td)) {
02239 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
02240
02241 break;
02242 } else {
02243
02244 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
02245 MarkTileDirtyByTile(tile);
02246 }
02247 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
02248 break;
02249 }
02250 }
02251
02252
02253 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);
02254
02255 free_tile = true;
02256 }
02257 }
02258
02259 static const byte _initial_tile_subcoord[6][4][3] = {
02260 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
02261 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
02262 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
02263 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
02264 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
02265 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
02266 };
02267
02280 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
02281 {
02282 switch (_settings_game.pf.pathfinder_for_trains) {
02283 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02284 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
02285
02286 default: NOT_REACHED();
02287 }
02288 }
02289
02295 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
02296 {
02297 PBSTileInfo origin = FollowTrainReservation(v);
02298
02299 CFollowTrackRail ft(v);
02300
02301 TileIndex tile = origin.tile;
02302 Trackdir cur_td = origin.trackdir;
02303 while (ft.Follow(tile, cur_td)) {
02304 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
02305
02306 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
02307 }
02308
02309 if (_settings_game.pf.forbid_90_deg) {
02310 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02311 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
02312 }
02313
02314
02315 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
02316 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
02317
02318
02319
02320
02321
02322
02323 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
02324
02325
02326
02327 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
02328
02329
02330 if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
02331 if (enterdir != NULL) *enterdir = ft.m_exitdir;
02332 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
02333 }
02334
02335 tile = ft.m_new_tile;
02336 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02337
02338 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
02339 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
02340 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
02341
02342 return PBSTileInfo(tile, cur_td, true);
02343 }
02344
02345 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
02346 }
02347
02348 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
02349
02350 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
02351 }
02352
02353
02354 tile = origin.tile;
02355 cur_td = origin.trackdir;
02356 TileIndex stopped = ft.m_old_tile;
02357 Trackdir stopped_td = ft.m_old_td;
02358 while (tile != stopped || cur_td != stopped_td) {
02359 if (!ft.Follow(tile, cur_td)) break;
02360
02361 if (_settings_game.pf.forbid_90_deg) {
02362 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
02363 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
02364 }
02365 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
02366
02367 tile = ft.m_new_tile;
02368 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
02369
02370 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
02371 }
02372
02373
02374 return PBSTileInfo();
02375 }
02376
02387 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
02388 {
02389 switch (_settings_game.pf.pathfinder_for_trains) {
02390 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02391 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
02392
02393 default: NOT_REACHED();
02394 }
02395 }
02396
02398 class VehicleOrderSaver {
02399 private:
02400 Train *v;
02401 Order old_order;
02402 TileIndex old_dest_tile;
02403 StationID old_last_station_visited;
02404 VehicleOrderID index;
02405 bool suppress_implicit_orders;
02406
02407 public:
02408 VehicleOrderSaver(Train *_v) :
02409 v(_v),
02410 old_order(_v->current_order),
02411 old_dest_tile(_v->dest_tile),
02412 old_last_station_visited(_v->last_station_visited),
02413 index(_v->cur_real_order_index),
02414 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
02415 {
02416 }
02417
02418 ~VehicleOrderSaver()
02419 {
02420 this->v->current_order = this->old_order;
02421 this->v->dest_tile = this->old_dest_tile;
02422 this->v->last_station_visited = this->old_last_station_visited;
02423 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
02424 }
02425
02431 bool SwitchToNextOrder(bool skip_first)
02432 {
02433 if (this->v->GetNumOrders() == 0) return false;
02434
02435 if (skip_first) ++this->index;
02436
02437 int conditional_depth = 0;
02438
02439 do {
02440
02441 if (this->index >= this->v->GetNumOrders()) this->index = 0;
02442
02443 Order *order = this->v->GetOrder(this->index);
02444 assert(order != NULL);
02445
02446 switch (order->GetType()) {
02447 case OT_GOTO_DEPOT:
02448
02449 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
02450 case OT_GOTO_STATION:
02451 case OT_GOTO_WAYPOINT:
02452 this->v->current_order = *order;
02453 return UpdateOrderDest(this->v, order, 0, true);
02454 case OT_CONDITIONAL: {
02455 if (conditional_depth > this->v->GetNumOrders()) return false;
02456 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
02457 if (next != INVALID_VEH_ORDER_ID) {
02458 conditional_depth++;
02459 this->index = next;
02460
02461 continue;
02462 }
02463 break;
02464 }
02465 default:
02466 break;
02467 }
02468
02469
02470 ++this->index;
02471 } while (this->index != this->v->cur_real_order_index);
02472
02473 return false;
02474 }
02475 };
02476
02477
02478 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
02479 {
02480 Track best_track = INVALID_TRACK;
02481 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
02482 bool changed_signal = false;
02483
02484 assert((tracks & ~TRACK_BIT_MASK) == 0);
02485
02486 if (got_reservation != NULL) *got_reservation = false;
02487
02488
02489 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
02490
02491 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
02492
02493
02494 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
02495 Track track = FindFirstTrack(tracks);
02496
02497 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
02498 do_track_reservation = true;
02499 changed_signal = true;
02500 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
02501 } else if (!do_track_reservation) {
02502 return track;
02503 }
02504 best_track = track;
02505 }
02506
02507 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
02508 DiagDirection dest_enterdir = enterdir;
02509 if (do_track_reservation) {
02510 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
02511 if (res_dest.tile == INVALID_TILE) {
02512
02513 if (mark_stuck) MarkTrainAsStuck(v);
02514 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
02515 return FindFirstTrack(tracks);
02516 }
02517 if (res_dest.okay) {
02518
02519 if (got_reservation != NULL) *got_reservation = true;
02520 if (changed_signal) MarkTileDirtyByTile(tile);
02521 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02522 return best_track;
02523 }
02524
02525
02526
02527
02528 CheckIfTrainNeedsService(v);
02529 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
02530 }
02531
02532
02533 VehicleOrderSaver orders(v);
02534
02535
02536
02537
02538
02539
02540
02541 if (v->current_order.IsType(OT_LEAVESTATION)) {
02542 orders.SwitchToNextOrder(false);
02543 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
02544 v->current_order.IsType(OT_GOTO_STATION) ?
02545 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
02546 v->tile == v->dest_tile))) {
02547 orders.SwitchToNextOrder(true);
02548 }
02549
02550 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02551
02552 bool path_found = true;
02553 TileIndex new_tile = res_dest.tile;
02554
02555 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
02556 if (new_tile == tile) best_track = next_track;
02557 v->HandlePathfindingResult(path_found);
02558 }
02559
02560
02561 if (!do_track_reservation) return best_track;
02562
02563
02564 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
02565 if (mark_stuck) MarkTrainAsStuck(v);
02566 FreeTrainTrackReservation(v);
02567 return best_track;
02568 }
02569
02570
02571 if (res_dest.tile == INVALID_TILE) {
02572
02573 PBSTileInfo origin = FollowTrainReservation(v);
02574 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
02575 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
02576 best_track = FindFirstTrack(res);
02577 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02578 if (got_reservation != NULL) *got_reservation = true;
02579 if (changed_signal) MarkTileDirtyByTile(tile);
02580 } else {
02581 FreeTrainTrackReservation(v);
02582 if (mark_stuck) MarkTrainAsStuck(v);
02583 }
02584 return best_track;
02585 }
02586
02587 if (got_reservation != NULL) *got_reservation = true;
02588
02589
02590 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
02591
02592 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
02593 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
02594 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
02595 if (_settings_game.pf.forbid_90_deg) {
02596 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
02597 }
02598
02599
02600 if (orders.SwitchToNextOrder(true)) {
02601 PBSTileInfo cur_dest;
02602 bool path_found;
02603 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
02604 if (cur_dest.tile != INVALID_TILE) {
02605 res_dest = cur_dest;
02606 if (res_dest.okay) continue;
02607
02608 FreeTrainTrackReservation(v);
02609 if (mark_stuck) MarkTrainAsStuck(v);
02610 if (got_reservation != NULL) *got_reservation = false;
02611 changed_signal = false;
02612 break;
02613 }
02614 }
02615
02616 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
02617 FreeTrainTrackReservation(v);
02618 if (mark_stuck) MarkTrainAsStuck(v);
02619 if (got_reservation != NULL) *got_reservation = false;
02620 changed_signal = false;
02621 }
02622 break;
02623 }
02624
02625 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
02626
02627 if (changed_signal) MarkTileDirtyByTile(tile);
02628
02629 return best_track;
02630 }
02631
02640 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
02641 {
02642 assert(v->IsFrontEngine());
02643
02644
02645
02646
02647 if (v->track == TRACK_BIT_DEPOT) {
02648 if (HasDepotReservation(v->tile)) {
02649 if (mark_as_stuck) MarkTrainAsStuck(v);
02650 return false;
02651 } else {
02652
02653 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
02654 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
02655 }
02656 }
02657
02658 Vehicle *other_train = NULL;
02659 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
02660
02661
02662
02663
02664
02665 if (other_train != NULL && other_train->index != v->index) {
02666 if (mark_as_stuck) MarkTrainAsStuck(v);
02667 return false;
02668 }
02669
02670 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
02671
02672 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02673 ClrBit(v->flags, VRF_TRAIN_STUCK);
02674 return true;
02675 }
02676
02677
02678 if (v->track == TRACK_BIT_DEPOT) {
02679 SetDepotReservation(v->tile, true);
02680 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
02681 }
02682
02683 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
02684 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
02685 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
02686
02687 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
02688
02689 bool res_made = false;
02690 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
02691
02692 if (!res_made) {
02693
02694 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
02695 return false;
02696 }
02697
02698 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
02699 v->wait_counter = 0;
02700 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
02701 }
02702 ClrBit(v->flags, VRF_TRAIN_STUCK);
02703 return true;
02704 }
02705
02706
02707 static bool CheckReverseTrain(const Train *v)
02708 {
02709 if (_settings_game.difficulty.line_reverse_mode != 0 ||
02710 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
02711 !(v->direction & 1)) {
02712 return false;
02713 }
02714
02715 assert(v->track != TRACK_BIT_NONE);
02716
02717 switch (_settings_game.pf.pathfinder_for_trains) {
02718 case VPF_NPF: return NPFTrainCheckReverse(v);
02719 case VPF_YAPF: return YapfTrainCheckReverse(v);
02720
02721 default: NOT_REACHED();
02722 }
02723 }
02724
02730 TileIndex Train::GetOrderStationLocation(StationID station)
02731 {
02732 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
02733
02734 const Station *st = Station::Get(station);
02735 if (!(st->facilities & FACIL_TRAIN)) {
02736
02737 this->IncrementRealOrderIndex();
02738 return 0;
02739 }
02740
02741 return st->xy;
02742 }
02743
02745 void Train::MarkDirty()
02746 {
02747 Train *v = this;
02748 do {
02749 v->UpdateViewport(false, false);
02750 } while ((v = v->Next()) != NULL);
02751
02752
02753 this->CargoChanged();
02754 this->UpdateAcceleration();
02755 }
02756
02764 int Train::UpdateSpeed()
02765 {
02766 switch (_settings_game.vehicle.train_acceleration_model) {
02767 default: NOT_REACHED();
02768 case AM_ORIGINAL:
02769 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->gcache.cached_max_track_speed);
02770
02771 case AM_REALISTIC:
02772 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
02773 }
02774 }
02775
02781 static void TrainEnterStation(Train *v, StationID station)
02782 {
02783 v->last_station_visited = station;
02784
02785
02786 Station *st = Station::Get(station);
02787 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
02788 st->had_vehicle_of_type |= HVOT_TRAIN;
02789 SetDParam(0, st->index);
02790 AddVehicleNewsItem(
02791 STR_NEWS_FIRST_TRAIN_ARRIVAL,
02792 v->owner == _local_company ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
02793 v->index,
02794 st->index
02795 );
02796 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
02797 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
02798 }
02799
02800 v->force_proceed = TFP_NONE;
02801 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
02802
02803 v->BeginLoading();
02804
02805 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
02806 }
02807
02808
02809 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
02810 {
02811 return IsTileOwner(tile, v->owner) &&
02812 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
02813 }
02814
02816 struct RailtypeSlowdownParams {
02817 byte small_turn;
02818 byte large_turn;
02819 byte z_up;
02820 byte z_down;
02821 };
02822
02824 static const RailtypeSlowdownParams _railtype_slowdown[] = {
02825
02826 {256 / 4, 256 / 2, 256 / 4, 2},
02827 {256 / 4, 256 / 2, 256 / 4, 2},
02828 {256 / 4, 256 / 2, 256 / 4, 2},
02829 {0, 256 / 2, 256 / 4, 2},
02830 };
02831
02837 static inline void AffectSpeedByZChange(Train *v, int old_z)
02838 {
02839 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
02840
02841 const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
02842
02843 if (old_z < v->z_pos) {
02844 v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
02845 } else {
02846 uint16 spd = v->cur_speed + rsp->z_down;
02847 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
02848 }
02849 }
02850
02851 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
02852 {
02853 if (IsTileType(tile, MP_RAILWAY) &&
02854 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
02855 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
02856 Trackdir trackdir = FindFirstTrackdir(tracks);
02857 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
02858
02859 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
02860 }
02861 }
02862 return false;
02863 }
02864
02866 void Train::ReserveTrackUnderConsist() const
02867 {
02868 for (const Train *u = this; u != NULL; u = u->Next()) {
02869 switch (u->track) {
02870 case TRACK_BIT_WORMHOLE:
02871 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
02872 break;
02873 case TRACK_BIT_DEPOT:
02874 break;
02875 default:
02876 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
02877 break;
02878 }
02879 }
02880 }
02881
02888 uint Train::Crash(bool flooded)
02889 {
02890 uint pass = 0;
02891 if (this->IsFrontEngine()) {
02892 pass += 2;
02893
02894
02895
02896 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
02897 for (const Train *v = this; v != NULL; v = v->Next()) {
02898 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
02899 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
02900
02901
02902 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
02903 }
02904 }
02905
02906
02907
02908 TileIndex crossing = TrainApproachingCrossingTile(this);
02909 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
02910
02911
02912 HideFillingPercent(&this->fill_percent_te_id);
02913 }
02914
02915 pass += this->GroundVehicleBase::Crash(flooded);
02916
02917 this->crash_anim_pos = flooded ? 4000 : 1;
02918 return pass;
02919 }
02920
02927 static uint TrainCrashed(Train *v)
02928 {
02929 uint num = 0;
02930
02931
02932 if (!(v->vehstatus & VS_CRASHED)) {
02933 num = v->Crash();
02934 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02935 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
02936 }
02937
02938
02939
02940 v->ReserveTrackUnderConsist();
02941
02942 return num;
02943 }
02944
02946 struct TrainCollideChecker {
02947 Train *v;
02948 uint num;
02949 };
02950
02957 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
02958 {
02959 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
02960
02961
02962 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
02963
02964
02965 if (v->owner != tcc->v->owner) return NULL;
02966
02967
02968 Train *coll = Train::From(v)->First();
02969
02970
02971 if (coll == tcc->v) return NULL;
02972
02973 int x_diff = v->x_pos - tcc->v->x_pos;
02974 int y_diff = v->y_pos - tcc->v->y_pos;
02975
02976
02977
02978
02979
02980 uint hash = (y_diff + 7) | (x_diff + 7);
02981 if (hash & ~15) return NULL;
02982
02983
02984 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
02985 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
02986
02987
02988 if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
02989
02990
02991 tcc->num += TrainCrashed(tcc->v);
02992 tcc->num += TrainCrashed(coll);
02993
02994 return NULL;
02995 }
02996
03004 static bool CheckTrainCollision(Train *v)
03005 {
03006
03007 if (v->track == TRACK_BIT_DEPOT) return false;
03008
03009 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
03010
03011 TrainCollideChecker tcc;
03012 tcc.v = v;
03013 tcc.num = 0;
03014
03015
03016 if (v->track == TRACK_BIT_WORMHOLE) {
03017 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
03018 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
03019 } else {
03020 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
03021 }
03022
03023
03024 if (tcc.num == 0) return false;
03025
03026 SetDParam(0, tcc.num);
03027 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH,
03028 NS_ACCIDENT,
03029 v->index
03030 );
03031
03032 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
03033 SndPlayVehicleFx(SND_13_BIG_CRASH, v);
03034 return true;
03035 }
03036
03037 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
03038 {
03039 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
03040
03041 Train *t = Train::From(v);
03042 DiagDirection exitdir = *(DiagDirection *)data;
03043
03044
03045 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
03046
03047 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
03048
03049 return t;
03050 }
03051
03059 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
03060 {
03061 Train *first = v->First();
03062 Train *prev;
03063 bool direction_changed = false;
03064
03065
03066 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
03067 DiagDirection enterdir = DIAGDIR_BEGIN;
03068 bool update_signals_crossing = false;
03069
03070 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
03071 if (v->track != TRACK_BIT_WORMHOLE) {
03072
03073 if (gp.old_tile == gp.new_tile) {
03074
03075 if (v->track == TRACK_BIT_DEPOT) {
03076
03077 gp.x = v->x_pos;
03078 gp.y = v->y_pos;
03079 } else {
03080
03081
03082
03083 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
03084
03085 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03086 if (HasBit(r, VETS_CANNOT_ENTER)) {
03087 goto invalid_rail;
03088 }
03089 if (HasBit(r, VETS_ENTERED_STATION)) {
03090
03091 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03092 }
03093 }
03094 } else {
03095
03096
03097
03098 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
03099 assert(IsValidDiagDirection(enterdir));
03100
03101
03102
03103 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
03104 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
03105
03106 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03107 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
03108
03109 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03110 if (_settings_game.pf.forbid_90_deg && prev == NULL) {
03111
03112
03113 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03114 }
03115
03116 if (bits == TRACK_BIT_NONE) goto invalid_rail;
03117
03118
03119
03120 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
03121
03122 TrackBits chosen_track;
03123 if (prev == NULL) {
03124
03125
03126 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
03127 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
03128
03129 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
03130
03131
03132
03133
03134 Trackdir dir = FindFirstTrackdir(trackdirbits);
03135 if (GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS ||
03136 !HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir))) {
03137
03138
03139 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
03140 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03141 }
03142 }
03143
03144
03145 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
03146
03147 Trackdir i = FindFirstTrackdir(trackdirbits);
03148
03149
03150 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
03151
03152 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
03153 v->cur_speed = 0;
03154 v->subspeed = 0;
03155 v->progress = 255 - 100;
03156 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
03157 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
03158 v->cur_speed = 0;
03159 v->subspeed = 0;
03160 v->progress = 255 - 10;
03161 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
03162 DiagDirection exitdir = TrackdirToExitdir(i);
03163 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
03164
03165 exitdir = ReverseDiagDir(exitdir);
03166
03167
03168 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
03169 }
03170 }
03171
03172
03173
03174
03175
03176 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
03177 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
03178 v->wait_counter = 0;
03179 return false;
03180 }
03181 goto reverse_train_direction;
03182 } else {
03183 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track));
03184 }
03185 } else {
03186
03187 if (prev->tile == gp.new_tile) {
03188
03189 if (prev->track == TRACK_BIT_WORMHOLE) {
03190
03191
03192 assert(IsTunnel(prev->tile));
03193 chosen_track = bits;
03194 } else {
03195 chosen_track = prev->track;
03196 }
03197 } else {
03198
03199
03200
03201
03202
03203
03204
03205 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
03206 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
03207 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
03208 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
03209 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
03210 };
03211 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
03212 assert(IsValidDiagDirection(exitdir));
03213 chosen_track = _connecting_track[enterdir][exitdir];
03214 }
03215 chosen_track &= bits;
03216 }
03217
03218
03219 assert(
03220 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
03221 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
03222 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
03223
03224
03225 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
03226 gp.x = (gp.x & ~0xF) | b[0];
03227 gp.y = (gp.y & ~0xF) | b[1];
03228 Direction chosen_dir = (Direction)b[2];
03229
03230
03231 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
03232 if (HasBit(r, VETS_CANNOT_ENTER)) {
03233 goto invalid_rail;
03234 }
03235
03236 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
03237 Track track = FindFirstTrack(chosen_track);
03238 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
03239 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
03240 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
03241 MarkTileDirtyByTile(gp.new_tile);
03242 }
03243
03244
03245 if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
03246
03247 v->tile = gp.new_tile;
03248
03249 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
03250 v->First()->RailtypeChanged();
03251 }
03252
03253 v->track = chosen_track;
03254 assert(v->track);
03255 }
03256
03257
03258
03259 update_signals_crossing = true;
03260
03261 if (chosen_dir != v->direction) {
03262 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
03263 const RailtypeSlowdownParams *rsp = &_railtype_slowdown[v->railtype];
03264 DirDiff diff = DirDifference(v->direction, chosen_dir);
03265 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
03266 }
03267 direction_changed = true;
03268 v->direction = chosen_dir;
03269 }
03270
03271 if (v->IsFrontEngine()) {
03272 v->wait_counter = 0;
03273
03274
03275 TileIndex crossing = TrainApproachingCrossingTile(v);
03276 if (crossing != INVALID_TILE && HasCrossingReservation(crossing)) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
03277
03278
03279 CheckNextTrainTile(v);
03280 }
03281
03282 if (HasBit(r, VETS_ENTERED_STATION)) {
03283
03284 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
03285 }
03286 }
03287 } else {
03288
03289
03290
03291 if (!(v->vehstatus & VS_HIDDEN)) {
03292 Train *first = v->First();
03293 first->cur_speed = min(first->cur_speed, GetBridgeSpec(GetBridgeType(v->tile))->speed);
03294 }
03295
03296 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
03297
03298 if (v->IsFrontEngine()) {
03299 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
03300 CheckNextTrainTile(v);
03301 }
03302
03303
03304 if (gp.old_tile == gp.new_tile) {
03305 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
03306 }
03307 } else {
03308 v->x_pos = gp.x;
03309 v->y_pos = gp.y;
03310 VehicleUpdatePosition(v);
03311 if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
03312 continue;
03313 }
03314 }
03315
03316
03317 v->UpdateDeltaXY(v->direction);
03318
03319 v->x_pos = gp.x;
03320 v->y_pos = gp.y;
03321 VehicleUpdatePosition(v);
03322
03323
03324 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
03325
03326 if (prev == NULL) {
03327
03328 AffectSpeedByZChange(v, old_z);
03329 }
03330
03331 if (update_signals_crossing) {
03332 if (v->IsFrontEngine()) {
03333 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
03334
03335
03336
03337
03338
03339
03340
03341
03342 if ((!HasReservedTracks(gp.new_tile, v->track) &&
03343 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
03344 !TryPathReserve(v)) {
03345 MarkTrainAsStuck(v);
03346 }
03347 }
03348 }
03349
03350
03351
03352 if (v->Next() == NULL) {
03353 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
03354 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
03355 }
03356 }
03357
03358
03359 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
03360 }
03361
03362 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
03363
03364 return true;
03365
03366 invalid_rail:
03367
03368 if (prev != NULL) error("Disconnecting train");
03369
03370 reverse_train_direction:
03371 if (reverse) {
03372 v->wait_counter = 0;
03373 v->cur_speed = 0;
03374 v->subspeed = 0;
03375 ReverseTrainDirection(v);
03376 }
03377
03378 return false;
03379 }
03380
03387 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
03388 {
03389 TrackBits *trackbits = (TrackBits *)data;
03390
03391 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
03392 TrackBits train_tbits = Train::From(v)->track;
03393 if (train_tbits == TRACK_BIT_WORMHOLE) {
03394
03395 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
03396 } else if (train_tbits != TRACK_BIT_DEPOT) {
03397 *trackbits |= train_tbits;
03398 }
03399 }
03400
03401 return NULL;
03402 }
03403
03411 static void DeleteLastWagon(Train *v)
03412 {
03413 Train *first = v->First();
03414
03415
03416
03417
03418 Train *u = v;
03419 for (; v->Next() != NULL; v = v->Next()) u = v;
03420 u->SetNext(NULL);
03421
03422 if (first != v) {
03423
03424 first->ConsistChanged(false);
03425
03426
03427 if (first->track == TRACK_BIT_DEPOT) {
03428 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
03429 }
03430 }
03431
03432
03433 TrackBits trackbits = v->track;
03434 TileIndex tile = v->tile;
03435 Owner owner = v->owner;
03436
03437 delete v;
03438 v = NULL;
03439
03440 if (trackbits == TRACK_BIT_WORMHOLE) {
03441
03442 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
03443 }
03444
03445 Track track = TrackBitsToTrack(trackbits);
03446 if (HasReservedTracks(tile, trackbits)) {
03447 UnreserveRailTrack(tile, track);
03448
03449
03450 TrackBits remaining_trackbits = TRACK_BIT_NONE;
03451 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
03452
03453
03454 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
03455 Track t;
03456 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
03457 }
03458
03459
03460 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
03461
03462
03463 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
03464 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
03465 } else {
03466 SetSignalsOnBothDir(tile, track, owner);
03467 }
03468 }
03469
03474 static void ChangeTrainDirRandomly(Train *v)
03475 {
03476 static const DirDiff delta[] = {
03477 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
03478 };
03479
03480 do {
03481
03482 if (!(v->vehstatus & VS_HIDDEN)) {
03483 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
03484 v->UpdateDeltaXY(v->direction);
03485 v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
03486
03487
03488
03489 if (v->track != TRACK_BIT_WORMHOLE) {
03490 VehicleUpdatePosition(v);
03491 v->UpdateInclination(false, false);
03492 }
03493 }
03494 } while ((v = v->Next()) != NULL);
03495 }
03496
03502 static bool HandleCrashedTrain(Train *v)
03503 {
03504 int state = ++v->crash_anim_pos;
03505
03506 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
03507 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
03508 }
03509
03510 uint32 r;
03511 if (state <= 200 && Chance16R(1, 7, r)) {
03512 int index = (r * 10 >> 16);
03513
03514 Vehicle *u = v;
03515 do {
03516 if (--index < 0) {
03517 r = Random();
03518
03519 CreateEffectVehicleRel(u,
03520 GB(r, 8, 3) + 2,
03521 GB(r, 16, 3) + 2,
03522 GB(r, 0, 3) + 5,
03523 EV_EXPLOSION_SMALL);
03524 break;
03525 }
03526 } while ((u = u->Next()) != NULL);
03527 }
03528
03529 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
03530
03531 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
03532 bool ret = v->Next() != NULL;
03533 DeleteLastWagon(v);
03534 return ret;
03535 }
03536
03537 return true;
03538 }
03539
03541 static const uint16 _breakdown_speeds[16] = {
03542 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
03543 };
03544
03545
03554 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
03555 {
03556
03557 uint x = v->x_pos & 0xF;
03558 uint y = v->y_pos & 0xF;
03559
03560
03561
03562 switch (v->direction) {
03563 case DIR_N : x = ~x + ~y + 25; break;
03564 case DIR_NW: x = y;
03565 case DIR_NE: x = ~x + 16; break;
03566 case DIR_E : x = ~x + y + 9; break;
03567 case DIR_SE: x = y; break;
03568 case DIR_S : x = x + y - 7; break;
03569 case DIR_W : x = ~y + x + 9; break;
03570 default: break;
03571 }
03572
03573
03574
03575
03576
03577
03578 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
03579
03580 v->cur_speed = 0;
03581 if (reverse) ReverseTrainDirection(v);
03582 return false;
03583 }
03584
03585
03586 v->vehstatus |= VS_TRAIN_SLOWING;
03587 uint16 break_speed = _breakdown_speeds[x & 0xF];
03588 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03589
03590 return true;
03591 }
03592
03593
03599 static bool TrainCanLeaveTile(const Train *v)
03600 {
03601
03602 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
03603
03604 TileIndex tile = v->tile;
03605
03606
03607 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
03608 DiagDirection dir = GetTunnelBridgeDirection(tile);
03609 if (DiagDirToDir(dir) == v->direction) return false;
03610 }
03611
03612
03613 if (IsRailDepotTile(tile)) {
03614 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
03615 if (DiagDirToDir(dir) == v->direction) return false;
03616 }
03617
03618 return true;
03619 }
03620
03621
03629 static TileIndex TrainApproachingCrossingTile(const Train *v)
03630 {
03631 assert(v->IsFrontEngine());
03632 assert(!(v->vehstatus & VS_CRASHED));
03633
03634 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
03635
03636 DiagDirection dir = TrainExitDir(v->direction, v->track);
03637 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03638
03639
03640 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
03641 !CheckCompatibleRail(v, tile)) {
03642 return INVALID_TILE;
03643 }
03644
03645 return tile;
03646 }
03647
03648
03656 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
03657 {
03658
03659
03660 int t = v->breakdown_ctr;
03661 if (t > 1) {
03662 v->vehstatus |= VS_TRAIN_SLOWING;
03663
03664 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
03665 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
03666 } else {
03667 v->vehstatus &= ~VS_TRAIN_SLOWING;
03668 }
03669
03670 if (!TrainCanLeaveTile(v)) return true;
03671
03672
03673 DiagDirection dir = TrainExitDir(v->direction, v->track);
03674
03675 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
03676
03677
03678 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
03679 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
03680
03681 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
03682 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
03683
03684
03685
03686
03687 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
03688 if (_settings_game.pf.forbid_90_deg) {
03689 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
03690 }
03691
03692
03693 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
03694 return TrainApproachingLineEnd(v, false, reverse);
03695 }
03696
03697
03698 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
03699
03700
03701 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
03702
03703 return true;
03704 }
03705
03706
03707 static bool TrainLocoHandler(Train *v, bool mode)
03708 {
03709
03710 if (v->vehstatus & VS_CRASHED) {
03711 return mode ? true : HandleCrashedTrain(v);
03712 }
03713
03714 if (v->force_proceed != TFP_NONE) {
03715 ClrBit(v->flags, VRF_TRAIN_STUCK);
03716 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03717 }
03718
03719
03720 if (v->HandleBreakdown()) return true;
03721
03722 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
03723 ReverseTrainDirection(v);
03724 }
03725
03726
03727 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
03728
03729 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
03730 if (ProcessOrders(v) && CheckReverseTrain(v)) {
03731 v->wait_counter = 0;
03732 v->cur_speed = 0;
03733 v->subspeed = 0;
03734 ClrBit(v->flags, VRF_LEAVING_STATION);
03735 ReverseTrainDirection(v);
03736 return true;
03737 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
03738
03739
03740
03741 DiagDirection dir = TrainExitDir(v->direction, v->track);
03742 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
03743
03744 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
03745 TryPathReserve(v, true, true);
03746 }
03747 ClrBit(v->flags, VRF_LEAVING_STATION);
03748 }
03749
03750 v->HandleLoading(mode);
03751
03752 if (v->current_order.IsType(OT_LOADING)) return true;
03753
03754 if (CheckTrainStayInDepot(v)) return true;
03755
03756 if (!mode) v->ShowVisualEffect();
03757
03758
03759 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
03760 CheckNextTrainTile(v);
03761 }
03762
03763
03764 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
03765 ++v->wait_counter;
03766
03767
03768 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
03769
03770 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
03771 if (!TryPathReserve(v)) {
03772
03773 if (turn_around) ReverseTrainDirection(v);
03774
03775 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
03776
03777 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
03778 SetDParam(0, v->index);
03779 AddVehicleNewsItem(
03780 STR_NEWS_TRAIN_IS_STUCK,
03781 NS_ADVICE,
03782 v->index
03783 );
03784 }
03785 v->wait_counter = 0;
03786 }
03787
03788 if (v->force_proceed == TFP_NONE) return true;
03789 ClrBit(v->flags, VRF_TRAIN_STUCK);
03790 v->wait_counter = 0;
03791 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03792 }
03793 }
03794
03795 if (v->current_order.IsType(OT_LEAVESTATION)) {
03796 v->current_order.Free();
03797 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03798 return true;
03799 }
03800
03801 int j = v->UpdateSpeed();
03802
03803
03804 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
03805
03806 v->force_proceed = TFP_NONE;
03807 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
03808 }
03809
03810 int adv_spd = v->GetAdvanceDistance();
03811 if (j < adv_spd) {
03812
03813 if (v->cur_speed == 0) v->SetLastSpeed();
03814 } else {
03815 TrainCheckIfLineEnds(v);
03816
03817 for (;;) {
03818 j -= adv_spd;
03819 TrainController(v, NULL);
03820
03821 if (CheckTrainCollision(v)) break;
03822
03823 adv_spd = v->GetAdvanceDistance();
03824
03825
03826 if (j < adv_spd || v->cur_speed == 0) break;
03827
03828 OrderType order_type = v->current_order.GetType();
03829
03830 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
03831 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
03832 IsTileType(v->tile, MP_STATION) &&
03833 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
03834 ProcessOrders(v);
03835 }
03836 }
03837 v->SetLastSpeed();
03838 }
03839
03840 for (Train *u = v; u != NULL; u = u->Next()) {
03841 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
03842
03843 u->UpdateViewport(false, false);
03844 }
03845
03846 if (v->progress == 0) v->progress = j;
03847
03848 return true;
03849 }
03850
03855 Money Train::GetRunningCost() const
03856 {
03857 Money cost = 0;
03858 const Train *v = this;
03859
03860 do {
03861 const Engine *e = v->GetEngine();
03862 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
03863
03864 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
03865 if (cost_factor == 0) continue;
03866
03867
03868 if (v->IsMultiheaded()) cost_factor /= 2;
03869
03870 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
03871 } while ((v = v->GetNextVehicle()) != NULL);
03872
03873 return cost;
03874 }
03875
03880 bool Train::Tick()
03881 {
03882 this->tick_counter++;
03883
03884 if (this->IsFrontEngine()) {
03885 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
03886
03887 this->current_order_time++;
03888
03889 if (!TrainLocoHandler(this, false)) return false;
03890
03891 return TrainLocoHandler(this, true);
03892 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
03893
03894 if (++this->crash_anim_pos >= 4400) {
03895 delete this;
03896 return false;
03897 }
03898 }
03899
03900 return true;
03901 }
03902
03907 static void CheckIfTrainNeedsService(Train *v)
03908 {
03909 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
03910 if (v->IsInDepot()) {
03911 VehicleServiceInDepot(v);
03912 return;
03913 }
03914
03915 uint max_penalty;
03916 switch (_settings_game.pf.pathfinder_for_trains) {
03917 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
03918 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
03919 default: NOT_REACHED();
03920 }
03921
03922 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
03923
03924 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
03925 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
03926
03927
03928
03929 v->current_order.MakeDummy();
03930 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03931 }
03932 return;
03933 }
03934
03935 DepotID depot = GetDepotIndex(tfdd.tile);
03936
03937 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
03938 v->current_order.GetDestination() != depot &&
03939 !Chance16(3, 16)) {
03940 return;
03941 }
03942
03943 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
03944 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
03945 v->dest_tile = tfdd.tile;
03946 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
03947 }
03948
03950 void Train::OnNewDay()
03951 {
03952 AgeVehicle(this);
03953
03954 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
03955
03956 if (this->IsFrontEngine()) {
03957 CheckVehicleBreakdown(this);
03958
03959 CheckIfTrainNeedsService(this);
03960
03961 CheckOrders(this);
03962
03963
03964 if (this->current_order.IsType(OT_GOTO_STATION)) {
03965 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
03966 if (tile != INVALID_TILE) this->dest_tile = tile;
03967 }
03968
03969 if (this->running_ticks != 0) {
03970
03971 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
03972
03973 this->profit_this_year -= cost.GetCost();
03974 this->running_ticks = 0;
03975
03976 SubtractMoneyFromCompanyFract(this->owner, cost);
03977
03978 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
03979 SetWindowClassesDirty(WC_TRAINS_LIST);
03980 }
03981 }
03982 }
03983
03988 Trackdir Train::GetVehicleTrackdir() const
03989 {
03990 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
03991
03992 if (this->track == TRACK_BIT_DEPOT) {
03993
03994 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile));
03995 }
03996
03997 if (this->track == TRACK_BIT_WORMHOLE) {
03998
03999 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
04000 }
04001
04002 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
04003 }