OpenTTD
train_cmd.cpp
Go to the documentation of this file.
1 /* $Id: train_cmd.cpp 27580 2016-05-22 11:45:03Z 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 
640  v->build_year = _cur_year;
641  v->cur_image = SPR_IMG_QUERY;
643 
644  v->group_id = DEFAULT_GROUP;
645 
647 
648  _new_vehicle_id = v->index;
649 
650  v->UpdatePosition();
653 
655 
656  /* Try to connect the vehicle to one of free chains of wagons. */
657  Train *w;
658  FOR_ALL_TRAINS(w) {
659  if (w->tile == tile &&
660  w->IsFreeWagon() &&
661  w->engine_type == e->index &&
662  w->First() != v &&
663  !(w->vehstatus & VS_CRASHED)) {
664  DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
665  break;
666  }
667  }
668  }
669 
670  return CommandCost();
671 }
672 
674 static void NormalizeTrainVehInDepot(const Train *u)
675 {
676  const Train *v;
677  FOR_ALL_TRAINS(v) {
678  if (v->IsFreeWagon() && v->tile == u->tile &&
679  v->track == TRACK_BIT_DEPOT) {
680  if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
682  break;
683  }
684  }
685 }
686 
687 static void AddRearEngineToMultiheadedTrain(Train *v)
688 {
689  Train *u = new Train();
690  v->value >>= 1;
691  u->value = v->value;
692  u->direction = v->direction;
693  u->owner = v->owner;
694  u->tile = v->tile;
695  u->x_pos = v->x_pos;
696  u->y_pos = v->y_pos;
697  u->z_pos = v->z_pos;
698  u->track = TRACK_BIT_DEPOT;
699  u->vehstatus = v->vehstatus & ~VS_STOPPED;
700  u->spritenum = v->spritenum + 1;
701  u->cargo_type = v->cargo_type;
703  u->cargo_cap = v->cargo_cap;
704  u->refit_cap = v->refit_cap;
705  u->railtype = v->railtype;
706  u->engine_type = v->engine_type;
708  u->build_year = v->build_year;
709  u->cur_image = SPR_IMG_QUERY;
711  v->SetMultiheaded();
712  u->SetMultiheaded();
713  v->SetNext(u);
714  u->UpdatePosition();
715 
716  /* Now we need to link the front and rear engines together */
717  v->other_multiheaded_part = u;
718  u->other_multiheaded_part = v;
719 }
720 
731 {
732  const RailVehicleInfo *rvi = &e->u.rail;
733 
734  if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
735 
736  /* Check if depot and new engine uses the same kind of tracks *
737  * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
738  if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
739 
740  if (flags & DC_EXEC) {
742  int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
743  int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
744 
745  Train *v = new Train();
746  *ret = v;
747  v->direction = DiagDirToDir(dir);
748  v->tile = tile;
749  v->owner = _current_company;
750  v->x_pos = x;
751  v->y_pos = y;
752  v->z_pos = GetSlopePixelZ(x, y);
753  v->track = TRACK_BIT_DEPOT;
755  v->spritenum = rvi->image_index;
757  v->cargo_cap = rvi->capacity;
758  v->refit_cap = 0;
759  v->last_station_visited = INVALID_STATION;
760  v->last_loading_station = INVALID_STATION;
761 
762  v->engine_type = e->index;
763  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
764 
765  v->reliability = e->reliability;
767  v->max_age = e->GetLifeLengthInDays();
768 
769  v->railtype = rvi->railtype;
770  _new_vehicle_id = v->index;
771 
772  v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
774  v->build_year = _cur_year;
775  v->cur_image = SPR_IMG_QUERY;
777 
779  v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
780 
781  v->group_id = DEFAULT_GROUP;
782 
783  v->SetFrontEngine();
784  v->SetEngine();
785 
786  v->UpdatePosition();
787 
788  if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
789  AddRearEngineToMultiheadedTrain(v);
790  } else {
792  }
793 
796 
797  if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
799  }
800 
802  }
803 
804  return CommandCost();
805 }
806 
807 static Train *FindGoodVehiclePos(const Train *src)
808 {
809  EngineID eng = src->engine_type;
810  TileIndex tile = src->tile;
811 
812  Train *dst;
813  FOR_ALL_TRAINS(dst) {
814  if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
815  /* check so all vehicles in the line have the same engine. */
816  Train *t = dst;
817  while (t->engine_type == eng) {
818  t = t->Next();
819  if (t == NULL) return dst;
820  }
821  }
822  }
823 
824  return NULL;
825 }
826 
829 
835 static void MakeTrainBackup(TrainList &list, Train *t)
836 {
837  for (; t != NULL; t = t->Next()) *list.Append() = t;
838 }
839 
844 static void RestoreTrainBackup(TrainList &list)
845 {
846  /* No train, nothing to do. */
847  if (list.Length() == 0) return;
848 
849  Train *prev = NULL;
850  /* Iterate over the list and rebuild it. */
851  for (Train **iter = list.Begin(); iter != list.End(); iter++) {
852  Train *t = *iter;
853  if (prev != NULL) {
854  prev->SetNext(t);
855  } else if (t->Previous() != NULL) {
856  /* Make sure the head of the train is always the first in the chain. */
857  t->Previous()->SetNext(NULL);
858  }
859  prev = t;
860  }
861 }
862 
868 static void RemoveFromConsist(Train *part, bool chain = false)
869 {
870  Train *tail = chain ? part->Last() : part->GetLastEnginePart();
871 
872  /* Unlink at the front, but make it point to the next
873  * vehicle after the to be remove part. */
874  if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
875 
876  /* Unlink at the back */
877  tail->SetNext(NULL);
878 }
879 
885 static void InsertInConsist(Train *dst, Train *chain)
886 {
887  /* We do not want to add something in the middle of an articulated part. */
888  assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
889 
890  chain->Last()->SetNext(dst->Next());
891  dst->SetNext(chain);
892 }
893 
899 static void NormaliseDualHeads(Train *t)
900 {
901  for (; t != NULL; t = t->GetNextVehicle()) {
902  if (!t->IsMultiheaded() || !t->IsEngine()) continue;
903 
904  /* Make sure that there are no free cars before next engine */
905  Train *u;
906  for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
907 
908  if (u == t->other_multiheaded_part) continue;
909 
910  /* Remove the part from the 'wrong' train */
911  RemoveFromConsist(t->other_multiheaded_part);
912  /* And add it to the 'right' train */
913  InsertInConsist(u, t->other_multiheaded_part);
914  }
915 }
916 
921 static void NormaliseSubtypes(Train *chain)
922 {
923  /* Nothing to do */
924  if (chain == NULL) return;
925 
926  /* We must be the first in the chain. */
927  assert(chain->Previous() == NULL);
928 
929  /* Set the appropriate bits for the first in the chain. */
930  if (chain->IsWagon()) {
931  chain->SetFreeWagon();
932  } else {
933  assert(chain->IsEngine());
934  chain->SetFrontEngine();
935  }
936 
937  /* Now clear the bits for the rest of the chain */
938  for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
939  t->ClearFreeWagon();
940  t->ClearFrontEngine();
941  }
942 }
943 
953 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
954 {
955  /* Just add 'new' engines and subtract the original ones.
956  * If that's less than or equal to 0 we can be sure we did
957  * not add any engines (read: trains) along the way. */
958  if ((src != NULL && src->IsEngine() ? 1 : 0) +
959  (dst != NULL && dst->IsEngine() ? 1 : 0) -
960  (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
961  (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
962  return CommandCost();
963  }
964 
965  /* Get a free unit number and check whether it's within the bounds.
966  * There will always be a maximum of one new train. */
968 
969  return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
970 }
971 
978 {
979  /* No multi-part train, no need to check. */
980  if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
981 
982  /* The maximum length for a train. For each part we decrease this by one
983  * and if the result is negative the train is simply too long. */
985 
986  Train *head = t;
987  Train *prev = t;
988 
989  /* Break the prev -> t link so it always holds within the loop. */
990  t = t->Next();
991  prev->SetNext(NULL);
992 
993  /* Make sure the cache is cleared. */
994  head->InvalidateNewGRFCache();
995 
996  while (t != NULL) {
997  allowed_len -= t->gcache.cached_veh_length;
998 
999  Train *next = t->Next();
1000 
1001  /* Unlink the to-be-added piece; it is already unlinked from the previous
1002  * part due to the fact that the prev -> t link is broken. */
1003  t->SetNext(NULL);
1004 
1005  /* Don't check callback for articulated or rear dual headed parts */
1006  if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1007  /* Back up and clear the first_engine data to avoid using wagon override group */
1008  EngineID first_engine = t->gcache.first_engine;
1010 
1011  /* We don't want the cache to interfere. head's cache is cleared before
1012  * the loop and after each callback does not need to be cleared here. */
1013  t->InvalidateNewGRFCache();
1014 
1015  uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1016 
1017  /* Restore original first_engine data */
1018  t->gcache.first_engine = first_engine;
1019 
1020  /* We do not want to remember any cached variables from the test run */
1021  t->InvalidateNewGRFCache();
1022  head->InvalidateNewGRFCache();
1023 
1024  if (callback != CALLBACK_FAILED) {
1025  /* A failing callback means everything is okay */
1026  StringID error = STR_NULL;
1027 
1028  if (head->GetGRF()->grf_version < 8) {
1029  if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1030  if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1031  if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1032  } else {
1033  if (callback < 0x400) {
1034  error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1035  } else {
1036  switch (callback) {
1037  case 0x400: // allow if railtypes match (always the case for OpenTTD)
1038  case 0x401: // allow
1039  break;
1040 
1041  default: // unknown reason -> disallow
1042  case 0x402: // disallow attaching
1043  error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1044  break;
1045  }
1046  }
1047  }
1048 
1049  if (error != STR_NULL) return_cmd_error(error);
1050  }
1051  }
1052 
1053  /* And link it to the new part. */
1054  prev->SetNext(t);
1055  prev = t;
1056  t = next;
1057  }
1058 
1059  if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1060  return CommandCost();
1061 }
1062 
1073 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1074 {
1075  /* Check whether we may actually construct the trains. */
1076  CommandCost ret = CheckTrainAttachment(src);
1077  if (ret.Failed()) return ret;
1078  ret = CheckTrainAttachment(dst);
1079  if (ret.Failed()) return ret;
1080 
1081  /* Check whether we need to build a new train. */
1082  return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1083 }
1084 
1093 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1094 {
1095  /* First determine the front of the two resulting trains */
1096  if (*src_head == *dst_head) {
1097  /* If we aren't moving part(s) to a new train, we are just moving the
1098  * front back and there is not destination head. */
1099  *dst_head = NULL;
1100  } else if (*dst_head == NULL) {
1101  /* If we are moving to a new train the head of the move train would become
1102  * the head of the new vehicle. */
1103  *dst_head = src;
1104  }
1105 
1106  if (src == *src_head) {
1107  /* If we are moving the front of a train then we are, in effect, creating
1108  * a new head for the train. Point to that. Unless we are moving the whole
1109  * train in which case there is not 'source' train anymore.
1110  * In case we are a multiheaded part we want the complete thing to come
1111  * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1112  * that is followed by a rear multihead we do not want to include that. */
1113  *src_head = move_chain ? NULL :
1114  (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1115  }
1116 
1117  /* Now it's just simply removing the part that we are going to move from the
1118  * source train and *if* the destination is a not a new train add the chain
1119  * at the destination location. */
1120  RemoveFromConsist(src, move_chain);
1121  if (*dst_head != src) InsertInConsist(dst, src);
1122 
1123  /* Now normalise the dual heads, that is move the dual heads around in such
1124  * a way that the head and rear of a dual head are in the same train */
1125  NormaliseDualHeads(*src_head);
1126  NormaliseDualHeads(*dst_head);
1127 }
1128 
1134 static void NormaliseTrainHead(Train *head)
1135 {
1136  /* Not much to do! */
1137  if (head == NULL) return;
1138 
1139  /* Tell the 'world' the train changed. */
1140  head->ConsistChanged(CCF_ARRANGE);
1141  UpdateTrainGroupID(head);
1142 
1143  /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1144  if (!head->IsFrontEngine()) return;
1145 
1146  /* Update the refit button and window */
1149 
1150  /* If we don't have a unit number yet, set one. */
1151  if (head->unitnumber != 0) return;
1153 }
1154 
1167 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1168 {
1169  VehicleID s = GB(p1, 0, 20);
1170  VehicleID d = GB(p2, 0, 20);
1171  bool move_chain = HasBit(p1, 20);
1172 
1173  Train *src = Train::GetIfValid(s);
1174  if (src == NULL) return CMD_ERROR;
1175 
1176  CommandCost ret = CheckOwnership(src->owner);
1177  if (ret.Failed()) return ret;
1178 
1179  /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1180  if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1181 
1182  /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1183  Train *dst;
1184  if (d == INVALID_VEHICLE) {
1185  dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1186  } else {
1187  dst = Train::GetIfValid(d);
1188  if (dst == NULL) return CMD_ERROR;
1189 
1190  CommandCost ret = CheckOwnership(dst->owner);
1191  if (ret.Failed()) return ret;
1192 
1193  /* Do not allow appending to crashed vehicles, too */
1194  if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1195  }
1196 
1197  /* if an articulated part is being handled, deal with its parent vehicle */
1198  src = src->GetFirstEnginePart();
1199  if (dst != NULL) {
1200  dst = dst->GetFirstEnginePart();
1201  }
1202 
1203  /* don't move the same vehicle.. */
1204  if (src == dst) return CommandCost();
1205 
1206  /* locate the head of the two chains */
1207  Train *src_head = src->First();
1208  Train *dst_head;
1209  if (dst != NULL) {
1210  dst_head = dst->First();
1211  if (dst_head->tile != src_head->tile) return CMD_ERROR;
1212  /* Now deal with articulated part of destination wagon */
1213  dst = dst->GetLastEnginePart();
1214  } else {
1215  dst_head = NULL;
1216  }
1217 
1218  if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1219 
1220  /* When moving all wagons, we can't have the same src_head and dst_head */
1221  if (move_chain && src_head == dst_head) return CommandCost();
1222 
1223  /* When moving a multiheaded part to be place after itself, bail out. */
1224  if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1225 
1226  /* Check if all vehicles in the source train are stopped inside a depot. */
1227  if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1228 
1229  /* Check if all vehicles in the destination train are stopped inside a depot. */
1230  if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1231 
1232  /* First make a backup of the order of the trains. That way we can do
1233  * whatever we want with the order and later on easily revert. */
1234  TrainList original_src;
1235  TrainList original_dst;
1236 
1237  MakeTrainBackup(original_src, src_head);
1238  MakeTrainBackup(original_dst, dst_head);
1239 
1240  /* Also make backup of the original heads as ArrangeTrains can change them.
1241  * For the destination head we do not care if it is the same as the source
1242  * head because in that case it's just a copy. */
1243  Train *original_src_head = src_head;
1244  Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1245 
1246  /* We want this information from before the rearrangement, but execute this after the validation.
1247  * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
1248  * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
1249  bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1250  bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
1251 
1252  /* (Re)arrange the trains in the wanted arrangement. */
1253  ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1254 
1255  if ((flags & DC_AUTOREPLACE) == 0) {
1256  /* If the autoreplace flag is set we do not need to test for the validity
1257  * because we are going to revert the train to its original state. As we
1258  * assume the original state was correct autoreplace can skip this. */
1259  CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1260  if (ret.Failed()) {
1261  /* Restore the train we had. */
1262  RestoreTrainBackup(original_src);
1263  RestoreTrainBackup(original_dst);
1264  return ret;
1265  }
1266  }
1267 
1268  /* do it? */
1269  if (flags & DC_EXEC) {
1270  /* Remove old heads from the statistics */
1271  if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1272  if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1273 
1274  /* First normalise the sub types of the chains. */
1275  NormaliseSubtypes(src_head);
1276  NormaliseSubtypes(dst_head);
1277 
1278  /* There are 14 different cases:
1279  * 1) front engine gets moved to a new train, it stays a front engine.
1280  * a) the 'next' part is a wagon that becomes a free wagon chain.
1281  * b) the 'next' part is an engine that becomes a front engine.
1282  * c) there is no 'next' part, nothing else happens
1283  * 2) front engine gets moved to another train, it is not a front engine anymore
1284  * a) the 'next' part is a wagon that becomes a free wagon chain.
1285  * b) the 'next' part is an engine that becomes a front engine.
1286  * c) there is no 'next' part, nothing else happens
1287  * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1288  * a) the 'next' part is a wagon that becomes a free wagon chain.
1289  * b) the 'next' part is an engine that becomes a front engine.
1290  * 4) free wagon gets moved
1291  * a) the 'next' part is a wagon that becomes a free wagon chain.
1292  * b) the 'next' part is an engine that becomes a front engine.
1293  * c) there is no 'next' part, nothing else happens
1294  * 5) non front engine gets moved and becomes a new train, nothing else happens
1295  * 6) non front engine gets moved within a train / to another train, nothing hapens
1296  * 7) wagon gets moved, nothing happens
1297  */
1298  if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1299  /* Cases #2 and #3: the front engine gets trashed. */
1305  DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1307 
1308  /* Delete orders, group stuff and the unit number as we're not the
1309  * front of any vehicle anymore. */
1310  DeleteVehicleOrders(src);
1312  src->unitnumber = 0;
1313  }
1314 
1315  /* We weren't a front engine but are becoming one. So
1316  * we should be put in the default group. */
1317  if (original_src_head != src && dst_head == src) {
1320  }
1321 
1322  /* Add new heads to statistics */
1323  if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1324  if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1325 
1326  /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1327  NormaliseTrainHead(src_head);
1328  NormaliseTrainHead(dst_head);
1329 
1330  if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1331  CheckCargoCapacity(src_head);
1332  CheckCargoCapacity(dst_head);
1333  }
1334 
1335  if (src_head != NULL) src_head->First()->MarkDirty();
1336  if (dst_head != NULL) dst_head->First()->MarkDirty();
1337 
1338  /* We are undoubtedly changing something in the depot and train list. */
1341  } else {
1342  /* We don't want to execute what we're just tried. */
1343  RestoreTrainBackup(original_src);
1344  RestoreTrainBackup(original_dst);
1345  }
1346 
1347  return CommandCost();
1348 }
1349 
1361 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1362 {
1363  /* Sell a chain of vehicles or not? */
1364  bool sell_chain = HasBit(data, 0);
1365 
1367  Train *first = v->First();
1368 
1369  if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1370 
1371  /* First make a backup of the order of the train. That way we can do
1372  * whatever we want with the order and later on easily revert. */
1373  TrainList original;
1374  MakeTrainBackup(original, first);
1375 
1376  /* We need to keep track of the new head and the head of what we're going to sell. */
1377  Train *new_head = first;
1378  Train *sell_head = NULL;
1379 
1380  /* Split the train in the wanted way. */
1381  ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1382 
1383  /* We don't need to validate the second train; it's going to be sold. */
1384  CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1385  if (ret.Failed()) {
1386  /* Restore the train we had. */
1387  RestoreTrainBackup(original);
1388  return ret;
1389  }
1390 
1391  if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
1392  /* Restore the train we had. */
1393  RestoreTrainBackup(original);
1394  return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1395  }
1396 
1398  for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1399 
1400  /* do it? */
1401  if (flags & DC_EXEC) {
1402  /* First normalise the sub types of the chain. */
1403  NormaliseSubtypes(new_head);
1404 
1405  if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1406  /* We are selling the front engine. In this case we want to
1407  * 'give' the order, unit number and such to the new head. */
1408  new_head->orders.list = first->orders.list;
1409  new_head->AddToShared(first);
1410  DeleteVehicleOrders(first);
1411 
1412  /* Copy other important data from the front engine */
1413  new_head->CopyVehicleConfigAndStatistics(first);
1414  GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1415  } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1416  OrderBackup::Backup(v, user);
1417  }
1418 
1419  /* We need to update the information about the train. */
1420  NormaliseTrainHead(new_head);
1421 
1422  /* We are undoubtedly changing something in the depot and train list. */
1425 
1426  /* Actually delete the sold 'goods' */
1427  delete sell_head;
1428  } else {
1429  /* We don't want to execute what we're just tried. */
1430  RestoreTrainBackup(original);
1431  }
1432 
1433  return cost;
1434 }
1435 
1437 {
1438  /* Set common defaults. */
1439  this->x_offs = -1;
1440  this->y_offs = -1;
1441  this->x_extent = 3;
1442  this->y_extent = 3;
1443  this->z_extent = 6;
1444  this->x_bb_offs = 0;
1445  this->y_bb_offs = 0;
1446 
1447  if (!IsDiagonalDirection(direction)) {
1448  static const int _sign_table[] =
1449  {
1450  /* x, y */
1451  -1, -1, // DIR_N
1452  -1, 1, // DIR_E
1453  1, 1, // DIR_S
1454  1, -1, // DIR_W
1455  };
1456 
1457  int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1458 
1459  /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1460  this->x_offs -= half_shorten * _sign_table[direction];
1461  this->y_offs -= half_shorten * _sign_table[direction + 1];
1462  this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1463  this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1464  } else {
1465  switch (direction) {
1466  /* Shorten southern corner of the bounding box according the vehicle length
1467  * and center the bounding box on the vehicle. */
1468  case DIR_NE:
1469  this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1470  this->x_extent = this->gcache.cached_veh_length - 1;
1471  this->x_bb_offs = -1;
1472  break;
1473 
1474  case DIR_NW:
1475  this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1476  this->y_extent = this->gcache.cached_veh_length - 1;
1477  this->y_bb_offs = -1;
1478  break;
1479 
1480  /* Move northern corner of the bounding box down according to vehicle length
1481  * and center the bounding box on the vehicle. */
1482  case DIR_SW:
1483  this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1484  this->x_extent = VEHICLE_LENGTH - 1;
1485  this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1486  break;
1487 
1488  case DIR_SE:
1489  this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1490  this->y_extent = VEHICLE_LENGTH - 1;
1491  this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1492  break;
1493 
1494  default:
1495  NOT_REACHED();
1496  }
1497  }
1498 }
1499 
1504 static void MarkTrainAsStuck(Train *v)
1505 {
1506  if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1507  /* It is the first time the problem occurred, set the "train stuck" flag. */
1508  SetBit(v->flags, VRF_TRAIN_STUCK);
1509 
1510  v->wait_counter = 0;
1511 
1512  /* Stop train */
1513  v->cur_speed = 0;
1514  v->subspeed = 0;
1515  v->SetLastSpeed();
1516 
1518  }
1519 }
1520 
1528 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1529 {
1530  uint16 flag1 = *swap_flag1;
1531  uint16 flag2 = *swap_flag2;
1532 
1533  /* Clear the flags */
1534  ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1535  ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1536  ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1537  ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1538 
1539  /* Reverse the rail-flags (if needed) */
1540  if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1541  SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1542  } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1543  SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1544  }
1545  if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1546  SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1547  } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1548  SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1549  }
1550 }
1551 
1557 {
1558  /* Reverse the direction. */
1559  if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1560 
1561  /* Call the proper EnterTile function unless we are in a wormhole. */
1562  if (v->track != TRACK_BIT_WORMHOLE) {
1563  VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1564  } else {
1565  /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1566  * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1567  * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1568  * when we shouldn't have. Check if this is the case. */
1569  TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1570  if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1571  VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1572  if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1573  /* We have just left the wormhole, possibly set the
1574  * "goingdown" bit. UpdateInclination() can be used
1575  * because we are at the border of the tile. */
1576  v->UpdatePosition();
1577  v->UpdateInclination(true, true);
1578  return;
1579  }
1580  }
1581  }
1582 
1583  v->UpdatePosition();
1584  v->UpdateViewport(true, true);
1585 }
1586 
1593 void ReverseTrainSwapVeh(Train *v, int l, int r)
1594 {
1595  Train *a, *b;
1596 
1597  /* locate vehicles to swap */
1598  for (a = v; l != 0; l--) a = a->Next();
1599  for (b = v; r != 0; r--) b = b->Next();
1600 
1601  if (a != b) {
1602  /* swap the hidden bits */
1603  {
1604  uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1605  b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1606  a->vehstatus = tmp;
1607  }
1608 
1609  Swap(a->track, b->track);
1610  Swap(a->direction, b->direction);
1611  Swap(a->x_pos, b->x_pos);
1612  Swap(a->y_pos, b->y_pos);
1613  Swap(a->tile, b->tile);
1614  Swap(a->z_pos, b->z_pos);
1615 
1616  SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1617 
1620  } else {
1621  /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1622  * This is a little bit redundant way, a->gv_flags will
1623  * be (re)set twice, but it reduces code duplication */
1624  SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1626  }
1627 }
1628 
1629 
1635 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1636 {
1637  return (v->type == VEH_TRAIN) ? v : NULL;
1638 }
1639 
1640 
1648 {
1649  if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
1650 
1651  Train *t = Train::From(v);
1652  if (!t->IsFrontEngine()) return NULL;
1653 
1654  TileIndex tile = *(TileIndex *)data;
1655 
1656  if (TrainApproachingCrossingTile(t) != tile) return NULL;
1657 
1658  return t;
1659 }
1660 
1661 
1669 {
1670  assert(IsLevelCrossingTile(tile));
1671 
1673  TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1674 
1675  if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1676 
1677  dir = ReverseDiagDir(dir);
1678  tile_from = tile + TileOffsByDiagDir(dir);
1679 
1680  return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1681 }
1682 
1683 
1690 void UpdateLevelCrossing(TileIndex tile, bool sound)
1691 {
1692  assert(IsLevelCrossingTile(tile));
1693 
1694  /* train on crossing || train approaching crossing || reserved */
1695  bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
1696 
1697  if (new_state != IsCrossingBarred(tile)) {
1698  if (new_state && sound) {
1699  if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1700  }
1701  SetCrossingBarred(tile, new_state);
1702  MarkTileDirtyByTile(tile);
1703  }
1704 }
1705 
1706 
1712 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1713 {
1714  if (!IsCrossingBarred(tile)) {
1715  BarCrossing(tile);
1716  if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1717  MarkTileDirtyByTile(tile);
1718  }
1719 }
1720 
1721 
1728 {
1729  Train *base = v;
1730  Train *first = base; // first vehicle to move
1731  Train *last = v->Last(); // last vehicle to move
1732  uint length = CountVehiclesInChain(v);
1733 
1734  while (length > 2) {
1735  last = last->Previous();
1736  first = first->Next();
1737 
1738  int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1739 
1740  /* do not update images now
1741  * negative differential will be handled in AdvanceWagonsAfterSwap() */
1742  for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1743 
1744  base = first; // == base->Next()
1745  length -= 2;
1746  }
1747 }
1748 
1749 
1756 {
1757  /* first of all, fix the situation when the train was entering a depot */
1758  Train *dep = v; // last vehicle in front of just left depot
1759  while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1760  dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1761  }
1762 
1763  Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1764 
1765  if (leave != NULL) {
1766  /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1767  int d = TicksToLeaveDepot(dep);
1768 
1769  if (d <= 0) {
1770  leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1771  leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1772  for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1773  }
1774  } else {
1775  dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1776  }
1777 
1778  Train *base = v;
1779  Train *first = base; // first vehicle to move
1780  Train *last = v->Last(); // last vehicle to move
1781  uint length = CountVehiclesInChain(v);
1782 
1783  /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1784  * they have already correct spacing, so we have to make sure they are moved how they should */
1785  bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1786 
1787  while (length > 2) {
1788  /* we reached vehicle (originally) in front of a depot, stop now
1789  * (we would move wagons that are already moved with new wagon length). */
1790  if (base == dep) break;
1791 
1792  /* the last wagon was that one leaving a depot, so do not move it anymore */
1793  if (last == dep) nomove = true;
1794 
1795  last = last->Previous();
1796  first = first->Next();
1797 
1798  int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1799 
1800  /* do not update images now */
1801  for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1802 
1803  base = first; // == base->Next()
1804  length -= 2;
1805  }
1806 }
1807 
1813 {
1814  if (IsRailDepotTile(v->tile)) {
1816  }
1817 
1818  /* Clear path reservation in front if train is not stuck. */
1819  if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1820 
1821  /* Check if we were approaching a rail/road-crossing */
1823 
1824  /* count number of vehicles */
1825  int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1826 
1828 
1829  /* swap start<>end, start+1<>end-1, ... */
1830  int l = 0;
1831  do {
1832  ReverseTrainSwapVeh(v, l++, r--);
1833  } while (l <= r);
1834 
1836 
1837  if (IsRailDepotTile(v->tile)) {
1839  }
1840 
1841  ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1842 
1843  ClrBit(v->flags, VRF_REVERSING);
1844 
1845  /* recalculate cached data */
1847 
1848  /* update all images */
1849  for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
1850 
1851  /* update crossing we were approaching */
1852  if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1853 
1854  /* maybe we are approaching crossing now, after reversal */
1855  crossing = TrainApproachingCrossingTile(v);
1856  if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1857 
1858  /* If we are inside a depot after reversing, don't bother with path reserving. */
1859  if (v->track == TRACK_BIT_DEPOT) {
1860  /* Can't be stuck here as inside a depot is always a safe tile. */
1862  ClrBit(v->flags, VRF_TRAIN_STUCK);
1863  return;
1864  }
1865 
1866  /* TrainExitDir does not always produce the desired dir for depots and
1867  * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
1868  DiagDirection dir = TrainExitDir(v->direction, v->track);
1870 
1872  /* If we are currently on a tile with conventional signals, we can't treat the
1873  * current tile as a safe tile or we would enter a PBS block without a reservation. */
1874  bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
1876  !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
1877 
1878  /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1879  if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
1880 
1882  if (TryPathReserve(v, false, first_tile_okay)) {
1883  /* Do a look-ahead now in case our current tile was already a safe tile. */
1884  CheckNextTrainTile(v);
1885  } else if (v->current_order.GetType() != OT_LOADING) {
1886  /* Do not wait for a way out when we're still loading */
1887  MarkTrainAsStuck(v);
1888  }
1889  } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1890  /* A train not inside a PBS block can't be stuck. */
1891  ClrBit(v->flags, VRF_TRAIN_STUCK);
1892  v->wait_counter = 0;
1893  }
1894 }
1895 
1905 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1906 {
1907  Train *v = Train::GetIfValid(p1);
1908  if (v == NULL) return CMD_ERROR;
1909 
1910  CommandCost ret = CheckOwnership(v->owner);
1911  if (ret.Failed()) return ret;
1912 
1913  if (p2 != 0) {
1914  /* turn a single unit around */
1915 
1916  if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1917  return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1918  }
1919  if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1920 
1921  Train *front = v->First();
1922  /* make sure the vehicle is stopped in the depot */
1923  if (!front->IsStoppedInDepot()) {
1924  return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1925  }
1926 
1927  if (flags & DC_EXEC) {
1928  ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1929 
1930  front->ConsistChanged(CCF_ARRANGE);
1935  }
1936  } else {
1937  /* turn the whole train around */
1938  if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
1939 
1940  if (flags & DC_EXEC) {
1941  /* Properly leave the station if we are loading and won't be loading anymore */
1942  if (v->current_order.IsType(OT_LOADING)) {
1943  const Vehicle *last = v;
1944  while (last->Next() != NULL) last = last->Next();
1945 
1946  /* not a station || different station --> leave the station */
1947  if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
1948  v->LeaveStation();
1949  }
1950  }
1951 
1952  /* We cancel any 'skip signal at dangers' here */
1953  v->force_proceed = TFP_NONE;
1955 
1956  if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
1957  ToggleBit(v->flags, VRF_REVERSING);
1958  } else {
1959  v->cur_speed = 0;
1960  v->SetLastSpeed();
1963  }
1964  }
1965  }
1966  return CommandCost();
1967 }
1968 
1978 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1979 {
1980  Train *t = Train::GetIfValid(p1);
1981  if (t == NULL) return CMD_ERROR;
1982 
1983  if (!t->IsPrimaryVehicle()) return CMD_ERROR;
1984 
1985  CommandCost ret = CheckOwnership(t->owner);
1986  if (ret.Failed()) return ret;
1987 
1988 
1989  if (flags & DC_EXEC) {
1990  /* If we are forced to proceed, cancel that order.
1991  * If we are marked stuck we would want to force the train
1992  * to proceed to the next signal. In the other cases we
1993  * would like to pass the signal at danger and run till the
1994  * next signal we encounter. */
1995  t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
1997  }
1998 
1999  return CommandCost();
2000 }
2001 
2009 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2010 {
2011  assert(!(v->vehstatus & VS_CRASHED));
2012 
2013  if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2014 
2015  PBSTileInfo origin = FollowTrainReservation(v);
2016  if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2017 
2019  case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2020  case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2021 
2022  default: NOT_REACHED();
2023  }
2024 }
2025 
2033 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2034 {
2035  FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2036  if (tfdd.best_length == UINT_MAX) return false;
2037 
2038  if (location != NULL) *location = tfdd.tile;
2039  if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2040  if (reverse != NULL) *reverse = tfdd.reverse;
2041 
2042  return true;
2043 }
2044 
2047 {
2048  static const SoundFx sfx[] = {
2049  SND_04_TRAIN,
2050  SND_0A_TRAIN_HORN,
2051  SND_0A_TRAIN_HORN,
2052  SND_47_MAGLEV_2,
2053  SND_41_MAGLEV
2054  };
2055 
2056  if (PlayVehicleSound(this, VSE_START)) return;
2057 
2058  EngineID engtype = this->engine_type;
2059  SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2060 }
2061 
2066 static void CheckNextTrainTile(Train *v)
2067 {
2068  /* Don't do any look-ahead if path_backoff_interval is 255. */
2069  if (_settings_game.pf.path_backoff_interval == 255) return;
2070 
2071  /* Exit if we are inside a depot. */
2072  if (v->track == TRACK_BIT_DEPOT) return;
2073 
2074  switch (v->current_order.GetType()) {
2075  /* Exit if we reached our destination depot. */
2076  case OT_GOTO_DEPOT:
2077  if (v->tile == v->dest_tile) return;
2078  break;
2079 
2080  case OT_GOTO_WAYPOINT:
2081  /* If we reached our waypoint, make sure we see that. */
2083  break;
2084 
2085  case OT_NOTHING:
2086  case OT_LEAVESTATION:
2087  case OT_LOADING:
2088  /* Exit if the current order doesn't have a destination, but the train has orders. */
2089  if (v->GetNumOrders() > 0) return;
2090  break;
2091 
2092  default:
2093  break;
2094  }
2095  /* Exit if we are on a station tile and are going to stop. */
2097 
2098  Trackdir td = v->GetVehicleTrackdir();
2099 
2100  /* On a tile with a red non-pbs signal, don't look ahead. */
2101  if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2102  !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2103  GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2104 
2105  CFollowTrackRail ft(v);
2106  if (!ft.Follow(v->tile, td)) return;
2107 
2109  /* Next tile is not reserved. */
2112  /* If the next tile is a PBS signal, try to make a reservation. */
2116  }
2117  ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
2118  }
2119  }
2120  }
2121 }
2122 
2129 {
2130  /* bail out if not all wagons are in the same depot or not in a depot at all */
2131  for (const Train *u = v; u != NULL; u = u->Next()) {
2132  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2133  }
2134 
2135  /* if the train got no power, then keep it in the depot */
2136  if (v->gcache.cached_power == 0) {
2137  v->vehstatus |= VS_STOPPED;
2139  return true;
2140  }
2141 
2142  SigSegState seg_state;
2143 
2144  if (v->force_proceed == TFP_NONE) {
2145  /* force proceed was not pressed */
2146  if (++v->wait_counter < 37) {
2148  return true;
2149  }
2150 
2151  v->wait_counter = 0;
2152 
2154  if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2155  /* Full and no PBS signal in block or depot reserved, can't exit. */
2157  return true;
2158  }
2159  } else {
2161  }
2162 
2163  /* We are leaving a depot, but have to go to the exact same one; re-enter */
2164  if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2165  /* We need to have a reservation for this to work. */
2166  if (HasDepotReservation(v->tile)) return true;
2167  SetDepotReservation(v->tile, true);
2168  VehicleEnterDepot(v);
2169  return true;
2170  }
2171 
2172  /* Only leave when we can reserve a path to our destination. */
2173  if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2174  /* No path and no force proceed. */
2176  MarkTrainAsStuck(v);
2177  return true;
2178  }
2179 
2180  SetDepotReservation(v->tile, true);
2182 
2185  v->PlayLeaveStationSound();
2186 
2187  v->track = TRACK_BIT_X;
2188  if (v->direction & 2) v->track = TRACK_BIT_Y;
2189 
2190  v->vehstatus &= ~VS_HIDDEN;
2191  v->cur_speed = 0;
2192 
2193  v->UpdateViewport(true, true);
2194  v->UpdatePosition();
2196  v->UpdateAcceleration();
2198 
2199  return false;
2200 }
2201 
2208 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2209 {
2210  DiagDirection dir = TrackdirToExitdir(track_dir);
2211 
2212  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2213  /* Are we just leaving a tunnel/bridge? */
2214  if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2215  TileIndex end = GetOtherTunnelBridgeEnd(tile);
2216 
2217  if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2218  /* Free the reservation only if no other train is on the tiles. */
2219  SetTunnelBridgeReservation(tile, false);
2220  SetTunnelBridgeReservation(end, false);
2221 
2223  if (IsBridge(tile)) {
2224  MarkBridgeDirty(tile);
2225  } else {
2226  MarkTileDirtyByTile(tile);
2227  MarkTileDirtyByTile(end);
2228  }
2229  }
2230  }
2231  }
2232  } else if (IsRailStationTile(tile)) {
2233  TileIndex new_tile = TileAddByDiagDir(tile, dir);
2234  /* If the new tile is not a further tile of the same station, we
2235  * clear the reservation for the whole platform. */
2236  if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2238  }
2239  } else {
2240  /* Any other tile */
2241  UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2242  }
2243 }
2244 
2251 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
2252 {
2253  assert(v->IsFrontEngine());
2254 
2255  TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
2256  Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
2257  bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2258  StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2259 
2260  /* Can't be holding a reservation if we enter a depot. */
2261  if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2262  if (v->track == TRACK_BIT_DEPOT) {
2263  /* Front engine is in a depot. We enter if some part is not in the depot. */
2264  for (const Train *u = v; u != NULL; u = u->Next()) {
2265  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2266  }
2267  }
2268  /* Don't free reservation if it's not ours. */
2270 
2272  while (ft.Follow(tile, td)) {
2273  tile = ft.m_new_tile;
2275  td = RemoveFirstTrackdir(&bits);
2276  assert(bits == TRACKDIR_BIT_NONE);
2277 
2278  if (!IsValidTrackdir(td)) break;
2279 
2280  if (IsTileType(tile, MP_RAILWAY)) {
2281  if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2282  /* Conventional signal along trackdir: remove reservation and stop. */
2284  break;
2285  }
2286  if (HasPbsSignalOnTrackdir(tile, td)) {
2287  if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2288  /* Red PBS signal? Can't be our reservation, would be green then. */
2289  break;
2290  } else {
2291  /* Turn the signal back to red. */
2293  MarkTileDirtyByTile(tile);
2294  }
2295  } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2296  break;
2297  }
2298  }
2299 
2300  /* Don't free first station/bridge/tunnel if we are on it. */
2301  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);
2302 
2303  free_tile = true;
2304  }
2305 }
2306 
2307 static const byte _initial_tile_subcoord[6][4][3] = {
2308 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2309 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2310 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2311 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2312 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2313 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2314 };
2315 
2328 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2329 {
2331  case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2332  case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2333 
2334  default: NOT_REACHED();
2335  }
2336 }
2337 
2343 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2344 {
2345  PBSTileInfo origin = FollowTrainReservation(v);
2346 
2347  CFollowTrackRail ft(v);
2348 
2349  TileIndex tile = origin.tile;
2350  Trackdir cur_td = origin.trackdir;
2351  while (ft.Follow(tile, cur_td)) {
2353  /* Possible signal tile. */
2355  }
2356 
2359  if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2360  }
2361 
2362  /* Station, depot or waypoint are a possible target. */
2363  bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2364  if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2365  /* Choice found or possible target encountered.
2366  * On finding a possible target, we need to stop and let the pathfinder handle the
2367  * remaining path. This is because we don't know if this target is in one of our
2368  * orders, so we might cause pathfinding to fail later on if we find a choice.
2369  * This failure would cause a bogous call to TryReserveSafePath which might reserve
2370  * a wrong path not leading to our next destination. */
2372 
2373  /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2374  * actually starts its search at the first unreserved tile. */
2376 
2377  /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2378  if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2379  if (enterdir != NULL) *enterdir = ft.m_exitdir;
2380  return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2381  }
2382 
2383  tile = ft.m_new_tile;
2384  cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2385 
2386  if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2387  bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2388  if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2389  /* Safe position is all good, path valid and okay. */
2390  return PBSTileInfo(tile, cur_td, true);
2391  }
2392 
2393  if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2394  }
2395 
2396  if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2397  /* End of line, path valid and okay. */
2398  return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2399  }
2400 
2401  /* Sorry, can't reserve path, back out. */
2402  tile = origin.tile;
2403  cur_td = origin.trackdir;
2404  TileIndex stopped = ft.m_old_tile;
2405  Trackdir stopped_td = ft.m_old_td;
2406  while (tile != stopped || cur_td != stopped_td) {
2407  if (!ft.Follow(tile, cur_td)) break;
2408 
2411  assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2412  }
2414 
2415  tile = ft.m_new_tile;
2416  cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2417 
2418  UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2419  }
2420 
2421  /* Path invalid. */
2422  return PBSTileInfo();
2423 }
2424 
2435 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
2436 {
2438  case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2439  case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2440 
2441  default: NOT_REACHED();
2442  }
2443 }
2444 
2447 private:
2448  Train *v;
2449  Order old_order;
2450  TileIndex old_dest_tile;
2451  StationID old_last_station_visited;
2452  VehicleOrderID index;
2453  bool suppress_implicit_orders;
2454 
2455 public:
2456  VehicleOrderSaver(Train *_v) :
2457  v(_v),
2458  old_order(_v->current_order),
2459  old_dest_tile(_v->dest_tile),
2460  old_last_station_visited(_v->last_station_visited),
2461  index(_v->cur_real_order_index),
2462  suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2463  {
2464  }
2465 
2467  {
2468  this->v->current_order = this->old_order;
2469  this->v->dest_tile = this->old_dest_tile;
2470  this->v->last_station_visited = this->old_last_station_visited;
2471  SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2472  }
2473 
2479  bool SwitchToNextOrder(bool skip_first)
2480  {
2481  if (this->v->GetNumOrders() == 0) return false;
2482 
2483  if (skip_first) ++this->index;
2484 
2485  int depth = 0;
2486 
2487  do {
2488  /* Wrap around. */
2489  if (this->index >= this->v->GetNumOrders()) this->index = 0;
2490 
2491  Order *order = this->v->GetOrder(this->index);
2492  assert(order != NULL);
2493 
2494  switch (order->GetType()) {
2495  case OT_GOTO_DEPOT:
2496  /* Skip service in depot orders when the train doesn't need service. */
2497  if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2498  case OT_GOTO_STATION:
2499  case OT_GOTO_WAYPOINT:
2500  this->v->current_order = *order;
2501  return UpdateOrderDest(this->v, order, 0, true);
2502  case OT_CONDITIONAL: {
2503  VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2504  if (next != INVALID_VEH_ORDER_ID) {
2505  depth++;
2506  this->index = next;
2507  /* Don't increment next, so no break here. */
2508  continue;
2509  }
2510  break;
2511  }
2512  default:
2513  break;
2514  }
2515  /* Don't increment inside the while because otherwise conditional
2516  * orders can lead to an infinite loop. */
2517  ++this->index;
2518  depth++;
2519  } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2520 
2521  return false;
2522  }
2523 };
2524 
2525 /* choose a track */
2526 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2527 {
2528  Track best_track = INVALID_TRACK;
2529  bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2530  bool changed_signal = false;
2531 
2532  assert((tracks & ~TRACK_BIT_MASK) == 0);
2533 
2534  if (got_reservation != NULL) *got_reservation = false;
2535 
2536  /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2537  TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2538  /* Do we have a suitable reserved track? */
2539  if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2540 
2541  /* Quick return in case only one possible track is available */
2542  if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2543  Track track = FindFirstTrack(tracks);
2544  /* We need to check for signals only here, as a junction tile can't have signals. */
2545  if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2546  do_track_reservation = true;
2547  changed_signal = true;
2549  } else if (!do_track_reservation) {
2550  return track;
2551  }
2552  best_track = track;
2553  }
2554 
2555  PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2556  DiagDirection dest_enterdir = enterdir;
2557  if (do_track_reservation) {
2558  res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2559  if (res_dest.tile == INVALID_TILE) {
2560  /* Reservation failed? */
2561  if (mark_stuck) MarkTrainAsStuck(v);
2562  if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2563  return FindFirstTrack(tracks);
2564  }
2565  if (res_dest.okay) {
2566  /* Got a valid reservation that ends at a safe target, quick exit. */
2567  if (got_reservation != NULL) *got_reservation = true;
2568  if (changed_signal) MarkTileDirtyByTile(tile);
2570  return best_track;
2571  }
2572 
2573  /* Check if the train needs service here, so it has a chance to always find a depot.
2574  * Also check if the current order is a service order so we don't reserve a path to
2575  * the destination but instead to the next one if service isn't needed. */
2577  if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2578  }
2579 
2580  /* Save the current train order. The destructor will restore the old order on function exit. */
2581  VehicleOrderSaver orders(v);
2582 
2583  /* If the current tile is the destination of the current order and
2584  * a reservation was requested, advance to the next order.
2585  * Don't advance on a depot order as depots are always safe end points
2586  * for a path and no look-ahead is necessary. This also avoids a
2587  * problem with depot orders not part of the order list when the
2588  * order list itself is empty. */
2589  if (v->current_order.IsType(OT_LEAVESTATION)) {
2590  orders.SwitchToNextOrder(false);
2591  } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2592  v->current_order.IsType(OT_GOTO_STATION) ?
2594  v->tile == v->dest_tile))) {
2595  orders.SwitchToNextOrder(true);
2596  }
2597 
2598  if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2599  /* Pathfinders are able to tell that route was only 'guessed'. */
2600  bool path_found = true;
2601  TileIndex new_tile = res_dest.tile;
2602 
2603  Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2604  if (new_tile == tile) best_track = next_track;
2605  v->HandlePathfindingResult(path_found);
2606  }
2607 
2608  /* No track reservation requested -> finished. */
2609  if (!do_track_reservation) return best_track;
2610 
2611  /* A path was found, but could not be reserved. */
2612  if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2613  if (mark_stuck) MarkTrainAsStuck(v);
2615  return best_track;
2616  }
2617 
2618  /* No possible reservation target found, we are probably lost. */
2619  if (res_dest.tile == INVALID_TILE) {
2620  /* Try to find any safe destination. */
2621  PBSTileInfo origin = FollowTrainReservation(v);
2622  if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2623  TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2624  best_track = FindFirstTrack(res);
2626  if (got_reservation != NULL) *got_reservation = true;
2627  if (changed_signal) MarkTileDirtyByTile(tile);
2628  } else {
2630  if (mark_stuck) MarkTrainAsStuck(v);
2631  }
2632  return best_track;
2633  }
2634 
2635  if (got_reservation != NULL) *got_reservation = true;
2636 
2637  /* Reservation target found and free, check if it is safe. */
2638  while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2639  /* Extend reservation until we have found a safe position. */
2640  DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2641  TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2644  reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2645  }
2646 
2647  /* Get next order with destination. */
2648  if (orders.SwitchToNextOrder(true)) {
2649  PBSTileInfo cur_dest;
2650  bool path_found;
2651  DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
2652  if (cur_dest.tile != INVALID_TILE) {
2653  res_dest = cur_dest;
2654  if (res_dest.okay) continue;
2655  /* Path found, but could not be reserved. */
2657  if (mark_stuck) MarkTrainAsStuck(v);
2658  if (got_reservation != NULL) *got_reservation = false;
2659  changed_signal = false;
2660  break;
2661  }
2662  }
2663  /* No order or no safe position found, try any position. */
2664  if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2666  if (mark_stuck) MarkTrainAsStuck(v);
2667  if (got_reservation != NULL) *got_reservation = false;
2668  changed_signal = false;
2669  }
2670  break;
2671  }
2672 
2674 
2675  if (changed_signal) MarkTileDirtyByTile(tile);
2676 
2677  return best_track;
2678 }
2679 
2688 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2689 {
2690  assert(v->IsFrontEngine());
2691 
2692  /* We have to handle depots specially as the track follower won't look
2693  * at the depot tile itself but starts from the next tile. If we are still
2694  * inside the depot, a depot reservation can never be ours. */
2695  if (v->track == TRACK_BIT_DEPOT) {
2696  if (HasDepotReservation(v->tile)) {
2697  if (mark_as_stuck) MarkTrainAsStuck(v);
2698  return false;
2699  } else {
2700  /* Depot not reserved, but the next tile might be. */
2702  if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2703  }
2704  }
2705 
2706  Vehicle *other_train = NULL;
2707  PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2708  /* The path we are driving on is already blocked by some other train.
2709  * This can only happen in certain situations when mixing path and
2710  * block signals or when changing tracks and/or signals.
2711  * Exit here as doing any further reservations will probably just
2712  * make matters worse. */
2713  if (other_train != NULL && other_train->index != v->index) {
2714  if (mark_as_stuck) MarkTrainAsStuck(v);
2715  return false;
2716  }
2717  /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2718  if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2719  /* Can't be stuck then. */
2721  ClrBit(v->flags, VRF_TRAIN_STUCK);
2722  return true;
2723  }
2724 
2725  /* If we are in a depot, tentatively reserve the depot. */
2726  if (v->track == TRACK_BIT_DEPOT) {
2727  SetDepotReservation(v->tile, true);
2729  }
2730 
2731  DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2732  TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2734 
2736 
2737  bool res_made = false;
2738  ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2739 
2740  if (!res_made) {
2741  /* Free the depot reservation as well. */
2742  if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2743  return false;
2744  }
2745 
2746  if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2747  v->wait_counter = 0;
2749  }
2750  ClrBit(v->flags, VRF_TRAIN_STUCK);
2751  return true;
2752 }
2753 
2754 
2755 static bool CheckReverseTrain(const Train *v)
2756 {
2758  v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2759  !(v->direction & 1)) {
2760  return false;
2761  }
2762 
2763  assert(v->track != TRACK_BIT_NONE);
2764 
2766  case VPF_NPF: return NPFTrainCheckReverse(v);
2767  case VPF_YAPF: return YapfTrainCheckReverse(v);
2768 
2769  default: NOT_REACHED();
2770  }
2771 }
2772 
2779 {
2780  if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2781 
2782  const Station *st = Station::Get(station);
2783  if (!(st->facilities & FACIL_TRAIN)) {
2784  /* The destination station has no trainstation tiles. */
2785  this->IncrementRealOrderIndex();
2786  return 0;
2787  }
2788 
2789  return st->xy;
2790 }
2791 
2794 {
2795  Train *v = this;
2796  do {
2797  v->colourmap = PAL_NONE;
2798  v->UpdateViewport(true, false);
2799  } while ((v = v->Next()) != NULL);
2800 
2801  /* need to update acceleration and cached values since the goods on the train changed. */
2802  this->CargoChanged();
2803  this->UpdateAcceleration();
2804 }
2805 
2814 {
2816  default: NOT_REACHED();
2817  case AM_ORIGINAL:
2818  return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2819 
2820  case AM_REALISTIC:
2821  return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2822  }
2823 }
2824 
2830 static void TrainEnterStation(Train *v, StationID station)
2831 {
2832  v->last_station_visited = station;
2833 
2834  /* check if a train ever visited this station before */
2835  Station *st = Station::Get(station);
2836  if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2837  st->had_vehicle_of_type |= HVOT_TRAIN;
2838  SetDParam(0, st->index);
2840  STR_NEWS_FIRST_TRAIN_ARRIVAL,
2842  v->index,
2843  st->index
2844  );
2845  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2846  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2847  }
2848 
2849  v->force_proceed = TFP_NONE;
2851 
2852  v->BeginLoading();
2853 
2855  TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2856 }
2857 
2858 /* Check if the vehicle is compatible with the specified tile */
2859 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
2860 {
2861  return IsTileOwner(tile, v->owner) &&
2862  (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
2863 }
2864 
2867  byte small_turn;
2868  byte large_turn;
2869  byte z_up;
2870  byte z_down;
2871 };
2872 
2875  /* normal accel */
2876  {256 / 4, 256 / 2, 256 / 4, 2},
2877  {256 / 4, 256 / 2, 256 / 4, 2},
2878  {0, 256 / 2, 256 / 4, 2},
2879 };
2880 
2886 static inline void AffectSpeedByZChange(Train *v, int old_z)
2887 {
2888  if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2889 
2890  const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2891 
2892  if (old_z < v->z_pos) {
2893  v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2894  } else {
2895  uint16 spd = v->cur_speed + asp->z_down;
2896  if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2897  }
2898 }
2899 
2900 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
2901 {
2902  if (IsTileType(tile, MP_RAILWAY) &&
2905  Trackdir trackdir = FindFirstTrackdir(tracks);
2906  if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
2907  /* A PBS block with a non-PBS signal facing us? */
2908  if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
2909  }
2910  }
2911  return false;
2912 }
2913 
2916 {
2917  for (const Train *u = this; u != NULL; u = u->Next()) {
2918  switch (u->track) {
2919  case TRACK_BIT_WORMHOLE:
2921  break;
2922  case TRACK_BIT_DEPOT:
2923  break;
2924  default:
2925  TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
2926  break;
2927  }
2928  }
2929 }
2930 
2937 uint Train::Crash(bool flooded)
2938 {
2939  uint pass = 0;
2940  if (this->IsFrontEngine()) {
2941  pass += 2; // driver
2942 
2943  /* Remove the reserved path in front of the train if it is not stuck.
2944  * Also clear all reserved tracks the train is currently on. */
2945  if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
2946  for (const Train *v = this; v != NULL; v = v->Next()) {
2948  if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
2949  /* ClearPathReservation will not free the wormhole exit
2950  * if the train has just entered the wormhole. */
2952  }
2953  }
2954 
2955  /* we may need to update crossing we were approaching,
2956  * but must be updated after the train has been marked crashed */
2957  TileIndex crossing = TrainApproachingCrossingTile(this);
2958  if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2959 
2960  /* Remove the loading indicators (if any) */
2962  }
2963 
2964  pass += this->GroundVehicleBase::Crash(flooded);
2965 
2966  this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
2967  return pass;
2968 }
2969 
2976 static uint TrainCrashed(Train *v)
2977 {
2978  uint num = 0;
2979 
2980  /* do not crash train twice */
2981  if (!(v->vehstatus & VS_CRASHED)) {
2982  num = v->Crash();
2983  AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2984  Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2985  }
2986 
2987  /* Try to re-reserve track under already crashed train too.
2988  * Crash() clears the reservation! */
2990 
2991  return num;
2992 }
2993 
2997  uint num;
2998 };
2999 
3006 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3007 {
3009 
3010  /* not a train or in depot */
3011  if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
3012 
3013  /* do not crash into trains of another company. */
3014  if (v->owner != tcc->v->owner) return NULL;
3015 
3016  /* get first vehicle now to make most usual checks faster */
3017  Train *coll = Train::From(v)->First();
3018 
3019  /* can't collide with own wagons */
3020  if (coll == tcc->v) return NULL;
3021 
3022  int x_diff = v->x_pos - tcc->v->x_pos;
3023  int y_diff = v->y_pos - tcc->v->y_pos;
3024 
3025  /* Do fast calculation to check whether trains are not in close vicinity
3026  * and quickly reject trains distant enough for any collision.
3027  * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3028  * Differences are then ORed and then we check for any higher bits */
3029  uint hash = (y_diff + 7) | (x_diff + 7);
3030  if (hash & ~15) return NULL;
3031 
3032  /* Slower check using multiplication */
3033  int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3034  if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
3035 
3036  /* Happens when there is a train under bridge next to bridge head */
3037  if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
3038 
3039  /* crash both trains */
3040  tcc->num += TrainCrashed(tcc->v);
3041  tcc->num += TrainCrashed(coll);
3042 
3043  return NULL; // continue searching
3044 }
3045 
3054 {
3055  /* can't collide in depot */
3056  if (v->track == TRACK_BIT_DEPOT) return false;
3057 
3058  assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3059 
3060  TrainCollideChecker tcc;
3061  tcc.v = v;
3062  tcc.num = 0;
3063 
3064  /* find colliding vehicles */
3065  if (v->track == TRACK_BIT_WORMHOLE) {
3068  } else {
3070  }
3071 
3072  /* any dead -> no crash */
3073  if (tcc.num == 0) return false;
3074 
3075  SetDParam(0, tcc.num);
3076  AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3077 
3078  ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3079  if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3080  return true;
3081 }
3082 
3083 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3084 {
3085  if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
3086 
3087  Train *t = Train::From(v);
3088  DiagDirection exitdir = *(DiagDirection *)data;
3089 
3090  /* not front engine of a train, inside wormhole or depot, crashed */
3091  if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
3092 
3093  if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
3094 
3095  return t;
3096 }
3097 
3105 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3106 {
3107  Train *first = v->First();
3108  Train *prev;
3109  bool direction_changed = false; // has direction of any part changed?
3110 
3111  /* For every vehicle after and including the given vehicle */
3112  for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3113  DiagDirection enterdir = DIAGDIR_BEGIN;
3114  bool update_signals_crossing = false; // will we update signals or crossing state?
3115 
3117  if (v->track != TRACK_BIT_WORMHOLE) {
3118  /* Not inside tunnel */
3119  if (gp.old_tile == gp.new_tile) {
3120  /* Staying in the old tile */
3121  if (v->track == TRACK_BIT_DEPOT) {
3122  /* Inside depot */
3123  gp.x = v->x_pos;
3124  gp.y = v->y_pos;
3125  } else {
3126  /* Not inside depot */
3127 
3128  /* Reverse when we are at the end of the track already, do not move to the new position */
3129  if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3130 
3131  uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3132  if (HasBit(r, VETS_CANNOT_ENTER)) {
3133  goto invalid_rail;
3134  }
3135  if (HasBit(r, VETS_ENTERED_STATION)) {
3136  /* The new position is the end of the platform */
3138  }
3139  }
3140  } else {
3141  /* A new tile is about to be entered. */
3142 
3143  /* Determine what direction we're entering the new tile from */
3144  enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3145  assert(IsValidDiagDirection(enterdir));
3146 
3147  /* Get the status of the tracks in the new tile and mask
3148  * away the bits that aren't reachable. */
3149  TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3150  TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3151 
3152  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3153  TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3154 
3155  TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3156  if (_settings_game.pf.forbid_90_deg && prev == NULL) {
3157  /* We allow wagons to make 90 deg turns, because forbid_90_deg
3158  * can be switched on halfway a turn */
3159  bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3160  }
3161 
3162  if (bits == TRACK_BIT_NONE) goto invalid_rail;
3163 
3164  /* Check if the new tile constrains tracks that are compatible
3165  * with the current train, if not, bail out. */
3166  if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3167 
3168  TrackBits chosen_track;
3169  if (prev == NULL) {
3170  /* Currently the locomotive is active. Determine which one of the
3171  * available tracks to choose */
3172  chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
3173  assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3174 
3175  if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3176  /* For each signal we find decrease the counter by one.
3177  * We start at two, so the first signal we pass decreases
3178  * this to one, then if we reach the next signal it is
3179  * decreased to zero and we won't pass that new signal. */
3180  Trackdir dir = FindFirstTrackdir(trackdirbits);
3181  if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3183  GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3184  /* However, we do not want to be stopped by PBS signals
3185  * entered via the back. */
3186  v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3187  SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3188  }
3189  }
3190 
3191  /* Check if it's a red signal and that force proceed is not clicked. */
3192  if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3193  /* In front of a red signal */
3194  Trackdir i = FindFirstTrackdir(trackdirbits);
3195 
3196  /* Don't handle stuck trains here. */
3197  if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3198 
3200  v->cur_speed = 0;
3201  v->subspeed = 0;
3202  v->progress = 255 - 100;
3203  if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
3204  } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3205  v->cur_speed = 0;
3206  v->subspeed = 0;
3207  v->progress = 255 - 10;
3208  if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3209  DiagDirection exitdir = TrackdirToExitdir(i);
3210  TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3211 
3212  exitdir = ReverseDiagDir(exitdir);
3213 
3214  /* check if a train is waiting on the other side */
3215  if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3216  }
3217  }
3218 
3219  /* If we would reverse but are currently in a PBS block and
3220  * reversing of stuck trains is disabled, don't reverse.
3221  * This does not apply if the reason for reversing is a one-way
3222  * signal blocking us, because a train would then be stuck forever. */
3224  UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3225  v->wait_counter = 0;
3226  return false;
3227  }
3228  goto reverse_train_direction;
3229  } else {
3230  TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3231  }
3232  } else {
3233  /* The wagon is active, simply follow the prev vehicle. */
3234  if (prev->tile == gp.new_tile) {
3235  /* Choose the same track as prev */
3236  if (prev->track == TRACK_BIT_WORMHOLE) {
3237  /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3238  * However, just choose the track into the wormhole. */
3239  assert(IsTunnel(prev->tile));
3240  chosen_track = bits;
3241  } else {
3242  chosen_track = prev->track;
3243  }
3244  } else {
3245  /* Choose the track that leads to the tile where prev is.
3246  * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3247  * I.e. when the tile between them has only space for a single vehicle like
3248  * 1) horizontal/vertical track tiles and
3249  * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3250  * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3251  */
3252  static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3257  };
3258  DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3259  assert(IsValidDiagDirection(exitdir));
3260  chosen_track = _connecting_track[enterdir][exitdir];
3261  }
3262  chosen_track &= bits;
3263  }
3264 
3265  /* Make sure chosen track is a valid track */
3266  assert(
3267  chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3268  chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3269  chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3270 
3271  /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3272  const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3273  gp.x = (gp.x & ~0xF) | b[0];
3274  gp.y = (gp.y & ~0xF) | b[1];
3275  Direction chosen_dir = (Direction)b[2];
3276 
3277  /* Call the landscape function and tell it that the vehicle entered the tile */
3278  uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3279  if (HasBit(r, VETS_CANNOT_ENTER)) {
3280  goto invalid_rail;
3281  }
3282 
3283  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3284  Track track = FindFirstTrack(chosen_track);
3285  Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3286  if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3289  }
3290 
3291  /* Clear any track reservation when the last vehicle leaves the tile */
3292  if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3293 
3294  v->tile = gp.new_tile;
3295 
3297  v->First()->ConsistChanged(CCF_TRACK);
3298  }
3299 
3300  v->track = chosen_track;
3301  assert(v->track);
3302  }
3303 
3304  /* We need to update signal status, but after the vehicle position hash
3305  * has been updated by UpdateInclination() */
3306  update_signals_crossing = true;
3307 
3308  if (chosen_dir != v->direction) {
3309  if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3310  const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3311  DirDiff diff = DirDifference(v->direction, chosen_dir);
3312  v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3313  }
3314  direction_changed = true;
3315  v->direction = chosen_dir;
3316  }
3317 
3318  if (v->IsFrontEngine()) {
3319  v->wait_counter = 0;
3320 
3321  /* If we are approaching a crossing that is reserved, play the sound now. */
3323  if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3324 
3325  /* Always try to extend the reservation when entering a tile. */
3326  CheckNextTrainTile(v);
3327  }
3328 
3329  if (HasBit(r, VETS_ENTERED_STATION)) {
3330  /* The new position is the location where we want to stop */
3332  }
3333  }
3334  } else {
3336  /* Perform look-ahead on tunnel exit. */
3337  if (v->IsFrontEngine()) {
3339  CheckNextTrainTile(v);
3340  }
3341  /* Prevent v->UpdateInclination() being called with wrong parameters.
3342  * This could happen if the train was reversed inside the tunnel/bridge. */
3343  if (gp.old_tile == gp.new_tile) {
3345  }
3346  } else {
3347  v->x_pos = gp.x;
3348  v->y_pos = gp.y;
3349  v->UpdatePosition();
3350  if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3351  continue;
3352  }
3353  }
3354 
3355  /* update image of train, as well as delta XY */
3356  v->UpdateDeltaXY(v->direction);
3357 
3358  v->x_pos = gp.x;
3359  v->y_pos = gp.y;
3360  v->UpdatePosition();
3361 
3362  /* update the Z position of the vehicle */
3363  int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3364 
3365  if (prev == NULL) {
3366  /* This is the first vehicle in the train */
3367  AffectSpeedByZChange(v, old_z);
3368  }
3369 
3370  if (update_signals_crossing) {
3371  if (v->IsFrontEngine()) {
3372  if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3373  /* We are entering a block with PBS signals right now, but
3374  * not through a PBS signal. This means we don't have a
3375  * reservation right now. As a conventional signal will only
3376  * ever be green if no other train is in the block, getting
3377  * a path should always be possible. If the player built
3378  * such a strange network that it is not possible, the train
3379  * will be marked as stuck and the player has to deal with
3380  * the problem. */
3381  if ((!HasReservedTracks(gp.new_tile, v->track) &&
3382  !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3383  !TryPathReserve(v)) {
3384  MarkTrainAsStuck(v);
3385  }
3386  }
3387  }
3388 
3389  /* Signals can only change when the first
3390  * (above) or the last vehicle moves. */
3391  if (v->Next() == NULL) {
3392  TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3394  }
3395  }
3396 
3397  /* Do not check on every tick to save some computing time. */
3398  if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
3399  }
3400 
3401  if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3402 
3403  return true;
3404 
3405 invalid_rail:
3406  /* We've reached end of line?? */
3407  if (prev != NULL) error("Disconnecting train");
3408 
3409 reverse_train_direction:
3410  if (reverse) {
3411  v->wait_counter = 0;
3412  v->cur_speed = 0;
3413  v->subspeed = 0;
3415  }
3416 
3417  return false;
3418 }
3419 
3427 {
3428  TrackBits *trackbits = (TrackBits *)data;
3429 
3430  if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3431  TrackBits train_tbits = Train::From(v)->track;
3432  if (train_tbits == TRACK_BIT_WORMHOLE) {
3433  /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3435  } else if (train_tbits != TRACK_BIT_DEPOT) {
3436  *trackbits |= train_tbits;
3437  }
3438  }
3439 
3440  return NULL;
3441 }
3442 
3450 static void DeleteLastWagon(Train *v)
3451 {
3452  Train *first = v->First();
3453 
3454  /* Go to the last wagon and delete the link pointing there
3455  * *u is then the one-before-last wagon, and *v the last
3456  * one which will physically be removed */
3457  Train *u = v;
3458  for (; v->Next() != NULL; v = v->Next()) u = v;
3459  u->SetNext(NULL);
3460 
3461  if (first != v) {
3462  /* Recalculate cached train properties */
3463  first->ConsistChanged(CCF_ARRANGE);
3464  /* Update the depot window if the first vehicle is in depot -
3465  * if v == first, then it is updated in PreDestructor() */
3466  if (first->track == TRACK_BIT_DEPOT) {
3468  }
3469  v->last_station_visited = first->last_station_visited; // for PreDestructor
3470  }
3471 
3472  /* 'v' shouldn't be accessed after it has been deleted */
3473  TrackBits trackbits = v->track;
3474  TileIndex tile = v->tile;
3475  Owner owner = v->owner;
3476 
3477  delete v;
3478  v = NULL; // make sure nobody will try to read 'v' anymore
3479 
3480  if (trackbits == TRACK_BIT_WORMHOLE) {
3481  /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3483  }
3484 
3485  Track track = TrackBitsToTrack(trackbits);
3486  if (HasReservedTracks(tile, trackbits)) {
3487  UnreserveRailTrack(tile, track);
3488 
3489  /* If there are still crashed vehicles on the tile, give the track reservation to them */
3490  TrackBits remaining_trackbits = TRACK_BIT_NONE;
3491  FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3492 
3493  /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3494  assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3495  Track t;
3496  FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
3497  }
3498 
3499  /* check if the wagon was on a road/rail-crossing */
3500  if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3501 
3502  /* Update signals */
3503  if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3505  } else {
3506  SetSignalsOnBothDir(tile, track, owner);
3507  }
3508 }
3509 
3515 {
3516  static const DirDiff delta[] = {
3518  };
3519 
3520  do {
3521  /* We don't need to twist around vehicles if they're not visible */
3522  if (!(v->vehstatus & VS_HIDDEN)) {
3523  v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3524  v->UpdateDeltaXY(v->direction);
3525  v->cur_image = v->GetImage(v->direction, EIT_ON_MAP);
3526  /* Refrain from updating the z position of the vehicle when on
3527  * a bridge, because UpdateInclination() will put the vehicle under
3528  * the bridge in that case */
3529  if (v->track != TRACK_BIT_WORMHOLE) {
3530  v->UpdatePosition();
3531  v->UpdateInclination(false, false);
3532  }
3533  }
3534  } while ((v = v->Next()) != NULL);
3535 }
3536 
3542 static bool HandleCrashedTrain(Train *v)
3543 {
3544  int state = ++v->crash_anim_pos;
3545 
3546  if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3548  }
3549 
3550  uint32 r;
3551  if (state <= 200 && Chance16R(1, 7, r)) {
3552  int index = (r * 10 >> 16);
3553 
3554  Vehicle *u = v;
3555  do {
3556  if (--index < 0) {
3557  r = Random();
3558 
3560  GB(r, 8, 3) + 2,
3561  GB(r, 16, 3) + 2,
3562  GB(r, 0, 3) + 5,
3564  break;
3565  }
3566  } while ((u = u->Next()) != NULL);
3567  }
3568 
3569  if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3570 
3571  if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3572  bool ret = v->Next() != NULL;
3573  DeleteLastWagon(v);
3574  return ret;
3575  }
3576 
3577  return true;
3578 }
3579 
3581 static const uint16 _breakdown_speeds[16] = {
3582  225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3583 };
3584 
3585 
3594 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3595 {
3596  /* Calc position within the current tile */
3597  uint x = v->x_pos & 0xF;
3598  uint y = v->y_pos & 0xF;
3599 
3600  /* for diagonal directions, 'x' will be 0..15 -
3601  * for other directions, it will be 1, 3, 5, ..., 15 */
3602  switch (v->direction) {
3603  case DIR_N : x = ~x + ~y + 25; break;
3604  case DIR_NW: x = y; // FALL THROUGH
3605  case DIR_NE: x = ~x + 16; break;
3606  case DIR_E : x = ~x + y + 9; break;
3607  case DIR_SE: x = y; break;
3608  case DIR_S : x = x + y - 7; break;
3609  case DIR_W : x = ~y + x + 9; break;
3610  default: break;
3611  }
3612 
3613  /* Do not reverse when approaching red signal. Make sure the vehicle's front
3614  * does not cross the tile boundary when we do reverse, but as the vehicle's
3615  * location is based on their center, use half a vehicle's length as offset.
3616  * Multiply the half-length by two for straight directions to compensate that
3617  * we only get odd x offsets there. */
3618  if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3619  /* we are too near the tile end, reverse now */
3620  v->cur_speed = 0;
3621  if (reverse) ReverseTrainDirection(v);
3622  return false;
3623  }
3624 
3625  /* slow down */
3627  uint16 break_speed = _breakdown_speeds[x & 0xF];
3628  if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3629 
3630  return true;
3631 }
3632 
3633 
3639 static bool TrainCanLeaveTile(const Train *v)
3640 {
3641  /* Exit if inside a tunnel/bridge or a depot */
3642  if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3643 
3644  TileIndex tile = v->tile;
3645 
3646  /* entering a tunnel/bridge? */
3647  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3649  if (DiagDirToDir(dir) == v->direction) return false;
3650  }
3651 
3652  /* entering a depot? */
3653  if (IsRailDepotTile(tile)) {
3655  if (DiagDirToDir(dir) == v->direction) return false;
3656  }
3657 
3658  return true;
3659 }
3660 
3661 
3670 {
3671  assert(v->IsFrontEngine());
3672  assert(!(v->vehstatus & VS_CRASHED));
3673 
3674  if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3675 
3676  DiagDirection dir = TrainExitDir(v->direction, v->track);
3677  TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3678 
3679  /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3680  if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3681  !CheckCompatibleRail(v, tile)) {
3682  return INVALID_TILE;
3683  }
3684 
3685  return tile;
3686 }
3687 
3688 
3696 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3697 {
3698  /* First, handle broken down train */
3699 
3700  int t = v->breakdown_ctr;
3701  if (t > 1) {
3703 
3704  uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3705  if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3706  } else {
3707  v->vehstatus &= ~VS_TRAIN_SLOWING;
3708  }
3709 
3710  if (!TrainCanLeaveTile(v)) return true;
3711 
3712  /* Determine the non-diagonal direction in which we will exit this tile */
3713  DiagDirection dir = TrainExitDir(v->direction, v->track);
3714  /* Calculate next tile */
3715  TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3716 
3717  /* Determine the track status on the next tile */
3718  TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3719  TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3720 
3721  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3722  TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3723 
3724  /* We are sure the train is not entering a depot, it is detected above */
3725 
3726  /* mask unreachable track bits if we are forbidden to do 90deg turns */
3727  TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3729  bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3730  }
3731 
3732  /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3733  if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3734  return TrainApproachingLineEnd(v, false, reverse);
3735  }
3736 
3737  /* approaching red signal */
3738  if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3739 
3740  /* approaching a rail/road crossing? then make it red */
3742 
3743  return true;
3744 }
3745 
3746 
3747 static bool TrainLocoHandler(Train *v, bool mode)
3748 {
3749  /* train has crashed? */
3750  if (v->vehstatus & VS_CRASHED) {
3751  return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3752  }
3753 
3754  if (v->force_proceed != TFP_NONE) {
3755  ClrBit(v->flags, VRF_TRAIN_STUCK);
3757  }
3758 
3759  /* train is broken down? */
3760  if (v->HandleBreakdown()) return true;
3761 
3762  if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3764  }
3765 
3766  /* exit if train is stopped */
3767  if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3768 
3769  bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3770  if (ProcessOrders(v) && CheckReverseTrain(v)) {
3771  v->wait_counter = 0;
3772  v->cur_speed = 0;
3773  v->subspeed = 0;
3774  ClrBit(v->flags, VRF_LEAVING_STATION);
3776  return true;
3777  } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3778  /* Try to reserve a path when leaving the station as we
3779  * might not be marked as wanting a reservation, e.g.
3780  * when an overlength train gets turned around in a station. */
3781  DiagDirection dir = TrainExitDir(v->direction, v->track);
3783 
3785  TryPathReserve(v, true, true);
3786  }
3787  ClrBit(v->flags, VRF_LEAVING_STATION);
3788  }
3789 
3790  v->HandleLoading(mode);
3791 
3792  if (v->current_order.IsType(OT_LOADING)) return true;
3793 
3794  if (CheckTrainStayInDepot(v)) return true;
3795 
3796  if (!mode) v->ShowVisualEffect();
3797 
3798  /* We had no order but have an order now, do look ahead. */
3799  if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3800  CheckNextTrainTile(v);
3801  }
3802 
3803  /* Handle stuck trains. */
3804  if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3805  ++v->wait_counter;
3806 
3807  /* Should we try reversing this tick if still stuck? */
3809 
3810  if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3811  if (!TryPathReserve(v)) {
3812  /* Still stuck. */
3813  if (turn_around) ReverseTrainDirection(v);
3814 
3816  /* Show message to player. */
3818  SetDParam(0, v->index);
3819  AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
3820  }
3821  v->wait_counter = 0;
3822  }
3823  /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3824  if (v->force_proceed == TFP_NONE) return true;
3825  ClrBit(v->flags, VRF_TRAIN_STUCK);
3826  v->wait_counter = 0;
3828  }
3829  }
3830 
3831  if (v->current_order.IsType(OT_LEAVESTATION)) {
3832  v->current_order.Free();
3834  return true;
3835  }
3836 
3837  int j = v->UpdateSpeed();
3838 
3839  /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
3840  if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
3841  /* If we manually stopped, we're not force-proceeding anymore. */
3842  v->force_proceed = TFP_NONE;
3844  }
3845 
3846  int adv_spd = v->GetAdvanceDistance();
3847  if (j < adv_spd) {
3848  /* if the vehicle has speed 0, update the last_speed field. */
3849  if (v->cur_speed == 0) v->SetLastSpeed();
3850  } else {
3852  /* Loop until the train has finished moving. */
3853  for (;;) {
3854  j -= adv_spd;
3855  TrainController(v, NULL);
3856  /* Don't continue to move if the train crashed. */
3857  if (CheckTrainCollision(v)) break;
3858  /* Determine distance to next map position */
3859  adv_spd = v->GetAdvanceDistance();
3860 
3861  /* No more moving this tick */
3862  if (j < adv_spd || v->cur_speed == 0) break;
3863 
3864  OrderType order_type = v->current_order.GetType();
3865  /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
3866  if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3868  IsTileType(v->tile, MP_STATION) &&
3870  ProcessOrders(v);
3871  }
3872  }
3873  v->SetLastSpeed();
3874  }
3875 
3876  for (Train *u = v; u != NULL; u = u->Next()) {
3877  if ((u->vehstatus & VS_HIDDEN) != 0) continue;
3878 
3879  u->UpdateViewport(false, false);
3880  }
3881 
3882  if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
3883 
3884  return true;
3885 }
3886 
3892 {
3893  Money cost = 0;
3894  const Train *v = this;
3895 
3896  do {
3897  const Engine *e = v->GetEngine();
3898  if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
3899 
3900  uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
3901  if (cost_factor == 0) continue;
3902 
3903  /* Halve running cost for multiheaded parts */
3904  if (v->IsMultiheaded()) cost_factor /= 2;
3905 
3906  cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
3907  } while ((v = v->GetNextVehicle()) != NULL);
3908 
3909  return cost;
3910 }
3911 
3917 {
3918  this->tick_counter++;
3919 
3920  if (this->IsFrontEngine()) {
3921  if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
3922 
3923  this->current_order_time++;
3924 
3925  if (!TrainLocoHandler(this, false)) return false;
3926 
3927  return TrainLocoHandler(this, true);
3928  } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
3929  /* Delete flooded standalone wagon chain */
3930  if (++this->crash_anim_pos >= 4400) {
3931  delete this;
3932  return false;
3933  }
3934  }
3935 
3936  return true;
3937 }
3938 
3944 {
3945  if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
3946  if (v->IsChainInDepot()) {
3948  return;
3949  }
3950 
3951  uint max_penalty;
3953  case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
3954  case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
3955  default: NOT_REACHED();
3956  }
3957 
3958  FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
3959  /* Only go to the depot if it is not too far out of our way. */
3960  if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
3961  if (v->current_order.IsType(OT_GOTO_DEPOT)) {
3962  /* If we were already heading for a depot but it has
3963  * suddenly moved farther away, we continue our normal
3964  * schedule? */
3965  v->current_order.MakeDummy();
3967  }
3968  return;
3969  }
3970 
3971  DepotID depot = GetDepotIndex(tfdd.tile);
3972 
3973  if (v->current_order.IsType(OT_GOTO_DEPOT) &&
3974  v->current_order.GetDestination() != depot &&
3975  !Chance16(3, 16)) {
3976  return;
3977  }
3978 
3981  v->dest_tile = tfdd.tile;
3983 }
3984 
3987 {
3988  AgeVehicle(this);
3989 
3990  if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
3991 
3992  if (this->IsFrontEngine()) {
3993  CheckVehicleBreakdown(this);
3994 
3996 
3997  CheckOrders(this);
3998 
3999  /* update destination */
4000  if (this->current_order.IsType(OT_GOTO_STATION)) {
4001  TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4002  if (tile != INVALID_TILE) this->dest_tile = tile;
4003  }
4004 
4005  if (this->running_ticks != 0) {
4006  /* running costs */
4008 
4009  this->profit_this_year -= cost.GetCost();
4010  this->running_ticks = 0;
4011 
4012  SubtractMoneyFromCompanyFract(this->owner, cost);
4013 
4016  }
4017  }
4018 }
4019 
4025 {
4026  if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4027 
4028  if (this->track == TRACK_BIT_DEPOT) {
4029  /* We'll assume the train is facing outwards */
4030  return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4031  }
4032 
4033  if (this->track == TRACK_BIT_WORMHOLE) {
4034  /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
4035  return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4036  }
4037 
4038  return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4039 }