OpenTTD
train_cmd.cpp
Go to the documentation of this file.
1 /* $Id: train_cmd.cpp 27419 2015-10-30 16:18:39Z frosch $ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "stdafx.h"
13 #include "error.h"
14 #include "articulated_vehicles.h"
15 #include "command_func.h"
17 #include "pathfinder/yapf/yapf.hpp"
18 #include "news_func.h"
19 #include "company_func.h"
20 #include "newgrf_sound.h"
21 #include "newgrf_text.h"
22 #include "strings_func.h"
23 #include "viewport_func.h"
24 #include "vehicle_func.h"
25 #include "sound_func.h"
26 #include "ai/ai.hpp"
27 #include "game/game.hpp"
28 #include "newgrf_station.h"
29 #include "effectvehicle_func.h"
30 #include "network/network.h"
31 #include "spritecache.h"
32 #include "core/random_func.hpp"
33 #include "company_base.h"
34 #include "newgrf.h"
35 #include "order_backup.h"
36 #include "zoom_func.h"
37 #include "newgrf_debug.h"
38 
39 #include "table/strings.h"
40 #include "table/train_cmd.h"
41 
42 #include "safeguards.h"
43 
44 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
45 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
46 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
48 static void CheckIfTrainNeedsService(Train *v);
49 static void CheckNextTrainTile(Train *v);
50 
51 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
52 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
53 
54 template <>
55 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
56 {
57  return image_index < lengthof(_engine_sprite_base);
58 }
59 
68 {
70 
71  DiagDirection diagdir = DirToDiagDir(direction);
72 
73  /* Determine the diagonal direction in which we will exit this tile */
74  if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
75  diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
76  }
77 
78  return diagdir;
79 }
80 
81 
88 {
89  if (!CargoSpec::Get(cargo)->is_freight) return 1;
91 }
92 
95 {
96  const Train *v;
97  bool first = true;
98 
99  FOR_ALL_TRAINS(v) {
100  if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
101  for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
102  if (u->track != TRACK_BIT_DEPOT) {
103  if ((w->track != TRACK_BIT_DEPOT &&
104  max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
105  (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
106  SetDParam(0, v->index);
107  SetDParam(1, v->owner);
108  ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
109 
110  if (!_networking && first) {
111  first = false;
113  }
114  /* Break so we warn only once for each train. */
115  break;
116  }
117  }
118  }
119  }
120  }
121 }
122 
130 {
131  uint16 max_speed = UINT16_MAX;
132 
133  assert(this->IsFrontEngine() || this->IsFreeWagon());
134 
135  const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
136  EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
137  this->gcache.cached_total_length = 0;
138  this->compatible_railtypes = RAILTYPES_NONE;
139 
140  bool train_can_tilt = true;
141 
142  for (Train *u = this; u != NULL; u = u->Next()) {
143  const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
144 
145  /* Check the this->first cache. */
146  assert(u->First() == this);
147 
148  /* update the 'first engine' */
149  u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
150  u->railtype = rvi_u->railtype;
151 
152  if (u->IsEngine()) first_engine = u->engine_type;
153 
154  /* Set user defined data to its default value */
155  u->tcache.user_def_data = rvi_u->user_def_data;
156  this->InvalidateNewGRFCache();
157  u->InvalidateNewGRFCache();
158  }
159 
160  for (Train *u = this; u != NULL; u = u->Next()) {
161  /* Update user defined data (must be done before other properties) */
162  u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
163  this->InvalidateNewGRFCache();
164  u->InvalidateNewGRFCache();
165  }
166 
167  for (Train *u = this; u != NULL; u = u->Next()) {
168  const Engine *e_u = u->GetEngine();
169  const RailVehicleInfo *rvi_u = &e_u->u.rail;
170 
171  if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
172 
173  /* Cache wagon override sprite group. NULL is returned if there is none */
174  u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
175 
176  /* Reset colour map */
177  u->colourmap = PAL_NONE;
178 
179  /* Update powered-wagon-status and visual effect */
180  u->UpdateVisualEffect(true);
181 
182  if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
183  UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
184  /* wagon is powered */
185  SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
186  } else {
187  ClrBit(u->flags, VRF_POWEREDWAGON);
188  }
189 
190  if (!u->IsArticulatedPart()) {
191  /* Do not count powered wagons for the compatible railtypes, as wagons always
192  have railtype normal */
193  if (rvi_u->power > 0) {
194  this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
195  }
196 
197  /* Some electric engines can be allowed to run on normal rail. It happens to all
198  * existing electric engines when elrails are disabled and then re-enabled */
199  if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
200  u->railtype = RAILTYPE_RAIL;
201  u->compatible_railtypes |= RAILTYPES_RAIL;
202  }
203 
204  /* max speed is the minimum of the speed limits of all vehicles in the consist */
205  if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
206  uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
207  if (speed != 0) max_speed = min(speed, max_speed);
208  }
209  }
210 
211  uint16 new_cap = e_u->DetermineCapacity(u);
212  if (allowed_changes & CCF_CAPACITY) {
213  /* Update vehicle capacity. */
214  if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
215  u->refit_cap = min(new_cap, u->refit_cap);
216  u->cargo_cap = new_cap;
217  } else {
218  /* Verify capacity hasn't changed. */
219  if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
220  }
221  u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
222 
223  /* check the vehicle length (callback) */
224  uint16 veh_len = CALLBACK_FAILED;
225  if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
226  /* Use callback 36 */
227  veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
228 
229  if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
231  }
232  } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
233  /* Use callback 11 */
234  veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
235  }
236  if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
237  veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
238 
239  if (allowed_changes & CCF_LENGTH) {
240  /* Update vehicle length. */
241  u->gcache.cached_veh_length = veh_len;
242  } else {
243  /* Verify length hasn't changed. */
244  if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
245  }
246 
247  this->gcache.cached_total_length += u->gcache.cached_veh_length;
248  this->InvalidateNewGRFCache();
249  u->InvalidateNewGRFCache();
250  }
251 
252  /* store consist weight/max speed in cache */
253  this->vcache.cached_max_speed = max_speed;
254  this->tcache.cached_tilt = train_can_tilt;
255  this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
256 
257  /* recalculate cached weights and power too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) */
258  this->CargoChanged();
259 
260  if (this->IsFrontEngine()) {
261  this->UpdateAcceleration();
265  InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
266  }
267 }
268 
279 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
280 {
281  const Station *st = Station::Get(station_id);
282  *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
283  *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
284 
285  /* Default to the middle of the station for stations stops that are not in
286  * the order list like intermediate stations when non-stop is disabled */
288  if (v->gcache.cached_total_length >= *station_length) {
289  /* The train is longer than the station, make it stop at the far end of the platform */
290  osl = OSL_PLATFORM_FAR_END;
291  } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
292  osl = v->current_order.GetStopLocation();
293  }
294 
295  /* The stop location of the FRONT! of the train */
296  int stop;
297  switch (osl) {
298  default: NOT_REACHED();
299 
301  stop = v->gcache.cached_total_length;
302  break;
303 
304  case OSL_PLATFORM_MIDDLE:
305  stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
306  break;
307 
309  stop = *station_length;
310  break;
311  }
312 
313  /* Subtract half the front vehicle length of the train so we get the real
314  * stop location of the train. */
315  return stop - (v->gcache.cached_veh_length + 1) / 2;
316 }
317 
318 
324 {
325  assert(this->First() == this);
326 
327  static const int absolute_max_speed = UINT16_MAX;
328  int max_speed = absolute_max_speed;
329 
330  if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
331 
332  int curvecount[2] = {0, 0};
333 
334  /* first find the curve speed limit */
335  int numcurve = 0;
336  int sum = 0;
337  int pos = 0;
338  int lastpos = -1;
339  for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
340  Direction this_dir = u->direction;
341  Direction next_dir = u->Next()->direction;
342 
343  DirDiff dirdiff = DirDifference(this_dir, next_dir);
344  if (dirdiff == DIRDIFF_SAME) continue;
345 
346  if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
347  if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
348  if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
349  if (lastpos != -1) {
350  numcurve++;
351  sum += pos - lastpos;
352  if (pos - lastpos == 1 && max_speed > 88) {
353  max_speed = 88;
354  }
355  }
356  lastpos = pos;
357  }
358 
359  /* if we have a 90 degree turn, fix the speed limit to 60 */
360  if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
361  max_speed = 61;
362  }
363  }
364 
365  if (numcurve > 0 && max_speed > 88) {
366  if (curvecount[0] == 1 && curvecount[1] == 1) {
367  max_speed = absolute_max_speed;
368  } else {
369  sum /= numcurve;
370  max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
371  }
372  }
373 
374  if (max_speed != absolute_max_speed) {
375  /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
376  const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
377  max_speed += (max_speed / 2) * rti->curve_speed;
378 
379  if (this->tcache.cached_tilt) {
380  /* Apply max_speed bonus of 20% for a tilting train */
381  max_speed += max_speed / 5;
382  }
383  }
384 
385  return max_speed;
386 }
387 
393 {
394  int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
396  this->tcache.cached_max_curve_speed;
397 
398  if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
399  StationID sid = GetStationIndex(this->tile);
400  if (this->current_order.ShouldStopAtStation(this, sid)) {
401  int station_ahead;
402  int station_length;
403  int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
404 
405  /* The distance to go is whatever is still ahead of the train minus the
406  * distance from the train's stop location to the end of the platform */
407  int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
408 
409  if (distance_to_go > 0) {
410  int st_max_speed = 120;
411 
412  int delta_v = this->cur_speed / (distance_to_go + 1);
413  if (max_speed > (this->cur_speed - delta_v)) {
414  st_max_speed = this->cur_speed - (delta_v / 10);
415  }
416 
417  st_max_speed = max(st_max_speed, 25 * distance_to_go);
418  max_speed = min(max_speed, st_max_speed);
419  }
420  }
421  }
422 
423  for (const Train *u = this; u != NULL; u = u->Next()) {
424  if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
425  max_speed = min(max_speed, 61);
426  break;
427  }
428 
429  /* Vehicle is on the middle part of a bridge. */
430  if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
431  max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
432  }
433  }
434 
435  max_speed = min(max_speed, this->current_order.GetMaxSpeed());
436  return min(max_speed, this->gcache.cached_max_track_speed);
437 }
438 
441 {
442  assert(this->IsFrontEngine() || this->IsFreeWagon());
443 
444  uint power = this->gcache.cached_power;
445  uint weight = this->gcache.cached_weight;
446  assert(weight != 0);
447  this->acceleration = Clamp(power / weight * 4, 1, 255);
448 }
449 
456 {
457  int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
458  int vehicle_pitch = 0;
459 
460  const Engine *e = this->GetEngine();
461  if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
462  reference_width = e->GetGRF()->traininfo_vehicle_width;
463  vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
464  }
465 
466  if (offset != NULL) {
467  offset->x = ScaleGUITrad(reference_width) / 2;
468  offset->y = ScaleGUITrad(vehicle_pitch);
469  }
470  return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
471 }
472 
473 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
474 {
475  assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
476  return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
477 }
478 
485 SpriteID Train::GetImage(Direction direction, EngineImageType image_type) const
486 {
487  uint8 spritenum = this->spritenum;
488  SpriteID sprite;
489 
490  if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
491 
492  if (is_custom_sprite(spritenum)) {
493  sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
494  if (sprite != 0) return sprite;
495 
496  spritenum = this->GetEngine()->original_image_index;
497  }
498 
499  assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
500  sprite = GetDefaultTrainSprite(spritenum, direction);
501 
502  if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
503 
504  return sprite;
505 }
506 
507 static SpriteID GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type)
508 {
509  const Engine *e = Engine::Get(engine);
510  Direction dir = rear_head ? DIR_E : DIR_W;
511  uint8 spritenum = e->u.rail.image_index;
512 
513  if (is_custom_sprite(spritenum)) {
514  SpriteID sprite = GetCustomVehicleIcon(engine, dir, image_type);
515  if (sprite != 0) {
516  if (e->GetGRF() != NULL) {
518  }
519  return sprite;
520  }
521 
522  spritenum = Engine::Get(engine)->original_image_index;
523  }
524 
525  if (rear_head) spritenum++;
526 
527  return GetDefaultTrainSprite(spritenum, DIR_W);
528 }
529 
530 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
531 {
532  if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
533  int yf = y;
534  int yr = y;
535 
536  SpriteID spritef = GetRailIcon(engine, false, yf, image_type);
537  SpriteID spriter = GetRailIcon(engine, true, yr, image_type);
538  const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL);
539  const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL);
540 
541  preferred_x = Clamp(preferred_x,
542  left - UnScaleGUI(real_spritef->x_offs) + ScaleGUITrad(14),
543  right - UnScaleGUI(real_spriter->width) - UnScaleGUI(real_spriter->x_offs) - ScaleGUITrad(15));
544 
545  DrawSprite(spritef, pal, preferred_x - ScaleGUITrad(14), yf);
546  DrawSprite(spriter, pal, preferred_x + ScaleGUITrad(15), yr);
547  } else {
548  SpriteID sprite = GetRailIcon(engine, false, y, image_type);
549  const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
550  preferred_x = Clamp(preferred_x,
551  left - UnScaleGUI(real_sprite->x_offs),
552  right - UnScaleGUI(real_sprite->width) - UnScaleGUI(real_sprite->x_offs));
553  DrawSprite(sprite, pal, preferred_x, y);
554  }
555 }
556 
566 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
567 {
568  int y = 0;
569 
570  SpriteID sprite = GetRailIcon(engine, false, y, image_type);
571  const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
572 
573  width = UnScaleGUI(real_sprite->width);
574  height = UnScaleGUI(real_sprite->height);
575  xoffs = UnScaleGUI(real_sprite->x_offs);
576  yoffs = UnScaleGUI(real_sprite->y_offs);
577 
578  if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
579  sprite = GetRailIcon(engine, true, y, image_type);
580  real_sprite = GetSprite(sprite, ST_NORMAL);
581 
582  /* Calculate values relative to an imaginary center between the two sprites. */
583  width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(real_sprite->width) + UnScaleGUI(real_sprite->x_offs) - xoffs;
584  height = max<uint>(height, UnScaleGUI(real_sprite->height));
585  xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
586  yoffs = min(yoffs, UnScaleGUI(real_sprite->y_offs));
587  }
588 }
589 
599 {
600  const RailVehicleInfo *rvi = &e->u.rail;
601 
602  /* Check that the wagon can drive on the track in question */
603  if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
604 
605  if (flags & DC_EXEC) {
606  Train *v = new Train();
607  *ret = v;
608  v->spritenum = rvi->image_index;
609 
610  v->engine_type = e->index;
611  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
612 
614 
615  v->direction = DiagDirToDir(dir);
616  v->tile = tile;
617 
618  int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
619  int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
620 
621  v->x_pos = x;
622  v->y_pos = y;
623  v->z_pos = GetSlopePixelZ(x, y);
624  v->owner = _current_company;
625  v->track = TRACK_BIT_DEPOT;
627 
628  v->SetWagon();
629 
630  v->SetFreeWagon();
632 
634  v->cargo_cap = rvi->capacity;
635  v->refit_cap = 0;
636 
637  v->railtype = rvi->railtype;
638 
639  v->build_year = _cur_year;
640  v->cur_image = SPR_IMG_QUERY;
642 
643  v->group_id = DEFAULT_GROUP;
644 
646 
647  _new_vehicle_id = v->index;
648 
649  v->UpdatePosition();
652 
654 
655  /* Try to connect the vehicle to one of free chains of wagons. */
656  Train *w;
657  FOR_ALL_TRAINS(w) {
658  if (w->tile == tile &&
659  w->IsFreeWagon() &&
660  w->engine_type == e->index &&
661  w->First() != v &&
662  !(w->vehstatus & VS_CRASHED)) {
663  DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
664  break;
665  }
666  }
667  }
668 
669  return CommandCost();
670 }
671 
673 static void NormalizeTrainVehInDepot(const Train *u)
674 {
675  const Train *v;
676  FOR_ALL_TRAINS(v) {
677  if (v->IsFreeWagon() && v->tile == u->tile &&
678  v->track == TRACK_BIT_DEPOT) {
679  if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
681  break;
682  }
683  }
684 }
685 
686 static void AddRearEngineToMultiheadedTrain(Train *v)
687 {
688  Train *u = new Train();
689  v->value >>= 1;
690  u->value = v->value;
691  u->direction = v->direction;
692  u->owner = v->owner;
693  u->tile = v->tile;
694  u->x_pos = v->x_pos;
695  u->y_pos = v->y_pos;
696  u->z_pos = v->z_pos;
697  u->track = TRACK_BIT_DEPOT;
698  u->vehstatus = v->vehstatus & ~VS_STOPPED;
699  u->spritenum = v->spritenum + 1;
700  u->cargo_type = v->cargo_type;
702  u->cargo_cap = v->cargo_cap;
703  u->refit_cap = v->refit_cap;
704  u->railtype = v->railtype;
705  u->engine_type = v->engine_type;
706  u->build_year = v->build_year;
707  u->cur_image = SPR_IMG_QUERY;
709  v->SetMultiheaded();
710  u->SetMultiheaded();
711  v->SetNext(u);
712  u->UpdatePosition();
713 
714  /* Now we need to link the front and rear engines together */
715  v->other_multiheaded_part = u;
716  u->other_multiheaded_part = v;
717 }
718 
729 {
730  const RailVehicleInfo *rvi = &e->u.rail;
731 
732  if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
733 
734  /* Check if depot and new engine uses the same kind of tracks *
735  * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
736  if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
737 
738  if (flags & DC_EXEC) {
740  int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
741  int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
742 
743  Train *v = new Train();
744  *ret = v;
745  v->direction = DiagDirToDir(dir);
746  v->tile = tile;
747  v->owner = _current_company;
748  v->x_pos = x;
749  v->y_pos = y;
750  v->z_pos = GetSlopePixelZ(x, y);
751  v->track = TRACK_BIT_DEPOT;
753  v->spritenum = rvi->image_index;
755  v->cargo_cap = rvi->capacity;
756  v->refit_cap = 0;
757  v->last_station_visited = INVALID_STATION;
758  v->last_loading_station = INVALID_STATION;
759 
760  v->engine_type = e->index;
761  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
762 
763  v->reliability = e->reliability;
765  v->max_age = e->GetLifeLengthInDays();
766 
767  v->railtype = rvi->railtype;
768  _new_vehicle_id = v->index;
769 
770  v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
772  v->build_year = _cur_year;
773  v->cur_image = SPR_IMG_QUERY;
775 
777  v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
778 
779  v->group_id = DEFAULT_GROUP;
780 
781  v->SetFrontEngine();
782  v->SetEngine();
783 
784  v->UpdatePosition();
785 
786  if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
787  AddRearEngineToMultiheadedTrain(v);
788  } else {
790  }
791 
794 
795  if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
797  }
798 
800  }
801 
802  return CommandCost();
803 }
804 
805 static Train *FindGoodVehiclePos(const Train *src)
806 {
807  EngineID eng = src->engine_type;
808  TileIndex tile = src->tile;
809 
810  Train *dst;
811  FOR_ALL_TRAINS(dst) {
812  if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
813  /* check so all vehicles in the line have the same engine. */
814  Train *t = dst;
815  while (t->engine_type == eng) {
816  t = t->Next();
817  if (t == NULL) return dst;
818  }
819  }
820  }
821 
822  return NULL;
823 }
824 
827 
833 static void MakeTrainBackup(TrainList &list, Train *t)
834 {
835  for (; t != NULL; t = t->Next()) *list.Append() = t;
836 }
837 
842 static void RestoreTrainBackup(TrainList &list)
843 {
844  /* No train, nothing to do. */
845  if (list.Length() == 0) return;
846 
847  Train *prev = NULL;
848  /* Iterate over the list and rebuild it. */
849  for (Train **iter = list.Begin(); iter != list.End(); iter++) {
850  Train *t = *iter;
851  if (prev != NULL) {
852  prev->SetNext(t);
853  } else if (t->Previous() != NULL) {
854  /* Make sure the head of the train is always the first in the chain. */
855  t->Previous()->SetNext(NULL);
856  }
857  prev = t;
858  }
859 }
860 
866 static void RemoveFromConsist(Train *part, bool chain = false)
867 {
868  Train *tail = chain ? part->Last() : part->GetLastEnginePart();
869 
870  /* Unlink at the front, but make it point to the next
871  * vehicle after the to be remove part. */
872  if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
873 
874  /* Unlink at the back */
875  tail->SetNext(NULL);
876 }
877 
883 static void InsertInConsist(Train *dst, Train *chain)
884 {
885  /* We do not want to add something in the middle of an articulated part. */
886  assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
887 
888  chain->Last()->SetNext(dst->Next());
889  dst->SetNext(chain);
890 }
891 
897 static void NormaliseDualHeads(Train *t)
898 {
899  for (; t != NULL; t = t->GetNextVehicle()) {
900  if (!t->IsMultiheaded() || !t->IsEngine()) continue;
901 
902  /* Make sure that there are no free cars before next engine */
903  Train *u;
904  for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
905 
906  if (u == t->other_multiheaded_part) continue;
907 
908  /* Remove the part from the 'wrong' train */
909  RemoveFromConsist(t->other_multiheaded_part);
910  /* And add it to the 'right' train */
911  InsertInConsist(u, t->other_multiheaded_part);
912  }
913 }
914 
919 static void NormaliseSubtypes(Train *chain)
920 {
921  /* Nothing to do */
922  if (chain == NULL) return;
923 
924  /* We must be the first in the chain. */
925  assert(chain->Previous() == NULL);
926 
927  /* Set the appropriate bits for the first in the chain. */
928  if (chain->IsWagon()) {
929  chain->SetFreeWagon();
930  } else {
931  assert(chain->IsEngine());
932  chain->SetFrontEngine();
933  }
934 
935  /* Now clear the bits for the rest of the chain */
936  for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
937  t->ClearFreeWagon();
938  t->ClearFrontEngine();
939  }
940 }
941 
951 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
952 {
953  /* Just add 'new' engines and subtract the original ones.
954  * If that's less than or equal to 0 we can be sure we did
955  * not add any engines (read: trains) along the way. */
956  if ((src != NULL && src->IsEngine() ? 1 : 0) +
957  (dst != NULL && dst->IsEngine() ? 1 : 0) -
958  (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
959  (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
960  return CommandCost();
961  }
962 
963  /* Get a free unit number and check whether it's within the bounds.
964  * There will always be a maximum of one new train. */
966 
967  return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
968 }
969 
976 {
977  /* No multi-part train, no need to check. */
978  if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
979 
980  /* The maximum length for a train. For each part we decrease this by one
981  * and if the result is negative the train is simply too long. */
983 
984  Train *head = t;
985  Train *prev = t;
986 
987  /* Break the prev -> t link so it always holds within the loop. */
988  t = t->Next();
989  prev->SetNext(NULL);
990 
991  /* Make sure the cache is cleared. */
992  head->InvalidateNewGRFCache();
993 
994  while (t != NULL) {
995  allowed_len -= t->gcache.cached_veh_length;
996 
997  Train *next = t->Next();
998 
999  /* Unlink the to-be-added piece; it is already unlinked from the previous
1000  * part due to the fact that the prev -> t link is broken. */
1001  t->SetNext(NULL);
1002 
1003  /* Don't check callback for articulated or rear dual headed parts */
1004  if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1005  /* Back up and clear the first_engine data to avoid using wagon override group */
1006  EngineID first_engine = t->gcache.first_engine;
1008 
1009  /* We don't want the cache to interfere. head's cache is cleared before
1010  * the loop and after each callback does not need to be cleared here. */
1011  t->InvalidateNewGRFCache();
1012 
1013  uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1014 
1015  /* Restore original first_engine data */
1016  t->gcache.first_engine = first_engine;
1017 
1018  /* We do not want to remember any cached variables from the test run */
1019  t->InvalidateNewGRFCache();
1020  head->InvalidateNewGRFCache();
1021 
1022  if (callback != CALLBACK_FAILED) {
1023  /* A failing callback means everything is okay */
1024  StringID error = STR_NULL;
1025 
1026  if (head->GetGRF()->grf_version < 8) {
1027  if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1028  if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1029  if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1030  } else {
1031  if (callback < 0x400) {
1032  error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1033  } else {
1034  switch (callback) {
1035  case 0x400: // allow if railtypes match (always the case for OpenTTD)
1036  case 0x401: // allow
1037  break;
1038 
1039  default: // unknown reason -> disallow
1040  case 0x402: // disallow attaching
1041  error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1042  break;
1043  }
1044  }
1045  }
1046 
1047  if (error != STR_NULL) return_cmd_error(error);
1048  }
1049  }
1050 
1051  /* And link it to the new part. */
1052  prev->SetNext(t);
1053  prev = t;
1054  t = next;
1055  }
1056 
1057  if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1058  return CommandCost();
1059 }
1060 
1071 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1072 {
1073  /* Check whether we may actually construct the trains. */
1074  CommandCost ret = CheckTrainAttachment(src);
1075  if (ret.Failed()) return ret;
1076  ret = CheckTrainAttachment(dst);
1077  if (ret.Failed()) return ret;
1078 
1079  /* Check whether we need to build a new train. */
1080  return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1081 }
1082 
1091 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1092 {
1093  /* First determine the front of the two resulting trains */
1094  if (*src_head == *dst_head) {
1095  /* If we aren't moving part(s) to a new train, we are just moving the
1096  * front back and there is not destination head. */
1097  *dst_head = NULL;
1098  } else if (*dst_head == NULL) {
1099  /* If we are moving to a new train the head of the move train would become
1100  * the head of the new vehicle. */
1101  *dst_head = src;
1102  }
1103 
1104  if (src == *src_head) {
1105  /* If we are moving the front of a train then we are, in effect, creating
1106  * a new head for the train. Point to that. Unless we are moving the whole
1107  * train in which case there is not 'source' train anymore.
1108  * In case we are a multiheaded part we want the complete thing to come
1109  * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1110  * that is followed by a rear multihead we do not want to include that. */
1111  *src_head = move_chain ? NULL :
1112  (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1113  }
1114 
1115  /* Now it's just simply removing the part that we are going to move from the
1116  * source train and *if* the destination is a not a new train add the chain
1117  * at the destination location. */
1118  RemoveFromConsist(src, move_chain);
1119  if (*dst_head != src) InsertInConsist(dst, src);
1120 
1121  /* Now normalise the dual heads, that is move the dual heads around in such
1122  * a way that the head and rear of a dual head are in the same train */
1123  NormaliseDualHeads(*src_head);
1124  NormaliseDualHeads(*dst_head);
1125 }
1126 
1132 static void NormaliseTrainHead(Train *head)
1133 {
1134  /* Not much to do! */
1135  if (head == NULL) return;
1136 
1137  /* Tell the 'world' the train changed. */
1138  head->ConsistChanged(CCF_ARRANGE);
1139  UpdateTrainGroupID(head);
1140 
1141  /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1142  if (!head->IsFrontEngine()) return;
1143 
1144  /* Update the refit button and window */
1147 
1148  /* If we don't have a unit number yet, set one. */
1149  if (head->unitnumber != 0) return;
1151 }
1152 
1165 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1166 {
1167  VehicleID s = GB(p1, 0, 20);
1168  VehicleID d = GB(p2, 0, 20);
1169  bool move_chain = HasBit(p1, 20);
1170 
1171  Train *src = Train::GetIfValid(s);
1172  if (src == NULL) return CMD_ERROR;
1173 
1174  CommandCost ret = CheckOwnership(src->owner);
1175  if (ret.Failed()) return ret;
1176 
1177  /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1178  if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1179 
1180  /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1181  Train *dst;
1182  if (d == INVALID_VEHICLE) {
1183  dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1184  } else {
1185  dst = Train::GetIfValid(d);
1186  if (dst == NULL) return CMD_ERROR;
1187 
1188  CommandCost ret = CheckOwnership(dst->owner);
1189  if (ret.Failed()) return ret;
1190 
1191  /* Do not allow appending to crashed vehicles, too */
1192  if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1193  }
1194 
1195  /* if an articulated part is being handled, deal with its parent vehicle */
1196  src = src->GetFirstEnginePart();
1197  if (dst != NULL) {
1198  dst = dst->GetFirstEnginePart();
1199  }
1200 
1201  /* don't move the same vehicle.. */
1202  if (src == dst) return CommandCost();
1203 
1204  /* locate the head of the two chains */
1205  Train *src_head = src->First();
1206  Train *dst_head;
1207  if (dst != NULL) {
1208  dst_head = dst->First();
1209  if (dst_head->tile != src_head->tile) return CMD_ERROR;
1210  /* Now deal with articulated part of destination wagon */
1211  dst = dst->GetLastEnginePart();
1212  } else {
1213  dst_head = NULL;
1214  }
1215 
1216  if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1217 
1218  /* When moving all wagons, we can't have the same src_head and dst_head */
1219  if (move_chain && src_head == dst_head) return CommandCost();
1220 
1221  /* When moving a multiheaded part to be place after itself, bail out. */
1222  if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1223 
1224  /* Check if all vehicles in the source train are stopped inside a depot. */
1225  if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1226 
1227  /* Check if all vehicles in the destination train are stopped inside a depot. */
1228  if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1229 
1230  /* First make a backup of the order of the trains. That way we can do
1231  * whatever we want with the order and later on easily revert. */
1232  TrainList original_src;
1233  TrainList original_dst;
1234 
1235  MakeTrainBackup(original_src, src_head);
1236  MakeTrainBackup(original_dst, dst_head);
1237 
1238  /* Also make backup of the original heads as ArrangeTrains can change them.
1239  * For the destination head we do not care if it is the same as the source
1240  * head because in that case it's just a copy. */
1241  Train *original_src_head = src_head;
1242  Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1243 
1244  /* We want this information from before the rearrangement, but execute this after the validation.
1245  * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
1246  * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
1247  bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1248  bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
1249 
1250  /* (Re)arrange the trains in the wanted arrangement. */
1251  ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1252 
1253  if ((flags & DC_AUTOREPLACE) == 0) {
1254  /* If the autoreplace flag is set we do not need to test for the validity
1255  * because we are going to revert the train to its original state. As we
1256  * assume the original state was correct autoreplace can skip this. */
1257  CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1258  if (ret.Failed()) {
1259  /* Restore the train we had. */
1260  RestoreTrainBackup(original_src);
1261  RestoreTrainBackup(original_dst);
1262  return ret;
1263  }
1264  }
1265 
1266  /* do it? */
1267  if (flags & DC_EXEC) {
1268  /* Remove old heads from the statistics */
1269  if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1270  if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1271 
1272  /* First normalise the sub types of the chains. */
1273  NormaliseSubtypes(src_head);
1274  NormaliseSubtypes(dst_head);
1275 
1276  /* There are 14 different cases:
1277  * 1) front engine gets moved to a new train, it stays a front engine.
1278  * a) the 'next' part is a wagon that becomes a free wagon chain.
1279  * b) the 'next' part is an engine that becomes a front engine.
1280  * c) there is no 'next' part, nothing else happens
1281  * 2) front engine gets moved to another train, it is not a front engine anymore
1282  * a) the 'next' part is a wagon that becomes a free wagon chain.
1283  * b) the 'next' part is an engine that becomes a front engine.
1284  * c) there is no 'next' part, nothing else happens
1285  * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1286  * a) the 'next' part is a wagon that becomes a free wagon chain.
1287  * b) the 'next' part is an engine that becomes a front engine.
1288  * 4) free wagon gets moved
1289  * a) the 'next' part is a wagon that becomes a free wagon chain.
1290  * b) the 'next' part is an engine that becomes a front engine.
1291  * c) there is no 'next' part, nothing else happens
1292  * 5) non front engine gets moved and becomes a new train, nothing else happens
1293  * 6) non front engine gets moved within a train / to another train, nothing hapens
1294  * 7) wagon gets moved, nothing happens
1295  */
1296  if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1297  /* Cases #2 and #3: the front engine gets trashed. */
1303  DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1305 
1306  /* Delete orders, group stuff and the unit number as we're not the
1307  * front of any vehicle anymore. */
1308  DeleteVehicleOrders(src);
1310  src->unitnumber = 0;
1311  }
1312 
1313  /* We weren't a front engine but are becoming one. So
1314  * we should be put in the default group. */
1315  if (original_src_head != src && dst_head == src) {
1318  }
1319 
1320  /* Add new heads to statistics */
1321  if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1322  if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1323 
1324  /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1325  NormaliseTrainHead(src_head);
1326  NormaliseTrainHead(dst_head);
1327 
1328  if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1329  CheckCargoCapacity(src_head);
1330  CheckCargoCapacity(dst_head);
1331  }
1332 
1333  if (src_head != NULL) src_head->First()->MarkDirty();
1334  if (dst_head != NULL) dst_head->First()->MarkDirty();
1335 
1336  /* We are undoubtedly changing something in the depot and train list. */
1339  } else {
1340  /* We don't want to execute what we're just tried. */
1341  RestoreTrainBackup(original_src);
1342  RestoreTrainBackup(original_dst);
1343  }
1344 
1345  return CommandCost();
1346 }
1347 
1359 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1360 {
1361  /* Sell a chain of vehicles or not? */
1362  bool sell_chain = HasBit(data, 0);
1363 
1365  Train *first = v->First();
1366 
1367  if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1368 
1369  /* First make a backup of the order of the train. That way we can do
1370  * whatever we want with the order and later on easily revert. */
1371  TrainList original;
1372  MakeTrainBackup(original, first);
1373 
1374  /* We need to keep track of the new head and the head of what we're going to sell. */
1375  Train *new_head = first;
1376  Train *sell_head = NULL;
1377 
1378  /* Split the train in the wanted way. */
1379  ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1380 
1381  /* We don't need to validate the second train; it's going to be sold. */
1382  CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1383  if (ret.Failed()) {
1384  /* Restore the train we had. */
1385  RestoreTrainBackup(original);
1386  return ret;
1387  }
1388 
1389  if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
1390  /* Restore the train we had. */
1391  RestoreTrainBackup(original);
1392  return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1393  }
1394 
1396  for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1397 
1398  /* do it? */
1399  if (flags & DC_EXEC) {
1400  /* First normalise the sub types of the chain. */
1401  NormaliseSubtypes(new_head);
1402 
1403  if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1404  /* We are selling the front engine. In this case we want to
1405  * 'give' the order, unit number and such to the new head. */
1406  new_head->orders.list = first->orders.list;
1407  new_head->AddToShared(first);
1408  DeleteVehicleOrders(first);
1409 
1410  /* Copy other important data from the front engine */
1411  new_head->CopyVehicleConfigAndStatistics(first);
1412  GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1413  } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1414  OrderBackup::Backup(v, user);
1415  }
1416 
1417  /* We need to update the information about the train. */
1418  NormaliseTrainHead(new_head);
1419 
1420  /* We are undoubtedly changing something in the depot and train list. */
1423 
1424  /* Actually delete the sold 'goods' */
1425  delete sell_head;
1426  } else {
1427  /* We don't want to execute what we're just tried. */
1428  RestoreTrainBackup(original);
1429  }
1430 
1431  return cost;
1432 }
1433 
1435 {
1436  /* Set common defaults. */
1437  this->x_offs = -1;
1438  this->y_offs = -1;
1439  this->x_extent = 3;
1440  this->y_extent = 3;
1441  this->z_extent = 6;
1442  this->x_bb_offs = 0;
1443  this->y_bb_offs = 0;
1444 
1445  if (!IsDiagonalDirection(direction)) {
1446  static const int _sign_table[] =
1447  {
1448  /* x, y */
1449  -1, -1, // DIR_N
1450  -1, 1, // DIR_E
1451  1, 1, // DIR_S
1452  1, -1, // DIR_W
1453  };
1454 
1455  int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1456 
1457  /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1458  this->x_offs -= half_shorten * _sign_table[direction];
1459  this->y_offs -= half_shorten * _sign_table[direction + 1];
1460  this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1461  this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1462  } else {
1463  switch (direction) {
1464  /* Shorten southern corner of the bounding box according the vehicle length
1465  * and center the bounding box on the vehicle. */
1466  case DIR_NE:
1467  this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1468  this->x_extent = this->gcache.cached_veh_length - 1;
1469  this->x_bb_offs = -1;
1470  break;
1471 
1472  case DIR_NW:
1473  this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1474  this->y_extent = this->gcache.cached_veh_length - 1;
1475  this->y_bb_offs = -1;
1476  break;
1477 
1478  /* Move northern corner of the bounding box down according to vehicle length
1479  * and center the bounding box on the vehicle. */
1480  case DIR_SW:
1481  this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1482  this->x_extent = VEHICLE_LENGTH - 1;
1483  this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1484  break;
1485 
1486  case DIR_SE:
1487  this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1488  this->y_extent = VEHICLE_LENGTH - 1;
1489  this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1490  break;
1491 
1492  default:
1493  NOT_REACHED();
1494  }
1495  }
1496 }
1497 
1502 static void MarkTrainAsStuck(Train *v)
1503 {
1504  if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1505  /* It is the first time the problem occurred, set the "train stuck" flag. */
1506  SetBit(v->flags, VRF_TRAIN_STUCK);
1507 
1508  v->wait_counter = 0;
1509 
1510  /* Stop train */
1511  v->cur_speed = 0;
1512  v->subspeed = 0;
1513  v->SetLastSpeed();
1514 
1516  }
1517 }
1518 
1526 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1527 {
1528  uint16 flag1 = *swap_flag1;
1529  uint16 flag2 = *swap_flag2;
1530 
1531  /* Clear the flags */
1532  ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1533  ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1534  ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1535  ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1536 
1537  /* Reverse the rail-flags (if needed) */
1538  if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1539  SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1540  } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1541  SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1542  }
1543  if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1544  SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1545  } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1546  SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1547  }
1548 }
1549 
1555 {
1556  /* Reverse the direction. */
1557  if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1558 
1559  /* Call the proper EnterTile function unless we are in a wormhole. */
1560  if (v->track != TRACK_BIT_WORMHOLE) {
1561  VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1562  } else {
1563  /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1564  * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1565  * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1566  * when we shouldn't have. Check if this is the case. */
1567  TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1568  if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1569  VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1570  if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1571  /* We have just left the wormhole, possibly set the
1572  * "goingdown" bit. UpdateInclination() can be used
1573  * because we are at the border of the tile. */
1574  v->UpdatePosition();
1575  v->UpdateInclination(true, true);
1576  return;
1577  }
1578  }
1579  }
1580 
1581  v->UpdatePosition();
1582  v->UpdateViewport(true, true);
1583 }
1584 
1591 void ReverseTrainSwapVeh(Train *v, int l, int r)
1592 {
1593  Train *a, *b;
1594 
1595  /* locate vehicles to swap */
1596  for (a = v; l != 0; l--) a = a->Next();
1597  for (b = v; r != 0; r--) b = b->Next();
1598 
1599  if (a != b) {
1600  /* swap the hidden bits */
1601  {
1602  uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1603  b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1604  a->vehstatus = tmp;
1605  }
1606 
1607  Swap(a->track, b->track);
1608  Swap(a->direction, b->direction);
1609  Swap(a->x_pos, b->x_pos);
1610  Swap(a->y_pos, b->y_pos);
1611  Swap(a->tile, b->tile);
1612  Swap(a->z_pos, b->z_pos);
1613 
1614  SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1615 
1618  } else {
1619  /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1620  * This is a little bit redundant way, a->gv_flags will
1621  * be (re)set twice, but it reduces code duplication */
1622  SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1624  }
1625 }
1626 
1627 
1633 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1634 {
1635  return (v->type == VEH_TRAIN) ? v : NULL;
1636 }
1637 
1638 
1646 {
1647  if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
1648 
1649  Train *t = Train::From(v);
1650  if (!t->IsFrontEngine()) return NULL;
1651 
1652  TileIndex tile = *(TileIndex *)data;
1653 
1654  if (TrainApproachingCrossingTile(t) != tile) return NULL;
1655 
1656  return t;
1657 }
1658 
1659 
1667 {
1668  assert(IsLevelCrossingTile(tile));
1669 
1671  TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1672 
1673  if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1674 
1675  dir = ReverseDiagDir(dir);
1676  tile_from = tile + TileOffsByDiagDir(dir);
1677 
1678  return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1679 }
1680 
1681 
1688 void UpdateLevelCrossing(TileIndex tile, bool sound)
1689 {
1690  assert(IsLevelCrossingTile(tile));
1691 
1692  /* train on crossing || train approaching crossing || reserved */
1693  bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
1694 
1695  if (new_state != IsCrossingBarred(tile)) {
1696  if (new_state && sound) {
1697  if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1698  }
1699  SetCrossingBarred(tile, new_state);
1700  MarkTileDirtyByTile(tile);
1701  }
1702 }
1703 
1704 
1710 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1711 {
1712  if (!IsCrossingBarred(tile)) {
1713  BarCrossing(tile);
1714  if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1715  MarkTileDirtyByTile(tile);
1716  }
1717 }
1718 
1719 
1726 {
1727  Train *base = v;
1728  Train *first = base; // first vehicle to move
1729  Train *last = v->Last(); // last vehicle to move
1730  uint length = CountVehiclesInChain(v);
1731 
1732  while (length > 2) {
1733  last = last->Previous();
1734  first = first->Next();
1735 
1736  int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1737 
1738  /* do not update images now
1739  * negative differential will be handled in AdvanceWagonsAfterSwap() */
1740  for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1741 
1742  base = first; // == base->Next()
1743  length -= 2;
1744  }
1745 }
1746 
1747 
1754 {
1755  /* first of all, fix the situation when the train was entering a depot */
1756  Train *dep = v; // last vehicle in front of just left depot
1757  while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1758  dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1759  }
1760 
1761  Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1762 
1763  if (leave != NULL) {
1764  /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1765  int d = TicksToLeaveDepot(dep);
1766 
1767  if (d <= 0) {
1768  leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1769  leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1770  for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1771  }
1772  } else {
1773  dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1774  }
1775 
1776  Train *base = v;
1777  Train *first = base; // first vehicle to move
1778  Train *last = v->Last(); // last vehicle to move
1779  uint length = CountVehiclesInChain(v);
1780 
1781  /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1782  * they have already correct spacing, so we have to make sure they are moved how they should */
1783  bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1784 
1785  while (length > 2) {
1786  /* we reached vehicle (originally) in front of a depot, stop now
1787  * (we would move wagons that are already moved with new wagon length). */
1788  if (base == dep) break;
1789 
1790  /* the last wagon was that one leaving a depot, so do not move it anymore */
1791  if (last == dep) nomove = true;
1792 
1793  last = last->Previous();
1794  first = first->Next();
1795 
1796  int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1797 
1798  /* do not update images now */
1799  for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1800 
1801  base = first; // == base->Next()
1802  length -= 2;
1803  }
1804 }
1805 
1811 {
1812  if (IsRailDepotTile(v->tile)) {
1814  }
1815 
1816  /* Clear path reservation in front if train is not stuck. */
1817  if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1818 
1819  /* Check if we were approaching a rail/road-crossing */
1821 
1822  /* count number of vehicles */
1823  int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1824 
1826 
1827  /* swap start<>end, start+1<>end-1, ... */
1828  int l = 0;
1829  do {
1830  ReverseTrainSwapVeh(v, l++, r--);
1831  } while (l <= r);
1832 
1834 
1835  if (IsRailDepotTile(v->tile)) {
1837  }
1838 
1839  ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1840 
1841  ClrBit(v->flags, VRF_REVERSING);
1842 
1843  /* recalculate cached data */
1845 
1846  /* update all images */
1847  for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
1848 
1849  /* update crossing we were approaching */
1850  if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1851 
1852  /* maybe we are approaching crossing now, after reversal */
1853  crossing = TrainApproachingCrossingTile(v);
1854  if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1855 
1856  /* If we are inside a depot after reversing, don't bother with path reserving. */
1857  if (v->track == TRACK_BIT_DEPOT) {
1858  /* Can't be stuck here as inside a depot is always a safe tile. */
1860  ClrBit(v->flags, VRF_TRAIN_STUCK);
1861  return;
1862  }
1863 
1864  /* TrainExitDir does not always produce the desired dir for depots and
1865  * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
1866  DiagDirection dir = TrainExitDir(v->direction, v->track);
1868 
1870  /* If we are currently on a tile with conventional signals, we can't treat the
1871  * current tile as a safe tile or we would enter a PBS block without a reservation. */
1872  bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
1874  !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
1875 
1876  /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1877  if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
1878 
1880  if (TryPathReserve(v, false, first_tile_okay)) {
1881  /* Do a look-ahead now in case our current tile was already a safe tile. */
1882  CheckNextTrainTile(v);
1883  } else if (v->current_order.GetType() != OT_LOADING) {
1884  /* Do not wait for a way out when we're still loading */
1885  MarkTrainAsStuck(v);
1886  }
1887  } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1888  /* A train not inside a PBS block can't be stuck. */
1889  ClrBit(v->flags, VRF_TRAIN_STUCK);
1890  v->wait_counter = 0;
1891  }
1892 }
1893 
1903 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1904 {
1905  Train *v = Train::GetIfValid(p1);
1906  if (v == NULL) return CMD_ERROR;
1907 
1908  CommandCost ret = CheckOwnership(v->owner);
1909  if (ret.Failed()) return ret;
1910 
1911  if (p2 != 0) {
1912  /* turn a single unit around */
1913 
1914  if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1915  return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1916  }
1917  if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1918 
1919  Train *front = v->First();
1920  /* make sure the vehicle is stopped in the depot */
1921  if (!front->IsStoppedInDepot()) {
1922  return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1923  }
1924 
1925  if (flags & DC_EXEC) {
1926  ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1927 
1928  front->ConsistChanged(CCF_ARRANGE);
1933  }
1934  } else {
1935  /* turn the whole train around */
1936  if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
1937 
1938  if (flags & DC_EXEC) {
1939  /* Properly leave the station if we are loading and won't be loading anymore */
1940  if (v->current_order.IsType(OT_LOADING)) {
1941  const Vehicle *last = v;
1942  while (last->Next() != NULL) last = last->Next();
1943 
1944  /* not a station || different station --> leave the station */
1945  if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
1946  v->LeaveStation();
1947  }
1948  }
1949 
1950  /* We cancel any 'skip signal at dangers' here */
1951  v->force_proceed = TFP_NONE;
1953 
1954  if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
1955  ToggleBit(v->flags, VRF_REVERSING);
1956  } else {
1957  v->cur_speed = 0;
1958  v->SetLastSpeed();
1961  }
1962  }
1963  }
1964  return CommandCost();
1965 }
1966 
1976 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1977 {
1978  Train *t = Train::GetIfValid(p1);
1979  if (t == NULL) return CMD_ERROR;
1980 
1981  if (!t->IsPrimaryVehicle()) return CMD_ERROR;
1982 
1983  CommandCost ret = CheckOwnership(t->owner);
1984  if (ret.Failed()) return ret;
1985 
1986 
1987  if (flags & DC_EXEC) {
1988  /* If we are forced to proceed, cancel that order.
1989  * If we are marked stuck we would want to force the train
1990  * to proceed to the next signal. In the other cases we
1991  * would like to pass the signal at danger and run till the
1992  * next signal we encounter. */
1993  t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
1995  }
1996 
1997  return CommandCost();
1998 }
1999 
2007 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2008 {
2009  assert(!(v->vehstatus & VS_CRASHED));
2010 
2011  if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2012 
2013  PBSTileInfo origin = FollowTrainReservation(v);
2014  if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2015 
2017  case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2018  case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2019 
2020  default: NOT_REACHED();
2021  }
2022 }
2023 
2031 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2032 {
2033  FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2034  if (tfdd.best_length == UINT_MAX) return false;
2035 
2036  if (location != NULL) *location = tfdd.tile;
2037  if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2038  if (reverse != NULL) *reverse = tfdd.reverse;
2039 
2040  return true;
2041 }
2042 
2045 {
2046  static const SoundFx sfx[] = {
2047  SND_04_TRAIN,
2048  SND_0A_TRAIN_HORN,
2049  SND_0A_TRAIN_HORN,
2050  SND_47_MAGLEV_2,
2051  SND_41_MAGLEV
2052  };
2053 
2054  if (PlayVehicleSound(this, VSE_START)) return;
2055 
2056  EngineID engtype = this->engine_type;
2057  SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2058 }
2059 
2064 static void CheckNextTrainTile(Train *v)
2065 {
2066  /* Don't do any look-ahead if path_backoff_interval is 255. */
2067  if (_settings_game.pf.path_backoff_interval == 255) return;
2068 
2069  /* Exit if we are inside a depot. */
2070  if (v->track == TRACK_BIT_DEPOT) return;
2071 
2072  switch (v->current_order.GetType()) {
2073  /* Exit if we reached our destination depot. */
2074  case OT_GOTO_DEPOT:
2075  if (v->tile == v->dest_tile) return;
2076  break;
2077 
2078  case OT_GOTO_WAYPOINT:
2079  /* If we reached our waypoint, make sure we see that. */
2081  break;
2082 
2083  case OT_NOTHING:
2084  case OT_LEAVESTATION:
2085  case OT_LOADING:
2086  /* Exit if the current order doesn't have a destination, but the train has orders. */
2087  if (v->GetNumOrders() > 0) return;
2088  break;
2089 
2090  default:
2091  break;
2092  }
2093  /* Exit if we are on a station tile and are going to stop. */
2095 
2096  Trackdir td = v->GetVehicleTrackdir();
2097 
2098  /* On a tile with a red non-pbs signal, don't look ahead. */
2099  if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2100  !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2101  GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2102 
2103  CFollowTrackRail ft(v);
2104  if (!ft.Follow(v->tile, td)) return;
2105 
2107  /* Next tile is not reserved. */
2110  /* If the next tile is a PBS signal, try to make a reservation. */
2114  }
2115  ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
2116  }
2117  }
2118  }
2119 }
2120 
2127 {
2128  /* bail out if not all wagons are in the same depot or not in a depot at all */
2129  for (const Train *u = v; u != NULL; u = u->Next()) {
2130  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2131  }
2132 
2133  /* if the train got no power, then keep it in the depot */
2134  if (v->gcache.cached_power == 0) {
2135  v->vehstatus |= VS_STOPPED;
2137  return true;
2138  }
2139 
2140  SigSegState seg_state;
2141 
2142  if (v->force_proceed == TFP_NONE) {
2143  /* force proceed was not pressed */
2144  if (++v->wait_counter < 37) {
2146  return true;
2147  }
2148 
2149  v->wait_counter = 0;
2150 
2152  if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2153  /* Full and no PBS signal in block or depot reserved, can't exit. */
2155  return true;
2156  }
2157  } else {
2159  }
2160 
2161  /* We are leaving a depot, but have to go to the exact same one; re-enter */
2162  if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2163  /* We need to have a reservation for this to work. */
2164  if (HasDepotReservation(v->tile)) return true;
2165  SetDepotReservation(v->tile, true);
2166  VehicleEnterDepot(v);
2167  return true;
2168  }
2169 
2170  /* Only leave when we can reserve a path to our destination. */
2171  if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2172  /* No path and no force proceed. */
2174  MarkTrainAsStuck(v);
2175  return true;
2176  }
2177 
2178  SetDepotReservation(v->tile, true);
2180 
2183  v->PlayLeaveStationSound();
2184 
2185  v->track = TRACK_BIT_X;
2186  if (v->direction & 2) v->track = TRACK_BIT_Y;
2187 
2188  v->vehstatus &= ~VS_HIDDEN;
2189  v->cur_speed = 0;
2190 
2191  v->UpdateViewport(true, true);
2192  v->UpdatePosition();
2194  v->UpdateAcceleration();
2196 
2197  return false;
2198 }
2199 
2206 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2207 {
2208  DiagDirection dir = TrackdirToExitdir(track_dir);
2209 
2210  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2211  /* Are we just leaving a tunnel/bridge? */
2212  if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2213  TileIndex end = GetOtherTunnelBridgeEnd(tile);
2214 
2215  if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2216  /* Free the reservation only if no other train is on the tiles. */
2217  SetTunnelBridgeReservation(tile, false);
2218  SetTunnelBridgeReservation(end, false);
2219 
2221  if (IsBridge(tile)) {
2222  MarkBridgeDirty(tile);
2223  } else {
2224  MarkTileDirtyByTile(tile);
2225  MarkTileDirtyByTile(end);
2226  }
2227  }
2228  }
2229  }
2230  } else if (IsRailStationTile(tile)) {
2231  TileIndex new_tile = TileAddByDiagDir(tile, dir);
2232  /* If the new tile is not a further tile of the same station, we
2233  * clear the reservation for the whole platform. */
2234  if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2236  }
2237  } else {
2238  /* Any other tile */
2239  UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2240  }
2241 }
2242 
2249 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
2250 {
2251  assert(v->IsFrontEngine());
2252 
2253  TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
2254  Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
2255  bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2256  StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2257 
2258  /* Can't be holding a reservation if we enter a depot. */
2259  if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2260  if (v->track == TRACK_BIT_DEPOT) {
2261  /* Front engine is in a depot. We enter if some part is not in the depot. */
2262  for (const Train *u = v; u != NULL; u = u->Next()) {
2263  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2264  }
2265  }
2266  /* Don't free reservation if it's not ours. */
2268 
2270  while (ft.Follow(tile, td)) {
2271  tile = ft.m_new_tile;
2273  td = RemoveFirstTrackdir(&bits);
2274  assert(bits == TRACKDIR_BIT_NONE);
2275 
2276  if (!IsValidTrackdir(td)) break;
2277 
2278  if (IsTileType(tile, MP_RAILWAY)) {
2279  if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2280  /* Conventional signal along trackdir: remove reservation and stop. */
2282  break;
2283  }
2284  if (HasPbsSignalOnTrackdir(tile, td)) {
2285  if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2286  /* Red PBS signal? Can't be our reservation, would be green then. */
2287  break;
2288  } else {
2289  /* Turn the signal back to red. */
2291  MarkTileDirtyByTile(tile);
2292  }
2293  } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2294  break;
2295  }
2296  }
2297 
2298  /* Don't free first station/bridge/tunnel if we are on it. */
2299  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);
2300 
2301  free_tile = true;
2302  }
2303 }
2304 
2305 static const byte _initial_tile_subcoord[6][4][3] = {
2306 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2307 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2308 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2309 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2310 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2311 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2312 };
2313 
2326 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2327 {
2329  case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2330  case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2331 
2332  default: NOT_REACHED();
2333  }
2334 }
2335 
2341 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2342 {
2343  PBSTileInfo origin = FollowTrainReservation(v);
2344 
2345  CFollowTrackRail ft(v);
2346 
2347  TileIndex tile = origin.tile;
2348  Trackdir cur_td = origin.trackdir;
2349  while (ft.Follow(tile, cur_td)) {
2351  /* Possible signal tile. */
2353  }
2354 
2357  if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2358  }
2359 
2360  /* Station, depot or waypoint are a possible target. */
2361  bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2362  if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2363  /* Choice found or possible target encountered.
2364  * On finding a possible target, we need to stop and let the pathfinder handle the
2365  * remaining path. This is because we don't know if this target is in one of our
2366  * orders, so we might cause pathfinding to fail later on if we find a choice.
2367  * This failure would cause a bogous call to TryReserveSafePath which might reserve
2368  * a wrong path not leading to our next destination. */
2370 
2371  /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2372  * actually starts its search at the first unreserved tile. */
2374 
2375  /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2376  if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2377  if (enterdir != NULL) *enterdir = ft.m_exitdir;
2378  return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2379  }
2380 
2381  tile = ft.m_new_tile;
2382  cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2383 
2384  if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2385  bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2386  if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2387  /* Safe position is all good, path valid and okay. */
2388  return PBSTileInfo(tile, cur_td, true);
2389  }
2390 
2391  if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2392  }
2393 
2394  if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2395  /* End of line, path valid and okay. */
2396  return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2397  }
2398 
2399  /* Sorry, can't reserve path, back out. */
2400  tile = origin.tile;
2401  cur_td = origin.trackdir;
2402  TileIndex stopped = ft.m_old_tile;
2403  Trackdir stopped_td = ft.m_old_td;
2404  while (tile != stopped || cur_td != stopped_td) {
2405  if (!ft.Follow(tile, cur_td)) break;
2406 
2409  assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2410  }
2412 
2413  tile = ft.m_new_tile;
2414  cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2415 
2416  UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2417  }
2418 
2419  /* Path invalid. */
2420  return PBSTileInfo();
2421 }
2422 
2433 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
2434 {
2436  case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2437  case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2438 
2439  default: NOT_REACHED();
2440  }
2441 }
2442 
2445 private:
2446  Train *v;
2447  Order old_order;
2448  TileIndex old_dest_tile;
2449  StationID old_last_station_visited;
2450  VehicleOrderID index;
2451  bool suppress_implicit_orders;
2452 
2453 public:
2454  VehicleOrderSaver(Train *_v) :
2455  v(_v),
2456  old_order(_v->current_order),
2457  old_dest_tile(_v->dest_tile),
2458  old_last_station_visited(_v->last_station_visited),
2459  index(_v->cur_real_order_index),
2460  suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2461  {
2462  }
2463 
2465  {
2466  this->v->current_order = this->old_order;
2467  this->v->dest_tile = this->old_dest_tile;
2468  this->v->last_station_visited = this->old_last_station_visited;
2469  SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2470  }
2471 
2477  bool SwitchToNextOrder(bool skip_first)
2478  {
2479  if (this->v->GetNumOrders() == 0) return false;
2480 
2481  if (skip_first) ++this->index;
2482 
2483  int depth = 0;
2484 
2485  do {
2486  /* Wrap around. */
2487  if (this->index >= this->v->GetNumOrders()) this->index = 0;
2488 
2489  Order *order = this->v->GetOrder(this->index);
2490  assert(order != NULL);
2491 
2492  switch (order->GetType()) {
2493  case OT_GOTO_DEPOT:
2494  /* Skip service in depot orders when the train doesn't need service. */
2495  if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2496  case OT_GOTO_STATION:
2497  case OT_GOTO_WAYPOINT:
2498  this->v->current_order = *order;
2499  return UpdateOrderDest(this->v, order, 0, true);
2500  case OT_CONDITIONAL: {
2501  VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2502  if (next != INVALID_VEH_ORDER_ID) {
2503  depth++;
2504  this->index = next;
2505  /* Don't increment next, so no break here. */
2506  continue;
2507  }
2508  break;
2509  }
2510  default:
2511  break;
2512  }
2513  /* Don't increment inside the while because otherwise conditional
2514  * orders can lead to an infinite loop. */
2515  ++this->index;
2516  depth++;
2517  } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2518 
2519  return false;
2520  }
2521 };
2522 
2523 /* choose a track */
2524 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2525 {
2526  Track best_track = INVALID_TRACK;
2527  bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2528  bool changed_signal = false;
2529 
2530  assert((tracks & ~TRACK_BIT_MASK) == 0);
2531 
2532  if (got_reservation != NULL) *got_reservation = false;
2533 
2534  /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2535  TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2536  /* Do we have a suitable reserved track? */
2537  if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2538 
2539  /* Quick return in case only one possible track is available */
2540  if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2541  Track track = FindFirstTrack(tracks);
2542  /* We need to check for signals only here, as a junction tile can't have signals. */
2543  if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2544  do_track_reservation = true;
2545  changed_signal = true;
2547  } else if (!do_track_reservation) {
2548  return track;
2549  }
2550  best_track = track;
2551  }
2552 
2553  PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2554  DiagDirection dest_enterdir = enterdir;
2555  if (do_track_reservation) {
2556  res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2557  if (res_dest.tile == INVALID_TILE) {
2558  /* Reservation failed? */
2559  if (mark_stuck) MarkTrainAsStuck(v);
2560  if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2561  return FindFirstTrack(tracks);
2562  }
2563  if (res_dest.okay) {
2564  /* Got a valid reservation that ends at a safe target, quick exit. */
2565  if (got_reservation != NULL) *got_reservation = true;
2566  if (changed_signal) MarkTileDirtyByTile(tile);
2568  return best_track;
2569  }
2570 
2571  /* Check if the train needs service here, so it has a chance to always find a depot.
2572  * Also check if the current order is a service order so we don't reserve a path to
2573  * the destination but instead to the next one if service isn't needed. */
2575  if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2576  }
2577 
2578  /* Save the current train order. The destructor will restore the old order on function exit. */
2579  VehicleOrderSaver orders(v);
2580 
2581  /* If the current tile is the destination of the current order and
2582  * a reservation was requested, advance to the next order.
2583  * Don't advance on a depot order as depots are always safe end points
2584  * for a path and no look-ahead is necessary. This also avoids a
2585  * problem with depot orders not part of the order list when the
2586  * order list itself is empty. */
2587  if (v->current_order.IsType(OT_LEAVESTATION)) {
2588  orders.SwitchToNextOrder(false);
2589  } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2590  v->current_order.IsType(OT_GOTO_STATION) ?
2592  v->tile == v->dest_tile))) {
2593  orders.SwitchToNextOrder(true);
2594  }
2595 
2596  if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2597  /* Pathfinders are able to tell that route was only 'guessed'. */
2598  bool path_found = true;
2599  TileIndex new_tile = res_dest.tile;
2600 
2601  Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2602  if (new_tile == tile) best_track = next_track;
2603  v->HandlePathfindingResult(path_found);
2604  }
2605 
2606  /* No track reservation requested -> finished. */
2607  if (!do_track_reservation) return best_track;
2608 
2609  /* A path was found, but could not be reserved. */
2610  if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2611  if (mark_stuck) MarkTrainAsStuck(v);
2613  return best_track;
2614  }
2615 
2616  /* No possible reservation target found, we are probably lost. */
2617  if (res_dest.tile == INVALID_TILE) {
2618  /* Try to find any safe destination. */
2619  PBSTileInfo origin = FollowTrainReservation(v);
2620  if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2621  TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2622  best_track = FindFirstTrack(res);
2624  if (got_reservation != NULL) *got_reservation = true;
2625  if (changed_signal) MarkTileDirtyByTile(tile);
2626  } else {
2628  if (mark_stuck) MarkTrainAsStuck(v);
2629  }
2630  return best_track;
2631  }
2632 
2633  if (got_reservation != NULL) *got_reservation = true;
2634 
2635  /* Reservation target found and free, check if it is safe. */
2636  while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2637  /* Extend reservation until we have found a safe position. */
2638  DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2639  TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2642  reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2643  }
2644 
2645  /* Get next order with destination. */
2646  if (orders.SwitchToNextOrder(true)) {
2647  PBSTileInfo cur_dest;
2648  bool path_found;
2649  DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
2650  if (cur_dest.tile != INVALID_TILE) {
2651  res_dest = cur_dest;
2652  if (res_dest.okay) continue;
2653  /* Path found, but could not be reserved. */
2655  if (mark_stuck) MarkTrainAsStuck(v);
2656  if (got_reservation != NULL) *got_reservation = false;
2657  changed_signal = false;
2658  break;
2659  }
2660  }
2661  /* No order or no safe position found, try any position. */
2662  if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2664  if (mark_stuck) MarkTrainAsStuck(v);
2665  if (got_reservation != NULL) *got_reservation = false;
2666  changed_signal = false;
2667  }
2668  break;
2669  }
2670 
2672 
2673  if (changed_signal) MarkTileDirtyByTile(tile);
2674 
2675  return best_track;
2676 }
2677 
2686 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2687 {
2688  assert(v->IsFrontEngine());
2689 
2690  /* We have to handle depots specially as the track follower won't look
2691  * at the depot tile itself but starts from the next tile. If we are still
2692  * inside the depot, a depot reservation can never be ours. */
2693  if (v->track == TRACK_BIT_DEPOT) {
2694  if (HasDepotReservation(v->tile)) {
2695  if (mark_as_stuck) MarkTrainAsStuck(v);
2696  return false;
2697  } else {
2698  /* Depot not reserved, but the next tile might be. */
2700  if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2701  }
2702  }
2703 
2704  Vehicle *other_train = NULL;
2705  PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2706  /* The path we are driving on is already blocked by some other train.
2707  * This can only happen in certain situations when mixing path and
2708  * block signals or when changing tracks and/or signals.
2709  * Exit here as doing any further reservations will probably just
2710  * make matters worse. */
2711  if (other_train != NULL && other_train->index != v->index) {
2712  if (mark_as_stuck) MarkTrainAsStuck(v);
2713  return false;
2714  }
2715  /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2716  if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2717  /* Can't be stuck then. */
2719  ClrBit(v->flags, VRF_TRAIN_STUCK);
2720  return true;
2721  }
2722 
2723  /* If we are in a depot, tentatively reserve the depot. */
2724  if (v->track == TRACK_BIT_DEPOT) {
2725  SetDepotReservation(v->tile, true);
2727  }
2728 
2729  DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2730  TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2732 
2734 
2735  bool res_made = false;
2736  ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2737 
2738  if (!res_made) {
2739  /* Free the depot reservation as well. */
2740  if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2741  return false;
2742  }
2743 
2744  if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2745  v->wait_counter = 0;
2747  }
2748  ClrBit(v->flags, VRF_TRAIN_STUCK);
2749  return true;
2750 }
2751 
2752 
2753 static bool CheckReverseTrain(const Train *v)
2754 {
2756  v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2757  !(v->direction & 1)) {
2758  return false;
2759  }
2760 
2761  assert(v->track != TRACK_BIT_NONE);
2762 
2764  case VPF_NPF: return NPFTrainCheckReverse(v);
2765  case VPF_YAPF: return YapfTrainCheckReverse(v);
2766 
2767  default: NOT_REACHED();
2768  }
2769 }
2770 
2777 {
2778  if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2779 
2780  const Station *st = Station::Get(station);
2781  if (!(st->facilities & FACIL_TRAIN)) {
2782  /* The destination station has no trainstation tiles. */
2783  this->IncrementRealOrderIndex();
2784  return 0;
2785  }
2786 
2787  return st->xy;
2788 }
2789 
2792 {
2793  Train *v = this;
2794  do {
2795  v->colourmap = PAL_NONE;
2796  v->UpdateViewport(true, false);
2797  } while ((v = v->Next()) != NULL);
2798 
2799  /* need to update acceleration and cached values since the goods on the train changed. */
2800  this->CargoChanged();
2801  this->UpdateAcceleration();
2802 }
2803 
2812 {
2814  default: NOT_REACHED();
2815  case AM_ORIGINAL:
2816  return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2817 
2818  case AM_REALISTIC:
2819  return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2820  }
2821 }
2822 
2828 static void TrainEnterStation(Train *v, StationID station)
2829 {
2830  v->last_station_visited = station;
2831 
2832  /* check if a train ever visited this station before */
2833  Station *st = Station::Get(station);
2834  if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2835  st->had_vehicle_of_type |= HVOT_TRAIN;
2836  SetDParam(0, st->index);
2838  STR_NEWS_FIRST_TRAIN_ARRIVAL,
2840  v->index,
2841  st->index
2842  );
2843  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2844  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2845  }
2846 
2847  v->force_proceed = TFP_NONE;
2849 
2850  v->BeginLoading();
2851 
2853  TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2854 }
2855 
2856 /* Check if the vehicle is compatible with the specified tile */
2857 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
2858 {
2859  return IsTileOwner(tile, v->owner) &&
2860  (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
2861 }
2862 
2865  byte small_turn;
2866  byte large_turn;
2867  byte z_up;
2868  byte z_down;
2869 };
2870 
2873  /* normal accel */
2874  {256 / 4, 256 / 2, 256 / 4, 2},
2875  {256 / 4, 256 / 2, 256 / 4, 2},
2876  {0, 256 / 2, 256 / 4, 2},
2877 };
2878 
2884 static inline void AffectSpeedByZChange(Train *v, int old_z)
2885 {
2886  if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2887 
2888  const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2889 
2890  if (old_z < v->z_pos) {
2891  v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2892  } else {
2893  uint16 spd = v->cur_speed + asp->z_down;
2894  if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2895  }
2896 }
2897 
2898 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
2899 {
2900  if (IsTileType(tile, MP_RAILWAY) &&
2903  Trackdir trackdir = FindFirstTrackdir(tracks);
2904  if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
2905  /* A PBS block with a non-PBS signal facing us? */
2906  if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
2907  }
2908  }
2909  return false;
2910 }
2911 
2914 {
2915  for (const Train *u = this; u != NULL; u = u->Next()) {
2916  switch (u->track) {
2917  case TRACK_BIT_WORMHOLE:
2919  break;
2920  case TRACK_BIT_DEPOT:
2921  break;
2922  default:
2923  TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
2924  break;
2925  }
2926  }
2927 }
2928 
2935 uint Train::Crash(bool flooded)
2936 {
2937  uint pass = 0;
2938  if (this->IsFrontEngine()) {
2939  pass += 2; // driver
2940 
2941  /* Remove the reserved path in front of the train if it is not stuck.
2942  * Also clear all reserved tracks the train is currently on. */
2943  if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
2944  for (const Train *v = this; v != NULL; v = v->Next()) {
2946  if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
2947  /* ClearPathReservation will not free the wormhole exit
2948  * if the train has just entered the wormhole. */
2950  }
2951  }
2952 
2953  /* we may need to update crossing we were approaching,
2954  * but must be updated after the train has been marked crashed */
2955  TileIndex crossing = TrainApproachingCrossingTile(this);
2956  if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2957 
2958  /* Remove the loading indicators (if any) */
2960  }
2961 
2962  pass += this->GroundVehicleBase::Crash(flooded);
2963 
2964  this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
2965  return pass;
2966 }
2967 
2974 static uint TrainCrashed(Train *v)
2975 {
2976  uint num = 0;
2977 
2978  /* do not crash train twice */
2979  if (!(v->vehstatus & VS_CRASHED)) {
2980  num = v->Crash();
2981  AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2982  Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2983  }
2984 
2985  /* Try to re-reserve track under already crashed train too.
2986  * Crash() clears the reservation! */
2988 
2989  return num;
2990 }
2991 
2995  uint num;
2996 };
2997 
3004 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3005 {
3007 
3008  /* not a train or in depot */
3009  if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
3010 
3011  /* do not crash into trains of another company. */
3012  if (v->owner != tcc->v->owner) return NULL;
3013 
3014  /* get first vehicle now to make most usual checks faster */
3015  Train *coll = Train::From(v)->First();
3016 
3017  /* can't collide with own wagons */
3018  if (coll == tcc->v) return NULL;
3019 
3020  int x_diff = v->x_pos - tcc->v->x_pos;
3021  int y_diff = v->y_pos - tcc->v->y_pos;
3022 
3023  /* Do fast calculation to check whether trains are not in close vicinity
3024  * and quickly reject trains distant enough for any collision.
3025  * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3026  * Differences are then ORed and then we check for any higher bits */
3027  uint hash = (y_diff + 7) | (x_diff + 7);
3028  if (hash & ~15) return NULL;
3029 
3030  /* Slower check using multiplication */
3031  int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3032  if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
3033 
3034  /* Happens when there is a train under bridge next to bridge head */
3035  if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
3036 
3037  /* crash both trains */
3038  tcc->num += TrainCrashed(tcc->v);
3039  tcc->num += TrainCrashed(coll);
3040 
3041  return NULL; // continue searching
3042 }
3043 
3052 {
3053  /* can't collide in depot */
3054  if (v->track == TRACK_BIT_DEPOT) return false;
3055 
3056  assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3057 
3058  TrainCollideChecker tcc;
3059  tcc.v = v;
3060  tcc.num = 0;
3061 
3062  /* find colliding vehicles */
3063  if (v->track == TRACK_BIT_WORMHOLE) {
3066  } else {
3068  }
3069 
3070  /* any dead -> no crash */
3071  if (tcc.num == 0) return false;
3072 
3073  SetDParam(0, tcc.num);
3074  AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3075 
3076  ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3077  if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3078  return true;
3079 }
3080 
3081 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3082 {
3083  if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
3084 
3085  Train *t = Train::From(v);
3086  DiagDirection exitdir = *(DiagDirection *)data;
3087 
3088  /* not front engine of a train, inside wormhole or depot, crashed */
3089  if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
3090 
3091  if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
3092 
3093  return t;
3094 }
3095 
3103 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3104 {
3105  Train *first = v->First();
3106  Train *prev;
3107  bool direction_changed = false; // has direction of any part changed?
3108 
3109  /* For every vehicle after and including the given vehicle */
3110  for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3111  DiagDirection enterdir = DIAGDIR_BEGIN;
3112  bool update_signals_crossing = false; // will we update signals or crossing state?
3113 
3115  if (v->track != TRACK_BIT_WORMHOLE) {
3116  /* Not inside tunnel */
3117  if (gp.old_tile == gp.new_tile) {
3118  /* Staying in the old tile */
3119  if (v->track == TRACK_BIT_DEPOT) {
3120  /* Inside depot */
3121  gp.x = v->x_pos;
3122  gp.y = v->y_pos;
3123  } else {
3124  /* Not inside depot */
3125 
3126  /* Reverse when we are at the end of the track already, do not move to the new position */
3127  if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3128 
3129  uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3130  if (HasBit(r, VETS_CANNOT_ENTER)) {
3131  goto invalid_rail;
3132  }
3133  if (HasBit(r, VETS_ENTERED_STATION)) {
3134  /* The new position is the end of the platform */
3136  }
3137  }
3138  } else {
3139  /* A new tile is about to be entered. */
3140 
3141  /* Determine what direction we're entering the new tile from */
3142  enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3143  assert(IsValidDiagDirection(enterdir));
3144 
3145  /* Get the status of the tracks in the new tile and mask
3146  * away the bits that aren't reachable. */
3147  TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3148  TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3149 
3150  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3151  TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3152 
3153  TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3154  if (_settings_game.pf.forbid_90_deg && prev == NULL) {
3155  /* We allow wagons to make 90 deg turns, because forbid_90_deg
3156  * can be switched on halfway a turn */
3157  bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3158  }
3159 
3160  if (bits == TRACK_BIT_NONE) goto invalid_rail;
3161 
3162  /* Check if the new tile constrains tracks that are compatible
3163  * with the current train, if not, bail out. */
3164  if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3165 
3166  TrackBits chosen_track;
3167  if (prev == NULL) {
3168  /* Currently the locomotive is active. Determine which one of the
3169  * available tracks to choose */
3170  chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
3171  assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3172 
3173  if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3174  /* For each signal we find decrease the counter by one.
3175  * We start at two, so the first signal we pass decreases
3176  * this to one, then if we reach the next signal it is
3177  * decreased to zero and we won't pass that new signal. */
3178  Trackdir dir = FindFirstTrackdir(trackdirbits);
3179  if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3181  GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3182  /* However, we do not want to be stopped by PBS signals
3183  * entered via the back. */
3184  v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3185  SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3186  }
3187  }
3188 
3189  /* Check if it's a red signal and that force proceed is not clicked. */
3190  if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3191  /* In front of a red signal */
3192  Trackdir i = FindFirstTrackdir(trackdirbits);
3193 
3194  /* Don't handle stuck trains here. */
3195  if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3196 
3198  v->cur_speed = 0;
3199  v->subspeed = 0;
3200  v->progress = 255 - 100;
3201  if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
3202  } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3203  v->cur_speed = 0;
3204  v->subspeed = 0;
3205  v->progress = 255 - 10;
3206  if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3207  DiagDirection exitdir = TrackdirToExitdir(i);
3208  TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3209 
3210  exitdir = ReverseDiagDir(exitdir);
3211 
3212  /* check if a train is waiting on the other side */
3213  if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3214  }
3215  }
3216 
3217  /* If we would reverse but are currently in a PBS block and
3218  * reversing of stuck trains is disabled, don't reverse.
3219  * This does not apply if the reason for reversing is a one-way
3220  * signal blocking us, because a train would then be stuck forever. */
3222  UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3223  v->wait_counter = 0;
3224  return false;
3225  }
3226  goto reverse_train_direction;
3227  } else {
3228  TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3229  }
3230  } else {
3231  /* The wagon is active, simply follow the prev vehicle. */
3232  if (prev->tile == gp.new_tile) {
3233  /* Choose the same track as prev */
3234  if (prev->track == TRACK_BIT_WORMHOLE) {
3235  /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3236  * However, just choose the track into the wormhole. */
3237  assert(IsTunnel(prev->tile));
3238  chosen_track = bits;
3239  } else {
3240  chosen_track = prev->track;
3241  }
3242  } else {
3243  /* Choose the track that leads to the tile where prev is.
3244  * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3245  * I.e. when the tile between them has only space for a single vehicle like
3246  * 1) horizontal/vertical track tiles and
3247  * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3248  * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3249  */
3250  static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3255  };
3256  DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3257  assert(IsValidDiagDirection(exitdir));
3258  chosen_track = _connecting_track[enterdir][exitdir];
3259  }
3260  chosen_track &= bits;
3261  }
3262 
3263  /* Make sure chosen track is a valid track */
3264  assert(
3265  chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3266  chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3267  chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3268 
3269  /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3270  const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3271  gp.x = (gp.x & ~0xF) | b[0];
3272  gp.y = (gp.y & ~0xF) | b[1];
3273  Direction chosen_dir = (Direction)b[2];
3274 
3275  /* Call the landscape function and tell it that the vehicle entered the tile */
3276  uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3277  if (HasBit(r, VETS_CANNOT_ENTER)) {
3278  goto invalid_rail;
3279  }
3280 
3281  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3282  Track track = FindFirstTrack(chosen_track);
3283  Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3284  if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3287  }
3288 
3289  /* Clear any track reservation when the last vehicle leaves the tile */
3290  if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3291 
3292  v->tile = gp.new_tile;
3293 
3295  v->First()->ConsistChanged(CCF_TRACK);
3296  }
3297 
3298  v->track = chosen_track;
3299  assert(v->track);
3300  }
3301 
3302  /* We need to update signal status, but after the vehicle position hash
3303  * has been updated by UpdateInclination() */
3304  update_signals_crossing = true;
3305 
3306  if (chosen_dir != v->direction) {
3307  if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3308  const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3309  DirDiff diff = DirDifference(v->direction, chosen_dir);
3310  v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3311  }
3312  direction_changed = true;
3313  v->direction = chosen_dir;
3314  }
3315 
3316  if (v->IsFrontEngine()) {
3317  v->wait_counter = 0;
3318 
3319  /* If we are approaching a crossing that is reserved, play the sound now. */
3321  if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3322 
3323  /* Always try to extend the reservation when entering a tile. */
3324  CheckNextTrainTile(v);
3325  }
3326 
3327  if (HasBit(r, VETS_ENTERED_STATION)) {
3328  /* The new position is the location where we want to stop */
3330  }
3331  }
3332  } else {
3334  /* Perform look-ahead on tunnel exit. */
3335  if (v->IsFrontEngine()) {
3337  CheckNextTrainTile(v);
3338  }
3339  /* Prevent v->UpdateInclination() being called with wrong parameters.
3340  * This could happen if the train was reversed inside the tunnel/bridge. */
3341  if (gp.old_tile == gp.new_tile) {
3343  }
3344  } else {
3345  v->x_pos = gp.x;
3346  v->y_pos = gp.y;
3347  v->UpdatePosition();
3348  if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3349  continue;
3350  }
3351  }
3352 
3353  /* update image of train, as well as delta XY */
3354  v->UpdateDeltaXY(v->direction);
3355 
3356  v->x_pos = gp.x;
3357  v->y_pos = gp.y;
3358  v->UpdatePosition();
3359 
3360  /* update the Z position of the vehicle */
3361  int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3362 
3363  if (prev == NULL) {
3364  /* This is the first vehicle in the train */
3365  AffectSpeedByZChange(v, old_z);
3366  }
3367 
3368  if (update_signals_crossing) {
3369  if (v->IsFrontEngine()) {
3370  if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3371  /* We are entering a block with PBS signals right now, but
3372  * not through a PBS signal. This means we don't have a
3373  * reservation right now. As a conventional signal will only
3374  * ever be green if no other train is in the block, getting
3375  * a path should always be possible. If the player built
3376  * such a strange network that it is not possible, the train
3377  * will be marked as stuck and the player has to deal with
3378  * the problem. */
3379  if ((!HasReservedTracks(gp.new_tile, v->track) &&
3380  !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3381  !TryPathReserve(v)) {
3382  MarkTrainAsStuck(v);
3383  }
3384  }
3385  }
3386 
3387  /* Signals can only change when the first
3388  * (above) or the last vehicle moves. */
3389  if (v->Next() == NULL) {
3390  TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3392  }
3393  }
3394 
3395  /* Do not check on every tick to save some computing time. */
3396  if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
3397  }
3398 
3399  if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3400 
3401  return true;
3402 
3403 invalid_rail:
3404  /* We've reached end of line?? */
3405  if (prev != NULL) error("Disconnecting train");
3406 
3407 reverse_train_direction:
3408  if (reverse) {
3409  v->wait_counter = 0;
3410  v->cur_speed = 0;
3411  v->subspeed = 0;
3413  }
3414 
3415  return false;
3416 }
3417 
3425 {
3426  TrackBits *trackbits = (TrackBits *)data;
3427 
3428  if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3429  TrackBits train_tbits = Train::From(v)->track;
3430  if (train_tbits == TRACK_BIT_WORMHOLE) {
3431  /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3433  } else if (train_tbits != TRACK_BIT_DEPOT) {
3434  *trackbits |= train_tbits;
3435  }
3436  }
3437 
3438  return NULL;
3439 }
3440 
3448 static void DeleteLastWagon(Train *v)
3449 {
3450  Train *first = v->First();
3451 
3452  /* Go to the last wagon and delete the link pointing there
3453  * *u is then the one-before-last wagon, and *v the last
3454  * one which will physically be removed */
3455  Train *u = v;
3456  for (; v->Next() != NULL; v = v->Next()) u = v;
3457  u->SetNext(NULL);
3458 
3459  if (first != v) {
3460  /* Recalculate cached train properties */
3461  first->ConsistChanged(CCF_ARRANGE);
3462  /* Update the depot window if the first vehicle is in depot -
3463  * if v == first, then it is updated in PreDestructor() */
3464  if (first->track == TRACK_BIT_DEPOT) {
3466  }
3467  v->last_station_visited = first->last_station_visited; // for PreDestructor
3468  }
3469 
3470  /* 'v' shouldn't be accessed after it has been deleted */
3471  TrackBits trackbits = v->track;
3472  TileIndex tile = v->tile;
3473  Owner owner = v->owner;
3474 
3475  delete v;
3476  v = NULL; // make sure nobody will try to read 'v' anymore
3477 
3478  if (trackbits == TRACK_BIT_WORMHOLE) {
3479  /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3481  }
3482 
3483  Track track = TrackBitsToTrack(trackbits);
3484  if (HasReservedTracks(tile, trackbits)) {
3485  UnreserveRailTrack(tile, track);
3486 
3487  /* If there are still crashed vehicles on the tile, give the track reservation to them */
3488  TrackBits remaining_trackbits = TRACK_BIT_NONE;
3489  FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3490 
3491  /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3492  assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3493  Track t;
3494  FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
3495  }
3496 
3497  /* check if the wagon was on a road/rail-crossing */
3498  if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3499 
3500  /* Update signals */
3501  if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3503  } else {
3504  SetSignalsOnBothDir(tile, track, owner);
3505  }
3506 }
3507 
3513 {
3514  static const DirDiff delta[] = {
3516  };
3517 
3518  do {
3519  /* We don't need to twist around vehicles if they're not visible */
3520  if (!(v->vehstatus & VS_HIDDEN)) {
3521  v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3522  v->UpdateDeltaXY(v->direction);
3523  v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
3524  /* Refrain from updating the z position of the vehicle when on
3525  * a bridge, because UpdateInclination() will put the vehicle under
3526  * the bridge in that case */
3527  if (v->track != TRACK_BIT_WORMHOLE) {
3528  v->UpdatePosition();
3529  v->UpdateInclination(false, false);
3530  }
3531  }
3532  } while ((v = v->Next()) != NULL);
3533 }
3534 
3540 static bool HandleCrashedTrain(Train *v)
3541 {
3542  int state = ++v->crash_anim_pos;
3543 
3544  if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3546  }
3547 
3548  uint32 r;
3549  if (state <= 200 && Chance16R(1, 7, r)) {
3550  int index = (r * 10 >> 16);
3551 
3552  Vehicle *u = v;
3553  do {
3554  if (--index < 0) {
3555  r = Random();
3556 
3558  GB(r, 8, 3) + 2,
3559  GB(r, 16, 3) + 2,
3560  GB(r, 0, 3) + 5,
3562  break;
3563  }
3564  } while ((u = u->Next()) != NULL);
3565  }
3566 
3567  if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3568 
3569  if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3570  bool ret = v->Next() != NULL;
3571  DeleteLastWagon(v);
3572  return ret;
3573  }
3574 
3575  return true;
3576 }
3577 
3579 static const uint16 _breakdown_speeds[16] = {
3580  225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3581 };
3582 
3583 
3592 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3593 {
3594  /* Calc position within the current tile */
3595  uint x = v->x_pos & 0xF;
3596  uint y = v->y_pos & 0xF;
3597 
3598  /* for diagonal directions, 'x' will be 0..15 -
3599  * for other directions, it will be 1, 3, 5, ..., 15 */
3600  switch (v->direction) {
3601  case DIR_N : x = ~x + ~y + 25; break;
3602  case DIR_NW: x = y; // FALL THROUGH
3603  case DIR_NE: x = ~x + 16; break;
3604  case DIR_E : x = ~x + y + 9; break;
3605  case DIR_SE: x = y; break;
3606  case DIR_S : x = x + y - 7; break;
3607  case DIR_W : x = ~y + x + 9; break;
3608  default: break;
3609  }
3610 
3611  /* Do not reverse when approaching red signal. Make sure the vehicle's front
3612  * does not cross the tile boundary when we do reverse, but as the vehicle's
3613  * location is based on their center, use half a vehicle's length as offset.
3614  * Multiply the half-length by two for straight directions to compensate that
3615  * we only get odd x offsets there. */
3616  if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3617  /* we are too near the tile end, reverse now */
3618  v->cur_speed = 0;
3619  if (reverse) ReverseTrainDirection(v);
3620  return false;
3621  }
3622 
3623  /* slow down */
3625  uint16 break_speed = _breakdown_speeds[x & 0xF];
3626  if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3627 
3628  return true;
3629 }
3630 
3631 
3637 static bool TrainCanLeaveTile(const Train *v)
3638 {
3639  /* Exit if inside a tunnel/bridge or a depot */
3640  if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3641 
3642  TileIndex tile = v->tile;
3643 
3644  /* entering a tunnel/bridge? */
3645  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3647  if (DiagDirToDir(dir) == v->direction) return false;
3648  }
3649 
3650  /* entering a depot? */
3651  if (IsRailDepotTile(tile)) {
3653  if (DiagDirToDir(dir) == v->direction) return false;
3654  }
3655 
3656  return true;
3657 }
3658 
3659 
3668 {
3669  assert(v->IsFrontEngine());
3670  assert(!(v->vehstatus & VS_CRASHED));
3671 
3672  if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3673 
3674  DiagDirection dir = TrainExitDir(v->direction, v->track);
3675  TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3676 
3677  /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3678  if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3679  !CheckCompatibleRail(v, tile)) {
3680  return INVALID_TILE;
3681  }
3682 
3683  return tile;
3684 }
3685 
3686 
3694 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3695 {
3696  /* First, handle broken down train */
3697 
3698  int t = v->breakdown_ctr;
3699  if (t > 1) {
3701 
3702  uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3703  if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3704  } else {
3705  v->vehstatus &= ~VS_TRAIN_SLOWING;
3706  }
3707 
3708  if (!TrainCanLeaveTile(v)) return true;
3709 
3710  /* Determine the non-diagonal direction in which we will exit this tile */
3711  DiagDirection dir = TrainExitDir(v->direction, v->track);
3712  /* Calculate next tile */
3713  TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3714 
3715  /* Determine the track status on the next tile */
3716  TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3717  TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3718 
3719  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3720  TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3721 
3722  /* We are sure the train is not entering a depot, it is detected above */
3723 
3724  /* mask unreachable track bits if we are forbidden to do 90deg turns */
3725  TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3727  bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3728  }
3729 
3730  /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3731  if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3732  return TrainApproachingLineEnd(v, false, reverse);
3733  }
3734 
3735  /* approaching red signal */
3736  if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3737 
3738  /* approaching a rail/road crossing? then make it red */
3740 
3741  return true;
3742 }
3743 
3744 
3745 static bool TrainLocoHandler(Train *v, bool mode)
3746 {
3747  /* train has crashed? */
3748  if (v->vehstatus & VS_CRASHED) {
3749  return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3750  }
3751 
3752  if (v->force_proceed != TFP_NONE) {
3753  ClrBit(v->flags, VRF_TRAIN_STUCK);
3755  }
3756 
3757  /* train is broken down? */
3758  if (v->HandleBreakdown()) return true;
3759 
3760  if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3762  }
3763 
3764  /* exit if train is stopped */
3765  if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3766 
3767  bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3768  if (ProcessOrders(v) && CheckReverseTrain(v)) {
3769  v->wait_counter = 0;
3770  v->cur_speed = 0;
3771  v->subspeed = 0;
3772  ClrBit(v->flags, VRF_LEAVING_STATION);
3774  return true;
3775  } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3776  /* Try to reserve a path when leaving the station as we
3777  * might not be marked as wanting a reservation, e.g.
3778  * when an overlength train gets turned around in a station. */
3779  DiagDirection dir = TrainExitDir(v->direction, v->track);
3781 
3783  TryPathReserve(v, true, true);
3784  }
3785  ClrBit(v->flags, VRF_LEAVING_STATION);
3786  }
3787 
3788  v->HandleLoading(mode);
3789 
3790  if (v->current_order.IsType(OT_LOADING)) return true;
3791 
3792  if (CheckTrainStayInDepot(v)) return true;
3793 
3794  if (!mode) v->ShowVisualEffect();
3795 
3796  /* We had no order but have an order now, do look ahead. */
3797  if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3798  CheckNextTrainTile(v);
3799  }
3800 
3801  /* Handle stuck trains. */
3802  if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3803  ++v->wait_counter;
3804 
3805  /* Should we try reversing this tick if still stuck? */
3807 
3808  if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3809  if (!TryPathReserve(v)) {
3810  /* Still stuck. */
3811  if (turn_around) ReverseTrainDirection(v);
3812 
3814  /* Show message to player. */
3816  SetDParam(0, v->index);
3817  AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
3818  }
3819  v->wait_counter = 0;
3820  }
3821  /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3822  if (v->force_proceed == TFP_NONE) return true;
3823  ClrBit(v->flags, VRF_TRAIN_STUCK);
3824  v->wait_counter = 0;
3826  }
3827  }
3828 
3829  if (v->current_order.IsType(OT_LEAVESTATION)) {
3830  v->current_order.Free();
3832  return true;
3833  }
3834 
3835  int j = v->UpdateSpeed();
3836 
3837  /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
3838  if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
3839  /* If we manually stopped, we're not force-proceeding anymore. */
3840  v->force_proceed = TFP_NONE;
3842  }
3843 
3844  int adv_spd = v->GetAdvanceDistance();
3845  if (j < adv_spd) {
3846  /* if the vehicle has speed 0, update the last_speed field. */
3847  if (v->cur_speed == 0) v->SetLastSpeed();
3848  } else {
3850  /* Loop until the train has finished moving. */
3851  for (;;) {
3852  j -= adv_spd;
3853  TrainController(v, NULL);
3854  /* Don't continue to move if the train crashed. */
3855  if (CheckTrainCollision(v)) break;
3856  /* Determine distance to next map position */
3857  adv_spd = v->GetAdvanceDistance();
3858 
3859  /* No more moving this tick */
3860  if (j < adv_spd || v->cur_speed == 0) break;
3861 
3862  OrderType order_type = v->current_order.GetType();
3863  /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
3864  if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3866  IsTileType(v->tile, MP_STATION) &&
3868  ProcessOrders(v);
3869  }
3870  }
3871  v->SetLastSpeed();
3872  }
3873 
3874  for (Train *u = v; u != NULL; u = u->Next()) {
3875  if ((u->vehstatus & VS_HIDDEN) != 0) continue;
3876 
3877  u->UpdateViewport(false, false);
3878  }
3879 
3880  if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
3881 
3882  return true;
3883 }
3884 
3890 {
3891  Money cost = 0;
3892  const Train *v = this;
3893 
3894  do {
3895  const Engine *e = v->GetEngine();
3896  if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
3897 
3898  uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
3899  if (cost_factor == 0) continue;
3900 
3901  /* Halve running cost for multiheaded parts */
3902  if (v->IsMultiheaded()) cost_factor /= 2;
3903 
3904  cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
3905  } while ((v = v->GetNextVehicle()) != NULL);
3906 
3907  return cost;
3908 }
3909 
3915 {
3916  this->tick_counter++;
3917 
3918  if (this->IsFrontEngine()) {
3919  if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
3920 
3921  this->current_order_time++;
3922 
3923  if (!TrainLocoHandler(this, false)) return false;
3924 
3925  return TrainLocoHandler(this, true);
3926  } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
3927  /* Delete flooded standalone wagon chain */
3928  if (++this->crash_anim_pos >= 4400) {
3929  delete this;
3930  return false;
3931  }
3932  }
3933 
3934  return true;
3935 }
3936 
3942 {
3943  if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
3944  if (v->IsChainInDepot()) {
3946  return;
3947  }
3948 
3949  uint max_penalty;
3951  case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
3952  case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
3953  default: NOT_REACHED();
3954  }
3955 
3956  FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
3957  /* Only go to the depot if it is not too far out of our way. */
3958  if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
3959  if (v->current_order.IsType(OT_GOTO_DEPOT)) {
3960  /* If we were already heading for a depot but it has
3961  * suddenly moved farther away, we continue our normal
3962  * schedule? */
3963  v->current_order.MakeDummy();
3965  }
3966  return;
3967  }
3968 
3969  DepotID depot = GetDepotIndex(tfdd.tile);
3970 
3971  if (v->current_order.IsType(OT_GOTO_DEPOT) &&
3972  v->current_order.GetDestination() != depot &&
3973  !Chance16(3, 16)) {
3974  return;
3975  }
3976 
3979  v->dest_tile = tfdd.tile;
3981 }
3982 
3985 {
3986  AgeVehicle(this);
3987 
3988  if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
3989 
3990  if (this->IsFrontEngine()) {
3991  CheckVehicleBreakdown(this);
3992 
3994 
3995  CheckOrders(this);
3996 
3997  /* update destination */
3998  if (this->current_order.IsType(OT_GOTO_STATION)) {
3999  TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4000  if (tile != INVALID_TILE) this->dest_tile = tile;
4001  }
4002 
4003  if (this->running_ticks != 0) {
4004  /* running costs */
4006 
4007  this->profit_this_year -= cost.GetCost();
4008  this->running_ticks = 0;
4009 
4010  SubtractMoneyFromCompanyFract(this->owner, cost);
4011 
4014  }
4015  }
4016 }
4017 
4023 {
4024  if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4025 
4026  if (this->track == TRACK_BIT_DEPOT) {
4027  /* We'll assume the train is facing outwards */
4028  return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4029  }
4030 
4031  if (this->track == TRACK_BIT_WORMHOLE) {
4032  /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
4033  return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4034  }
4035 
4036  return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4037 }