OpenTTD Source  1.11.2
train_cmd.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #include "stdafx.h"
11 #include "error.h"
12 #include "articulated_vehicles.h"
13 #include "command_func.h"
15 #include "pathfinder/yapf/yapf.hpp"
16 #include "news_func.h"
17 #include "company_func.h"
18 #include "newgrf_sound.h"
19 #include "newgrf_text.h"
20 #include "strings_func.h"
21 #include "viewport_func.h"
22 #include "vehicle_func.h"
23 #include "sound_func.h"
24 #include "ai/ai.hpp"
25 #include "game/game.hpp"
26 #include "newgrf_station.h"
27 #include "effectvehicle_func.h"
28 #include "network/network.h"
29 #include "spritecache.h"
30 #include "core/random_func.hpp"
31 #include "company_base.h"
32 #include "newgrf.h"
33 #include "order_backup.h"
34 #include "zoom_func.h"
35 #include "newgrf_debug.h"
36 #include "framerate_type.h"
37 
38 #include "table/strings.h"
39 #include "table/train_cmd.h"
40 
41 #include "safeguards.h"
42 
43 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
44 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
45 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
47 static void CheckIfTrainNeedsService(Train *v);
48 static void CheckNextTrainTile(Train *v);
49 
50 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
51 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
52 
53 template <>
54 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
55 {
56  return image_index < lengthof(_engine_sprite_base);
57 }
58 
59 
66 {
67  if (!CargoSpec::Get(cargo)->is_freight) return 1;
69 }
70 
73 {
74  bool first = true;
75 
76  for (const Train *v : Train::Iterate()) {
77  if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
78  for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
79  if (u->track != TRACK_BIT_DEPOT) {
80  if ((w->track != TRACK_BIT_DEPOT &&
81  std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
82  (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
83  SetDParam(0, v->index);
84  SetDParam(1, v->owner);
85  ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
86 
87  if (!_networking && first) {
88  first = false;
90  }
91  /* Break so we warn only once for each train. */
92  break;
93  }
94  }
95  }
96  }
97  }
98 }
99 
107 {
108  uint16 max_speed = UINT16_MAX;
109 
110  assert(this->IsFrontEngine() || this->IsFreeWagon());
111 
112  const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
113  EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
114  this->gcache.cached_total_length = 0;
115  this->compatible_railtypes = RAILTYPES_NONE;
116 
117  bool train_can_tilt = true;
118 
119  for (Train *u = this; u != nullptr; u = u->Next()) {
120  const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
121 
122  /* Check the this->first cache. */
123  assert(u->First() == this);
124 
125  /* update the 'first engine' */
126  u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
127  u->railtype = rvi_u->railtype;
128 
129  if (u->IsEngine()) first_engine = u->engine_type;
130 
131  /* Set user defined data to its default value */
132  u->tcache.user_def_data = rvi_u->user_def_data;
133  this->InvalidateNewGRFCache();
134  u->InvalidateNewGRFCache();
135  }
136 
137  for (Train *u = this; u != nullptr; u = u->Next()) {
138  /* Update user defined data (must be done before other properties) */
139  u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
140  this->InvalidateNewGRFCache();
141  u->InvalidateNewGRFCache();
142  }
143 
144  for (Train *u = this; u != nullptr; u = u->Next()) {
145  const Engine *e_u = u->GetEngine();
146  const RailVehicleInfo *rvi_u = &e_u->u.rail;
147 
148  if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
149 
150  /* Cache wagon override sprite group. nullptr is returned if there is none */
151  u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
152 
153  /* Reset colour map */
154  u->colourmap = PAL_NONE;
155 
156  /* Update powered-wagon-status and visual effect */
157  u->UpdateVisualEffect(true);
158 
159  if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
160  UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
161  /* wagon is powered */
162  SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
163  } else {
164  ClrBit(u->flags, VRF_POWEREDWAGON);
165  }
166 
167  if (!u->IsArticulatedPart()) {
168  /* Do not count powered wagons for the compatible railtypes, as wagons always
169  have railtype normal */
170  if (rvi_u->power > 0) {
171  this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
172  }
173 
174  /* Some electric engines can be allowed to run on normal rail. It happens to all
175  * existing electric engines when elrails are disabled and then re-enabled */
176  if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
177  u->railtype = RAILTYPE_RAIL;
178  u->compatible_railtypes |= RAILTYPES_RAIL;
179  }
180 
181  /* max speed is the minimum of the speed limits of all vehicles in the consist */
182  if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
183  uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
184  if (speed != 0) max_speed = std::min(speed, max_speed);
185  }
186  }
187 
188  uint16 new_cap = e_u->DetermineCapacity(u);
189  if (allowed_changes & CCF_CAPACITY) {
190  /* Update vehicle capacity. */
191  if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
192  u->refit_cap = std::min(new_cap, u->refit_cap);
193  u->cargo_cap = new_cap;
194  } else {
195  /* Verify capacity hasn't changed. */
196  if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
197  }
198  u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
199 
200  /* check the vehicle length (callback) */
201  uint16 veh_len = CALLBACK_FAILED;
202  if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
203  /* Use callback 36 */
204  veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
205 
206  if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
208  }
209  } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
210  /* Use callback 11 */
211  veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
212  }
213  if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
214  veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
215 
216  if (allowed_changes & CCF_LENGTH) {
217  /* Update vehicle length. */
218  u->gcache.cached_veh_length = veh_len;
219  } else {
220  /* Verify length hasn't changed. */
221  if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
222  }
223 
224  this->gcache.cached_total_length += u->gcache.cached_veh_length;
225  this->InvalidateNewGRFCache();
226  u->InvalidateNewGRFCache();
227  }
228 
229  /* store consist weight/max speed in cache */
230  this->vcache.cached_max_speed = max_speed;
231  this->tcache.cached_tilt = train_can_tilt;
232  this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
233 
234  /* 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) */
235  this->CargoChanged();
236 
237  if (this->IsFrontEngine()) {
238  this->UpdateAcceleration();
242  InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
243  }
244 }
245 
256 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
257 {
258  const Station *st = Station::Get(station_id);
259  *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
260  *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
261 
262  /* Default to the middle of the station for stations stops that are not in
263  * the order list like intermediate stations when non-stop is disabled */
265  if (v->gcache.cached_total_length >= *station_length) {
266  /* The train is longer than the station, make it stop at the far end of the platform */
267  osl = OSL_PLATFORM_FAR_END;
268  } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
269  osl = v->current_order.GetStopLocation();
270  }
271 
272  /* The stop location of the FRONT! of the train */
273  int stop;
274  switch (osl) {
275  default: NOT_REACHED();
276 
278  stop = v->gcache.cached_total_length;
279  break;
280 
281  case OSL_PLATFORM_MIDDLE:
282  stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
283  break;
284 
286  stop = *station_length;
287  break;
288  }
289 
290  /* Subtract half the front vehicle length of the train so we get the real
291  * stop location of the train. */
292  return stop - (v->gcache.cached_veh_length + 1) / 2;
293 }
294 
295 
301 {
302  assert(this->First() == this);
303 
304  static const int absolute_max_speed = UINT16_MAX;
305  int max_speed = absolute_max_speed;
306 
307  if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
308 
309  int curvecount[2] = {0, 0};
310 
311  /* first find the curve speed limit */
312  int numcurve = 0;
313  int sum = 0;
314  int pos = 0;
315  int lastpos = -1;
316  for (const Vehicle *u = this; u->Next() != nullptr; u = u->Next(), pos++) {
317  Direction this_dir = u->direction;
318  Direction next_dir = u->Next()->direction;
319 
320  DirDiff dirdiff = DirDifference(this_dir, next_dir);
321  if (dirdiff == DIRDIFF_SAME) continue;
322 
323  if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
324  if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
325  if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
326  if (lastpos != -1) {
327  numcurve++;
328  sum += pos - lastpos;
329  if (pos - lastpos == 1 && max_speed > 88) {
330  max_speed = 88;
331  }
332  }
333  lastpos = pos;
334  }
335 
336  /* if we have a 90 degree turn, fix the speed limit to 60 */
337  if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
338  max_speed = 61;
339  }
340  }
341 
342  if (numcurve > 0 && max_speed > 88) {
343  if (curvecount[0] == 1 && curvecount[1] == 1) {
344  max_speed = absolute_max_speed;
345  } else {
346  sum /= numcurve;
347  max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
348  }
349  }
350 
351  if (max_speed != absolute_max_speed) {
352  /* Apply the current railtype's curve speed advantage */
353  const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
354  max_speed += (max_speed / 2) * rti->curve_speed;
355 
356  if (this->tcache.cached_tilt) {
357  /* Apply max_speed bonus of 20% for a tilting train */
358  max_speed += max_speed / 5;
359  }
360  }
361 
362  return max_speed;
363 }
364 
370 {
371  int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
373  this->tcache.cached_max_curve_speed;
374 
375  if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
376  StationID sid = GetStationIndex(this->tile);
377  if (this->current_order.ShouldStopAtStation(this, sid)) {
378  int station_ahead;
379  int station_length;
380  int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
381 
382  /* The distance to go is whatever is still ahead of the train minus the
383  * distance from the train's stop location to the end of the platform */
384  int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
385 
386  if (distance_to_go > 0) {
387  int st_max_speed = 120;
388 
389  int delta_v = this->cur_speed / (distance_to_go + 1);
390  if (max_speed > (this->cur_speed - delta_v)) {
391  st_max_speed = this->cur_speed - (delta_v / 10);
392  }
393 
394  st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
395  max_speed = std::min(max_speed, st_max_speed);
396  }
397  }
398  }
399 
400  for (const Train *u = this; u != nullptr; u = u->Next()) {
401  if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
402  max_speed = std::min(max_speed, 61);
403  break;
404  }
405 
406  /* Vehicle is on the middle part of a bridge. */
407  if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
408  max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
409  }
410  }
411 
412  max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
413  return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
414 }
415 
418 {
419  assert(this->IsFrontEngine() || this->IsFreeWagon());
420 
421  uint power = this->gcache.cached_power;
422  uint weight = this->gcache.cached_weight;
423  assert(weight != 0);
424  this->acceleration = Clamp(power / weight * 4, 1, 255);
425 }
426 
433 {
434  int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
435  int vehicle_pitch = 0;
436 
437  const Engine *e = this->GetEngine();
438  if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
439  reference_width = e->GetGRF()->traininfo_vehicle_width;
440  vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
441  }
442 
443  if (offset != nullptr) {
444  offset->x = ScaleGUITrad(reference_width) / 2;
445  offset->y = ScaleGUITrad(vehicle_pitch);
446  }
447  return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
448 }
449 
450 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
451 {
452  assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
453  return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
454 }
455 
463 {
464  uint8 spritenum = this->spritenum;
465 
467 
468  if (is_custom_sprite(spritenum)) {
469  GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
470  if (result->IsValid()) return;
471 
473  }
474 
475  assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
476  SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
477 
478  if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
479 
480  result->Set(sprite);
481 }
482 
483 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
484 {
485  const Engine *e = Engine::Get(engine);
486  Direction dir = rear_head ? DIR_E : DIR_W;
487  uint8 spritenum = e->u.rail.image_index;
488 
489  if (is_custom_sprite(spritenum)) {
490  GetCustomVehicleIcon(engine, dir, image_type, result);
491  if (result->IsValid()) {
492  if (e->GetGRF() != nullptr) {
494  }
495  return;
496  }
497 
498  spritenum = Engine::Get(engine)->original_image_index;
499  }
500 
501  if (rear_head) spritenum++;
502 
503  result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
504 }
505 
506 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
507 {
508  if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
509  int yf = y;
510  int yr = y;
511 
512  VehicleSpriteSeq seqf, seqr;
513  GetRailIcon(engine, false, yf, image_type, &seqf);
514  GetRailIcon(engine, true, yr, image_type, &seqr);
515 
516  Rect rectf, rectr;
517  seqf.GetBounds(&rectf);
518  seqr.GetBounds(&rectr);
519 
520  preferred_x = Clamp(preferred_x,
521  left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
522  right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
523 
524  seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
525  seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
526  } else {
527  VehicleSpriteSeq seq;
528  GetRailIcon(engine, false, y, image_type, &seq);
529 
530  Rect rect;
531  seq.GetBounds(&rect);
532  preferred_x = Clamp(preferred_x,
533  left - UnScaleGUI(rect.left),
534  right - UnScaleGUI(rect.right));
535 
536  seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
537  }
538 }
539 
549 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
550 {
551  int y = 0;
552 
553  VehicleSpriteSeq seq;
554  GetRailIcon(engine, false, y, image_type, &seq);
555 
556  Rect rect;
557  seq.GetBounds(&rect);
558 
559  width = UnScaleGUI(rect.right - rect.left + 1);
560  height = UnScaleGUI(rect.bottom - rect.top + 1);
561  xoffs = UnScaleGUI(rect.left);
562  yoffs = UnScaleGUI(rect.top);
563 
564  if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
565  GetRailIcon(engine, true, y, image_type, &seq);
566  seq.GetBounds(&rect);
567 
568  /* Calculate values relative to an imaginary center between the two sprites. */
569  width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
570  height = std::max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
571  xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
572  yoffs = std::min(yoffs, UnScaleGUI(rect.top));
573  }
574 }
575 
585 {
586  const RailVehicleInfo *rvi = &e->u.rail;
587 
588  /* Check that the wagon can drive on the track in question */
589  if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
590 
591  if (flags & DC_EXEC) {
592  Train *v = new Train();
593  *ret = v;
594  v->spritenum = rvi->image_index;
595 
596  v->engine_type = e->index;
597  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
598 
600 
601  v->direction = DiagDirToDir(dir);
602  v->tile = tile;
603 
604  int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
605  int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
606 
607  v->x_pos = x;
608  v->y_pos = y;
609  v->z_pos = GetSlopePixelZ(x, y);
610  v->owner = _current_company;
611  v->track = TRACK_BIT_DEPOT;
613 
614  v->SetWagon();
615 
616  v->SetFreeWagon();
618 
620  v->cargo_cap = rvi->capacity;
621  v->refit_cap = 0;
622 
623  v->railtype = rvi->railtype;
624 
626  v->build_year = _cur_year;
627  v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
629 
630  v->group_id = DEFAULT_GROUP;
631 
633 
634  _new_vehicle_id = v->index;
635 
636  v->UpdatePosition();
639 
641 
642  /* Try to connect the vehicle to one of free chains of wagons. */
643  for (Train *w : Train::Iterate()) {
644  if (w->tile == tile &&
645  w->IsFreeWagon() &&
646  w->engine_type == e->index &&
647  w->First() != v &&
648  !(w->vehstatus & VS_CRASHED)) {
649  if (DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE).Succeeded()) {
650  break;
651  }
652  }
653  }
654  }
655 
656  return CommandCost();
657 }
658 
660 static void NormalizeTrainVehInDepot(const Train *u)
661 {
662  for (const Train *v : Train::Iterate()) {
663  if (v->IsFreeWagon() && v->tile == u->tile &&
664  v->track == TRACK_BIT_DEPOT) {
665  if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
667  break;
668  }
669  }
670 }
671 
672 static void AddRearEngineToMultiheadedTrain(Train *v)
673 {
674  Train *u = new Train();
675  v->value >>= 1;
676  u->value = v->value;
677  u->direction = v->direction;
678  u->owner = v->owner;
679  u->tile = v->tile;
680  u->x_pos = v->x_pos;
681  u->y_pos = v->y_pos;
682  u->z_pos = v->z_pos;
683  u->track = TRACK_BIT_DEPOT;
684  u->vehstatus = v->vehstatus & ~VS_STOPPED;
685  u->spritenum = v->spritenum + 1;
686  u->cargo_type = v->cargo_type;
688  u->cargo_cap = v->cargo_cap;
689  u->refit_cap = v->refit_cap;
690  u->railtype = v->railtype;
691  u->engine_type = v->engine_type;
693  u->build_year = v->build_year;
694  u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
696  v->SetMultiheaded();
697  u->SetMultiheaded();
698  v->SetNext(u);
699  u->UpdatePosition();
700 
701  /* Now we need to link the front and rear engines together */
702  v->other_multiheaded_part = u;
703  u->other_multiheaded_part = v;
704 }
705 
716 {
717  const RailVehicleInfo *rvi = &e->u.rail;
718 
719  if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
720 
721  /* Check if depot and new engine uses the same kind of tracks *
722  * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
723  if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
724 
725  if (flags & DC_EXEC) {
727  int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
728  int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
729 
730  Train *v = new Train();
731  *ret = v;
732  v->direction = DiagDirToDir(dir);
733  v->tile = tile;
734  v->owner = _current_company;
735  v->x_pos = x;
736  v->y_pos = y;
737  v->z_pos = GetSlopePixelZ(x, y);
738  v->track = TRACK_BIT_DEPOT;
740  v->spritenum = rvi->image_index;
742  v->cargo_cap = rvi->capacity;
743  v->refit_cap = 0;
744  v->last_station_visited = INVALID_STATION;
745  v->last_loading_station = INVALID_STATION;
746 
747  v->engine_type = e->index;
748  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
749 
750  v->reliability = e->reliability;
752  v->max_age = e->GetLifeLengthInDays();
753 
754  v->railtype = rvi->railtype;
755  _new_vehicle_id = v->index;
756 
757  v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
759  v->build_year = _cur_year;
760  v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
762 
764  v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
765 
766  v->group_id = DEFAULT_GROUP;
767 
768  v->SetFrontEngine();
769  v->SetEngine();
770 
771  v->UpdatePosition();
772 
773  if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
774  AddRearEngineToMultiheadedTrain(v);
775  } else {
777  }
778 
781 
782  if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
784  }
785 
787  }
788 
789  return CommandCost();
790 }
791 
792 static Train *FindGoodVehiclePos(const Train *src)
793 {
794  EngineID eng = src->engine_type;
795  TileIndex tile = src->tile;
796 
797  for (Train *dst : Train::Iterate()) {
798  if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
799  /* check so all vehicles in the line have the same engine. */
800  Train *t = dst;
801  while (t->engine_type == eng) {
802  t = t->Next();
803  if (t == nullptr) return dst;
804  }
805  }
806  }
807 
808  return nullptr;
809 }
810 
812 typedef std::vector<Train *> TrainList;
813 
820 {
821  for (; t != nullptr; t = t->Next()) list.push_back(t);
822 }
823 
829 {
830  /* No train, nothing to do. */
831  if (list.size() == 0) return;
832 
833  Train *prev = nullptr;
834  /* Iterate over the list and rebuild it. */
835  for (Train *t : list) {
836  if (prev != nullptr) {
837  prev->SetNext(t);
838  } else if (t->Previous() != nullptr) {
839  /* Make sure the head of the train is always the first in the chain. */
840  t->Previous()->SetNext(nullptr);
841  }
842  prev = t;
843  }
844 }
845 
851 static void RemoveFromConsist(Train *part, bool chain = false)
852 {
853  Train *tail = chain ? part->Last() : part->GetLastEnginePart();
854 
855  /* Unlink at the front, but make it point to the next
856  * vehicle after the to be remove part. */
857  if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
858 
859  /* Unlink at the back */
860  tail->SetNext(nullptr);
861 }
862 
868 static void InsertInConsist(Train *dst, Train *chain)
869 {
870  /* We do not want to add something in the middle of an articulated part. */
871  assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
872 
873  chain->Last()->SetNext(dst->Next());
874  dst->SetNext(chain);
875 }
876 
882 static void NormaliseDualHeads(Train *t)
883 {
884  for (; t != nullptr; t = t->GetNextVehicle()) {
885  if (!t->IsMultiheaded() || !t->IsEngine()) continue;
886 
887  /* Make sure that there are no free cars before next engine */
888  Train *u;
889  for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
890 
891  if (u == t->other_multiheaded_part) continue;
892 
893  /* Remove the part from the 'wrong' train */
894  RemoveFromConsist(t->other_multiheaded_part);
895  /* And add it to the 'right' train */
896  InsertInConsist(u, t->other_multiheaded_part);
897  }
898 }
899 
904 static void NormaliseSubtypes(Train *chain)
905 {
906  /* Nothing to do */
907  if (chain == nullptr) return;
908 
909  /* We must be the first in the chain. */
910  assert(chain->Previous() == nullptr);
911 
912  /* Set the appropriate bits for the first in the chain. */
913  if (chain->IsWagon()) {
914  chain->SetFreeWagon();
915  } else {
916  assert(chain->IsEngine());
917  chain->SetFrontEngine();
918  }
919 
920  /* Now clear the bits for the rest of the chain */
921  for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
922  t->ClearFreeWagon();
923  t->ClearFrontEngine();
924  }
925 }
926 
936 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
937 {
938  /* Just add 'new' engines and subtract the original ones.
939  * If that's less than or equal to 0 we can be sure we did
940  * not add any engines (read: trains) along the way. */
941  if ((src != nullptr && src->IsEngine() ? 1 : 0) +
942  (dst != nullptr && dst->IsEngine() ? 1 : 0) -
943  (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
944  (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
945  return CommandCost();
946  }
947 
948  /* Get a free unit number and check whether it's within the bounds.
949  * There will always be a maximum of one new train. */
951 
952  return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
953 }
954 
961 {
962  /* No multi-part train, no need to check. */
963  if (t == nullptr || t->Next() == nullptr) return CommandCost();
964 
965  /* The maximum length for a train. For each part we decrease this by one
966  * and if the result is negative the train is simply too long. */
968 
969  /* For free-wagon chains, check if they are within the max_train_length limit. */
970  if (!t->IsEngine()) {
971  t = t->Next();
972  while (t != nullptr) {
973  allowed_len -= t->gcache.cached_veh_length;
974 
975  t = t->Next();
976  }
977 
978  if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
979  return CommandCost();
980  }
981 
982  Train *head = t;
983  Train *prev = t;
984 
985  /* Break the prev -> t link so it always holds within the loop. */
986  t = t->Next();
987  prev->SetNext(nullptr);
988 
989  /* Make sure the cache is cleared. */
990  head->InvalidateNewGRFCache();
991 
992  while (t != nullptr) {
993  allowed_len -= t->gcache.cached_veh_length;
994 
995  Train *next = t->Next();
996 
997  /* Unlink the to-be-added piece; it is already unlinked from the previous
998  * part due to the fact that the prev -> t link is broken. */
999  t->SetNext(nullptr);
1000 
1001  /* Don't check callback for articulated or rear dual headed parts */
1002  if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1003  /* Back up and clear the first_engine data to avoid using wagon override group */
1004  EngineID first_engine = t->gcache.first_engine;
1006 
1007  /* We don't want the cache to interfere. head's cache is cleared before
1008  * the loop and after each callback does not need to be cleared here. */
1009  t->InvalidateNewGRFCache();
1010 
1011  uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1012 
1013  /* Restore original first_engine data */
1014  t->gcache.first_engine = first_engine;
1015 
1016  /* We do not want to remember any cached variables from the test run */
1017  t->InvalidateNewGRFCache();
1018  head->InvalidateNewGRFCache();
1019 
1020  if (callback != CALLBACK_FAILED) {
1021  /* A failing callback means everything is okay */
1022  StringID error = STR_NULL;
1023 
1024  if (head->GetGRF()->grf_version < 8) {
1025  if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1026  if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1027  if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1028  } else {
1029  if (callback < 0x400) {
1030  error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1031  } else {
1032  switch (callback) {
1033  case 0x400: // allow if railtypes match (always the case for OpenTTD)
1034  case 0x401: // allow
1035  break;
1036 
1037  default: // unknown reason -> disallow
1038  case 0x402: // disallow attaching
1039  error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1040  break;
1041  }
1042  }
1043  }
1044 
1045  if (error != STR_NULL) return_cmd_error(error);
1046  }
1047  }
1048 
1049  /* And link it to the new part. */
1050  prev->SetNext(t);
1051  prev = t;
1052  t = next;
1053  }
1054 
1055  if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1056  return CommandCost();
1057 }
1058 
1069 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1070 {
1071  /* Check whether we may actually construct the trains. */
1072  CommandCost ret = CheckTrainAttachment(src);
1073  if (ret.Failed()) return ret;
1074  ret = CheckTrainAttachment(dst);
1075  if (ret.Failed()) return ret;
1076 
1077  /* Check whether we need to build a new train. */
1078  return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1079 }
1080 
1089 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1090 {
1091  /* First determine the front of the two resulting trains */
1092  if (*src_head == *dst_head) {
1093  /* If we aren't moving part(s) to a new train, we are just moving the
1094  * front back and there is not destination head. */
1095  *dst_head = nullptr;
1096  } else if (*dst_head == nullptr) {
1097  /* If we are moving to a new train the head of the move train would become
1098  * the head of the new vehicle. */
1099  *dst_head = src;
1100  }
1101 
1102  if (src == *src_head) {
1103  /* If we are moving the front of a train then we are, in effect, creating
1104  * a new head for the train. Point to that. Unless we are moving the whole
1105  * train in which case there is not 'source' train anymore.
1106  * In case we are a multiheaded part we want the complete thing to come
1107  * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1108  * that is followed by a rear multihead we do not want to include that. */
1109  *src_head = move_chain ? nullptr :
1110  (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1111  }
1112 
1113  /* Now it's just simply removing the part that we are going to move from the
1114  * source train and *if* the destination is a not a new train add the chain
1115  * at the destination location. */
1116  RemoveFromConsist(src, move_chain);
1117  if (*dst_head != src) InsertInConsist(dst, src);
1118 
1119  /* Now normalise the dual heads, that is move the dual heads around in such
1120  * a way that the head and rear of a dual head are in the same train */
1121  NormaliseDualHeads(*src_head);
1122  NormaliseDualHeads(*dst_head);
1123 }
1124 
1130 static void NormaliseTrainHead(Train *head)
1131 {
1132  /* Not much to do! */
1133  if (head == nullptr) return;
1134 
1135  /* Tell the 'world' the train changed. */
1136  head->ConsistChanged(CCF_ARRANGE);
1137  UpdateTrainGroupID(head);
1138 
1139  /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1140  if (!head->IsFrontEngine()) return;
1141 
1142  /* Update the refit button and window */
1145 
1146  /* If we don't have a unit number yet, set one. */
1147  if (head->unitnumber != 0) return;
1149 }
1150 
1163 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1164 {
1165  VehicleID s = GB(p1, 0, 20);
1166  VehicleID d = GB(p2, 0, 20);
1167  bool move_chain = HasBit(p1, 20);
1168 
1169  Train *src = Train::GetIfValid(s);
1170  if (src == nullptr) return CMD_ERROR;
1171 
1172  CommandCost ret = CheckOwnership(src->owner);
1173  if (ret.Failed()) return ret;
1174 
1175  /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1176  if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1177 
1178  /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1179  Train *dst;
1180  if (d == INVALID_VEHICLE) {
1181  dst = src->IsEngine() ? nullptr : FindGoodVehiclePos(src);
1182  } else {
1183  dst = Train::GetIfValid(d);
1184  if (dst == nullptr) return CMD_ERROR;
1185 
1186  CommandCost ret = CheckOwnership(dst->owner);
1187  if (ret.Failed()) return ret;
1188 
1189  /* Do not allow appending to crashed vehicles, too */
1190  if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1191  }
1192 
1193  /* if an articulated part is being handled, deal with its parent vehicle */
1194  src = src->GetFirstEnginePart();
1195  if (dst != nullptr) {
1196  dst = dst->GetFirstEnginePart();
1197  }
1198 
1199  /* don't move the same vehicle.. */
1200  if (src == dst) return CommandCost();
1201 
1202  /* locate the head of the two chains */
1203  Train *src_head = src->First();
1204  Train *dst_head;
1205  if (dst != nullptr) {
1206  dst_head = dst->First();
1207  if (dst_head->tile != src_head->tile) return CMD_ERROR;
1208  /* Now deal with articulated part of destination wagon */
1209  dst = dst->GetLastEnginePart();
1210  } else {
1211  dst_head = nullptr;
1212  }
1213 
1214  if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1215 
1216  /* When moving all wagons, we can't have the same src_head and dst_head */
1217  if (move_chain && src_head == dst_head) return CommandCost();
1218 
1219  /* When moving a multiheaded part to be place after itself, bail out. */
1220  if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1221 
1222  /* Check if all vehicles in the source train are stopped inside a depot. */
1223  if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1224 
1225  /* Check if all vehicles in the destination train are stopped inside a depot. */
1226  if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1227 
1228  /* First make a backup of the order of the trains. That way we can do
1229  * whatever we want with the order and later on easily revert. */
1230  TrainList original_src;
1231  TrainList original_dst;
1232 
1233  MakeTrainBackup(original_src, src_head);
1234  MakeTrainBackup(original_dst, dst_head);
1235 
1236  /* Also make backup of the original heads as ArrangeTrains can change them.
1237  * For the destination head we do not care if it is the same as the source
1238  * head because in that case it's just a copy. */
1239  Train *original_src_head = src_head;
1240  Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1241 
1242  /* We want this information from before the rearrangement, but execute this after the validation.
1243  * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1244  * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1245  bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1246  bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1247 
1248  /* (Re)arrange the trains in the wanted arrangement. */
1249  ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1250 
1251  if ((flags & DC_AUTOREPLACE) == 0) {
1252  /* If the autoreplace flag is set we do not need to test for the validity
1253  * because we are going to revert the train to its original state. As we
1254  * assume the original state was correct autoreplace can skip this. */
1255  CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1256  if (ret.Failed()) {
1257  /* Restore the train we had. */
1258  RestoreTrainBackup(original_src);
1259  RestoreTrainBackup(original_dst);
1260  return ret;
1261  }
1262  }
1263 
1264  /* do it? */
1265  if (flags & DC_EXEC) {
1266  /* Remove old heads from the statistics */
1267  if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1268  if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1269 
1270  /* First normalise the sub types of the chains. */
1271  NormaliseSubtypes(src_head);
1272  NormaliseSubtypes(dst_head);
1273 
1274  /* There are 14 different cases:
1275  * 1) front engine gets moved to a new train, it stays a front engine.
1276  * a) the 'next' part is a wagon that becomes a free wagon chain.
1277  * b) the 'next' part is an engine that becomes a front engine.
1278  * c) there is no 'next' part, nothing else happens
1279  * 2) front engine gets moved to another train, it is not a front engine anymore
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  * 3) front engine gets moved to later in the current 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  * 4) free wagon gets moved
1287  * a) the 'next' part is a wagon that becomes a free wagon chain.
1288  * b) the 'next' part is an engine that becomes a front engine.
1289  * c) there is no 'next' part, nothing else happens
1290  * 5) non front engine gets moved and becomes a new train, nothing else happens
1291  * 6) non front engine gets moved within a train / to another train, nothing happens
1292  * 7) wagon gets moved, nothing happens
1293  */
1294  if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1295  /* Cases #2 and #3: the front engine gets trashed. */
1301  DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1303 
1304  /* Delete orders, group stuff and the unit number as we're not the
1305  * front of any vehicle anymore. */
1306  DeleteVehicleOrders(src);
1308  src->unitnumber = 0;
1309  }
1310 
1311  /* We weren't a front engine but are becoming one. So
1312  * we should be put in the default group. */
1313  if (original_src_head != src && dst_head == src) {
1316  }
1317 
1318  /* Add new heads to statistics */
1319  if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1320  if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1321 
1322  /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1323  NormaliseTrainHead(src_head);
1324  NormaliseTrainHead(dst_head);
1325 
1326  if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1327  CheckCargoCapacity(src_head);
1328  CheckCargoCapacity(dst_head);
1329  }
1330 
1331  if (src_head != nullptr) src_head->First()->MarkDirty();
1332  if (dst_head != nullptr) dst_head->First()->MarkDirty();
1333 
1334  /* We are undoubtedly changing something in the depot and train list. */
1337  } else {
1338  /* We don't want to execute what we're just tried. */
1339  RestoreTrainBackup(original_src);
1340  RestoreTrainBackup(original_dst);
1341  }
1342 
1343  return CommandCost();
1344 }
1345 
1357 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1358 {
1359  /* Sell a chain of vehicles or not? */
1360  bool sell_chain = HasBit(data, 0);
1361 
1363  Train *first = v->First();
1364 
1365  if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1366 
1367  /* First make a backup of the order of the train. That way we can do
1368  * whatever we want with the order and later on easily revert. */
1369  TrainList original;
1370  MakeTrainBackup(original, first);
1371 
1372  /* We need to keep track of the new head and the head of what we're going to sell. */
1373  Train *new_head = first;
1374  Train *sell_head = nullptr;
1375 
1376  /* Split the train in the wanted way. */
1377  ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1378 
1379  /* We don't need to validate the second train; it's going to be sold. */
1380  CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1381  if (ret.Failed()) {
1382  /* Restore the train we had. */
1383  RestoreTrainBackup(original);
1384  return ret;
1385  }
1386 
1387  if (first->orders.list == nullptr && !OrderList::CanAllocateItem()) {
1388  /* Restore the train we had. */
1389  RestoreTrainBackup(original);
1390  return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1391  }
1392 
1394  for (Train *t = sell_head; t != nullptr; t = t->Next()) cost.AddCost(-t->value);
1395 
1396  /* do it? */
1397  if (flags & DC_EXEC) {
1398  /* First normalise the sub types of the chain. */
1399  NormaliseSubtypes(new_head);
1400 
1401  if (v == first && v->IsEngine() && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1402  /* We are selling the front engine. In this case we want to
1403  * 'give' the order, unit number and such to the new head. */
1404  new_head->orders.list = first->orders.list;
1405  new_head->AddToShared(first);
1407 
1408  /* Copy other important data from the front engine */
1410  GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1411  } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1412  OrderBackup::Backup(v, user);
1413  }
1414 
1415  /* We need to update the information about the train. */
1416  NormaliseTrainHead(new_head);
1417 
1418  /* We are undoubtedly changing something in the depot and train list. */
1421 
1422  /* Actually delete the sold 'goods' */
1423  delete sell_head;
1424  } else {
1425  /* We don't want to execute what we're just tried. */
1426  RestoreTrainBackup(original);
1427  }
1428 
1429  return cost;
1430 }
1431 
1433 {
1434  /* Set common defaults. */
1435  this->x_offs = -1;
1436  this->y_offs = -1;
1437  this->x_extent = 3;
1438  this->y_extent = 3;
1439  this->z_extent = 6;
1440  this->x_bb_offs = 0;
1441  this->y_bb_offs = 0;
1442 
1443  if (!IsDiagonalDirection(this->direction)) {
1444  static const int _sign_table[] =
1445  {
1446  /* x, y */
1447  -1, -1, // DIR_N
1448  -1, 1, // DIR_E
1449  1, 1, // DIR_S
1450  1, -1, // DIR_W
1451  };
1452 
1453  int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1454 
1455  /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1456  this->x_offs -= half_shorten * _sign_table[this->direction];
1457  this->y_offs -= half_shorten * _sign_table[this->direction + 1];
1458  this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1459  this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1460  } else {
1461  switch (this->direction) {
1462  /* Shorten southern corner of the bounding box according the vehicle length
1463  * and center the bounding box on the vehicle. */
1464  case DIR_NE:
1465  this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1466  this->x_extent = this->gcache.cached_veh_length - 1;
1467  this->x_bb_offs = -1;
1468  break;
1469 
1470  case DIR_NW:
1471  this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1472  this->y_extent = this->gcache.cached_veh_length - 1;
1473  this->y_bb_offs = -1;
1474  break;
1475 
1476  /* Move northern corner of the bounding box down according to vehicle length
1477  * and center the bounding box on the vehicle. */
1478  case DIR_SW:
1479  this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1480  this->x_extent = VEHICLE_LENGTH - 1;
1481  this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1482  break;
1483 
1484  case DIR_SE:
1485  this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1486  this->y_extent = VEHICLE_LENGTH - 1;
1487  this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1488  break;
1489 
1490  default:
1491  NOT_REACHED();
1492  }
1493  }
1494 }
1495 
1500 static void MarkTrainAsStuck(Train *v)
1501 {
1502  if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1503  /* It is the first time the problem occurred, set the "train stuck" flag. */
1504  SetBit(v->flags, VRF_TRAIN_STUCK);
1505 
1506  v->wait_counter = 0;
1507 
1508  /* Stop train */
1509  v->cur_speed = 0;
1510  v->subspeed = 0;
1511  v->SetLastSpeed();
1512 
1514  }
1515 }
1516 
1524 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1525 {
1526  uint16 flag1 = *swap_flag1;
1527  uint16 flag2 = *swap_flag2;
1528 
1529  /* Clear the flags */
1530  ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1531  ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1532  ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1533  ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1534 
1535  /* Reverse the rail-flags (if needed) */
1536  if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1537  SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1538  } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1539  SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1540  }
1541  if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1542  SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1543  } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1544  SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1545  }
1546 }
1547 
1553 {
1554  /* Reverse the direction. */
1555  if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1556 
1557  /* Call the proper EnterTile function unless we are in a wormhole. */
1558  if (v->track != TRACK_BIT_WORMHOLE) {
1559  VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1560  } else {
1561  /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1562  * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1563  * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1564  * when we shouldn't have. Check if this is the case. */
1565  TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1566  if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1567  VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1568  if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1569  /* We have just left the wormhole, possibly set the
1570  * "goingdown" bit. UpdateInclination() can be used
1571  * because we are at the border of the tile. */
1572  v->UpdatePosition();
1573  v->UpdateInclination(true, true);
1574  return;
1575  }
1576  }
1577  }
1578 
1579  v->UpdatePosition();
1580  v->UpdateViewport(true, true);
1581 }
1582 
1589 void ReverseTrainSwapVeh(Train *v, int l, int r)
1590 {
1591  Train *a, *b;
1592 
1593  /* locate vehicles to swap */
1594  for (a = v; l != 0; l--) a = a->Next();
1595  for (b = v; r != 0; r--) b = b->Next();
1596 
1597  if (a != b) {
1598  /* swap the hidden bits */
1599  {
1600  uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1601  b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1602  a->vehstatus = tmp;
1603  }
1604 
1605  Swap(a->track, b->track);
1606  Swap(a->direction, b->direction);
1607  Swap(a->x_pos, b->x_pos);
1608  Swap(a->y_pos, b->y_pos);
1609  Swap(a->tile, b->tile);
1610  Swap(a->z_pos, b->z_pos);
1611 
1612  SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1613 
1616  } else {
1617  /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1618  * This is a little bit redundant way, a->gv_flags will
1619  * be (re)set twice, but it reduces code duplication */
1620  SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1622  }
1623 }
1624 
1625 
1631 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1632 {
1633  return (v->type == VEH_TRAIN) ? v : nullptr;
1634 }
1635 
1636 
1644 {
1645  if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
1646 
1647  Train *t = Train::From(v);
1648  if (!t->IsFrontEngine()) return nullptr;
1649 
1650  TileIndex tile = *(TileIndex *)data;
1651 
1652  if (TrainApproachingCrossingTile(t) != tile) return nullptr;
1653 
1654  return t;
1655 }
1656 
1657 
1665 {
1666  assert(IsLevelCrossingTile(tile));
1667 
1669  TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1670 
1671  if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1672 
1673  dir = ReverseDiagDir(dir);
1674  tile_from = tile + TileOffsByDiagDir(dir);
1675 
1676  return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1677 }
1678 
1679 
1687 {
1688  assert(IsLevelCrossingTile(tile));
1689 
1690  /* reserved || train on crossing || train approaching crossing */
1692 
1693  if (new_state != IsCrossingBarred(tile)) {
1694  if (new_state && sound) {
1696  }
1697  SetCrossingBarred(tile, new_state);
1699  }
1700 }
1701 
1702 
1709 {
1710  if (!IsCrossingBarred(tile)) {
1711  BarCrossing(tile);
1714  }
1715 }
1716 
1717 
1724 {
1725  Train *base = v;
1726  Train *first = base; // first vehicle to move
1727  Train *last = v->Last(); // last vehicle to move
1728  uint length = CountVehiclesInChain(v);
1729 
1730  while (length > 2) {
1731  last = last->Previous();
1732  first = first->Next();
1733 
1734  int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1735 
1736  /* do not update images now
1737  * negative differential will be handled in AdvanceWagonsAfterSwap() */
1738  for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1739 
1740  base = first; // == base->Next()
1741  length -= 2;
1742  }
1743 }
1744 
1745 
1752 {
1753  /* first of all, fix the situation when the train was entering a depot */
1754  Train *dep = v; // last vehicle in front of just left depot
1755  while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1756  dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1757  }
1758 
1759  Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1760 
1761  if (leave != nullptr) {
1762  /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1763  int d = TicksToLeaveDepot(dep);
1764 
1765  if (d <= 0) {
1766  leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1767  leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1768  for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1769  }
1770  } else {
1771  dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1772  }
1773 
1774  Train *base = v;
1775  Train *first = base; // first vehicle to move
1776  Train *last = v->Last(); // last vehicle to move
1777  uint length = CountVehiclesInChain(v);
1778 
1779  /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1780  * they have already correct spacing, so we have to make sure they are moved how they should */
1781  bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1782 
1783  while (length > 2) {
1784  /* we reached vehicle (originally) in front of a depot, stop now
1785  * (we would move wagons that are already moved with new wagon length). */
1786  if (base == dep) break;
1787 
1788  /* the last wagon was that one leaving a depot, so do not move it anymore */
1789  if (last == dep) nomove = true;
1790 
1791  last = last->Previous();
1792  first = first->Next();
1793 
1794  int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1795 
1796  /* do not update images now */
1797  for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
1798 
1799  base = first; // == base->Next()
1800  length -= 2;
1801  }
1802 }
1803 
1809 {
1810  if (IsRailDepotTile(v->tile)) {
1812  }
1813 
1814  /* Clear path reservation in front if train is not stuck. */
1815  if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1816 
1817  /* Check if we were approaching a rail/road-crossing */
1819 
1820  /* count number of vehicles */
1821  int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1822 
1824 
1825  /* swap start<>end, start+1<>end-1, ... */
1826  int l = 0;
1827  do {
1828  ReverseTrainSwapVeh(v, l++, r--);
1829  } while (l <= r);
1830 
1832 
1833  if (IsRailDepotTile(v->tile)) {
1835  }
1836 
1837  ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1838 
1839  ClrBit(v->flags, VRF_REVERSING);
1840 
1841  /* recalculate cached data */
1843 
1844  /* update all images */
1845  for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
1846 
1847  /* update crossing we were approaching */
1848  if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1849 
1850  /* maybe we are approaching crossing now, after reversal */
1851  crossing = TrainApproachingCrossingTile(v);
1852  if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1853 
1854  /* If we are inside a depot after reversing, don't bother with path reserving. */
1855  if (v->track == TRACK_BIT_DEPOT) {
1856  /* Can't be stuck here as inside a depot is always a safe tile. */
1858  ClrBit(v->flags, VRF_TRAIN_STUCK);
1859  return;
1860  }
1861 
1862  /* VehicleExitDir does not always produce the desired dir for depots and
1863  * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
1864  DiagDirection dir = VehicleExitDir(v->direction, v->track);
1866 
1868  /* If we are currently on a tile with conventional signals, we can't treat the
1869  * current tile as a safe tile or we would enter a PBS block without a reservation. */
1870  bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
1872  !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
1873 
1874  /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1875  if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
1876 
1878  if (TryPathReserve(v, false, first_tile_okay)) {
1879  /* Do a look-ahead now in case our current tile was already a safe tile. */
1880  CheckNextTrainTile(v);
1881  } else if (v->current_order.GetType() != OT_LOADING) {
1882  /* Do not wait for a way out when we're still loading */
1883  MarkTrainAsStuck(v);
1884  }
1885  } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1886  /* A train not inside a PBS block can't be stuck. */
1887  ClrBit(v->flags, VRF_TRAIN_STUCK);
1888  v->wait_counter = 0;
1889  }
1890 }
1891 
1901 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1902 {
1903  Train *v = Train::GetIfValid(p1);
1904  if (v == nullptr) return CMD_ERROR;
1905 
1906  CommandCost ret = CheckOwnership(v->owner);
1907  if (ret.Failed()) return ret;
1908 
1909  if (p2 != 0) {
1910  /* turn a single unit around */
1911 
1912  if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1913  return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1914  }
1915  if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1916 
1917  Train *front = v->First();
1918  /* make sure the vehicle is stopped in the depot */
1919  if (!front->IsStoppedInDepot()) {
1920  return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1921  }
1922 
1923  if (flags & DC_EXEC) {
1924  ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1925 
1926  front->ConsistChanged(CCF_ARRANGE);
1931  }
1932  } else {
1933  /* turn the whole train around */
1934  if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
1935 
1936  if (flags & DC_EXEC) {
1937  /* Properly leave the station if we are loading and won't be loading anymore */
1938  if (v->current_order.IsType(OT_LOADING)) {
1939  const Vehicle *last = v;
1940  while (last->Next() != nullptr) last = last->Next();
1941 
1942  /* not a station || different station --> leave the station */
1943  if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
1944  v->LeaveStation();
1945  }
1946  }
1947 
1948  /* We cancel any 'skip signal at dangers' here */
1949  v->force_proceed = TFP_NONE;
1951 
1952  if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
1953  ToggleBit(v->flags, VRF_REVERSING);
1954  } else {
1955  v->cur_speed = 0;
1956  v->SetLastSpeed();
1959  }
1960  }
1961  }
1962  return CommandCost();
1963 }
1964 
1974 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1975 {
1976  Train *t = Train::GetIfValid(p1);
1977  if (t == nullptr) return CMD_ERROR;
1978 
1979  if (!t->IsPrimaryVehicle()) return CMD_ERROR;
1980 
1981  CommandCost ret = CheckOwnership(t->owner);
1982  if (ret.Failed()) return ret;
1983 
1984 
1985  if (flags & DC_EXEC) {
1986  /* If we are forced to proceed, cancel that order.
1987  * If we are marked stuck we would want to force the train
1988  * to proceed to the next signal. In the other cases we
1989  * would like to pass the signal at danger and run till the
1990  * next signal we encounter. */
1991  t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
1993  }
1994 
1995  return CommandCost();
1996 }
1997 
2005 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2006 {
2007  assert(!(v->vehstatus & VS_CRASHED));
2008 
2009  if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2010 
2011  PBSTileInfo origin = FollowTrainReservation(v);
2012  if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2013 
2015  case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2016  case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2017 
2018  default: NOT_REACHED();
2019  }
2020 }
2021 
2029 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2030 {
2031  FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2032  if (tfdd.best_length == UINT_MAX) return false;
2033 
2034  if (location != nullptr) *location = tfdd.tile;
2035  if (destination != nullptr) *destination = GetDepotIndex(tfdd.tile);
2036  if (reverse != nullptr) *reverse = tfdd.reverse;
2037 
2038  return true;
2039 }
2040 
2043 {
2044  static const SoundFx sfx[] = {
2050  };
2051 
2052  if (PlayVehicleSound(this, VSE_START)) return;
2053 
2054  EngineID engtype = this->engine_type;
2055  SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2056 }
2057 
2062 static void CheckNextTrainTile(Train *v)
2063 {
2064  /* Don't do any look-ahead if path_backoff_interval is 255. */
2065  if (_settings_game.pf.path_backoff_interval == 255) return;
2066 
2067  /* Exit if we are inside a depot. */
2068  if (v->track == TRACK_BIT_DEPOT) return;
2069 
2070  switch (v->current_order.GetType()) {
2071  /* Exit if we reached our destination depot. */
2072  case OT_GOTO_DEPOT:
2073  if (v->tile == v->dest_tile) return;
2074  break;
2075 
2076  case OT_GOTO_WAYPOINT:
2077  /* If we reached our waypoint, make sure we see that. */
2079  break;
2080 
2081  case OT_NOTHING:
2082  case OT_LEAVESTATION:
2083  case OT_LOADING:
2084  /* Exit if the current order doesn't have a destination, but the train has orders. */
2085  if (v->GetNumOrders() > 0) return;
2086  break;
2087 
2088  default:
2089  break;
2090  }
2091  /* Exit if we are on a station tile and are going to stop. */
2093 
2094  Trackdir td = v->GetVehicleTrackdir();
2095 
2096  /* On a tile with a red non-pbs signal, don't look ahead. */
2097  if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2098  !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2099  GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2100 
2101  CFollowTrackRail ft(v);
2102  if (!ft.Follow(v->tile, td)) return;
2103 
2105  /* Next tile is not reserved. */
2108  /* If the next tile is a PBS signal, try to make a reservation. */
2112  }
2113  ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, nullptr, false);
2114  }
2115  }
2116  }
2117 }
2118 
2125 {
2126  /* bail out if not all wagons are in the same depot or not in a depot at all */
2127  for (const Train *u = v; u != nullptr; u = u->Next()) {
2128  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2129  }
2130 
2131  /* if the train got no power, then keep it in the depot */
2132  if (v->gcache.cached_power == 0) {
2133  v->vehstatus |= VS_STOPPED;
2135  return true;
2136  }
2137 
2138  SigSegState seg_state;
2139 
2140  if (v->force_proceed == TFP_NONE) {
2141  /* force proceed was not pressed */
2142  if (++v->wait_counter < 37) {
2144  return true;
2145  }
2146 
2147  v->wait_counter = 0;
2148 
2150  if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2151  /* Full and no PBS signal in block or depot reserved, can't exit. */
2153  return true;
2154  }
2155  } else {
2157  }
2158 
2159  /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2160  if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2161  /* Service when depot has no reservation. */
2163  return true;
2164  }
2165 
2166  /* Only leave when we can reserve a path to our destination. */
2167  if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2168  /* No path and no force proceed. */
2170  MarkTrainAsStuck(v);
2171  return true;
2172  }
2173 
2174  SetDepotReservation(v->tile, true);
2176 
2179  v->PlayLeaveStationSound();
2180 
2181  v->track = TRACK_BIT_X;
2182  if (v->direction & 2) v->track = TRACK_BIT_Y;
2183 
2184  v->vehstatus &= ~VS_HIDDEN;
2185  v->cur_speed = 0;
2186 
2187  v->UpdateViewport(true, true);
2188  v->UpdatePosition();
2190  v->UpdateAcceleration();
2192 
2193  return false;
2194 }
2195 
2202 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2203 {
2204  DiagDirection dir = TrackdirToExitdir(track_dir);
2205 
2207  /* Are we just leaving a tunnel/bridge? */
2210 
2211  if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2212  /* Free the reservation only if no other train is on the tiles. */
2214  SetTunnelBridgeReservation(end, false);
2215 
2217  if (IsBridge(tile)) {
2219  } else {
2221  MarkTileDirtyByTile(end);
2222  }
2223  }
2224  }
2225  }
2226  } else if (IsRailStationTile(tile)) {
2227  TileIndex new_tile = TileAddByDiagDir(tile, dir);
2228  /* If the new tile is not a further tile of the same station, we
2229  * clear the reservation for the whole platform. */
2230  if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2232  }
2233  } else {
2234  /* Any other tile */
2236  }
2237 }
2238 
2244 {
2245  assert(v->IsFrontEngine());
2246 
2247  TileIndex tile = v->tile;
2248  Trackdir td = v->GetVehicleTrackdir();
2249  bool free_tile = !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2250  StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2251 
2252  /* Can't be holding a reservation if we enter a depot. */
2254  if (v->track == TRACK_BIT_DEPOT) {
2255  /* Front engine is in a depot. We enter if some part is not in the depot. */
2256  for (const Train *u = v; u != nullptr; u = u->Next()) {
2257  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2258  }
2259  }
2260  /* Don't free reservation if it's not ours. */
2262 
2264  while (ft.Follow(tile, td)) {
2265  tile = ft.m_new_tile;
2267  td = RemoveFirstTrackdir(&bits);
2268  assert(bits == TRACKDIR_BIT_NONE);
2269 
2270  if (!IsValidTrackdir(td)) break;
2271 
2272  if (IsTileType(tile, MP_RAILWAY)) {
2273  if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2274  /* Conventional signal along trackdir: remove reservation and stop. */
2276  break;
2277  }
2278  if (HasPbsSignalOnTrackdir(tile, td)) {
2280  /* Red PBS signal? Can't be our reservation, would be green then. */
2281  break;
2282  } else {
2283  /* Turn the signal back to red. */
2286  }
2288  break;
2289  }
2290  }
2291 
2292  /* Don't free first station/bridge/tunnel if we are on it. */
2293  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);
2294 
2295  free_tile = true;
2296  }
2297 }
2298 
2299 static const byte _initial_tile_subcoord[6][4][3] = {
2300 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2301 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2302 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2303 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2304 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2305 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2306 };
2307 
2320 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2321 {
2323  case VPF_NPF: return NPFTrainChooseTrack(v, path_found, do_track_reservation, dest);
2324  case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2325 
2326  default: NOT_REACHED();
2327  }
2328 }
2329 
2335 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2336 {
2337  PBSTileInfo origin = FollowTrainReservation(v);
2338 
2339  CFollowTrackRail ft(v);
2340 
2341  TileIndex tile = origin.tile;
2342  Trackdir cur_td = origin.trackdir;
2343  while (ft.Follow(tile, cur_td)) {
2345  /* Possible signal tile. */
2347  }
2348 
2351  if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2352  }
2353 
2354  /* Station, depot or waypoint are a possible target. */
2355  bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2356  if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2357  /* Choice found or possible target encountered.
2358  * On finding a possible target, we need to stop and let the pathfinder handle the
2359  * remaining path. This is because we don't know if this target is in one of our
2360  * orders, so we might cause pathfinding to fail later on if we find a choice.
2361  * This failure would cause a bogous call to TryReserveSafePath which might reserve
2362  * a wrong path not leading to our next destination. */
2364 
2365  /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2366  * actually starts its search at the first unreserved tile. */
2368 
2369  /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2370  if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2371  if (enterdir != nullptr) *enterdir = ft.m_exitdir;
2372  return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2373  }
2374 
2375  tile = ft.m_new_tile;
2376  cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2377 
2378  if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2379  bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2380  if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2381  /* Safe position is all good, path valid and okay. */
2382  return PBSTileInfo(tile, cur_td, true);
2383  }
2384 
2385  if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2386  }
2387 
2388  if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2389  /* End of line, path valid and okay. */
2390  return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2391  }
2392 
2393  /* Sorry, can't reserve path, back out. */
2394  tile = origin.tile;
2395  cur_td = origin.trackdir;
2396  TileIndex stopped = ft.m_old_tile;
2397  Trackdir stopped_td = ft.m_old_td;
2398  while (tile != stopped || cur_td != stopped_td) {
2399  if (!ft.Follow(tile, cur_td)) break;
2400 
2403  assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2404  }
2406 
2407  tile = ft.m_new_tile;
2408  cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2409 
2411  }
2412 
2413  /* Path invalid. */
2414  return PBSTileInfo();
2415 }
2416 
2427 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2428 {
2430  case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_railtype);
2431  case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2432 
2433  default: NOT_REACHED();
2434  }
2435 }
2436 
2439 private:
2440  Train *v;
2441  Order old_order;
2442  TileIndex old_dest_tile;
2443  StationID old_last_station_visited;
2444  VehicleOrderID index;
2445  bool suppress_implicit_orders;
2446 
2447 public:
2448  VehicleOrderSaver(Train *_v) :
2449  v(_v),
2450  old_order(_v->current_order),
2451  old_dest_tile(_v->dest_tile),
2452  old_last_station_visited(_v->last_station_visited),
2453  index(_v->cur_real_order_index),
2454  suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2455  {
2456  }
2457 
2459  {
2460  this->v->current_order = this->old_order;
2461  this->v->dest_tile = this->old_dest_tile;
2462  this->v->last_station_visited = this->old_last_station_visited;
2463  SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2464  }
2465 
2471  bool SwitchToNextOrder(bool skip_first)
2472  {
2473  if (this->v->GetNumOrders() == 0) return false;
2474 
2475  if (skip_first) ++this->index;
2476 
2477  int depth = 0;
2478 
2479  do {
2480  /* Wrap around. */
2481  if (this->index >= this->v->GetNumOrders()) this->index = 0;
2482 
2483  Order *order = this->v->GetOrder(this->index);
2484  assert(order != nullptr);
2485 
2486  switch (order->GetType()) {
2487  case OT_GOTO_DEPOT:
2488  /* Skip service in depot orders when the train doesn't need service. */
2489  if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2490  FALLTHROUGH;
2491  case OT_GOTO_STATION:
2492  case OT_GOTO_WAYPOINT:
2493  this->v->current_order = *order;
2494  return UpdateOrderDest(this->v, order, 0, true);
2495  case OT_CONDITIONAL: {
2496  VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2497  if (next != INVALID_VEH_ORDER_ID) {
2498  depth++;
2499  this->index = next;
2500  /* Don't increment next, so no break here. */
2501  continue;
2502  }
2503  break;
2504  }
2505  default:
2506  break;
2507  }
2508  /* Don't increment inside the while because otherwise conditional
2509  * orders can lead to an infinite loop. */
2510  ++this->index;
2511  depth++;
2512  } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2513 
2514  return false;
2515  }
2516 };
2517 
2518 /* choose a track */
2519 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2520 {
2521  Track best_track = INVALID_TRACK;
2522  bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2523  bool changed_signal = false;
2524 
2525  assert((tracks & ~TRACK_BIT_MASK) == 0);
2526 
2527  if (got_reservation != nullptr) *got_reservation = false;
2528 
2529  /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2530  TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2531  /* Do we have a suitable reserved track? */
2532  if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2533 
2534  /* Quick return in case only one possible track is available */
2535  if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2536  Track track = FindFirstTrack(tracks);
2537  /* We need to check for signals only here, as a junction tile can't have signals. */
2538  if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2539  do_track_reservation = true;
2540  changed_signal = true;
2542  } else if (!do_track_reservation) {
2543  return track;
2544  }
2545  best_track = track;
2546  }
2547 
2548  PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2549  DiagDirection dest_enterdir = enterdir;
2550  if (do_track_reservation) {
2551  res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2552  if (res_dest.tile == INVALID_TILE) {
2553  /* Reservation failed? */
2554  if (mark_stuck) MarkTrainAsStuck(v);
2555  if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2556  return FindFirstTrack(tracks);
2557  }
2558  if (res_dest.okay) {
2559  /* Got a valid reservation that ends at a safe target, quick exit. */
2560  if (got_reservation != nullptr) *got_reservation = true;
2561  if (changed_signal) MarkTileDirtyByTile(tile);
2563  return best_track;
2564  }
2565 
2566  /* Check if the train needs service here, so it has a chance to always find a depot.
2567  * Also check if the current order is a service order so we don't reserve a path to
2568  * the destination but instead to the next one if service isn't needed. */
2570  if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2571  }
2572 
2573  /* Save the current train order. The destructor will restore the old order on function exit. */
2574  VehicleOrderSaver orders(v);
2575 
2576  /* If the current tile is the destination of the current order and
2577  * a reservation was requested, advance to the next order.
2578  * Don't advance on a depot order as depots are always safe end points
2579  * for a path and no look-ahead is necessary. This also avoids a
2580  * problem with depot orders not part of the order list when the
2581  * order list itself is empty. */
2582  if (v->current_order.IsType(OT_LEAVESTATION)) {
2583  orders.SwitchToNextOrder(false);
2584  } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2585  v->current_order.IsType(OT_GOTO_STATION) ?
2587  v->tile == v->dest_tile))) {
2588  orders.SwitchToNextOrder(true);
2589  }
2590 
2591  if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2592  /* Pathfinders are able to tell that route was only 'guessed'. */
2593  bool path_found = true;
2594  TileIndex new_tile = res_dest.tile;
2595 
2596  Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2597  if (new_tile == tile) best_track = next_track;
2598  v->HandlePathfindingResult(path_found);
2599  }
2600 
2601  /* No track reservation requested -> finished. */
2602  if (!do_track_reservation) return best_track;
2603 
2604  /* A path was found, but could not be reserved. */
2605  if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2606  if (mark_stuck) MarkTrainAsStuck(v);
2608  return best_track;
2609  }
2610 
2611  /* No possible reservation target found, we are probably lost. */
2612  if (res_dest.tile == INVALID_TILE) {
2613  /* Try to find any safe destination. */
2614  PBSTileInfo origin = FollowTrainReservation(v);
2615  if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2616  TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2617  best_track = FindFirstTrack(res);
2619  if (got_reservation != nullptr) *got_reservation = true;
2620  if (changed_signal) MarkTileDirtyByTile(tile);
2621  } else {
2623  if (mark_stuck) MarkTrainAsStuck(v);
2624  }
2625  return best_track;
2626  }
2627 
2628  if (got_reservation != nullptr) *got_reservation = true;
2629 
2630  /* Reservation target found and free, check if it is safe. */
2631  while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2632  /* Extend reservation until we have found a safe position. */
2633  DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2634  TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2636  if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2637  reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2638  }
2639 
2640  /* Get next order with destination. */
2641  if (orders.SwitchToNextOrder(true)) {
2642  PBSTileInfo cur_dest;
2643  bool path_found;
2644  DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
2645  if (cur_dest.tile != INVALID_TILE) {
2646  res_dest = cur_dest;
2647  if (res_dest.okay) continue;
2648  /* Path found, but could not be reserved. */
2650  if (mark_stuck) MarkTrainAsStuck(v);
2651  if (got_reservation != nullptr) *got_reservation = false;
2652  changed_signal = false;
2653  break;
2654  }
2655  }
2656  /* No order or no safe position found, try any position. */
2657  if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2659  if (mark_stuck) MarkTrainAsStuck(v);
2660  if (got_reservation != nullptr) *got_reservation = false;
2661  changed_signal = false;
2662  }
2663  break;
2664  }
2665 
2667 
2668  if (changed_signal) MarkTileDirtyByTile(tile);
2669 
2670  return best_track;
2671 }
2672 
2681 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2682 {
2683  assert(v->IsFrontEngine());
2684 
2685  /* We have to handle depots specially as the track follower won't look
2686  * at the depot tile itself but starts from the next tile. If we are still
2687  * inside the depot, a depot reservation can never be ours. */
2688  if (v->track == TRACK_BIT_DEPOT) {
2689  if (HasDepotReservation(v->tile)) {
2690  if (mark_as_stuck) MarkTrainAsStuck(v);
2691  return false;
2692  } else {
2693  /* Depot not reserved, but the next tile might be. */
2695  if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2696  }
2697  }
2698 
2699  Vehicle *other_train = nullptr;
2700  PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2701  /* The path we are driving on is already blocked by some other train.
2702  * This can only happen in certain situations when mixing path and
2703  * block signals or when changing tracks and/or signals.
2704  * Exit here as doing any further reservations will probably just
2705  * make matters worse. */
2706  if (other_train != nullptr && other_train->index != v->index) {
2707  if (mark_as_stuck) MarkTrainAsStuck(v);
2708  return false;
2709  }
2710  /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2711  if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2712  /* Can't be stuck then. */
2714  ClrBit(v->flags, VRF_TRAIN_STUCK);
2715  return true;
2716  }
2717 
2718  /* If we are in a depot, tentatively reserve the depot. */
2719  if (v->track == TRACK_BIT_DEPOT) {
2720  SetDepotReservation(v->tile, true);
2722  }
2723 
2724  DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2725  TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2727 
2729 
2730  bool res_made = false;
2731  ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2732 
2733  if (!res_made) {
2734  /* Free the depot reservation as well. */
2735  if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2736  return false;
2737  }
2738 
2739  if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2740  v->wait_counter = 0;
2742  }
2743  ClrBit(v->flags, VRF_TRAIN_STUCK);
2744  return true;
2745 }
2746 
2747 
2748 static bool CheckReverseTrain(const Train *v)
2749 {
2751  v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2752  !(v->direction & 1)) {
2753  return false;
2754  }
2755 
2756  assert(v->track != TRACK_BIT_NONE);
2757 
2759  case VPF_NPF: return NPFTrainCheckReverse(v);
2760  case VPF_YAPF: return YapfTrainCheckReverse(v);
2761 
2762  default: NOT_REACHED();
2763  }
2764 }
2765 
2772 {
2773  if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2774 
2775  const Station *st = Station::Get(station);
2776  if (!(st->facilities & FACIL_TRAIN)) {
2777  /* The destination station has no trainstation tiles. */
2778  this->IncrementRealOrderIndex();
2779  return 0;
2780  }
2781 
2782  return st->xy;
2783 }
2784 
2787 {
2788  Train *v = this;
2789  do {
2790  v->colourmap = PAL_NONE;
2791  v->UpdateViewport(true, false);
2792  } while ((v = v->Next()) != nullptr);
2793 
2794  /* need to update acceleration and cached values since the goods on the train changed. */
2795  this->CargoChanged();
2796  this->UpdateAcceleration();
2797 }
2798 
2807 {
2809  default: NOT_REACHED();
2810  case AM_ORIGINAL:
2811  return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2812 
2813  case AM_REALISTIC:
2814  return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2815  }
2816 }
2817 
2823 static void TrainEnterStation(Train *v, StationID station)
2824 {
2825  v->last_station_visited = station;
2826 
2827  /* check if a train ever visited this station before */
2828  Station *st = Station::Get(station);
2829  if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2830  st->had_vehicle_of_type |= HVOT_TRAIN;
2831  SetDParam(0, st->index);
2833  STR_NEWS_FIRST_TRAIN_ARRIVAL,
2835  v->index,
2836  st->index
2837  );
2838  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2839  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2840  }
2841 
2842  v->force_proceed = TFP_NONE;
2844 
2845  v->BeginLoading();
2846 
2848  TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2849 }
2850 
2851 /* Check if the vehicle is compatible with the specified tile */
2852 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
2853 {
2854  return IsTileOwner(tile, v->owner) &&
2855  (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
2856 }
2857 
2860  byte small_turn;
2861  byte large_turn;
2862  byte z_up;
2863  byte z_down;
2864 };
2865 
2868  /* normal accel */
2869  {256 / 4, 256 / 2, 256 / 4, 2},
2870  {256 / 4, 256 / 2, 256 / 4, 2},
2871  {0, 256 / 2, 256 / 4, 2},
2872 };
2873 
2879 static inline void AffectSpeedByZChange(Train *v, int old_z)
2880 {
2881  if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2882 
2884 
2885  if (old_z < v->z_pos) {
2886  v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2887  } else {
2888  uint16 spd = v->cur_speed + asp->z_down;
2889  if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2890  }
2891 }
2892 
2893 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
2894 {
2895  if (IsTileType(tile, MP_RAILWAY) &&
2898  Trackdir trackdir = FindFirstTrackdir(tracks);
2899  if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
2900  /* A PBS block with a non-PBS signal facing us? */
2901  if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
2902  }
2903  }
2904  return false;
2905 }
2906 
2909 {
2910  for (const Train *u = this; u != nullptr; u = u->Next()) {
2911  switch (u->track) {
2912  case TRACK_BIT_WORMHOLE:
2914  break;
2915  case TRACK_BIT_DEPOT:
2916  break;
2917  default:
2918  TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
2919  break;
2920  }
2921  }
2922 }
2923 
2930 uint Train::Crash(bool flooded)
2931 {
2932  uint pass = 0;
2933  if (this->IsFrontEngine()) {
2934  pass += 2; // driver
2935 
2936  /* Remove the reserved path in front of the train if it is not stuck.
2937  * Also clear all reserved tracks the train is currently on. */
2938  if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
2939  for (const Train *v = this; v != nullptr; v = v->Next()) {
2941  if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
2942  /* ClearPathReservation will not free the wormhole exit
2943  * if the train has just entered the wormhole. */
2945  }
2946  }
2947 
2948  /* we may need to update crossing we were approaching,
2949  * but must be updated after the train has been marked crashed */
2950  TileIndex crossing = TrainApproachingCrossingTile(this);
2951  if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2952 
2953  /* Remove the loading indicators (if any) */
2955  }
2956 
2957  pass += this->GroundVehicleBase::Crash(flooded);
2958 
2959  this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
2960  return pass;
2961 }
2962 
2969 static uint TrainCrashed(Train *v)
2970 {
2971  uint num = 0;
2972 
2973  /* do not crash train twice */
2974  if (!(v->vehstatus & VS_CRASHED)) {
2975  num = v->Crash();
2976  AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2977  Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2978  }
2979 
2980  /* Try to re-reserve track under already crashed train too.
2981  * Crash() clears the reservation! */
2983 
2984  return num;
2985 }
2986 
2990  uint num;
2991 };
2992 
2999 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3000 {
3002 
3003  /* not a train or in depot */
3004  if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
3005 
3006  /* do not crash into trains of another company. */
3007  if (v->owner != tcc->v->owner) return nullptr;
3008 
3009  /* get first vehicle now to make most usual checks faster */
3010  Train *coll = Train::From(v)->First();
3011 
3012  /* can't collide with own wagons */
3013  if (coll == tcc->v) return nullptr;
3014 
3015  int x_diff = v->x_pos - tcc->v->x_pos;
3016  int y_diff = v->y_pos - tcc->v->y_pos;
3017 
3018  /* Do fast calculation to check whether trains are not in close vicinity
3019  * and quickly reject trains distant enough for any collision.
3020  * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3021  * Differences are then ORed and then we check for any higher bits */
3022  uint hash = (y_diff + 7) | (x_diff + 7);
3023  if (hash & ~15) return nullptr;
3024 
3025  /* Slower check using multiplication */
3026  int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3027  if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return nullptr;
3028 
3029  /* Happens when there is a train under bridge next to bridge head */
3030  if (abs(v->z_pos - tcc->v->z_pos) > 5) return nullptr;
3031 
3032  /* crash both trains */
3033  tcc->num += TrainCrashed(tcc->v);
3034  tcc->num += TrainCrashed(coll);
3035 
3036  return nullptr; // continue searching
3037 }
3038 
3047 {
3048  /* can't collide in depot */
3049  if (v->track == TRACK_BIT_DEPOT) return false;
3050 
3051  assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3052 
3053  TrainCollideChecker tcc;
3054  tcc.v = v;
3055  tcc.num = 0;
3056 
3057  /* find colliding vehicles */
3058  if (v->track == TRACK_BIT_WORMHOLE) {
3061  } else {
3063  }
3064 
3065  /* any dead -> no crash */
3066  if (tcc.num == 0) return false;
3067 
3068  SetDParam(0, tcc.num);
3069  AddTileNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->tile);
3070 
3071  ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3072  if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, v);
3073  return true;
3074 }
3075 
3076 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3077 {
3078  if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
3079 
3080  Train *t = Train::From(v);
3081  DiagDirection exitdir = *(DiagDirection *)data;
3082 
3083  /* not front engine of a train, inside wormhole or depot, crashed */
3084  if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr;
3085 
3086  if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return nullptr;
3087 
3088  return t;
3089 }
3090 
3098 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3099 {
3100  Train *first = v->First();
3101  Train *prev;
3102  bool direction_changed = false; // has direction of any part changed?
3103 
3104  /* For every vehicle after and including the given vehicle */
3105  for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3106  DiagDirection enterdir = DIAGDIR_BEGIN;
3107  bool update_signals_crossing = false; // will we update signals or crossing state?
3108 
3110  if (v->track != TRACK_BIT_WORMHOLE) {
3111  /* Not inside tunnel */
3112  if (gp.old_tile == gp.new_tile) {
3113  /* Staying in the old tile */
3114  if (v->track == TRACK_BIT_DEPOT) {
3115  /* Inside depot */
3116  gp.x = v->x_pos;
3117  gp.y = v->y_pos;
3118  } else {
3119  /* Not inside depot */
3120 
3121  /* Reverse when we are at the end of the track already, do not move to the new position */
3122  if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3123 
3124  uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3125  if (HasBit(r, VETS_CANNOT_ENTER)) {
3126  goto invalid_rail;
3127  }
3128  if (HasBit(r, VETS_ENTERED_STATION)) {
3129  /* The new position is the end of the platform */
3131  }
3132  }
3133  } else {
3134  /* A new tile is about to be entered. */
3135 
3136  /* Determine what direction we're entering the new tile from */
3137  enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3138  assert(IsValidDiagDirection(enterdir));
3139 
3140  /* Get the status of the tracks in the new tile and mask
3141  * away the bits that aren't reachable. */
3142  TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3143  TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3144 
3145  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3146  TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3147 
3148  TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3149  if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3150  /* We allow wagons to make 90 deg turns, because forbid_90_deg
3151  * can be switched on halfway a turn */
3152  bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3153  }
3154 
3155  if (bits == TRACK_BIT_NONE) goto invalid_rail;
3156 
3157  /* Check if the new tile constrains tracks that are compatible
3158  * with the current train, if not, bail out. */
3159  if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3160 
3161  TrackBits chosen_track;
3162  if (prev == nullptr) {
3163  /* Currently the locomotive is active. Determine which one of the
3164  * available tracks to choose */
3165  chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
3166  assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3167 
3168  if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3169  /* For each signal we find decrease the counter by one.
3170  * We start at two, so the first signal we pass decreases
3171  * this to one, then if we reach the next signal it is
3172  * decreased to zero and we won't pass that new signal. */
3173  Trackdir dir = FindFirstTrackdir(trackdirbits);
3174  if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3176  GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3177  /* However, we do not want to be stopped by PBS signals
3178  * entered via the back. */
3179  v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3181  }
3182  }
3183 
3184  /* Check if it's a red signal and that force proceed is not clicked. */
3185  if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3186  /* In front of a red signal */
3187  Trackdir i = FindFirstTrackdir(trackdirbits);
3188 
3189  /* Don't handle stuck trains here. */
3190  if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3191 
3193  v->cur_speed = 0;
3194  v->subspeed = 0;
3195  v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3197  } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3198  v->cur_speed = 0;
3199  v->subspeed = 0;
3200  v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3202  DiagDirection exitdir = TrackdirToExitdir(i);
3203  TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3204 
3205  exitdir = ReverseDiagDir(exitdir);
3206 
3207  /* check if a train is waiting on the other side */
3208  if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3209  }
3210  }
3211 
3212  /* If we would reverse but are currently in a PBS block and
3213  * reversing of stuck trains is disabled, don't reverse.
3214  * This does not apply if the reason for reversing is a one-way
3215  * signal blocking us, because a train would then be stuck forever. */
3217  UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3218  v->wait_counter = 0;
3219  return false;
3220  }
3221  goto reverse_train_direction;
3222  } else {
3223  TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3224  }
3225  } else {
3226  /* The wagon is active, simply follow the prev vehicle. */
3227  if (prev->tile == gp.new_tile) {
3228  /* Choose the same track as prev */
3229  if (prev->track == TRACK_BIT_WORMHOLE) {
3230  /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3231  * However, just choose the track into the wormhole. */
3232  assert(IsTunnel(prev->tile));
3233  chosen_track = bits;
3234  } else {
3235  chosen_track = prev->track;
3236  }
3237  } else {
3238  /* Choose the track that leads to the tile where prev is.
3239  * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3240  * I.e. when the tile between them has only space for a single vehicle like
3241  * 1) horizontal/vertical track tiles and
3242  * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3243  * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3244  */
3245  static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3250  };
3251  DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3252  assert(IsValidDiagDirection(exitdir));
3253  chosen_track = _connecting_track[enterdir][exitdir];
3254  }
3255  chosen_track &= bits;
3256  }
3257 
3258  /* Make sure chosen track is a valid track */
3259  assert(
3260  chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3261  chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3262  chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3263 
3264  /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3265  const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3266  gp.x = (gp.x & ~0xF) | b[0];
3267  gp.y = (gp.y & ~0xF) | b[1];
3268  Direction chosen_dir = (Direction)b[2];
3269 
3270  /* Call the landscape function and tell it that the vehicle entered the tile */
3271  uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3272  if (HasBit(r, VETS_CANNOT_ENTER)) {
3273  goto invalid_rail;
3274  }
3275 
3276  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3277  Track track = FindFirstTrack(chosen_track);
3278  Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3279  if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3282  }
3283 
3284  /* Clear any track reservation when the last vehicle leaves the tile */
3285  if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3286 
3287  v->tile = gp.new_tile;
3288 
3291  }
3292 
3293  v->track = chosen_track;
3294  assert(v->track);
3295  }
3296 
3297  /* We need to update signal status, but after the vehicle position hash
3298  * has been updated by UpdateInclination() */
3299  update_signals_crossing = true;
3300 
3301  if (chosen_dir != v->direction) {
3302  if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3304  DirDiff diff = DirDifference(v->direction, chosen_dir);
3305  v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3306  }
3307  direction_changed = true;
3308  v->direction = chosen_dir;
3309  }
3310 
3311  if (v->IsFrontEngine()) {
3312  v->wait_counter = 0;
3313 
3314  /* If we are approaching a crossing that is reserved, play the sound now. */
3316  if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3317 
3318  /* Always try to extend the reservation when entering a tile. */
3319  CheckNextTrainTile(v);
3320  }
3321 
3322  if (HasBit(r, VETS_ENTERED_STATION)) {
3323  /* The new position is the location where we want to stop */
3325  }
3326  }
3327  } else {
3329  /* Perform look-ahead on tunnel exit. */
3330  if (v->IsFrontEngine()) {
3332  CheckNextTrainTile(v);
3333  }
3334  /* Prevent v->UpdateInclination() being called with wrong parameters.
3335  * This could happen if the train was reversed inside the tunnel/bridge. */
3336  if (gp.old_tile == gp.new_tile) {
3338  }
3339  } else {
3340  v->x_pos = gp.x;
3341  v->y_pos = gp.y;
3342  v->UpdatePosition();
3343  if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3344  continue;
3345  }
3346  }
3347 
3348  /* update image of train, as well as delta XY */
3349  v->UpdateDeltaXY();
3350 
3351  v->x_pos = gp.x;
3352  v->y_pos = gp.y;
3353  v->UpdatePosition();
3354 
3355  /* update the Z position of the vehicle */
3356  int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3357 
3358  if (prev == nullptr) {
3359  /* This is the first vehicle in the train */
3360  AffectSpeedByZChange(v, old_z);
3361  }
3362 
3363  if (update_signals_crossing) {
3364  if (v->IsFrontEngine()) {
3365  if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3366  /* We are entering a block with PBS signals right now, but
3367  * not through a PBS signal. This means we don't have a
3368  * reservation right now. As a conventional signal will only
3369  * ever be green if no other train is in the block, getting
3370  * a path should always be possible. If the player built
3371  * such a strange network that it is not possible, the train
3372  * will be marked as stuck and the player has to deal with
3373  * the problem. */
3374  if ((!HasReservedTracks(gp.new_tile, v->track) &&
3375  !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3376  !TryPathReserve(v)) {
3377  MarkTrainAsStuck(v);
3378  }
3379  }
3380  }
3381 
3382  /* Signals can only change when the first
3383  * (above) or the last vehicle moves. */
3384  if (v->Next() == nullptr) {
3385  TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3387  }
3388  }
3389 
3390  /* Do not check on every tick to save some computing time. */
3392  }
3393 
3394  if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3395 
3396  return true;
3397 
3398 invalid_rail:
3399  /* We've reached end of line?? */
3400  if (prev != nullptr) error("Disconnecting train");
3401 
3402 reverse_train_direction:
3403  if (reverse) {
3404  v->wait_counter = 0;
3405  v->cur_speed = 0;
3406  v->subspeed = 0;
3408  }
3409 
3410  return false;
3411 }
3412 
3420 {
3421  TrackBits *trackbits = (TrackBits *)data;
3422 
3423  if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3424  TrackBits train_tbits = Train::From(v)->track;
3425  if (train_tbits == TRACK_BIT_WORMHOLE) {
3426  /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3428  } else if (train_tbits != TRACK_BIT_DEPOT) {
3429  *trackbits |= train_tbits;
3430  }
3431  }
3432 
3433  return nullptr;
3434 }
3435 
3443 static void DeleteLastWagon(Train *v)
3444 {
3445  Train *first = v->First();
3446 
3447  /* Go to the last wagon and delete the link pointing there
3448  * *u is then the one-before-last wagon, and *v the last
3449  * one which will physically be removed */
3450  Train *u = v;
3451  for (; v->Next() != nullptr; v = v->Next()) u = v;
3452  u->SetNext(nullptr);
3453 
3454  if (first != v) {
3455  /* Recalculate cached train properties */
3456  first->ConsistChanged(CCF_ARRANGE);
3457  /* Update the depot window if the first vehicle is in depot -
3458  * if v == first, then it is updated in PreDestructor() */
3459  if (first->track == TRACK_BIT_DEPOT) {
3461  }
3462  v->last_station_visited = first->last_station_visited; // for PreDestructor
3463  }
3464 
3465  /* 'v' shouldn't be accessed after it has been deleted */
3466  TrackBits trackbits = v->track;
3467  TileIndex tile = v->tile;
3468  Owner owner = v->owner;
3469 
3470  delete v;
3471  v = nullptr; // make sure nobody will try to read 'v' anymore
3472 
3473  if (trackbits == TRACK_BIT_WORMHOLE) {
3474  /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3476  }
3477 
3478  Track track = TrackBitsToTrack(trackbits);
3479  if (HasReservedTracks(tile, trackbits)) {
3480  UnreserveRailTrack(tile, track);
3481 
3482  /* If there are still crashed vehicles on the tile, give the track reservation to them */
3483  TrackBits remaining_trackbits = TRACK_BIT_NONE;
3484  FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3485 
3486  /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3487  assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3488  Track t;
3489  FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
3490  }
3491 
3492  /* check if the wagon was on a road/rail-crossing */
3493  if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3494 
3495  /* Update signals */
3496  if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3498  } else {
3499  SetSignalsOnBothDir(tile, track, owner);
3500  }
3501 }
3502 
3508 {
3509  static const DirDiff delta[] = {
3511  };
3512 
3513  do {
3514  /* We don't need to twist around vehicles if they're not visible */
3515  if (!(v->vehstatus & VS_HIDDEN)) {
3516  v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3517  /* Refrain from updating the z position of the vehicle when on
3518  * a bridge, because UpdateInclination() will put the vehicle under
3519  * the bridge in that case */
3520  if (v->track != TRACK_BIT_WORMHOLE) {
3521  v->UpdatePosition();
3522  v->UpdateInclination(false, true);
3523  } else {
3524  v->UpdateViewport(false, true);
3525  }
3526  }
3527  } while ((v = v->Next()) != nullptr);
3528 }
3529 
3535 static bool HandleCrashedTrain(Train *v)
3536 {
3537  int state = ++v->crash_anim_pos;
3538 
3539  if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3541  }
3542 
3543  uint32 r;
3544  if (state <= 200 && Chance16R(1, 7, r)) {
3545  int index = (r * 10 >> 16);
3546 
3547  Vehicle *u = v;
3548  do {
3549  if (--index < 0) {
3550  r = Random();
3551 
3553  GB(r, 8, 3) + 2,
3554  GB(r, 16, 3) + 2,
3555  GB(r, 0, 3) + 5,
3557  break;
3558  }
3559  } while ((u = u->Next()) != nullptr);
3560  }
3561 
3562  if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3563 
3564  if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3565  bool ret = v->Next() != nullptr;
3566  DeleteLastWagon(v);
3567  return ret;
3568  }
3569 
3570  return true;
3571 }
3572 
3574 static const uint16 _breakdown_speeds[16] = {
3575  225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3576 };
3577 
3578 
3587 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3588 {
3589  /* Calc position within the current tile */
3590  uint x = v->x_pos & 0xF;
3591  uint y = v->y_pos & 0xF;
3592 
3593  /* for diagonal directions, 'x' will be 0..15 -
3594  * for other directions, it will be 1, 3, 5, ..., 15 */
3595  switch (v->direction) {
3596  case DIR_N : x = ~x + ~y + 25; break;
3597  case DIR_NW: x = y; FALLTHROUGH;
3598  case DIR_NE: x = ~x + 16; break;
3599  case DIR_E : x = ~x + y + 9; break;
3600  case DIR_SE: x = y; break;
3601  case DIR_S : x = x + y - 7; break;
3602  case DIR_W : x = ~y + x + 9; break;
3603  default: break;
3604  }
3605 
3606  /* Do not reverse when approaching red signal. Make sure the vehicle's front
3607  * does not cross the tile boundary when we do reverse, but as the vehicle's
3608  * location is based on their center, use half a vehicle's length as offset.
3609  * Multiply the half-length by two for straight directions to compensate that
3610  * we only get odd x offsets there. */
3611  if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3612  /* we are too near the tile end, reverse now */
3613  v->cur_speed = 0;
3614  if (reverse) ReverseTrainDirection(v);
3615  return false;
3616  }
3617 
3618  /* slow down */
3620  uint16 break_speed = _breakdown_speeds[x & 0xF];
3621  if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3622 
3623  return true;
3624 }
3625 
3626 
3632 static bool TrainCanLeaveTile(const Train *v)
3633 {
3634  /* Exit if inside a tunnel/bridge or a depot */
3635  if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3636 
3637  TileIndex tile = v->tile;
3638 
3639  /* entering a tunnel/bridge? */
3640  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3642  if (DiagDirToDir(dir) == v->direction) return false;
3643  }
3644 
3645  /* entering a depot? */
3646  if (IsRailDepotTile(tile)) {
3648  if (DiagDirToDir(dir) == v->direction) return false;
3649  }
3650 
3651  return true;
3652 }
3653 
3654 
3663 {
3664  assert(v->IsFrontEngine());
3665  assert(!(v->vehstatus & VS_CRASHED));
3666 
3667  if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3668 
3669  DiagDirection dir = VehicleExitDir(v->direction, v->track);
3670  TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3671 
3672  /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3673  if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3674  !CheckCompatibleRail(v, tile)) {
3675  return INVALID_TILE;
3676  }
3677 
3678  return tile;
3679 }
3680 
3681 
3689 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3690 {
3691  /* First, handle broken down train */
3692 
3693  int t = v->breakdown_ctr;
3694  if (t > 1) {
3696 
3697  uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3698  if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3699  } else {
3700  v->vehstatus &= ~VS_TRAIN_SLOWING;
3701  }
3702 
3703  if (!TrainCanLeaveTile(v)) return true;
3704 
3705  /* Determine the non-diagonal direction in which we will exit this tile */
3706  DiagDirection dir = VehicleExitDir(v->direction, v->track);
3707  /* Calculate next tile */
3708  TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3709 
3710  /* Determine the track status on the next tile */
3711  TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3712  TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3713 
3714  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3715  TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3716 
3717  /* We are sure the train is not entering a depot, it is detected above */
3718 
3719  /* mask unreachable track bits if we are forbidden to do 90deg turns */
3720  TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3722  bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3723  }
3724 
3725  /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3726  if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3727  return TrainApproachingLineEnd(v, false, reverse);
3728  }
3729 
3730  /* approaching red signal */
3731  if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3732 
3733  /* approaching a rail/road crossing? then make it red */
3735 
3736  return true;
3737 }
3738 
3739 
3740 static bool TrainLocoHandler(Train *v, bool mode)
3741 {
3742  /* train has crashed? */
3743  if (v->vehstatus & VS_CRASHED) {
3744  return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3745  }
3746 
3747  if (v->force_proceed != TFP_NONE) {
3748  ClrBit(v->flags, VRF_TRAIN_STUCK);
3750  }
3751 
3752  /* train is broken down? */
3753  if (v->HandleBreakdown()) return true;
3754 
3755  if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3757  }
3758 
3759  /* exit if train is stopped */
3760  if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3761 
3762  bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3763  if (ProcessOrders(v) && CheckReverseTrain(v)) {
3764  v->wait_counter = 0;
3765  v->cur_speed = 0;
3766  v->subspeed = 0;
3767  ClrBit(v->flags, VRF_LEAVING_STATION);
3769  return true;
3770  } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3771  /* Try to reserve a path when leaving the station as we
3772  * might not be marked as wanting a reservation, e.g.
3773  * when an overlength train gets turned around in a station. */
3774  DiagDirection dir = VehicleExitDir(v->direction, v->track);
3776 
3778  TryPathReserve(v, true, true);
3779  }
3780  ClrBit(v->flags, VRF_LEAVING_STATION);
3781  }
3782 
3783  v->HandleLoading(mode);
3784 
3785  if (v->current_order.IsType(OT_LOADING)) return true;
3786 
3787  if (CheckTrainStayInDepot(v)) return true;
3788 
3789  if (!mode) v->ShowVisualEffect();
3790 
3791  /* We had no order but have an order now, do look ahead. */
3792  if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3793  CheckNextTrainTile(v);
3794  }
3795 
3796  /* Handle stuck trains. */
3797  if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3798  ++v->wait_counter;
3799 
3800  /* Should we try reversing this tick if still stuck? */
3802 
3803  if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3804  if (!TryPathReserve(v)) {
3805  /* Still stuck. */
3806  if (turn_around) ReverseTrainDirection(v);
3807 
3809  /* Show message to player. */
3811  SetDParam(0, v->index);
3812  AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
3813  }
3814  v->wait_counter = 0;
3815  }
3816  /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3817  if (v->force_proceed == TFP_NONE) return true;
3818  ClrBit(v->flags, VRF_TRAIN_STUCK);
3819  v->wait_counter = 0;
3821  }
3822  }
3823 
3824  if (v->current_order.IsType(OT_LEAVESTATION)) {
3825  v->current_order.Free();
3827  return true;
3828  }
3829 
3830  int j = v->UpdateSpeed();
3831 
3832  /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
3833  if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
3834  /* If we manually stopped, we're not force-proceeding anymore. */
3835  v->force_proceed = TFP_NONE;
3837  }
3838 
3839  int adv_spd = v->GetAdvanceDistance();
3840  if (j < adv_spd) {
3841  /* if the vehicle has speed 0, update the last_speed field. */
3842  if (v->cur_speed == 0) v->SetLastSpeed();
3843  } else {
3845  /* Loop until the train has finished moving. */
3846  for (;;) {
3847  j -= adv_spd;
3848  TrainController(v, nullptr);
3849  /* Don't continue to move if the train crashed. */
3850  if (CheckTrainCollision(v)) break;
3851  /* Determine distance to next map position */
3852  adv_spd = v->GetAdvanceDistance();
3853 
3854  /* No more moving this tick */
3855  if (j < adv_spd || v->cur_speed == 0) break;
3856 
3857  OrderType order_type = v->current_order.GetType();
3858  /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
3859  if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3861  IsTileType(v->tile, MP_STATION) &&
3863  ProcessOrders(v);
3864  }
3865  }
3866  v->SetLastSpeed();
3867  }
3868 
3869  for (Train *u = v; u != nullptr; u = u->Next()) {
3870  if ((u->vehstatus & VS_HIDDEN) != 0) continue;
3871 
3872  u->UpdateViewport(false, false);
3873  }
3874 
3875  if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
3876 
3877  return true;
3878 }
3879 
3885 {
3886  Money cost = 0;
3887  const Train *v = this;
3888 
3889  do {
3890  const Engine *e = v->GetEngine();
3891  if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
3892 
3893  uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
3894  if (cost_factor == 0) continue;
3895 
3896  /* Halve running cost for multiheaded parts */
3897  if (v->IsMultiheaded()) cost_factor /= 2;
3898 
3899  cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
3900  } while ((v = v->GetNextVehicle()) != nullptr);
3901 
3902  return cost;
3903 }
3904 
3910 {
3912 
3913  this->tick_counter++;
3914 
3915  if (this->IsFrontEngine()) {
3916  if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
3917 
3918  this->current_order_time++;
3919 
3920  if (!TrainLocoHandler(this, false)) return false;
3921 
3922  return TrainLocoHandler(this, true);
3923  } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
3924  /* Delete flooded standalone wagon chain */
3925  if (++this->crash_anim_pos >= 4400) {
3926  delete this;
3927  return false;
3928  }
3929  }
3930 
3931  return true;
3932 }
3933 
3939 {
3940  if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
3941  if (v->IsChainInDepot()) {
3943  return;
3944  }
3945 
3946  uint max_penalty;
3948  case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
3949  case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
3950  default: NOT_REACHED();
3951  }
3952 
3953  FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
3954  /* Only go to the depot if it is not too far out of our way. */
3955  if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
3956  if (v->current_order.IsType(OT_GOTO_DEPOT)) {
3957  /* If we were already heading for a depot but it has
3958  * suddenly moved farther away, we continue our normal
3959  * schedule? */
3960  v->current_order.MakeDummy();
3962  }
3963  return;
3964  }
3965 
3966  DepotID depot = GetDepotIndex(tfdd.tile);
3967 
3968  if (v->current_order.IsType(OT_GOTO_DEPOT) &&
3969  v->current_order.GetDestination() != depot &&
3970  !Chance16(3, 16)) {
3971  return;
3972  }
3973 
3976  v->dest_tile = tfdd.tile;
3978 }
3979 
3982 {
3983  AgeVehicle(this);
3984 
3985  if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
3986 
3987  if (this->IsFrontEngine()) {
3988  CheckVehicleBreakdown(this);
3989 
3991 
3992  CheckOrders(this);
3993 
3994  /* update destination */
3995  if (this->current_order.IsType(OT_GOTO_STATION)) {
3997  if (tile != INVALID_TILE) this->dest_tile = tile;
3998  }
3999 
4000  if (this->running_ticks != 0) {
4001  /* running costs */
4003 
4004  this->profit_this_year -= cost.GetCost();
4005  this->running_ticks = 0;
4006 
4007  SubtractMoneyFromCompanyFract(this->owner, cost);
4008 
4011  }
4012  }
4013 }
4014 
4020 {
4021  if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4022 
4023  if (this->track == TRACK_BIT_DEPOT) {
4024  /* We'll assume the train is facing outwards */
4025  return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4026  }
4027 
4028  if (this->track == TRACK_BIT_WORMHOLE) {
4029  /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
4030  return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4031  }
4032 
4033  return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4034 }
Train::GetDisplayImageWidth
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
Definition: train_cmd.cpp:432
VSE_START
@ VSE_START
Vehicle starting, i.e. leaving, the station.
Definition: newgrf_sound.h:19
VehicleOrderSaver
This class will save the current order of a vehicle and restore it on destruction.
Definition: train_cmd.cpp:2438
GUISettings::lost_vehicle_warn
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
Definition: settings_type.h:94
SpecializedVehicle::GetNextVehicle
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
Definition: vehicle_base.h:1121
VETS_STATION_ID_OFFSET
@ VETS_STATION_ID_OFFSET
Shift the VehicleEnterTileStatus this many bits to the right to get the station ID when VETS_ENTERED_...
Definition: tile_cmd.h:30
game.hpp
Train::GetImage
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Get the sprite to display the train.
Definition: train_cmd.cpp:462
VehicleExitDir
static DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
Definition: track_func.h:722
SetTrainGroupID
void SetTrainGroupID(Train *v, GroupID grp)
Affect the groupID of a train to new_g.
Definition: group_cmd.cpp:730
CFollowTrackT::m_is_station
bool m_is_station
last turn passed station
Definition: follow_track.hpp:48
EF_RAIL_TILTS
@ EF_RAIL_TILTS
Rail vehicle tilts in curves.
Definition: engine_type.h:153
TRACK_BIT_MASK
@ TRACK_BIT_MASK
Bitmask for the first 6 bits.
Definition: track_type.h:54
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:734
FindFirstTrackdir
static Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR.
Definition: track_func.h:219
PBSTileInfo::okay
bool okay
True if tile is a safe waiting position, false otherwise.
Definition: pbs.h:29
VRF_TOGGLE_REVERSE
@ VRF_TOGGLE_REVERSE
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition: train.h:31
BaseStation::facilities
StationFacility facilities
The facilities that this station has.
Definition: base_station_base.h:63
TRACK_BIT_WORMHOLE
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels)
Definition: track_type.h:55
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:174
PlayVehicleSound
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Definition: newgrf_sound.cpp:185
VehicleOrderID
byte VehicleOrderID
The index of an order within its current vehicle (not pool related)
Definition: order_type.h:15
NPFTrainFindNearestDepot
FindDepotData NPFTrainFindNearestDepot(const Train *v, int max_penalty)
Used when user sends train to the nearest depot or if train needs servicing using NPF.
Definition: npf.cpp:1238
Engine::GetGRFID
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition: engine.cpp:158
TileIndex
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:83
VehicleCargoList::StoredCount
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:351
PathfinderSettings::npf
NPFSettings npf
pathfinder settings for the new pathfinder
Definition: settings_type.h:449
HasReservedTracks
static bool HasReservedTracks(TileIndex tile, TrackBits tracks)
Check whether some of tracks is reserved on a tile.
Definition: pbs.h:58
DIR_SW
@ DIR_SW
Southwest.
Definition: direction_type.h:31
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3321
Order::MakeDummy
void MakeDummy()
Makes this order a Dummy order.
Definition: order_cmd.cpp:132
sound_func.h
PROP_TRAIN_SPEED
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
Definition: newgrf_properties.h:21
TRACK_BIT_NONE
@ TRACK_BIT_NONE
No track.
Definition: track_type.h:39
PathfinderSettings::wait_for_pbs_path
byte wait_for_pbs_path
how long to wait for a path reservation.
Definition: settings_type.h:446
ArrangeTrains
static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
Arrange the trains in the wanted way.
Definition: train_cmd.cpp:1089
newgrf_station.h
Chance16
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
Definition: random_func.hpp:131
CheckNewTrain
static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
Check/validate whether we may actually build a new train.
Definition: train_cmd.cpp:936
DoCommand
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:450
CCF_CAPACITY
@ CCF_CAPACITY
Allow vehicles to change capacity.
Definition: train.h:46
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:61
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:329
TileOffsByDiagDir
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:341
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:24
Vehicle::y_pos
int32 y_pos
y coordinate.
Definition: vehicle_base.h:279
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3220
MutableSpriteCache::sprite_seq
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Definition: vehicle_base.h:193
Station::GetPlatformLength
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const override
Determines the REMAINING length of a platform, starting at (and including) the given tile.
Definition: station.cpp:266
GetPrice
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:950
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
NT_ARRIVAL_OTHER
@ NT_ARRIVAL_OTHER
First vehicle arrived for competitor.
Definition: news_type.h:23
Vehicle::value
Money value
Value of the vehicle.
Definition: vehicle_base.h:251
YapfTrainFindNearestSafeTile
bool YapfTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
Try to extend the reserved path of a train to the nearest safe tile using YAPF.
Definition: yapf_rail.cpp:624
CMD_MOVE_RAIL_VEHICLE
@ CMD_MOVE_RAIL_VEHICLE
move a rail vehicle (in the depot)
Definition: command_type.h:220
VehicleSettings::train_acceleration_model
uint8 train_acceleration_model
realistic acceleration for trains
Definition: settings_type.h:466
Vehicle::x_pos
int32 x_pos
x coordinate.
Definition: vehicle_base.h:278
DIRDIFF_45LEFT
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
Definition: direction_type.h:68
ChangeDir
static Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
Definition: direction_func.h:104
GetBridgeType
static BridgeType GetBridgeType(TileIndex t)
Determines the type of bridge on a tile.
Definition: bridge_map.h:56
GroundVehicle< Train, VEH_TRAIN >::GetAcceleration
int GetAcceleration() const
Calculates the acceleration of the vehicle under its current conditions.
Definition: ground_vehicle.cpp:105
FindDepotData
Helper container to find a depot.
Definition: pathfinder_type.h:53
RemoveFirstTrackdir
static Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
Definition: track_func.h:164
command_func.h
TrackdirBits
TrackdirBits
Enumeration of bitmasks for the TrackDirs.
Definition: track_type.h:101
DIR_SE
@ DIR_SE
Southeast.
Definition: direction_type.h:29
IsRailWaypointTile
static bool IsRailWaypointTile(TileIndex t)
Is this tile a station tile and a rail waypoint?
Definition: station_map.h:123
CFollowTrackT::m_old_tile
TileIndex m_old_tile
the origin (vehicle moved from) before move
Definition: follow_track.hpp:41
PathfinderSettings::forbid_90_deg
bool forbid_90_deg
forbid trains to make 90 deg turns
Definition: settings_type.h:439
ODTFB_SERVICE
@ ODTFB_SERVICE
This depot order is because of the servicing limit.
Definition: order_type.h:95
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:23
MaybeBarCrossingWithSound
static void MaybeBarCrossingWithSound(TileIndex tile)
Bars crossing and plays ding-ding sound if not barred already.
Definition: train_cmd.cpp:1708
TrainCache::cached_tilt
bool cached_tilt
train can tilt; feature provides a bonus in curves
Definition: train.h:74
PROP_TRAIN_RUNNING_COST_FACTOR
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:23
AccelerationSlowdownParams::small_turn
byte small_turn
Speed change due to a small turn.
Definition: train_cmd.cpp:2860
HasVehicleOnPos
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
Definition: vehicle.cpp:513
CheckOrders
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
Definition: order_cmd.cpp:1729
GVF_SUPPRESS_IMPLICIT_ORDERS
@ GVF_SUPPRESS_IMPLICIT_ORDERS
Disable insertion and removal of automatic orders until the vehicle completes the real order.
Definition: ground_vehicle.hpp:54
Engine::reliability_spd_dec
uint16 reliability_spd_dec
Speed of reliability decay between services (per day).
Definition: engine_base.h:26
GroundVehicleCache::first_engine
EngineID first_engine
Cached EngineID of the front vehicle. INVALID_ENGINE for the front vehicle itself.
Definition: ground_vehicle.hpp:43
Vehicle::LeaveStation
void LeaveStation()
Perform all actions when leaving a station.
Definition: vehicle.cpp:2242
company_base.h
GroundVehicle::ClearFreeWagon
void ClearFreeWagon()
Clear a vehicle from being a free wagon.
Definition: ground_vehicle.hpp:294
FindClosestTrainDepot
static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
Try to find a depot nearby.
Definition: train_cmd.cpp:2005
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:592
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
SpecializedVehicle::Next
T * Next() const
Get next vehicle in the chain.
Definition: vehicle_base.h:1077
TRANSPORT_RAIL
@ TRANSPORT_RAIL
Transport by train.
Definition: transport_type.h:27
CheckConsistencyOfArticulatedVehicle
void CheckConsistencyOfArticulatedVehicle(const Vehicle *v)
Checks whether the specs of freshly build articulated vehicles are consistent with the information sp...
Definition: articulated_vehicles.cpp:311
SetRailStationPlatformReservation
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
Definition: pbs.cpp:57
GetReservedTrackbits
TrackBits GetReservedTrackbits(TileIndex t)
Get the reserved trackbits for any tile, regardless of type.
Definition: pbs.cpp:24
DIRDIFF_SAME
@ DIRDIFF_SAME
Both directions faces to the same direction.
Definition: direction_type.h:63
Vehicle::y_extent
byte y_extent
y-extent of vehicle bounding box
Definition: vehicle_base.h:291
Station
Station data structure.
Definition: station_base.h:450
Order::GetDestination
DestinationID GetDestination() const
Gets the destination of this order.
Definition: order_base.h:94
Vehicle::NeedsAutomaticServicing
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
Definition: vehicle.cpp:252
Vehicle::z_pos
int32 z_pos
z coordinate.
Definition: vehicle_base.h:280
ProcessConditionalOrder
VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
Process a conditional order and determine the next order.
Definition: order_cmd.cpp:1972
UpdateStatusAfterSwap
static void UpdateStatusAfterSwap(Train *v)
Updates some variables after swapping the vehicle.
Definition: train_cmd.cpp:1552
VehicleSpriteSeq::Set
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
Definition: vehicle_base.h:161
DIR_NW
@ DIR_NW
Northwest.
Definition: direction_type.h:33
yapf.hpp
DiagDirToAxis
static Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition: direction_func.h:214
IsDiagonalDirection
static bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
Definition: direction_func.h:273
FindDepotData::reverse
bool reverse
True if reversing is necessary for the train to get to this depot.
Definition: pathfinder_type.h:56
CheckTrainAttachment
static CommandCost CheckTrainAttachment(Train *t)
Check whether the train parts can be attached.
Definition: train_cmd.cpp:960
RAIL_TILE_SIGNALS
@ RAIL_TILE_SIGNALS
Normal rail tile with signals.
Definition: rail_map.h:25
SAT_TRAIN_ARRIVES
@ SAT_TRAIN_ARRIVES
Trigger platform when train arrives.
Definition: newgrf_animation_type.h:30
Vehicle::random_bits
byte random_bits
Bits used for determining which randomized variational spritegroups to use when drawing.
Definition: vehicle_base.h:308
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:326
NormaliseTrainHead
static void NormaliseTrainHead(Train *head)
Normalise the head of the train again, i.e.
Definition: train_cmd.cpp:1130
DIAGDIR_END
@ DIAGDIR_END
Used for iterations.
Definition: direction_type.h:83
GroundVehicle::ClearFrontEngine
void ClearFrontEngine()
Remove the front engine state.
Definition: ground_vehicle.hpp:254
VPF_YAPF
@ VPF_YAPF
Yet Another PathFinder.
Definition: vehicle_type.h:61
TRACK_BEGIN
@ TRACK_BEGIN
Used for iterations.
Definition: track_type.h:20
VehicleOrderSaver::SwitchToNextOrder
bool SwitchToNextOrder(bool skip_first)
Set the current vehicle order to the next order in the order list.
Definition: train_cmd.cpp:2471
VS_DEFPAL
@ VS_DEFPAL
Use default vehicle palette.
Definition: vehicle_base.h:33
DepotID
uint16 DepotID
Type for the unique identifier of depots.
Definition: depot_type.h:13
YapfTrainCheckReverse
bool YapfTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using YAPF.
Definition: yapf_rail.cpp:546
Pool::PoolItem<&_vehicle_pool >::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:227
Vehicle::SetNext
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition: vehicle.cpp:2721
VRF_POWEREDWAGON
@ VRF_POWEREDWAGON
Wagon is powered.
Definition: train.h:27
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:117
Train::crash_anim_pos
uint16 crash_anim_pos
Crash animation counter.
Definition: train.h:91
Vehicle::acceleration
byte acceleration
used by train & aircraft
Definition: vehicle_base.h:304
MakeTrainBackup
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
Definition: train_cmd.cpp:819
AddArticulatedParts
void AddArticulatedParts(Vehicle *first)
Add the remaining articulated parts to the given vehicle.
Definition: articulated_vehicles.cpp:353
HasPowerOnRail
static bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition: rail.h:332
TRACK_X
@ TRACK_X
Track along the x-axis (north-east to south-west)
Definition: track_type.h:21
FollowTrainReservation
PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
Follow a train reservation to the last tile.
Definition: pbs.cpp:289
OSL_PLATFORM_MIDDLE
@ OSL_PLATFORM_MIDDLE
Stop at the middle of the platform.
Definition: order_type.h:85
Vehicle::group_id
GroupID group_id
Index of group Pool array.
Definition: vehicle_base.h:335
Order::Free
void Free()
'Free' the order
Definition: order_cmd.cpp:62
InsertInConsist
static void InsertInConsist(Train *dst, Train *chain)
Inserts a chain into the train at dst.
Definition: train_cmd.cpp:868
Train::UpdateSpeed
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
Definition: train_cmd.cpp:2806
Train::GetAccelerationStatus
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition: train.h:262
KillFirstBit
static T KillFirstBit(T value)
Clear the first bit in an integer.
Definition: bitmath_func.hpp:239
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:563
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
GroupStatistics::CountVehicle
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
Definition: group_cmd.cpp:133
UnScaleGUI
static int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition: zoom_func.h:66
SIGNAL_STATE_GREEN
@ SIGNAL_STATE_GREEN
The signal is green.
Definition: signal_type.h:46
RailtypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:124
DiagDirToDiagTrackdir
static Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition: track_func.h:545
ClrBit
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
IsCompatibleTrainStationTile
static bool IsCompatibleTrainStationTile(TileIndex test_tile, TileIndex station_tile)
Check if a tile is a valid continuation to a railstation tile.
Definition: station_map.h:378
VehicleSettings::wagon_speed_limits
bool wagon_speed_limits
enable wagon speed limits
Definition: settings_type.h:470
HideFillingPercent
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
Definition: misc_gui.cpp:672
TracksOverlap
static bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Definition: track_func.h:653
MP_RAILWAY
@ MP_RAILWAY
A railway.
Definition: tile_type.h:47
Vehicle::next
Vehicle * next
pointer to the next vehicle in the chain
Definition: vehicle_base.h:227
Vehicle::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:751
Train::FindClosestDepot
bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
Locate the closest depot for this consist, and return the information to the caller.
Definition: train_cmd.cpp:2029
IsValidDiagDirection
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition: direction_func.h:21
RestoreTrainBackup
static void RestoreTrainBackup(TrainList &list)
Restore the train from the backup list.
Definition: train_cmd.cpp:828
zoom_func.h
InvalidateNewGRFInspectWindow
void InvalidateNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Invalidate the inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:718
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:13
VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL
@ VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL
Electric train engine is allowed to run on normal rail. *‍/.
Definition: train.h:30
ClearPathReservation
static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
Clear the reservation of tile that was just left by a wagon on track_dir.
Definition: train_cmd.cpp:2202
AddVehicleNewsItem
static void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station=INVALID_STATION)
Adds a newsitem referencing a vehicle.
Definition: news_func.h:30
Vehicle::running_ticks
byte running_ticks
Number of ticks this vehicle was not stopped this day.
Definition: vehicle_base.h:324
GetTrackBits
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
Definition: rail_map.h:136
CmdBuildRailVehicle
CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
Build a railroad vehicle.
Definition: train_cmd.cpp:715
UpdateSignalsOnSegment
SigSegState UpdateSignalsOnSegment(TileIndex tile, DiagDirection side, Owner owner)
Update signals, starting at one side of a tile Will check tile next to this at opposite side too.
Definition: signal.cpp:638
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:219
DirDifference
static DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Definition: direction_func.h:68
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:79
HasSignals
static bool HasSignals(TileIndex t)
Checks if a rail tile has signals.
Definition: rail_map.h:72
VehicleEnterDepot
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
Definition: vehicle.cpp:1475
VehicleLengthChanged
void VehicleLengthChanged(const Vehicle *u)
Logs a bug in GRF and shows a warning message if this is for the first time this happened.
Definition: vehicle.cpp:330
WC_VEHICLE_TIMETABLE
@ WC_VEHICLE_TIMETABLE
Vehicle timetable; Window numbers:
Definition: window_type.h:217
newgrf_debug.h
TileY
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:215
RailVehicleInfo::power
uint16 power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition: engine_type.h:48
Engine::GetLifeLengthInDays
Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition: engine.cpp:442
NPFTrainCheckReverse
bool NPFTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using NPF.
Definition: npf.cpp:1281
Rail90DegTurnDisallowed
static bool Rail90DegTurnDisallowed(RailType rt1, RailType rt2, bool def=_settings_game.pf.forbid_90_deg)
Test if 90 degree turns are disallowed between two railtypes.
Definition: rail.h:354
GroundVehicle::IsRearDualheaded
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Definition: ground_vehicle.hpp:334
VS_TRAIN_SLOWING
@ VS_TRAIN_SLOWING
Train is slowing down.
Definition: vehicle_base.h:34
WC_COMPANY
@ WC_COMPANY
Company view; Window numbers:
Definition: window_type.h:362
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
EV_EXPLOSION_SMALL
@ EV_EXPLOSION_SMALL
Various explosions.
Definition: effectvehicle_func.h:24
NormaliseDualHeads
static void NormaliseDualHeads(Train *t)
Normalise the dual heads in the train, i.e.
Definition: train_cmd.cpp:882
EngineImageType
EngineImageType
Visualisation contexts of vehicles and engines.
Definition: vehicle_type.h:85
Engine
Definition: engine_base.h:21
GetTrainStopLocation
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station.
Definition: train_cmd.cpp:256
Vehicle::cur_speed
uint16 cur_speed
current speed
Definition: vehicle_base.h:302
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:222
RAILTYPES_NONE
@ RAILTYPES_NONE
No rail types.
Definition: rail_type.h:47
VETS_ENTERED_STATION
@ VETS_ENTERED_STATION
The vehicle entered a station.
Definition: tile_cmd.h:21
Engine::GetDefaultCargoType
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition: engine_base.h:79
VehicleSpriteSeq::Draw
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Definition: vehicle.cpp:126
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:283
TryPathReserve
bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
Try to reserve a path to a safe position.
Definition: train_cmd.cpp:2681
Train::GetVehicleTrackdir
Trackdir GetVehicleTrackdir() const
Get the tracks of the train vehicle.
Definition: train_cmd.cpp:4019
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
BridgeSpec::speed
uint16 speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: bridge.h:46
EV_EXPLOSION_LARGE
@ EV_EXPLOSION_LARGE
Various explosions.
Definition: effectvehicle_func.h:22
GetVehicleCallback
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
Definition: newgrf_engine.cpp:1188
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:348
FindTrainCollideEnum
static Vehicle * FindTrainCollideEnum(Vehicle *v, void *data)
Collision test function.
Definition: train_cmd.cpp:2999
DIR_N
@ DIR_N
North.
Definition: direction_type.h:26
CBM_VEHICLE_ARTIC_ENGINE
@ CBM_VEHICLE_ARTIC_ENGINE
Add articulated engines (trains and road vehicles)
Definition: newgrf_callbacks.h:293
_accel_slowdown
static const AccelerationSlowdownParams _accel_slowdown[]
Speed update fractions for each acceleration type.
Definition: train_cmd.cpp:2867
DeleteVehicleOrders
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
Definition: order_cmd.cpp:1890
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:199
OrderStopLocation
OrderStopLocation
Where to stop the trains.
Definition: order_type.h:83
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:346
VehicleServiceInDepot
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition: vehicle.cpp:162
GroundVehicle::SetWagon
void SetWagon()
Set a vehicle to be a wagon.
Definition: ground_vehicle.hpp:269
GetRailDepotDirection
static DiagDirection GetRailDepotDirection(TileIndex t)
Returns the direction the depot is facing to.
Definition: rail_map.h:171
HasPbsSignalOnTrackdir
static bool HasPbsSignalOnTrackdir(TileIndex tile, Trackdir td)
Is a pbs signal present along the trackdir?
Definition: rail_map.h:463
ExtendTrainReservation
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
Extend a train path as far as possible.
Definition: train_cmd.cpp:2335
TRACK_BIT_UPPER
@ TRACK_BIT_UPPER
Upper track.
Definition: track_type.h:42
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:150
CFollowTrackT::m_is_bridge
bool m_is_bridge
last turn passed bridge ramp
Definition: follow_track.hpp:47
TrackToTrackBits
static TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
Definition: track_func.h:85
TryReserveRailTrack
bool TryReserveRailTrack(TileIndex tile, Track t, bool trigger_stations)
Try to reserve a specific track on a tile.
Definition: pbs.cpp:80
TileX
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:205
train_cmd.h
SwapTrainFlags
static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
Swap the two up/down flags in two ways:
Definition: train_cmd.cpp:1524
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:372
GetTileTrackStatus
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
Definition: landscape.cpp:590
Vehicle::IsArticulatedPart
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:904
effectvehicle_func.h
TRACK_BIT_RIGHT
@ TRACK_BIT_RIGHT
Right track.
Definition: track_type.h:45
CheckTrainCollision
static bool CheckTrainCollision(Train *v)
Checks whether the specified train has a collision with another vehicle.
Definition: train_cmd.cpp:3046
ai.hpp
Order::MakeGoToDepot
void MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoID cargo=CT_NO_REFIT)
Makes this order a Go To Depot order.
Definition: order_cmd.cpp:89
PFE_GL_TRAINS
@ PFE_GL_TRAINS
Time spent processing trains.
Definition: framerate_type.h:51
Order::GetType
OrderType GetType() const
Get the type of order of this order.
Definition: order_base.h:67
TrainOnTileEnum
static Vehicle * TrainOnTileEnum(Vehicle *v, void *)
Check if the vehicle is a train.
Definition: train_cmd.cpp:1631
Order::GetMaxSpeed
uint16 GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination.
Definition: order_base.h:192
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
GVF_GOINGDOWN_BIT
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration)
Definition: ground_vehicle.hpp:53
Order::GetStopLocation
OrderStopLocation GetStopLocation() const
Where must we stop at the platform?
Definition: order_base.h:133
RemoveVehicleFromGroup
void RemoveVehicleFromGroup(const Vehicle *v)
Decrease the num_vehicle variable before delete an front engine from a group.
Definition: group_cmd.cpp:716
CBM_VEHICLE_LENGTH
@ CBM_VEHICLE_LENGTH
Vehicle length (trains and road vehicles)
Definition: newgrf_callbacks.h:290
GBUG_VEH_CAPACITY
@ GBUG_VEH_CAPACITY
Capacity of vehicle changes when not refitting or arranging.
Definition: newgrf_config.h:48
PathfinderSettings::wait_oneway_signal
byte wait_oneway_signal
waitingtime in days before a oneway signal
Definition: settings_type.h:442
SetSignalsOnBothDir
void SetSignalsOnBothDir(TileIndex tile, Track track, Owner owner)
Update signals at segments that are at both ends of given (existent or non-existent) track.
Definition: signal.cpp:656
SoundSettings::ambient
bool ambient
Play ambient, industry and town sounds.
Definition: settings_type.h:201
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:138
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition: newgrf.h:142
GetRailTypeInfo
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:304
SetWindowWidgetDirty
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition: window.cpp:3234
NormaliseSubtypes
static void NormaliseSubtypes(Train *chain)
Normalise the sub types of the parts in this chain.
Definition: train_cmd.cpp:904
ENGINE_EXCLUSIVE_PREVIEW
@ ENGINE_EXCLUSIVE_PREVIEW
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
Definition: engine_type.h:169
Train::GetCurrentMaxSpeed
int GetCurrentMaxSpeed() const
Calculates the maximum speed of the vehicle under its current conditions.
Definition: train_cmd.cpp:369
VRF_LEAVING_STATION
@ VRF_LEAVING_STATION
Train is just leaving a station.
Definition: train.h:33
GetBridgeSpec
static const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
Definition: bridge.h:65
Order::GetNonStopType
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
Definition: order_base.h:131
UpdateOrderDest
bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool pbs_look_ahead)
Update the vehicle's destination tile from an order.
Definition: order_cmd.cpp:2002
Vehicle::BeginLoading
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition: vehicle.cpp:2095
GameSettings::pf
PathfinderSettings pf
settings for all pathfinders
Definition: settings_type.h:570
TrackdirReachesTrackdirs
static TrackdirBits TrackdirReachesTrackdirs(Trackdir trackdir)
Maps a trackdir to the trackdirs that can be reached from it (ie, when entering the next tile.
Definition: track_func.h:592
Vehicle::breakdown_ctr
byte breakdown_ctr
Counter for managing breakdown events.
Definition: vehicle_base.h:273
VS_HIDDEN
@ VS_HIDDEN
Vehicle is not visible.
Definition: vehicle_base.h:30
SIGTYPE_PBS
@ SIGTYPE_PBS
normal pbs signal
Definition: signal_type.h:28
EngineID
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
UnreserveRailTrack
void UnreserveRailTrack(TileIndex tile, Track t)
Lift the reservation of a specific track on a tile.
Definition: pbs.cpp:141
FindDepotData::best_length
uint best_length
The distance towards the depot in penalty, or UINT_MAX if not found.
Definition: pathfinder_type.h:55
TrainList
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
Definition: rail_cmd.cpp:42
PathfinderSettings::wait_twoway_signal
byte wait_twoway_signal
waitingtime in days before a twoway signal
Definition: settings_type.h:443
RailVehicleInfo
Information about a rail vehicle.
Definition: engine_type.h:42
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition: company_cmd.cpp:311
VehicleSpriteSeq::IsValid
bool IsValid() const
Check whether the sequence contains any sprites.
Definition: vehicle_base.h:145
GroundVehicleCache::cached_total_length
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
Definition: ground_vehicle.hpp:42
Vehicle::dest_tile
TileIndex dest_tile
Heading for this tile.
Definition: vehicle_base.h:247
DirToDiagDir
static DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Definition: direction_func.h:166
FOR_EACH_SET_TRACK
#define FOR_EACH_SET_TRACK(var, track_bits)
Iterate through each set Track in a TrackBits value.
Definition: track_func.h:27
Vehicle::HandlePathfindingResult
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Definition: vehicle.cpp:773
_breakdown_speeds
static const uint16 _breakdown_speeds[16]
Maximum speeds for train that is broken down or approaching line end.
Definition: train_cmd.cpp:3574
TrackBitsToTrack
static Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
Definition: track_func.h:201
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:33
TriggerStationRandomisation
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
Definition: newgrf_station.cpp:966
IsWaitingPositionFree
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
Definition: pbs.cpp:427
AI::NewEvent
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition: ai_core.cpp:234
DoTrainPathfind
static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
Perform pathfinding for a train.
Definition: train_cmd.cpp:2320
IsBridgeTile
static bool IsBridgeTile(TileIndex t)
checks if there is a bridge on this tile
Definition: bridge_map.h:35
CommandCost
Common return value for all commands.
Definition: command_type.h:23
TRACK_Y
@ TRACK_Y
Track along the y-axis (north-west to south-east)
Definition: track_type.h:22
CheckTrainStayInDepot
static bool CheckTrainStayInDepot(Train *v)
Will the train stay in the depot the next tick?
Definition: train_cmd.cpp:2124
VRF_TRAIN_STUCK
@ VRF_TRAIN_STUCK
Train can't get a path reservation.
Definition: train.h:32
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
CmdReverseTrainDirection
CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Reverse train.
Definition: train_cmd.cpp:1901
UpdateTrainGroupID
void UpdateTrainGroupID(Train *v)
Recalculates the groupID of a train.
Definition: group_cmd.cpp:758
WC_VEHICLE_VIEW
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
Definition: window_type.h:332
ClientSettings::sound
SoundSettings sound
sound effect settings
Definition: settings_type.h:584
Vehicle::AddToShared
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Definition: vehicle.cpp:2750
DoCommandP
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Definition: command.cpp:541
YapfTrainFindNearestDepot
FindDepotData YapfTrainFindNearestDepot(const Train *v, int max_distance)
Used when user sends train to the nearest depot or if train needs servicing using YAPF.
Definition: yapf_rail.cpp:605
GroundVehicle::SetMultiheaded
void SetMultiheaded()
Set a vehicle as a multiheaded engine.
Definition: ground_vehicle.hpp:299
BaseStation::train_station
TileArea train_station
Tile area the train 'station' part covers.
Definition: base_station_base.h:75
NPFTrainChooseTrack
Track NPFTrainChooseTrack(const Train *v, bool &path_found, bool reserve_track, struct PBSTileInfo *target)
Finds the best path for given train using NPF.
Definition: npf.cpp:1300
INVALID_VEH_ORDER_ID
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel)
Definition: order_type.h:21
CMD_PAUSE
@ CMD_PAUSE
pause the game
Definition: command_type.h:256
DIRDIFF_90LEFT
@ DIRDIFF_90LEFT
Angle of 90 degrees left.
Definition: direction_type.h:67
EngineInfo::callback_mask
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:143
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
Train::Crash
uint Crash(bool flooded=false)
The train vehicle crashed! Update its status and other parts around it.
Definition: train_cmd.cpp:2930
CmdForceTrainProceed
CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Force a train through a red signal.
Definition: train_cmd.cpp:1974
TrackBitsToTrackdirBits
static TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition: track_func.h:327
GVF_GOINGUP_BIT
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration)
Definition: ground_vehicle.hpp:52
GetRailTileType
static RailTileType GetRailTileType(TileIndex t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
Definition: rail_map.h:36
SubtractMoneyFromCompanyFract
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
Definition: company_cmd.cpp:254
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:240
DeleteLastWagon
static void DeleteLastWagon(Train *v)
Deletes/Clears the last wagon of a crashed train.
Definition: train_cmd.cpp:3443
SIGNAL_STATE_RED
@ SIGNAL_STATE_RED
The signal is red.
Definition: signal_type.h:45
INVALID_VEHICLE
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
Definition: vehicle_type.h:55
npf_func.h
TrackdirToExitdir
static DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition: track_func.h:447
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:297
PBSTileInfo
This struct contains information about the end of a reserved path.
Definition: pbs.h:26
PathfinderSettings::path_backoff_interval
byte path_backoff_interval
ticks between checks for a free path.
Definition: settings_type.h:447
GroundVehicleCache::cached_veh_length
uint8 cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
Definition: ground_vehicle.hpp:44
VS_CRASHED
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:37
VETS_CANNOT_ENTER
@ VETS_CANNOT_ENTER
The vehicle cannot enter the tile.
Definition: tile_cmd.h:23
VehicleSpriteSeq
Sprite sequence for a vehicle part.
Definition: vehicle_base.h:128
SB
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
SND_41_DEPARTURE_MAGLEV
@ SND_41_DEPARTURE_MAGLEV
65 == 0x41 Station departure: maglev engine
Definition: sound_type.h:104
GetTrainSpriteSize
void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
Definition: train_cmd.cpp:549
Vehicle::last_station_visited
StationID last_station_visited
The last station we stopped at.
Definition: vehicle_base.h:311
GetFreeUnitNumber
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Definition: vehicle.cpp:1788
NPFSettings::maximum_go_to_depot_penalty
uint32 maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
Definition: settings_type.h:369
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:318
CheckTrainsLengths
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition: train_cmd.cpp:72
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:159
CmdSellRailWagon
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
Sell a (single) train wagon/engine.
Definition: train_cmd.cpp:1357
CCF_ARRANGE
@ CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Definition: train.h:52
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:327
GroundVehicleCache::cached_max_track_speed
uint16 cached_max_track_speed
Maximum consist speed (in internal units) limited by track type (valid only for the first engine).
Definition: ground_vehicle.hpp:37
GroundVehicle::IsChainInDepot
bool IsChainInDepot() const override
Check whether the whole vehicle chain is in the depot.
Definition: ground_vehicle.cpp:190
PBSTileInfo::trackdir
Trackdir trackdir
The reserved trackdir on the tile.
Definition: pbs.h:28
HasSignalOnTrackdir
static bool HasSignalOnTrackdir(TileIndex tile, Trackdir trackdir)
Checks for the presence of signals along the given trackdir on the given rail tile.
Definition: rail_map.h:426
Vehicle::max_age
Date max_age
Maximum age.
Definition: vehicle_base.h:269
GroundVehicle< Train, VEH_TRAIN >::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition: ground_vehicle.hpp:80
DIR_NE
@ DIR_NE
Northeast.
Definition: direction_type.h:27
RAILTYPES_RAIL
@ RAILTYPES_RAIL
Non-electrified rails.
Definition: rail_type.h:48
GroundVehicle::SetFrontEngine
void SetFrontEngine()
Set front engine state.
Definition: ground_vehicle.hpp:249
HVOT_TRAIN
@ HVOT_TRAIN
Station has seen a train.
Definition: station_type.h:64
Vehicle::IsFrontEngine
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:895
HasDepotReservation
static bool HasDepotReservation(TileIndex t)
Get the reservation state of the depot.
Definition: rail_map.h:258
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
CheckIfTrainNeedsService
static void CheckIfTrainNeedsService(Train *v)
Check whether a train needs service, and if so, find a depot or service it.
Definition: train_cmd.cpp:3938
DiagDirToDiagTrack
static Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track incidating with that diagdir.
Definition: track_func.h:520
DC_AUTOREPLACE
@ DC_AUTOREPLACE
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
Definition: command_type.h:355
WC_VEHICLE_DETAILS
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
Definition: window_type.h:193
Game::NewEvent
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:141
HandleCrashedTrain
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
Definition: train_cmd.cpp:3535
TrackdirCrossesTrackdirs
static TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
Maps a trackdir to all trackdirs that make 90 deg turns with it.
Definition: track_func.h:614
IsCrossingBarred
static bool IsCrossingBarred(TileIndex t)
Check if the level crossing is barred.
Definition: road_map.h:416
VS_STOPPED
@ VS_STOPPED
Vehicle is stopped by the player.
Definition: vehicle_base.h:31
Vehicle::GetGRFID
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:761
Vehicle::ShowVisualEffect
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
Definition: vehicle.cpp:2571
SetSignalStateByTrackdir
static void SetSignalStateByTrackdir(TileIndex tile, Trackdir trackdir, SignalState state)
Sets the state of the signal along the given trackdir.
Definition: rail_map.h:449
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
Vehicle::GetEngine
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:741
TRACK_BIT_X
@ TRACK_BIT_X
X-axis track.
Definition: track_type.h:40
VehicleEnterTile
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
Definition: vehicle.cpp:1737
TrainApproachingLineEnd
static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
Definition: train_cmd.cpp:3587
DiagdirReachesTracks
static TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
Definition: track_func.h:581
safeguards.h
IsRailDepotTile
static bool IsRailDepotTile(TileIndex t)
Is this tile rail tile and a rail depot?
Definition: rail_map.h:105
Vehicle::CopyVehicleConfigAndStatistics
void CopyVehicleConfigAndStatistics(const Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
Definition: vehicle_base.h:723
GroundVehicle::SetLastSpeed
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
Definition: ground_vehicle.hpp:341
SIGSEG_PBS
@ SIGSEG_PBS
Segment is a PBS segment.
Definition: signal_func.h:52
GetNewVehiclePosResult::new_tile
TileIndex new_tile
Tile of the vehicle after moving.
Definition: vehicle_func.h:78
Vehicle::reliability_spd_dec
uint16 reliability_spd_dec
Reliability decrease speed.
Definition: vehicle_base.h:272
Vehicle::last_loading_station
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded.
Definition: vehicle_base.h:312
Train
'Train' is either a loco or a wagon.
Definition: train.h:85
DiagDirToDir
static Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
Definition: direction_func.h:182
MAKE_ORDER_BACKUP_FLAG
static const uint32 MAKE_ORDER_BACKUP_FLAG
Flag to pass to the vehicle construction command when an order should be preserved.
Definition: order_backup.h:29
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:82
Train::GetOrderStationLocation
TileIndex GetOrderStationLocation(StationID station)
Get the location of the next station to visit.
Definition: train_cmd.cpp:2771
DEFAULT_GROUP
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition: group_type.h:17
YapfTrainChooseTrack
Track YapfTrainChooseTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, struct PBSTileInfo *target)
Finds the best path for given train using YAPF.
Definition: yapf_rail.cpp:531
FreightWagonMult
byte FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition: train_cmd.cpp:65
TileAddByDiagDir
static TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:382
ReverseDiagDir
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition: direction_func.h:118
HasOnewaySignalBlockingTrackdir
static bool HasOnewaySignalBlockingTrackdir(TileIndex tile, Trackdir td)
Is a one-way signal blocking the trackdir? A one-way signal on the trackdir against will block,...
Definition: rail_map.h:475
DIR_S
@ DIR_S
South.
Definition: direction_type.h:30
IsBridge
static bool IsBridge(TileIndex t)
Checks if this is a bridge, instead of a tunnel.
Definition: bridge_map.h:24
Vehicle::profit_this_year
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
Definition: vehicle_base.h:249
GetGRFStringID
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:602
IsTileOwner
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
IsSafeWaitingPosition
bool IsSafeWaitingPosition(const Train *v, TileIndex tile, Trackdir trackdir, bool include_line_end, bool forbid_90deg)
Determine whether a certain track on a tile is a safe position to end a path.
Definition: pbs.cpp:381
GetVehicleCallbackParent
uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
Definition: newgrf_engine.cpp:1204
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:52
INVALID_DIAGDIR
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
Definition: direction_type.h:84
VRF_REVERSE_DIRECTION
@ VRF_REVERSE_DIRECTION
Reverse the visible direction of the vehicle.
Definition: train.h:28
Train::MarkDirty
void MarkDirty()
Goods at the consist have changed, update the graphics, cargo, and acceleration.
Definition: train_cmd.cpp:2786
MP_TUNNELBRIDGE
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:55
CheckNextTrainTile
static void CheckNextTrainTile(Train *v)
Check if the train is on the last reserved tile and try to extend the path then.
Definition: train_cmd.cpp:2062
newgrf_text.h
INVALID_TRACKDIR
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
Definition: track_type.h:89
SoundSettings::disaster
bool disaster
Play disaster and accident sounds.
Definition: settings_type.h:199
ValidateTrains
static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
Validate whether we are going to create valid trains.
Definition: train_cmd.cpp:1069
Point
Coordinates of a point in 2D.
Definition: geometry_type.hpp:21
HasCrossingReservation
static bool HasCrossingReservation(TileIndex t)
Get the reservation state of the rail crossing.
Definition: road_map.h:380
error.h
DirDiff
DirDiff
Enumeration for the difference between two directions.
Definition: direction_type.h:62
CheckCargoCapacity
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
Definition: autoreplace_cmd.cpp:104
MarkBridgeDirty
void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
Mark bridge tiles dirty.
Definition: tunnelbridge_cmd.cpp:64
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:77
WC_TRAINS_LIST
@ WC_TRAINS_LIST
Trains list; Window numbers:
Definition: window_type.h:301
ConsistChangeFlags
ConsistChangeFlags
Flags for Train::ConsistChanged.
Definition: train.h:44
Vehicle::HandleLoading
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
Definition: vehicle.cpp:2304
SigSegState
SigSegState
State of the signal segment.
Definition: signal_func.h:49
CreateEffectVehicleRel
EffectVehicle * CreateEffectVehicleRel(const Vehicle *v, int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular vehicle.
Definition: effectvehicle.cpp:638
SND_0E_LEVEL_CROSSING
@ SND_0E_LEVEL_CROSSING
12 == 0x0C Train passes through level crossing
Definition: sound_type.h:51
GRFFile::traininfo_vehicle_width
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Definition: newgrf.h:143
AccelerationSlowdownParams
Data structure for storing engine speed changes of an acceleration type.
Definition: train_cmd.cpp:2859
IsRailStationTile
static bool IsRailStationTile(TileIndex t)
Is this tile a station tile and a rail station?
Definition: station_map.h:102
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:62
TRACK_BIT_LOWER
@ TRACK_BIT_LOWER
Lower track.
Definition: track_type.h:43
GUISettings::show_track_reservation
bool show_track_reservation
highlight reserved tracks.
Definition: settings_type.h:144
AffectSpeedByZChange
static void AffectSpeedByZChange(Train *v, int old_z)
Modify the speed of the vehicle due to a change in altitude.
Definition: train_cmd.cpp:2879
stdafx.h
ShowNewGrfVehicleError
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBugs bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
Definition: vehicle.cpp:297
BaseConsist::vehicle_flags
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
Definition: base_consist.h:31
WID_VV_START_STOP
@ WID_VV_START_STOP
Start or stop this vehicle, and show information about the current state.
Definition: vehicle_widget.h:17
IsOnewaySignal
static bool IsOnewaySignal(TileIndex t, Track track)
One-way signals can't be passed the 'wrong' way.
Definition: rail_map.h:319
Vehicle::sprite_cache
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
Definition: vehicle_base.h:341
RailVehicleInfo::pow_wag_power
uint16 pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:55
SoundFx
SoundFx
Sound effects from baseset.
Definition: sound_type.h:37
VPF_NPF
@ VPF_NPF
New PathFinder.
Definition: vehicle_type.h:60
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:142
Vehicle::y_offs
int8 y_offs
y offset for vehicle sprite
Definition: vehicle_base.h:296
viewport_func.h
Vehicle::colourmap
SpriteID colourmap
NOSAVE: cached colour mapping.
Definition: vehicle_base.h:264
AxisToDiagDir
static DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
Definition: direction_func.h:232
RemoveFromConsist
static void RemoveFromConsist(Train *part, bool chain=false)
Remove the given wagon from its consist.
Definition: train_cmd.cpp:851
OSL_PLATFORM_NEAR_END
@ OSL_PLATFORM_NEAR_END
Stop at the near end of the platform.
Definition: order_type.h:84
RailtypeInfo::powered_railtypes
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
Definition: rail.h:185
IsTileType
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition: engine_type.h:29
SetDepotReservation
static void SetDepotReservation(TileIndex t, bool b)
Set the reservation state of the depot.
Definition: rail_map.h:270
WC_VEHICLE_REFIT
@ WC_VEHICLE_REFIT
Vehicle refit; Window numbers:
Definition: window_type.h:199
GetTunnelBridgeDirection
static DiagDirection GetTunnelBridgeDirection(TileIndex t)
Get the direction pointing to the other end.
Definition: tunnelbridge_map.h:26
Train::ReserveTrackUnderConsist
void ReserveTrackUnderConsist() const
Tries to reserve track under whole train consist.
Definition: train_cmd.cpp:2908
Vehicle::IncrementRealOrderIndex
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
Definition: vehicle_base.h:836
GetTileOwner
static Owner GetTileOwner(TileIndex tile)
Returns the owner of a tile.
Definition: tile_map.h:178
VF_BUILT_AS_PROTOTYPE
@ VF_BUILT_AS_PROTOTYPE
Vehicle is a prototype (accepted as exclusive preview).
Definition: vehicle_base.h:44
CFollowTrackT::m_old_td
Trackdir m_old_td
the trackdir (the vehicle was on) before move
Definition: follow_track.hpp:42
VIWD_CONSIST_CHANGED
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
Definition: vehicle_gui.h:34
Vehicle::direction
Direction direction
facing
Definition: vehicle_base.h:281
Train::GetCurveSpeedLimit
int GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
Definition: train_cmd.cpp:300
TrainCollideChecker
Temporary data storage for testing collisions.
Definition: train_cmd.cpp:2988
DiagdirReachesTrackdirs
static TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
Definition: track_func.h:563
TRACK_BIT_DEPOT
@ TRACK_BIT_DEPOT
Bitflag for a depot.
Definition: track_type.h:56
PathfinderSettings::pathfinder_for_trains
uint8 pathfinder_for_trains
the pathfinder to use for trains
Definition: settings_type.h:433
RAILTYPE_RAIL
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition: rail_type.h:29
Vehicle::list
OrderList * list
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:330
BaseConsist::cur_real_order_index
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
Definition: base_consist.h:28
ONSF_NO_STOP_AT_DESTINATION_STATION
@ ONSF_NO_STOP_AT_DESTINATION_STATION
The vehicle will stop at any station it passes except the destination.
Definition: order_type.h:75
TrainCanLeaveTile
static bool TrainCanLeaveTile(const Train *v)
Determines whether train would like to leave the tile.
Definition: train_cmd.cpp:3632
PerformanceAccumulator
RAII class for measuring multi-step elements of performance.
Definition: framerate_type.h:114
PBSTileInfo::tile
TileIndex tile
Tile the path ends, INVALID_TILE if no valid path was found.
Definition: pbs.h:27
ProcessOrders
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
Definition: order_cmd.cpp:2130
spritecache.h
ReverseDir
static Direction ReverseDir(Direction d)
Return the reverse of a direction.
Definition: direction_func.h:54
Vehicle::x_extent
byte x_extent
x-extent of vehicle bounding box
Definition: vehicle_base.h:290
Train::wait_counter
uint16 wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition: train.h:100
RailtypeInfo::acceleration_type
uint8 acceleration_type
Acceleration type of this rail type.
Definition: rail.h:223
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:404
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
TRACKDIR_BIT_NONE
@ TRACKDIR_BIT_NONE
No track build.
Definition: track_type.h:102
IsCompatibleRail
static bool IsCompatibleRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType can drive on a tile with a given RailType.
Definition: rail.h:319
Vehicle::vcache
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:339
Train::PlayLeaveStationSound
void PlayLeaveStationSound() const
Play a sound for a train leaving the station.
Definition: train_cmd.cpp:2042
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
GroundVehicle::UpdateInclination
int UpdateInclination(bool new_tile, bool update_delta)
Checks if the vehicle is in a slope and sets the required flags in that case.
Definition: ground_vehicle.hpp:232
TrainList
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
Definition: train_cmd.cpp:812
vehicle_func.h
AdvanceWagonsBeforeSwap
static void AdvanceWagonsBeforeSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
Definition: train_cmd.cpp:1723
newgrf_sound.h
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
VEHICLE_LENGTH
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
Definition: vehicle_type.h:76
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition: sprites.h:1594
strings_func.h
Train::OnNewDay
void OnNewDay()
Update day counters of the train vehicle.
Definition: train_cmd.cpp:3981
PROP_TRAIN_SHORTEN_FACTOR
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:28
DeleteWindowById
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1165
RailVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:47
Vehicle::tick_counter
byte tick_counter
Increased by one for each tick.
Definition: vehicle_base.h:323
OSL_PLATFORM_FAR_END
@ OSL_PLATFORM_FAR_END
Stop at the far end of the platform.
Definition: order_type.h:86
SND_0A_DEPARTURE_TRAIN
@ SND_0A_DEPARTURE_TRAIN
8 == 0x08 Station departure: diesel and electric engine
Definition: sound_type.h:47
Vehicle::cargo_cap
uint16 cargo_cap
total capacity
Definition: vehicle_base.h:316
TRACK_BIT_LEFT
@ TRACK_BIT_LEFT
Left track.
Definition: track_type.h:44
Train::UpdateDeltaXY
void UpdateDeltaXY()
Updates the x and y offsets and the size of the sprite used for this vehicle.
Definition: train_cmd.cpp:1432
GroundVehicleCache::cached_power
uint32 cached_power
Total power of the consist (valid only for the first engine).
Definition: ground_vehicle.hpp:38
VehicleSettings::max_trains
UnitID max_trains
max trains in game per company
Definition: settings_type.h:472
IsPlainRail
static bool IsPlainRail(TileIndex t)
Returns whether this is plain rails, with or without signals.
Definition: rail_map.h:49
Vehicle::x_offs
int8 x_offs
x offset for vehicle sprite
Definition: vehicle_base.h:295
Vehicle::subspeed
byte subspeed
fractional speed
Definition: vehicle_base.h:303
DiagdirBetweenTiles
static DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
Definition: map_func.h:394
FACIL_TRAIN
@ FACIL_TRAIN
Station with train station.
Definition: station_type.h:52
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1162
DIRDIFF_45RIGHT
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
Definition: direction_type.h:64
Train::ConsistChanged
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:106
Vehicle::z_extent
byte z_extent
z-extent of vehicle bounding box
Definition: vehicle_base.h:292
GroundVehicle::SetEngine
void SetEngine()
Set engine status.
Definition: ground_vehicle.hpp:279
VehicleRandomBits
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
Definition: vehicle.cpp:363
ScaleGUITrad
static int ScaleGUITrad(int value)
Scale traditional pixel dimensions to GUI zoom level.
Definition: zoom_func.h:76
AccelerationSlowdownParams::z_up
byte z_up
Fraction to remove when moving up.
Definition: train_cmd.cpp:2862
AdvanceWagonsAfterSwap
static void AdvanceWagonsAfterSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
Definition: train_cmd.cpp:1751
Train::UpdateAcceleration
void UpdateAcceleration()
Update acceleration of the train from the cached power and weight.
Definition: train_cmd.cpp:417
IsTunnel
static bool IsTunnel(TileIndex t)
Is this a tunnel (entrance)?
Definition: tunnel_map.h:23
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:17
PaletteID
uint32 PaletteID
The number of the palette.
Definition: gfx_type.h:18
TryReserveSafeTrack
static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
Try to reserve any path to a safe tile, ignoring the vehicle's destination.
Definition: train_cmd.cpp:2427
DC_NO_CARGO_CAP_CHECK
@ DC_NO_CARGO_CAP_CHECK
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
Definition: command_type.h:356
framerate_type.h
InvalidateWindowClassesData
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition: window.cpp:3339
NPFTrainFindNearestSafeTile
bool NPFTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir trackdir, bool override_railtype)
Try to extend the reserved path of a train to the nearest safe tile using NPF.
Definition: npf.cpp:1260
FreeTrainTrackReservation
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition: train_cmd.cpp:2243
GroundVehicle::IsEngine
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
Definition: ground_vehicle.hpp:316
SetTunnelBridgeReservation
static void SetTunnelBridgeReservation(TileIndex t, bool b)
Set the reservation state of the rail tunnel/bridge.
Definition: tunnelbridge_map.h:104
GetSignalStateByTrackdir
static SignalState GetSignalStateByTrackdir(TileIndex tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
Definition: rail_map.h:438
GroundVehicle::SetFreeWagon
void SetFreeWagon()
Set a vehicle as a free wagon.
Definition: ground_vehicle.hpp:289
RAILVEH_MULTIHEAD
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition: engine_type.h:28
BaseConsist::current_order_time
uint32 current_order_time
How many ticks have passed since this order started.
Definition: base_consist.h:22
MarkTileDirtyByTile
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:1985
SND_13_TRAIN_COLLISION
@ SND_13_TRAIN_COLLISION
15 == 0x11 Train+train crash
Definition: sound_type.h:56
SND_47_DEPARTURE_MONORAIL
@ SND_47_DEPARTURE_MONORAIL
71 == 0x47 Station departure: monorail engine
Definition: sound_type.h:110
RailVehicleInfo::user_def_data
byte user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition: engine_type.h:61
GetRailType
static RailType GetRailType(TileIndex t)
Gets the rail type of the given tile.
Definition: rail_map.h:115
GetNewVehiclePosResult
Position information of a vehicle after it moved.
Definition: vehicle_func.h:75
WC_VEHICLE_DEPOT
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
Definition: window_type.h:344
TrackStatusToRedSignals
static TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
Definition: track_func.h:384
Vehicle::orders
union Vehicle::@51 orders
The orders currently assigned to the vehicle.
newgrf.h
VE_DISABLE_WAGON_POWER
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
Definition: vehicle_base.h:90
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:51
SND_04_DEPARTURE_STEAM
@ SND_04_DEPARTURE_STEAM
2 == 0x02 Station departure: steam engine
Definition: sound_type.h:41
GetStationIndex
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
Definition: station_map.h:28
GetCrossingRailAxis
static Axis GetCrossingRailAxis(TileIndex t)
Get the rail axis of a level crossing.
Definition: road_map.h:337
Vehicle::build_year
Year build_year
Year the vehicle has been built.
Definition: vehicle_base.h:267
FindVehicleOnPos
void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
Definition: vehicle.cpp:498
Pool::PoolItem<&_orderlist_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:299
UsesWagonOverride
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
Definition: newgrf_engine.cpp:1173
NT_ACCIDENT
@ NT_ACCIDENT
An accident or disaster has occurred.
Definition: news_type.h:24
DIAGDIR_BEGIN
@ DIAGDIR_BEGIN
Used for iterations.
Definition: direction_type.h:78
DAYS_IN_YEAR
static const int DAYS_IN_YEAR
days per year
Definition: date_type.h:29
TrackDirectionToTrackdir
static Trackdir TrackDirectionToTrackdir(Track track, Direction dir)
Maps a track and a full (8-way) direction to the trackdir that represents the track running in the gi...
Definition: track_func.h:506
TrackStatusToTrackdirBits
static TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
Definition: track_func.h:360
GroundVehicle::gv_flags
uint16 gv_flags
Definition: ground_vehicle.hpp:81
TrainApproachingCrossingEnum
static Vehicle * TrainApproachingCrossingEnum(Vehicle *v, void *data)
Checks if a train is approaching a rail-road crossing.
Definition: train_cmd.cpp:1643
FindDepotData::tile
TileIndex tile
The tile of the depot.
Definition: pathfinder_type.h:54
PathfinderSettings::reverse_at_signals
bool reverse_at_signals
whether to reverse at signals at all
Definition: settings_type.h:441
DIRDIFF_90RIGHT
@ DIRDIFF_90RIGHT
Angle of 90 degrees right.
Definition: direction_type.h:65
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition: base_station_base.h:53
TrainCollideChecker::num
uint num
Total number of victims if train collided.
Definition: train_cmd.cpp:2990
Vehicle::unitnumber
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:300
DifficultySettings::line_reverse_mode
bool line_reverse_mode
reversing at stations or not
Definition: settings_type.h:77
SIGSEG_FULL
@ SIGSEG_FULL
Occupied by a train.
Definition: signal_func.h:51
SpecializedVehicle< Train, Type >::GetIfValid
static Train * GetIfValid(size_t index)
Returns vehicle if the index is a valid index for this vehicle type.
Definition: vehicle_base.h:1152
TrackEnterdirToTrackdir
static Trackdir TrackEnterdirToTrackdir(Track track, DiagDirection diagdir)
Maps a track and an (4-way) dir to the trackdir that represents the track with the entry in the given...
Definition: track_func.h:494
TrainCollideChecker::v
Train * v
Vehicle we are testing for collision.
Definition: train_cmd.cpp:2989
VehicleCache::cached_max_speed
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:121
company_func.h
BarCrossing
static void BarCrossing(TileIndex t)
Bar a level crossing.
Definition: road_map.h:447
GetRailDepotTrack
static Track GetRailDepotTrack(TileIndex t)
Returns the track of a depot, ignoring direction.
Definition: rail_map.h:182
FindFirstTrack
static Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
Definition: track_func.h:185
SpecializedVehicle< Train, Type >::Iterate
static Pool::IterateWrapper< Train > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
Definition: vehicle_base.h:1231
IsLevelCrossingTile
static bool IsLevelCrossingTile(TileIndex t)
Return whether a tile is a level crossing tile.
Definition: road_map.h:94
TrainCache::cached_max_curve_speed
int cached_max_curve_speed
max consist speed limited by curves
Definition: train.h:79
NT_ARRIVAL_COMPANY
@ NT_ARRIVAL_COMPANY
First vehicle arrived for company.
Definition: news_type.h:22
Engine::original_image_index
uint8 original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition: engine_base.h:39
GetNewVehiclePosResult::old_tile
TileIndex old_tile
Current tile of the vehicle.
Definition: vehicle_func.h:77
Vehicle::x_bb_offs
int8 x_bb_offs
x offset of vehicle bounding box
Definition: vehicle_base.h:293
EXPENSES_NEW_VEHICLES
@ EXPENSES_NEW_VEHICLES
New vehicles.
Definition: economy_type.h:159
CFollowTrackT::m_new_tile
TileIndex m_new_tile
the new tile (the vehicle has entered)
Definition: follow_track.hpp:43
AccelerationSlowdownParams::large_turn
byte large_turn
Speed change due to a large turn.
Definition: train_cmd.cpp:2861
abs
static T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:21
Order::ShouldStopAtStation
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
Definition: order_cmd.cpp:2229
VehicleID
uint32 VehicleID
The type all our vehicle IDs have.
Definition: vehicle_type.h:16
OrderType
OrderType
Order types.
Definition: order_type.h:35
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:132
Order::GetDepotOrderType
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Definition: order_base.h:135
Vehicle::InvalidateNewGRFCache
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
Definition: vehicle_base.h:462
network.h
RailVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:58
AddVehicleAdviceNewsItem
static void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition: news_func.h:40
TrackBits
TrackBits
Bitfield corresponding to Track.
Definition: track_type.h:38
Vehicle::day_counter
byte day_counter
Increased by one for each day.
Definition: vehicle_base.h:322
FindVehicleOnPosXY
void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
Find a vehicle from a specific location.
Definition: vehicle.cpp:438
TicksToLeaveDepot
int TicksToLeaveDepot(const Train *v)
Compute number of ticks when next wagon will leave a depot.
Definition: rail_cmd.cpp:2943
ToggleBit
static T ToggleBit(T &x, const uint8 y)
Toggles a bit in a variable.
Definition: bitmath_func.hpp:181
Train::IsPrimaryVehicle
bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: train.h:113
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:369
Train::Tick
bool Tick()
Update train vehicle data for a tick.
Definition: train_cmd.cpp:3909
CFollowTrackT::Follow
bool Follow(TileIndex old_tile, Trackdir old_td)
main follower routine.
Definition: follow_track.hpp:119
DiagDirToDiagTrackBits
static TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
Definition: track_func.h:532
OrderBackup::Backup
static void Backup(const Vehicle *v, uint32 user)
Create an order backup for the given vehicle.
Definition: order_backup.cpp:100
Train::GetRunningCost
Money GetRunningCost() const
Get running cost for the train consist.
Definition: train_cmd.cpp:3884
PathfinderSettings::yapf
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
Definition: settings_type.h:450
random_func.hpp
EXPENSES_TRAIN_RUN
@ EXPENSES_TRAIN_RUN
Running costs trains.
Definition: economy_type.h:160
AgeVehicle
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition: vehicle.cpp:1366
Vehicle::progress
byte progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
Definition: vehicle_base.h:306
RailtypeInfo::compatible_railtypes
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
Definition: rail.h:188
CmdMoveRailVehicle
CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Move a rail vehicle around inside the depot.
Definition: train_cmd.cpp:1163
Engine::DetermineCapacity
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition: engine.cpp:202
OverflowSafeInt< int64, INT64_MAX, INT64_MIN >
CFollowTrackT::m_exitdir
DiagDirection m_exitdir
exit direction (leaving the old tile)
Definition: follow_track.hpp:45
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
Vehicle::IsStoppedInDepot
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition: vehicle_base.h:527
IsPlainRailTile
static bool IsPlainRailTile(TileIndex t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:60
TrainCrashed
static uint TrainCrashed(Train *v)
Marks train as crashed and creates an AI event.
Definition: train_cmd.cpp:2969
CFollowTrackT::m_new_td_bits
TrackdirBits m_new_td_bits
the new set of available trackdirs
Definition: follow_track.hpp:44
TFP_SIGNAL
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
Definition: train.h:40
CmdBuildRailWagon
static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
Build a railroad wagon.
Definition: train_cmd.cpp:584
CCF_LENGTH
@ CCF_LENGTH
Allow vehicles to change length.
Definition: train.h:45
INVALID_TILE
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:88
EF_RAIL_FLIPS
@ EF_RAIL_FLIPS
Rail vehicle can be flipped in the depot.
Definition: engine_type.h:157
GroundVehicle< Train, VEH_TRAIN >::CargoChanged
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
Definition: ground_vehicle.cpp:79
Chance16R
static bool Chance16R(const uint a, const uint b, uint32 &r)
Flips a coin with a given probability and saves the randomize-number in a variable.
Definition: random_func.hpp:155
UpdateLevelCrossing
void UpdateLevelCrossing(TileIndex tile, bool sound)
Sets correct crossing state.
Definition: train_cmd.cpp:1686
GetTileRailType
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Definition: rail.cpp:155
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:314
TrainCheckIfLineEnds
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
Definition: train_cmd.cpp:3689
VehicleSettings::max_train_length
uint8 max_train_length
maximum length for trains
Definition: settings_type.h:464
Vehicle::spritenum
byte spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
Definition: vehicle_base.h:289
Train::GetNextUnit
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
Definition: train.h:143
GetCrossingRoadAxis
static Axis GetCrossingRoadAxis(TileIndex t)
Get the road axis of a level crossing.
Definition: road_map.h:325
GetOtherTunnelBridgeEnd
static TileIndex GetOtherTunnelBridgeEnd(TileIndex t)
Determines type of the wormhole and returns its other end.
Definition: tunnelbridge_map.h:78
ReverseTrackdir
static Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition: track_func.h:255
NormalizeTrainVehInDepot
static void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
Definition: train_cmd.cpp:660
SpecializedVehicle::GetLastEnginePart
T * GetLastEnginePart()
Get the last part of an articulated engine.
Definition: vehicle_base.h:1115
GroundVehicle::IsWagon
bool IsWagon() const
Check if a vehicle is a wagon.
Definition: ground_vehicle.hpp:322
RailVehicleInfo::running_cost
byte running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition: engine_type.h:50
TRACK_BIT_Y
@ TRACK_BIT_Y
Y-axis track.
Definition: track_type.h:41
CBID_VEHICLE_LENGTH
@ CBID_VEHICLE_LENGTH
Vehicle length, returns the amount of 1/8's the vehicle is shorter for trains and RVs.
Definition: newgrf_callbacks.h:33
Train::CalcNextVehicleOffset
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle's center to the following center taking the vehicle lengths in...
Definition: train.h:167
articulated_vehicles.h
CCF_TRACK
@ CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
Definition: train.h:48
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:572
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition: newgrf_commons.cpp:516
SpecializedVehicle::Previous
T * Previous() const
Get previous vehicle in the chain.
Definition: vehicle_base.h:1083
Trackdir
Trackdir
Enumeration for tracks and directions.
Definition: track_type.h:70
TrainApproachingCrossing
static bool TrainApproachingCrossing(TileIndex tile)
Finds a vehicle approaching rail-road crossing.
Definition: train_cmd.cpp:1664
Vehicle::cargo_subtype
byte cargo_subtype
Used for livery refits (NewGRF variations)
Definition: vehicle_base.h:315
TFP_NONE
@ TFP_NONE
Normal operation.
Definition: train.h:38
GroundVehicle< Train, VEH_TRAIN >::IsFreeWagon
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
Definition: ground_vehicle.hpp:310
TFP_STUCK
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
Definition: train.h:39
TrackCrossesTracks
static TrackBits TrackCrossesTracks(Track track)
Maps a track to all tracks that make 90 deg turns with it.
Definition: track_func.h:428
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
CollectTrackbitsFromCrashedVehiclesEnum
static Vehicle * CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
Collect trackbits of all crashed train vehicles on a tile.
Definition: train_cmd.cpp:3419
YAPFSettings::maximum_go_to_depot_penalty
uint32 maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
Definition: settings_type.h:393
Vehicle::GetAdvanceDistance
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
Definition: vehicle_base.h:425
RailVehicleInfo::capacity
byte capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition: engine_type.h:53
Vehicle::GetOrder
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
Definition: vehicle_base.h:872
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
Vehicle::reliability
uint16 reliability
Reliability.
Definition: vehicle_base.h:271
SpecializedVehicle< Train, Type >::First
Train * First() const
Get the first vehicle in the chain.
Definition: vehicle_base.h:1059
SetCrossingBarred
static void SetCrossingBarred(TileIndex t, bool barred)
Set the bar state of a level crossing.
Definition: road_map.h:428
Vehicle::UpdatePosition
void UpdatePosition()
Update the position of the vehicle.
Definition: vehicle.cpp:1598
Swap
static void Swap(T &a, T &b)
Type safe swap operation.
Definition: math_func.hpp:215
Engine::flags
byte flags
Flags of the engine.
Definition: engine_base.h:33
AS_BRAKE
@ AS_BRAKE
We want to stop.
Definition: ground_vehicle.hpp:22
Track
Track
These are used to specify a single track.
Definition: track_type.h:19
Vehicle::HandleBreakdown
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
Definition: vehicle.cpp:1300
DecreaseVehicleValue
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition: vehicle.cpp:1238
Vehicle::y_bb_offs
int8 y_bb_offs
y offset of vehicle bounding box
Definition: vehicle_base.h:294
GetNewVehiclePosResult::y
int y
x and y position of the vehicle after moving
Definition: vehicle_func.h:76
order_backup.h
ChangeTrainDirRandomly
static void ChangeTrainDirRandomly(Train *v)
Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
Definition: train_cmd.cpp:3507
TrackdirBitsToTrackBits
static TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
Definition: track_func.h:316
PROP_TRAIN_CARGO_AGE_PERIOD
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:30
VehicleSettings::freight_trains
uint8 freight_trains
value to multiply the weight of cargo by
Definition: settings_type.h:477
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition: geometry_type.hpp:47
GroundVehicle::Crash
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
Definition: ground_vehicle.hpp:100
PM_PAUSED_ERROR
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
Definition: openttd.h:64
TrainEnterStation
static void TrainEnterStation(Train *v, StationID station)
Trains enters a station, send out a news item if it is the first train, and start loading.
Definition: train_cmd.cpp:2823
FIND_FIRST_BIT
#define FIND_FIRST_BIT(x)
Returns the first non-zero bit in a 6-bit value (from right).
Definition: bitmath_func.hpp:200
Vehicle::GetNumOrders
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
Definition: vehicle_base.h:698
SpecializedVehicle::Last
T * Last()
Get the last vehicle in the chain.
Definition: vehicle_base.h:1065
GroundVehicle< Train, VEH_TRAIN >::DoUpdateSpeed
uint DoUpdateSpeed(uint accel, int min_speed, int max_speed)
Update the speed of the vehicle.
Definition: ground_vehicle.hpp:363
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3248
VehicleSpriteSeq::GetBounds
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition: vehicle.cpp:98
PathfinderSettings::reserve_paths
bool reserve_paths
always reserve paths regardless of signal type.
Definition: settings_type.h:445
TrainController
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
Definition: train_cmd.cpp:3098
Vehicle::first
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
Definition: vehicle_base.h:229
IsValidTrackdir
static bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
Definition: track_func.h:60
SpecializedVehicle::UpdateViewport
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Definition: vehicle_base.h:1184
Vehicle::fill_percent_te_id
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
Definition: vehicle_base.h:299
SRT_TRAIN_ARRIVES
@ SRT_TRAIN_ARRIVES
Trigger platform when train arrives.
Definition: newgrf_station.h:106
EngineInfo::cargo_age_period
uint16 cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:146
Order
Definition: order_base.h:32
WID_VV_REFIT
@ WID_VV_REFIT
Open the refit window.
Definition: vehicle_widget.h:22
GroundVehicleCache::cached_weight
uint32 cached_weight
Total weight of the consist (valid only for the first engine).
Definition: ground_vehicle.hpp:31
RailtypeInfo::curve_speed
byte curve_speed
Multiplier for curve maximum speed advantage.
Definition: rail.h:203
MarkTrainAsStuck
static void MarkTrainAsStuck(Train *v)
Mark a train as stuck and stop it if it isn't stopped right now.
Definition: train_cmd.cpp:1500
DAY_TICKS
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
Definition: date_type.h:28
ReverseTrainSwapVeh
void ReverseTrainSwapVeh(Train *v, int l, int r)
Swap vehicles l and r in consist v, and reverse their direction.
Definition: train_cmd.cpp:1589
CFollowTrackT
Track follower helper template class (can serve pathfinders and vehicle controllers).
Definition: follow_track.hpp:28
CFollowTrackT::m_tiles_skipped
int m_tiles_skipped
number of skipped tunnel or station tiles
Definition: follow_track.hpp:49
GetDepotIndex
static DepotID GetDepotIndex(TileIndex t)
Get the index of which depot is attached to the tile.
Definition: depot_map.h:52
SpecializedVehicle::GetFirstEnginePart
T * GetFirstEnginePart()
Get the first part of an articulated engine.
Definition: vehicle_base.h:1103
CFollowTrackT::m_is_tunnel
bool m_is_tunnel
last turn passed tunnel
Definition: follow_track.hpp:46
TunnelBridgeIsFree
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
Definition: vehicle.cpp:568
TrackdirToTrack
static Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
Definition: track_func.h:270
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
WC_VEHICLE_ORDERS
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
Definition: window_type.h:205
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:581
PROP_TRAIN_USER_DATA
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
Definition: newgrf_properties.h:29
Engine::reliability
uint16 reliability
Current reliability of the engine.
Definition: engine_base.h:25
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:25
Vehicle::refit_cap
uint16 refit_cap
Capacity left over from before last refit.
Definition: vehicle_base.h:317
GroundVehicle::IsMultiheaded
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
Definition: ground_vehicle.hpp:328
Vehicle::date_of_last_service
Date date_of_last_service
Last date the vehicle had a service at a depot.
Definition: vehicle_base.h:270
GetNewVehiclePos
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing.
Definition: vehicle.cpp:1683
CBID_TRAIN_ALLOW_WAGON_ATTACH
@ CBID_TRAIN_ALLOW_WAGON_ATTACH
Determine whether a wagon can be attached to an already existing train.
Definition: newgrf_callbacks.h:72
TileVirtXY
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition: map_func.h:194
TrainApproachingCrossingTile
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred)
Definition: train_cmd.cpp:3662
news_func.h
ReverseTrainDirection
void ReverseTrainDirection(Train *v)
Turn a train around.
Definition: train_cmd.cpp:1808
AccelerationSlowdownParams::z_down
byte z_down
Fraction to add when moving down.
Definition: train_cmd.cpp:2863
VETS_ENTERED_WORMHOLE
@ VETS_ENTERED_WORMHOLE
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
Definition: tile_cmd.h:22
INVALID_TRACK
@ INVALID_TRACK
Flag for an invalid track.
Definition: track_type.h:28