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